Skip to main content

A sidecar belief state tracker for LLM agents to detect contradictions and maintain persistent facts.

Project description

BeliefState

Persistent memory for LLM applications.
Extract facts, resolve contradictions, and recall knowledge — automatically.

PyPI License Python CI Lint Docs


The Problem

Every time a user starts a new conversation, your LLM starts from zero. It doesn't remember that the user is a Rust developer in Berlin, prefers dark mode, or already explained their project architecture three messages ago.

You can dump the full chat history into the system prompt, but that burns tokens fast — and most of it is noise. RAG helps with documents, but user facts (preferences, identity, context) fall through the cracks. There's no clean way to say "remember this about the user" without manual bookkeeping.

How BeliefState Works

BeliefState sits between your LLM and your application. Every time the LLM responds, it silently:

  1. Extracts facts — "user prefers Rust", "project uses PostgreSQL", "works at Google"
  2. Detects contradictions — if the user says "I live in Tokyo" after saying "I live in Berlin", it flags the conflict
  3. Stores beliefs — persisted in SQLite, PostgreSQL, or Redis with full history
  4. Injects context — on the next call, relevant beliefs are added to the system prompt automatically

All of this happens in the background. Zero added latency to your request path.

from beliefstate import BeliefTracker
from beliefstate.adapters import OpenAIAdapter

tracker = BeliefTracker(
    adapter=OpenAIAdapter(model="gpt-4o"),
    config=TrackerConfig(store_type="sqlite", store_kwargs={"db_path": "beliefs.db"})
)

@tracker.wrap
async def chat(messages):
    return await openai_client.chat.completions.create(model="gpt-4o", messages=messages)

tracker.set_session("user_123")
await chat([{"role": "user", "content": "I live in Tokyo and work at Google."}])
# BeliefState extracts: {subject: "user", predicate: "lives_in", value: "Tokyo"}

Features

Feature Description
Zero-latency tracking Background extraction pipeline — no added latency to your request path
Dual-source extraction Extracts beliefs from both user messages and assistant responses every turn
5+ LLM providers OpenAI, Anthropic, Gemini, Ollama, LiteLLM (100+ models via LiteLLM)
Dual-adapter architecture Expensive model for your app, cheap/local model for background tracking
NLI contradiction detection 3-stage pipeline: rule-based → embedding similarity → LLM judge, with negation awareness and exact-match dedup
3 resolution strategies overwrite, keep_old, or raise — with escalation logic (ASK → BLOCK) and per-belief resolution notes
Confidence calibration Automatic hedging detection, per-source confidence caps (user/assistant), hypothetical flagging
Belief categorization Extracted beliefs grouped into 5 categories: identity, technical, planning, constraint, state
Persistent stores SQLite, PostgreSQL, Redis — with full audit trails, binary embedding storage, and automatic schema migration
Streaming support @tracker.wrap(stream=True) intercepts async generators, accumulates text, and dispatches tracking on completion
Automatic context injection Relevant beliefs injected into the system prompt on every call — with category-grouped summarization
Token-aware injection Relevance-based belief selection within a configurable token budget using vector similarity
Framework integrations LangChain, LlamaIndex, FastAPI, Flask, ASGI, WSGI, OpenAI Assistants
Production resilience Retry with exponential backoff, circuit breakers (per operation), health checks, graceful shutdown with task draining
Pluggable dispatchers Asyncio (in-process), Sync, Celery, Redis Queue — survives server restarts
GDPR-compliant clear_session() with auditable deletion receipts and in-flight task draining
Staleness scoring & TTL Automatic belief decay (confidence / days_since_reference) and configurable time-based pruning
Belief export/import JSON round-trip for portable belief data; CSV export via dashboard
Developer Dashboard Live browser UI with charts, session compare, contradiction heatmaps, global search, alert rules, keyboard shortcuts, and real-time SSE pipeline events
Observability OpenTelemetry traces and metrics, structured TrackerEvent logging with JSON output

Installation

pip install beliefstate

With optional extras:

pip install "beliefstate[openai]"         # OpenAI adapter
pip install "beliefstate[anthropic]"      # Anthropic adapter
pip install "beliefstate[gemini]"         # Gemini adapter
pip install "beliefstate[ollama]"         # Ollama adapter (local)
pip install "beliefstate[litellm]"        # LiteLLM (100+ providers)
pip install "beliefstate[local]"          # Local embeddings (sentence-transformers)
pip install "beliefstate[redis]"          # Redis store
pip install "beliefstate[postgres]"       # PostgreSQL store
pip install "beliefstate[langchain]"      # LangChain integration
pip install "beliefstate[llamaindex]"     # LlamaIndex integration
pip install "beliefstate[fastapi]"        # FastAPI middleware
pip install "beliefstate[flask]"          # Flask middleware
pip install "beliefstate[dashboard]"      # Developer dashboard (fastapi, uvicorn)
pip install "beliefstate[all]"            # Everything

Documentation

For provider setup, store configuration, framework integrations, advanced usage, and API reference:

https://abhay-2108.github.io/beliefstate/


Quick Example: Dual-Adapter Setup

Use Claude for your app, Llama 3 for background tracking — zero API costs for belief extraction:

from beliefstate import BeliefTracker
from beliefstate.adapters import AnthropicAdapter, OllamaAdapter

tracker = BeliefTracker(
    adapter=AnthropicAdapter(model="claude-3-5-sonnet-latest"),
    internal_adapter=OllamaAdapter(model="llama3", embed_model="nomic-embed-text"),
)

Development

git clone https://github.com/abhay-2108/beliefstate.git
cd beliefstate
pip install -e ".[dev]"
pytest
ruff check beliefstate/

Contributing

Contributions are welcome! Please read our Contributing Guide for details on the development setup, coding standards, and pull request process.

This project follows a Code of Conduct. By participating, you agree to uphold it.

For security vulnerabilities, please see our Security Policy.

For version history, see the Changelog.


License

Apache License 2.0. See LICENSE for details.

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

beliefstate-1.2.0.tar.gz (2.5 MB view details)

Uploaded Source

Built Distribution

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

beliefstate-1.2.0-py3-none-any.whl (1.9 MB view details)

Uploaded Python 3

File details

Details for the file beliefstate-1.2.0.tar.gz.

File metadata

  • Download URL: beliefstate-1.2.0.tar.gz
  • Upload date:
  • Size: 2.5 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for beliefstate-1.2.0.tar.gz
Algorithm Hash digest
SHA256 42586431ca8411a2b4a5c1ae6df4e9cddbcecdbd9572efad2b8b5cd4f5f8d625
MD5 4f84106666f4b5c38abdcfbad9554432
BLAKE2b-256 fd2fb5cbfda23049ee1e76124c430f622c8fe9d3ba511f96d655780467b38631

See more details on using hashes here.

Provenance

The following attestation bundles were made for beliefstate-1.2.0.tar.gz:

Publisher: publish.yml on abhay-2108/beliefstate

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file beliefstate-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: beliefstate-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 1.9 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.13

File hashes

Hashes for beliefstate-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 49b32574aca7471d9f4b5a4bd3a8840a3b3a6ded683dbd50762c738059dc5acf
MD5 e59e1930b69357faaf795ff3ab60f4c0
BLAKE2b-256 9828f264c529fabb52270caf7ab8bb92d5e31c12503b9b0efaa09cb7dc07db30

See more details on using hashes here.

Provenance

The following attestation bundles were made for beliefstate-1.2.0-py3-none-any.whl:

Publisher: publish.yml on abhay-2108/beliefstate

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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