Skip to main content

Multi-threaded Shapley explainability for LLMs: words, sentences, documents, and tools.

Project description

llmSHAP logo

llmSHAP

Unit Tests Documentation PyPI Downloads

A multi-threaded explainability framework using Shapley values for LLM-based outputs.


Getting started

Install the llmshap package (with all optional dependencies):

pip install "llmshap[full]"

Install in editable mode with all optional dependencies (after cloning the repository):

pip install -e ".[full]"

Documentation is available at llmSHAP Docs and a hands-on tutorial can be found here.


Example usage

from llmSHAP import DataHandler, BasicPromptCodec, ShapleyAttribution
from llmSHAP.llm import OpenAIInterface

data = "In what city is the Eiffel Tower?"
handler = DataHandler(data, permanent_keys={0,3,4})
result = ShapleyAttribution(model=OpenAIInterface("gpt-4o-mini"),
                            data_handler=handler,
                            prompt_codec=BasicPromptCodec(system="Answer the question briefly."),
                            use_cache=True,
                            num_threads=16,
                            ).attribution()

print("\n\n### OUTPUT ###")
print(result.output)

print("\n\n### ATTRIBUTION ###")
print(result.attribution)

print("\n\n### HEATMAP ###")
print(result.render())

Multimodal example with Image:

The following example shows llmSHAP with images. Note: EmbeddingCosineSimilarity downloads an embedding model on first use.

from llmSHAP import DataHandler, BasicPromptCodec, ShapleyAttribution, EmbeddingCosineSimilarity, Image
from llmSHAP.llm import OpenAIInterface

data = {
    "question": "Has our stockprice increased or decreased since the beginning?",
    "Num employees"        : "The company has about 450 employees.",
    "[IMAGE] Stock chart"  : Image(image_path="./docs/_static/demo-stock-price.png"),
    "Report release date"  : "Quarterly reports are released on the 15th.",
    "Headquarter Location" : "The headquarters is located in a mid-sized city.",
    "Num countries"        : "It has offices in three countries."
}

result = ShapleyAttribution(model=OpenAIInterface("gpt-5-mini", reasoning="low"),
                            data_handler=DataHandler(data, permanent_keys={"question"}),
                            prompt_codec=BasicPromptCodec(system="Answer the question briefly."),
                            use_cache=True,
                            num_threads=35,
                            value_function=EmbeddingCosineSimilarity(),
                            ).attribution()

print("\n\n### OUTPUT ###")
print(result.output)

print("\n\n### HEATMAP ###")
print(result.render(abs_values=True, render_labels=True))
llmSHAP logo

Example data

You can pass either a string or a dictionary:

from llmSHAP import DataHandler

# String input
data = "The quick brown fox jumps over the lazy dog"
handler = DataHandler(data)

# Dictionary input
data = {"a": "The", "b": "quick", "c": "brown", "d": "fox"}
handler = DataHandler(data)

To exclude certain keys from the computations, use permanent_keys:

from llmSHAP import DataHandler

data = {"a": "The", "b": "quick", "c": "brown", "d": "fox"}
handler = DataHandler(data, permanent_keys={"a", "d"})

# Get data with index 1 WITHOUT the permanent features.
print(handler.get_data({1}, exclude_permanent_keys=True, mask=False))
# Output: {'b': 'quick'}

# Get data with index 1 AND the permanent features.
print(handler.get_data({1}, exclude_permanent_keys=False, mask=False))
# Output: {'a': 'The', 'b': 'quick', 'd': 'fox'}

Comparison with TokenSHAP

Capability llmSHAP TokenSHAP
Threaded ✅ (optional num_threads)
Modular architecture
Exact Shapley option ✅ (Full enumeration) ❌ (Monte Carlo sampling)
Generation caching across coalitions
Heuristics SlidingWindow • Monte Carlo • Counterfactual Monte Carlo
Sentence-/chunk-level attribution
Permanent context pinning (always-included features)
Pluggable similarity metric ✅ TF-IDF, embeddings ✅ TF-IDF, embeddings
Docs & tutorial ✅ Sphinx docs + tutorial ✅ README only
Unit tests & CI ✅ Pytest + GitHub Actions
Vision object attribution ✅ PixelSHAP

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

llmshap-1.5.0.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

llmshap-1.5.0-py3-none-any.whl (18.7 kB view details)

Uploaded Python 3

File details

Details for the file llmshap-1.5.0.tar.gz.

File metadata

  • Download URL: llmshap-1.5.0.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for llmshap-1.5.0.tar.gz
Algorithm Hash digest
SHA256 d835d62f41545c4e793c3e85f0dc984342b1d91294ccb5a5364dbfe8b702e33c
MD5 36d93d0d8aa3b763c7137840de6e6906
BLAKE2b-256 1355ff6c5fe2fa6712918fd98628847905f1ec17ba57b71b0b4f58efdfb108a8

See more details on using hashes here.

File details

Details for the file llmshap-1.5.0-py3-none-any.whl.

File metadata

  • Download URL: llmshap-1.5.0-py3-none-any.whl
  • Upload date:
  • Size: 18.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.5

File hashes

Hashes for llmshap-1.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 fb6e94c68e960ec2736c8879f37985879f1ce86e20b2ceee0de729cb97c6b3e2
MD5 a1cc8931b337cddbd6cf4a6e482d458b
BLAKE2b-256 8c5de3b1e6bacebe906ab90c909e5e0e308deaf83008e976be7166a62513b6e9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page