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={"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_123", predicate: "lives_in", value: "Tokyo"}

Features

Feature Description
Zero-latency Background extraction — no added latency to your request path
5 LLM providers OpenAI, Anthropic, Gemini, Ollama, LiteLLM (100+ via LiteLLM)
Dual-adapter Expensive model for your app, cheap/local model for tracking
Contradiction detection NLI judge resolves conflicting facts gracefully
Persistent stores SQLite, PostgreSQL, Redis — with full audit trails
Framework integrations LangChain, LlamaIndex, FastAPI, Flask, OpenAI Assistants
Production resilience Retry with backoff, circuit breakers, health checks
Pluggable dispatchers Celery, Redis Queue — survives server restarts
GDPR-ready One-call clear_session() with auditable deletion receipts
Observability OpenTelemetry traces and metrics — built-in, optional

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[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

MIT License. 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.1.0.tar.gz (310.9 kB view details)

Uploaded Source

Built Distribution

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

beliefstate-1.1.0-py3-none-any.whl (89.2 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for beliefstate-1.1.0.tar.gz
Algorithm Hash digest
SHA256 77432897f60e3d9bbf9a34f295a9b3c402d2cf016868f954f95668e479f95c17
MD5 fef488fbe756914698217c89c79ae8dc
BLAKE2b-256 a3d3acc3a3bd4042b1f0f8e373866b29d3a8a028a27990eab14adc2384d52a6a

See more details on using hashes here.

Provenance

The following attestation bundles were made for beliefstate-1.1.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.1.0-py3-none-any.whl.

File metadata

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

File hashes

Hashes for beliefstate-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 645d9def2dca8c33585eecc2e35b11fcae15a1ff35fc52d526eefb50db0c2eaa
MD5 ea23e38d9d56eb09aa372d9ea3d14e67
BLAKE2b-256 c1057ba0238e4f710d84721a15db28552efe9506ed9062310cd9a2a3b3d30b43

See more details on using hashes here.

Provenance

The following attestation bundles were made for beliefstate-1.1.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