Skip to main content

LongTracer Logo

RAG hallucination detection, multi-project tracing, and pluggable backends — all batteries included.

PyPI Version Total Downloads Monthly Downloads GitHub Stars CI Python Versions License

📖 Documentation  ·  Quick Start  ·  API Reference  ·  Changelog

Detect hallucinations in LLM-generated responses. LongTracer verifies every claim against source documents using hybrid STS + NLI, works with any RAG framework, and traces the full verification pipeline.

Quick Start

pip install longtracer

🎬 Demo

Interactive TUI Demo — full verification workflow:

LongTracer TUI Demo

Python API — one-liner verification:

LongTracer Python API

Web Dashboard — browse metrics and traces locally:

LongTracer Dashboard

Full TUI workflow demo: python demos/hallucination_detection.py

One-Liner & Batch API

from longtracer import check, check_batch

# Verify a single response
result = check(
    "The Eiffel Tower is 330 meters tall and located in Berlin.",
    ["The Eiffel Tower is a wrought-iron lattice tower in Paris, France. It is 330 metres tall."]
)

print(result.verdict)             # "FAIL"
print(result.trust_score)         # 0.0 - 1.0
print(result.hallucination_count) # 1 ("Berlin" contradicts "Paris")

# Verify in bulk
results = check_batch([
    {"response": "P is NP.", "sources": ["It is not known if P is NP."]},
    {"response": "Water boils at 100C.", "sources": ["Water boils at 100C."]}
])

CLI (no Python needed)

longtracer check "The Eiffel Tower is in Berlin." "The Eiffel Tower is in Paris."
# ✗ FAIL  trust=0.50  hallucinations=1

Full API

from longtracer import CitationVerifier

verifier = CitationVerifier(cache=True)  # optional result caching
result = verifier.verify_parallel(
    response="The Eiffel Tower is 330 meters tall and located in Berlin.",
    sources=["The Eiffel Tower is a wrought-iron lattice tower in Paris, France. It is 330 metres tall."]
)

No vector store dependency. No LLM dependency. Just strings in, verification out.

Honest, Typed Results (v0.3.0+)

check() / verify_parallel() keep their existing behaviour unchanged. Alongside them, check_case() and verify_case() return a typed CaseResult that reports an explicit execution state, a per-claim assessment with a reason code, and a policy gate — computed separately from the raw measurement. A RAG pipeline that returns an empty answer can never be reported as a perfect result.

from longtracer import check_case

case = check_case("", ["some source"])
print(case.availability)   # NO_ASSESSABLE_CLAIMS
print(case.reason)         # EMPTY_RESPONSE
print(case.quality_gate)   # FAIL — never a silent "PASS"

case = check_case(
    "The Eiffel Tower is 330 meters tall and located in Berlin.",
    ["The Eiffel Tower is a wrought-iron lattice tower in Paris, France. It is 330 metres tall."],
)
for claim in case.claims:
    print(claim.assessment, claim.reason, claim.confidence)

See the Result States guide for the full list of execution states, claim assessments, and how CaseResult relates to the legacy VerificationResult.

How It Works

  1. Claim splitting — LLM response is split into individual sentences/claims
  2. STS matching — Fast bi-encoder (all-MiniLM-L6-v2) finds the best-matching source sentence for each claim
  3. NLI verification — Cross-encoder (nli-deberta-v3-xsmall) classifies entailment/contradiction/neutral
  4. Verdict — Trust score computed, hallucinations flagged

Framework Adapters

LangChain (3 lines)

pip install "longtracer[langchain]"
from longtracer import LongTracer, instrument_langchain

LongTracer.init(verbose=True)
instrument_langchain(your_chain)
# Your chain.invoke() now auto-verifies every response

LlamaIndex (3 lines)

pip install "longtracer[llamaindex]"
from longtracer import LongTracer, instrument_llamaindex

LongTracer.init(verbose=True)
instrument_llamaindex(your_query_engine)

Direct API (any framework)

from longtracer.guard.verifier import CitationVerifier

verifier = CitationVerifier()
result = verifier.verify_parallel(
    response="LLM said this...",
    sources=["chunk 1 text", "chunk 2 text"],
    source_metadata=[{"source": "doc.pdf", "page": 1}, {"source": "doc.pdf", "page": 2}]
)

Haystack v2

pip install "longtracer[haystack]"
from longtracer.adapters.haystack_handler import LongTracerVerifier

pipeline.add_component("verifier", LongTracerVerifier())
pipeline.connect("generator.replies", "verifier.response")
pipeline.connect("retriever.documents", "verifier.documents")

LangGraph Agents

pip install "longtracer[langgraph]"
from longtracer import instrument_langgraph

handler = instrument_langgraph(graph)
result = agent.invoke(
    {"messages": [("user", "What is X?")]},
    config={"callbacks": [handler]}
)

LangChain Agents

from longtracer import instrument_langchain_agent

handler = instrument_langchain_agent(agent_executor)
result = agent_executor.invoke({"input": "What is X?"})

Async Support

result = await verifier.verify_parallel_async(response, sources)

Works with Haystack, custom pipelines, or any code that produces strings.

Observability & Analytics

LongTracer v0.2.0+ introduces a complete, production-ready observability suite.

Built-in Web Dashboard

Browse all your verified RAG traces, hallucination rates, and metrics locally.

longtracer serve

Then visit http://localhost:8000/dashboard in your browser.

Alerts & Notifications

Automatically trigger Webhooks, Slack, Discord, or Email notifications when an LLM's trust score drops below your acceptable threshold. Configured easily via environment variables or pyproject.toml.

OpenTelemetry Export

pip install "longtracer[otel]"

Automatically emits standard OTLP traces (longtracer.verify) with attributes like trust_score, hallucination_count, and verdict. Fully compatible with Jaeger, Datadog, Honeycomb, or Grafana Tempo. We also include a pre-configured Grafana Dashboard Template.

Multi-Project Tracing

Track multiple RAG applications independently:

from longtracer import LongTracer

LongTracer.init(project_name="chatbot-prod", backend="sqlite")

# Get project-specific tracers
chatbot = LongTracer.get_tracer("chatbot-prod")
search  = LongTracer.get_tracer("search-api")

# Each project's traces are tagged and filterable
chatbot.start_root(inputs={"query": "..."})

Vector Store & LLM Agnostic

The SDK core takes plain str and List[str]. It does not depend on any vector store (Chroma, FAISS, Pinecone, Weaviate, Qdrant, pgvector) or any LLM provider (OpenAI, Anthropic, Ollama, Bedrock). Use whatever you want — LongTracer just verifies the output.

Trace Storage Backends

LongTracer.init(backend="sqlite")   # default — persists to ~/.longtracer/traces.db
LongTracer.init(backend="memory")   # in-memory, lost on restart
LongTracer.init(backend="mongo")    # production, distributed
Backend Install Where traces live
SQLite built-in (default) ~/.longtracer/traces.db
Memory built-in RAM only, lost on restart
MongoDB pip install "longtracer[mongo]" MongoDB database
PostgreSQL pip install "longtracer[postgres]" PostgreSQL database
Redis pip install "longtracer[redis]" Redis key-value store

Viewing Traces

CLI

longtracer view                        # list recent traces
longtracer view --last                 # view most recent
longtracer view --id <trace_id>        # view specific trace
longtracer view --project chatbot-prod # filter by project
longtracer view --export <trace_id>    # export to JSON
longtracer view --html <trace_id>      # export to HTML report

Console (verbose mode)

[longtracer] span=retrieval    chunks=5
[longtracer] span=llm_call     answer_len=179
[longtracer] span=eval_claims  total=3 supported=2
[longtracer] span=grounding    score=0.67 verdict=FAIL

HTML Report

from longtracer.guard.trace_report import export_trace_html
export_trace_html(tracer, filepath="report.html")

Generates a standalone HTML file with trust scores, a summary stats bar, and clickable per-claim evidence diffs — viewable in any browser, zero external dependencies.

JSON Export

from longtracer.guard.trace_report import export_trace_json
export_trace_json(tracer, filepath="trace.json")

Optional Dependencies

Extra Install What it adds
langchain pip install "longtracer[langchain]" LangChain callback adapter
llamaindex pip install "longtracer[llamaindex]" LlamaIndex event adapter
haystack pip install "longtracer[haystack]" Haystack v2 component adapter
langgraph pip install "longtracer[langgraph]" LangGraph & LangChain agent tracing
mongo pip install "longtracer[mongo]" MongoDB trace backend
postgres pip install "longtracer[postgres]" PostgreSQL trace backend
redis pip install "longtracer[redis]" Redis trace backend
chroma pip install "longtracer[chroma]" ChromaDB + HuggingFace embeddings
all pip install "longtracer[all]" Everything

Configuration

Set project-level defaults effortlessly via pyproject.toml or environment variables (env vars override file).

pyproject.toml

[tool.longtracer]
project = "my-rag-app"
backend = "sqlite"
threshold = 0.5
verbose = true
log_level = "INFO"

Environment Variables

Variable Default Description
LONGTRACER_ENABLED false Auto-enable with LongTracer.auto()
LONGTRACER_VERBOSE false Print per-span summaries
LONGTRACER_LOG_LEVEL INFO Python logging level
LONGTRACER_PROJECT longtracer Default project name
TRACE_CACHE_BACKEND sqlite Trace storage: sqlite, memory, mongo, postgres, redis
MONGODB_URI — MongoDB connection URI
POSTGRES_HOST — PostgreSQL host
REDIS_HOST — Redis host

Demo Application

The examples/ directory contains a complete RAG demo using ChromaDB + Ollama. It is NOT part of the published PyPI package. See examples/README.md for setup instructions.

Documentation

Full documentation at endevsols.github.io/LongTracer

License

MIT

Metadata

Release files for longtracer 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for longtracer 0.3.0
File Size Uploaded Provenance Actions
longtracer-0.3.0.tar.gz 122.2 kB Without provenance Details for longtracer-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for longtracer 0.3.0
File Interpreter ABI Platform Actions
longtracer-0.3.0-py3-none-any.whl Python 3 none any Details for longtracer-0.3.0-py3-none-any.whl

Total release size: 266.4 kB

Release files / longtracer-0.3.0.tar.gz

Download URL longtracer-0.3.0.tar.gz
Size 122.2 kB
Tags Source
SHA-256 checksum
How to use checksums
72f3b9cfaf86cdee18eafa464794cee01ef2ac7ab9c77c2cda6743d788cc8c55
BLAKE2b-256 checksum
How to use checksums
a3c5c5d3289cfbe99e282e4bfcfc89d5d9971d74dbf52864f201accd48e73770
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.10

Release files / longtracer-0.3.0-py3-none-any.whl

Download URL longtracer-0.3.0-py3-none-any.whl
Size 144.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
85546c1efb6068ed91c54e1f4371127ede00d08808b6afb65b874385e44a3329
BLAKE2b-256 checksum
How to use checksums
ea81122bf3a3e290ab9496d3264c7ebfbe5a9a1589ce4682affbac86b600a390
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.10

Security for longtracer 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page