Pages
Reference Sections

Reference

API Reference & Changelog

Complete structural specifications of public elements, models, and exception cases, along with release cycle updates.


API Reference

Complete public API for the BeliefTracker class and related models.

BeliefTracker

The orchestrator class managing session environments, adapter normalizations, and persistence routing.

__init__.py
def BeliefTracker( config: TrackerConfig, adapter: ProviderAdapter, internal_adapter: Optional[ProviderAdapter] = None, dispatcher: Optional[Dispatcher] = None, judge: Optional[LLMJudge] = None, store: Optional[Store] = None, detector: Optional[BeliefDetector] = None, resolver: Optional[BeliefResolver] = None )

Methods

Method Signature Returns Description
wrap @tracker.wrap (decorator) Callable Wraps async or sync LLM function
set_session set_session(session_id: str) None Sets active session via ContextVar
set_conversation set_conversation(id: str) None Sets conversation within session
get_context_prompt get_context_prompt(session_id, conversation_id, current_user_message) async str Returns formatted belief summary
track_async track_async(call, response, session_id, turn) async None Manual async tracking
track_sync track_sync(call, response, session_id, turn) None Manual sync tracking
clear_session clear_session(session_id) async DeletionReceipt GDPR deletion
get_beliefs get_beliefs(session_id, conversation_id=None, category=None, belief_type=None) async list[Belief] Query stored beliefs with optional filters.
health_check health_check() async dict {"store": bool, "adapter": bool}

Belief

The core data representation of an extracted user/assistant belief. Persisted as a Pydantic model.

Field Type Default Description
subject str required Who or what the belief is about (normalized to USER or ASSISTANT).
predicate str required The relationship or attribute (e.g., 'lives in', 'likes').
value str required The normalized value of the claim.
confidence float required Confidence score from 0.0 to 1.0.
turn int required The conversation turn index when this was extracted.
source str required Who made the claim: 'user' or 'assistant'.
belief_type str "assertion" The type of belief: 'assertion' or 'update'.
is_hypothetical bool False Speculative claims, excluded from prompt context.
embedding Optional[list[float]] None Vector embedding of the fact text.
embedding_model Optional[str] None Model used to generate the embedding.
embedding_dim Optional[int] None Dimension count of the embedding vector.
session_id str required Owner session ID.
conversation_id Optional[str] None Owner conversation thread ID.
created_at datetime auto UTC timestamp when created.
last_referenced_at Optional[datetime] None UTC timestamp of last prompt injection.
category str "general" Domain category (e.g., 'preference', 'fact', 'context').
source_quote str "" Original text snippet (max 100 chars) that triggered extraction.

TrackerConfig

Full reference on the Configuration page.

View TrackerConfig →

DeletionReceipt

Returned by session clear execution scopes to serve as audit receipts.

Field Type Default Description
session_id str required The identifier of the cleared session.
beliefs_deleted int required Count of belief records deleted.
in_flight_tasks_drained int 0 Count of background tasks cancelled during shutdown.
deleted_at datetime required UTC timestamp of the deletion completion.

TrackerStats

Runtime statistics tracker built into BeliefTracker. Exposes counters and a rolling success rate window.

Field Type Description
total_turns_processed int Total number of conversation turns processed.
total_beliefs_extracted int Total belief triples extracted across all turns.
total_contradictions_detected int Total contradictions detected.
total_duplicates_skipped int Total exact/entailed duplicates skipped during deduplication.
extraction_errors int Total extraction errors encountered.
last_error str Message from the most recent error.
last_successful_extraction Optional[datetime] UTC timestamp of last successful extraction.
extraction_success_rate float Rolling success rate (last 100 turns). Returns 1.0 when empty.
stats_usage.py
stats = tracker.get_stats() print(stats.total_beliefs_extracted) print(stats.extraction_success_rate) # rolling 100-turn window

Outcome & DetectionResult

Detection outcomes for each belief after running through the contradiction detector and deduplication pipeline.

Outcome

Value Description
Outcome.NEW Belief is novel — no existing match found. Proceeds to store.
Outcome.DUPLICATE Belief is an exact or entailed duplicate of an existing belief.
Outcome.CONTRADICTION Belief contradicts an existing belief (NLI score above threshold).

DetectionResult

Field Type Description
belief Belief The new belief that was evaluated.
outcome Outcome Result of the detection: NEW, DUPLICATE, or CONTRADICTION.
matched_belief Optional[Belief] The existing belief that matched, if any.
score float Similarity or NLI score for the match.
reason str Human-readable explanation of the detection result.

Utility Functions

Public utility functions exported from the beliefstate package.

calibrate_confidence(belief)

Post-extraction confidence calibration. Scans the belief's source_quote for hedging patterns (e.g., "might", "perhaps", "not sure") and lowers the confidence score to a pattern-specific ceiling. Sets is_hypothetical=True for strong hedging (ceiling ≤ 0.60).

calibrate.py
from beliefstate import calibrate_confidence # After extraction, calibrate based on hedging patterns belief = calibrate_confidence(belief) # If source_quote contains "might" → confidence capped at 0.60 # If source_quote contains "not sure" → confidence capped at 0.50, is_hypothetical=True

normalize_value(value)

NFKC-normalizes a belief value for exact-match deduplication comparison. Lowercases, strips punctuation, and collapses whitespace. Used by the detector's O(1) exact duplicate check.

normalize.py
from beliefstate import normalize_value normalize_value("New York, NY") # → "new york ny" normalize_value("$5,000") # → "5000" normalize_value(" Hello World ") # → "hello world"

summary_for_prompt(beliefs, max_beliefs=50, max_speculative_beliefs=5)

Formats a list of beliefs into a compact, category-grouped summary string suitable for injection into LLM system prompts. Speculative beliefs (is_hypothetical=True) are grouped separately and capped at max_speculative_beliefs.

summary.py
from beliefstate.store.base import summary_for_prompt text = summary_for_prompt(beliefs, max_beliefs=30) # Output: # Known facts about USER: # - preference: likes vegetarian food (confidence 0.95) # - fact: lives in Seattle (confidence 0.90) # # Speculative (unconfirmed): # - planning: considering a move (confidence 0.40)

Exceptions

Common pipeline exceptions raised during verification and execution blocks.

Exception When Raised
CircuitBreakerOpenException Circuit breaker is OPEN
TransientError Retryable error (network timeout, rate limit)
PermanentError Non-retryable error (auth failure, invalid request)

ProviderAdapter Protocol

Defines the expected interface signature for normalizations and vendor integrations.

adapter_protocol.py
class ProviderAdapter(Protocol): def to_llm_call(self, *args, **kwargs) -> LLMCall: ... def to_llm_response(self, response) -> LLMResponse: ... async def generate(self, call, response_format) -> LLMResponse: ... async def get_embedding(self, text) -> list[float]: ... async def get_embeddings(self, texts) -> list[list[float]]: ... async def health_check(self) -> bool: ...
Note

Implement this protocol to add support for any custom LLM provider or internal gateway.


Changelog

All notable changes. Follows semantic versioning.

v1.1.0 2026-06-26 Minor

v1.1.0 — Current

Added
  • Open-source community files: CONTRIBUTING.md, CODE_OF_CONDUCT.md, SECURITY.md
  • GitHub issue templates, PR template, CODEOWNERS, Dependabot
  • Pre-commit hooks (ruff + mypy) and .editorconfig
  • CHANGELOG.md with Keep a Changelog format
  • Dynamic CI/lint badges in README
  • Codecov integration in CI workflow
Changed
  • Split CI and lint workflows for faster feedback
  • Hardened store backends: lowercase normalization, conversation_id in field keys
  • Pin third-party GitHub Actions to specific versions
  • pyproject.toml: added keywords, fixed Documentation URL
Fixed
  • LlamaIndex callback handler test (mock import ordering)
  • Unused mypy type: ignore comments in integrations
  • FastAPI get_session_id guarded behind HAS_FASTAPI import check
  • PostgreSQL get_by_key/remove_belief lowercase normalization
  • Redis/Memory store field key includes conversation_id
v1.0.2 2026-06-25 Patch

v1.0.2

Fixed
  • SQLite connection leak on high-concurrency workloads
  • Redis embedding precision loss on float32 round-trip
  • summary_for_prompt() not enforcing max_beliefs cap
v1.0.1 2026-04-12 Patch

v1.0.1

Fixed
  • Belief model migrated from @dataclass to Pydantic BaseModel
  • NLI model predict() now runs in run_in_executor (non-blocking)
  • SQLite persistent connection via open()/close() pattern
  • resolve() UPDATE strategy now receives store parameter
v1.0.0 2026-01-15 Major

v1.0.0 — Initial release

Added
  • BeliefTracker with @tracker.wrap decorator
  • OpenAI, Anthropic, Gemini, Ollama, LiteLLM adapters
  • SQLite and Redis store backends
  • Two-stage contradiction detection (cosine + NLI)
  • WARN / ASK / BLOCK / UPDATE resolution strategies
  • FastAPI, Flask, ASGI middleware
  • LangChain and LlamaIndex callbacks
  • OpenAI Assistants observer
  • Celery and RQ dispatcher support
  • OpenTelemetry instrumentation
  • GDPR clear_session() with DeletionReceipt
  • Circuit breaker and exponential backoff resilience