Skip to main content

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

Project description

llmSHAP logo

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[all]"

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

pip install -e ".[all]"

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.

from llmSHAP import DataHandler, BasicPromptCodec, ShapleyAttribution, 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,
                            ).attribution()

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

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

Embedding-Based Output Scoring

EmbeddingCosineSimilarity measures semantic similarity between outputs using embeddings. It supports two backends:

  • API — any OpenAI-compatible embeddings endpoint via api_url_endpoint.
  • Local — a sentence-transformers model downloaded on first use.

For the local backend, install the embeddings extra:

pip install "llmshap[embeddings]"

The example below uses the API backend, which is already included in [all].

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

data = "In what city is the Eiffel Tower?"
handler = DataHandler(data)
result = ShapleyAttribution(model=OpenAIInterface("gpt-4o-mini"),
                            data_handler=handler,
                            prompt_codec=BasicPromptCodec(system="Answer the question briefly."),
                            use_cache=True,
                            num_threads=16,
                            value_function=EmbeddingCosineSimilarity(
                                model_name = "text-embedding-3-small",
                                api_url_endpoint = "https://api.openai.com/v1")
                            ).attribution()

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

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

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




Stars ⭐️

Star History Chart

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.1.tar.gz (18.9 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.1-py3-none-any.whl (20.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: llmshap-1.5.1.tar.gz
  • Upload date:
  • Size: 18.9 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.1.tar.gz
Algorithm Hash digest
SHA256 266f42a9c942cce8e36f502563929c05884404c9c8db0d66dd5921848c995a19
MD5 46ae0682a4ffab7e5e375f38be8ca060
BLAKE2b-256 b1a0e5a3c7427a0a73d2c6d6c386cf640fcfe878ae96c454bfc8ffb52f1bdd00

See more details on using hashes here.

File details

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

File metadata

  • Download URL: llmshap-1.5.1-py3-none-any.whl
  • Upload date:
  • Size: 20.3 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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 c4888c29d6728f33ca5bc29ba5c08472aa87c759519ddcb2b49907a8d8854fb8
MD5 c0b7e0c4c8d7bb45a5693907f87d0930
BLAKE2b-256 7d2ea3cc93abc4e5c402ab8a23151e8ada30507d30170e28370c60b940ca2e7c

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