Context and memory
The layer that retrieves, grounds and remembers: vector indexes, rank fusion, knowledge stores, reply grounding and per-user memory.
Imagine an assistant answering how much a supplier is owed. It must find the right records, retain the required facts between turns and make the answer traceable to the evidence it actually read. This layer builds that working material and checks the answer against it. Its four jobs are retrieval, grounding, cross-session memory and source storage with exact citations. All four are deterministic; the caller supplies a model to draft the text. For the underlying ideas, see context engineering.
The layer ends where the model call starts and where the data platform starts. Prompt assembly and provider caching sit in Model route. Pipelines that build and publish the data a store holds sit in Data platform. Run-level state for a harness sits in Harness state.
Bounded context
A context budget is a limit for one model call, not a measure of which facts are true. Spend it on the task's relevant evidence and constraints first.
The PydanticAI extension can shorten earlier turns and replace older tool payloads with evidence references. The host chooses what stays visible and checks access before serving additional detail. An application that sends data through a Kit disclosure gate can also inspect the proposed payload and record the decision at that boundary.
Owners
The layer has four sub-roles and one core owner for each. They answer different questions in one turn: what to retrieve, whether the reply is grounded, what the system remembers about this user, and where the source documents live.
| Sub-role | Core owner | Import path | Tier | What it is for |
|---|---|---|---|---|
| Retrieval | Vector indexes | recohut_kit.vectors | core | One VectorIndex contract with an exact SQLite store and adapters for pgvector, Qdrant, Weaviate, Pinecone, Redis Search, Chroma, OpenSearch and S3 Vectors |
| Retrieval | Rank fusion | recohut_kit.retrieval | core (module) | reciprocal_rank_fusion, recall_at_k, reciprocal_rank over identifiers |
| Grounding | Reply grounding | recohut_kit.grounding | core | Per-turn registry of observed records, enum-bound reply schema, host validation of stated values, receipts |
| Memory | User context | recohut_kit.user_context | core | Per-user facts with provenance, consent, decay and an audit row per change; token-budgeted turn packs |
| Knowledge store | Knowledge base | recohut_kit.knowledge | core (module) | SQLiteKnowledgeBase with FTS5 BM25 search, source and version binding, authority dates, exact-quote cite() |
The supported and catalog packages extend these owners. Only the owners above are the starting point for a new build.
| Package | Import path | Tier | What it is for |
|---|---|---|---|
| Evidence wiki | recohut_kit.evidence_wiki | supported | Compiled policy wiki over hashed paragraphs, a typed evidence graph, claim verification, locate and expand tools, refresh plans and grading |
| Advanced retrieval | recohut_kit.retrieval_advanced | catalog | Weighted fusion, query expansion and decomposition, maximal marginal relevance, span compression, failure diagnosis |
| Sparse and fused retrieval | recohut_kit.retrieval_sparse | catalog | One text-query contract over FTS5, exact vectors and rank fusion |
| Governed retrieval | recohut_kit.governed_retrieval | catalog | GovernedHybridRetriever with RetrievalLimits, stage observations and a budget cut record |
| RAG workflow | recohut_kit.rag | catalog | Retrieve, assemble and answer chat with three citation gates (passage supplied, verbatim quote, version agreement) |
| Knowledge partitions | recohut_kit.knowledge_partitions | catalog | Owner, client and shared partitions in SQLite; role policy resolved before search; audit rows |
| Knowledge assistant | recohut_kit.knowledge_assistant | catalog | Support Q&A contracts: index snapshots, cited answer or escalation |
| Organizational memory | recohut_kit.organizational | catalog | Bounded, sanitised reads of files, Git and GitHub, with retention and content-addressed lifecycle |
| Semantic backend | recohut_kit.semantic_backend | catalog | Read-only query contract for semantic stores |
| Context graph | recohut_kit.context_graph | catalog | Governed graph memory contracts with tenant-first queries; needs a graph store |
| Graph contracts | recohut_kit.graphs, recohut_kit.graphrag, recohut_kit.graph_plans | catalog | Knowledge-graph statements, GraphRAG contracts, closed intent plans |
| Truth maintenance | recohut_kit.truth_maintenance, recohut_kit.decision_chains | catalog | Rule closure with support ids; per-subject decision history with validity windows |
| Context platform | recohut_kit.context_platform | catalog | Event-time session state and decision bundles |
| Multimodal | recohut_kit.multimodal | catalog | Embedding-space identity and compression experiments, edge memory |
| Prompt ledger | recohut_kit.prompting | catalog | Attributes each visible prompt entry to its author and token count; admits or evicts entries |
Vendor bindings for Neo4j, Stardog, LangChain and LangGraph memory live under recohut_kit.integrations. Browse the full set in Packages.
How the pieces fit
A turn flows through the owners in a fixed order. Retrieval produces ranked candidates, memory adds consented facts, the model drafts against the observed records, and the grounding gate decides whether the draft may be shown.
The owners do not call each other. The host wires them: it runs both retrieval lanes, filters by permission, fuses ranks, builds the pack and passes the observed records to the grounding gate. No test or notebook composes all four owners in one turn, so treat the wiring in your application as your own integration point.
Worked examples
The examples below run against the core owners with the standard library plus the kit. They use temporary files and in-memory databases.
Index vectors and fuse two lanes
SQLiteVectorIndex takes a caller-owned sqlite3 connection. Scores are exact cosine similarity, higher is closer. upsert stays uncommitted until you commit.
import sqlite3
from recohut_kit.retrieval import reciprocal_rank_fusion, recall_at_k, reciprocal_rank
from recohut_kit.vectors.contracts import VectorRecord
from recohut_kit.vectors.sqlite import SQLiteVectorIndex
connection = sqlite3.connect(":memory:")
index = SQLiteVectorIndex(connection)
index.create_collection("docs", dimensions=3)
index.upsert(
"docs",
[
VectorRecord("a", (1.0, 0.0, 0.0), {"team": "hr"}),
VectorRecord("b", (0.0, 1.0, 0.0), {"team": "it"}),
VectorRecord("c", (0.9, 0.1, 0.0), {"team": "hr"}),
],
)
connection.commit()
# Metadata filters are a mapping of top-level key to a JSON scalar.
hits = index.query("docs", (1.0, 0.0, 0.0), limit=2, metadata_filter={"team": "hr"})
print([(hit.identifier, round(hit.score, 3)) for hit in hits])
# [('a', 1.0), ('c', 0.994)]
fused = reciprocal_rank_fusion(
{"dense": [hit.identifier for hit in hits], "keyword": ["c", "a"]}
)
print([(item.identifier, item.ranks) for item in fused])
print(recall_at_k(["c", "a"], {"a"}, k=1)) # 0.0
print(reciprocal_rank(["c", "a"], {"a"})) # 0.5reciprocal_rank_fusion takes a mapping of lane name to an ordered list of identifiers and returns FusedRank items with a score and the rank in each lane. Equal scores keep first-seen order. It grants no access, so filter each lane by permission before you pass the lists in.
Store documents and cite an exact quote
SQLiteKnowledgeBase ingests a Document, searches it with BM25, and binds every passage to its source and a content version. cite checks that a quote appears in a retrieved passage and returns its source lines.
import tempfile
from pathlib import Path
from recohut_kit.knowledge import Document, SQLiteKnowledgeBase, cite
kb = SQLiteKnowledgeBase(Path(tempfile.mkdtemp()) / "kb.sqlite")
kb.ingest(
Document(
"leave-policy",
"hr/leave.txt",
"Employees receive 24 days of paid leave.\nUnused days carry over for 30 days.",
)
)
hits = kb.search("paid leave days", limit=3) # list of Passage, BM25 ranked
citation = cite(hits, hits[0].identifier, "24 days of paid leave")
print(citation.source, citation.first_line, citation.last_line)
# hr/leave.txt 1 1
try:
cite(hits, hits[0].identifier, "30 days of paid leave")
except ValueError as error:
print(error)
# The quotation was not found in its selected retrieved source.
print(kb.delete("leave-policy")) # 1 document removed
print(kb.search("paid leave")) # []Ingesting the same Document again is idempotent. Changing the text replaces the old passages and changes the version. Pass authority=Authority("authoritative", effective_from="2026-01-01") on a Document to record which source is current; choosing between sources stays application policy.
Remember facts with consent and a budget
UserContextStore keeps every revision of a fact with provenance and writes an audit row for each change. A fact is only eligible for a prompt if the user consented to the context use for its category.
import tempfile
from datetime import datetime, timedelta, timezone
from pathlib import Path
from recohut_kit.user_context import (
ByteEstimateTokenizer, CategoryRegistry, ConsentPolicy, ContextBudget, DecayPolicy,
ListNotes, TrustedView, UserContextStore, UserNote, UserRef, build_turn_pack,
recall_for_user,
)
now = datetime(2026, 10, 1, tzinfo=timezone.utc)
registry = CategoryRegistry({
"goals": DecayPolicy("goals-90d", expires_after=timedelta(days=90)),
"wellbeing": DecayPolicy("wellbeing-30d", expires_after=timedelta(days=30)),
})
store = UserContextStore(Path(tempfile.mkdtemp()) / "uc.sqlite", registry, now=lambda: now)
user = UserRef("tenant-1", "u1")
policy = ConsentPolicy(user).grant("goals", "store", "context").grant("wellbeing", "store", "context")
store.set_consent(policy, by="host", reason="setup")
goal = store.state(user, "goals", "primary", "run 10k", turn_ref="turn-1", by="host")
store.state(user, "wellbeing", "sleep", "short sleep", turn_ref="turn-2", by="host")
fixed = store.correct(goal, "run a half marathon", by="user:u1", reason="corrected")
print(fixed.cite()) # user_fact:goals/primary@2
store.withdraw(user, "wellbeing", by="user:u1", reason="withdrawn")
pack = build_turn_pack(
user, "half marathon plan", ContextBudget(500), store.consent(user),
facts=store.facts(user), tokenizer=ByteEstimateTokenizer(),
)
print([omission.label() for omission in pack.omissions])
# ['consent_withdrawn:wellbeing']
print(TrustedView(pack).render()) # untrusted-data envelope for the prompt
# Cross-user reads are refused before any source is read.
other = UserRef("tenant-1", "u2")
notes = ListNotes("notes", [UserNote("u1", "n1", "text", "coach")])
denial = recall_for_user(user, "email", [notes], subject=other)
print(type(denial).__name__, notes.reads) # UserScopeDenial 0With ContextBudget(12) the same call omits the goal fact with the label budget:user_fact:goals/primary@2. Nothing is truncated: an item that does not fit is listed as omitted, together with every later item. TrustedView.render() wraps the pack in an untrusted_user_context envelope and states that memory cannot grant permissions.
Gate a reply on observed values
ObservedSources records what the tools returned in this turn. ReplySchema.build produces a JSON schema where citations and fact refs are enums of the observed references. The host then validates what the model stated.
from recohut_kit.grounding import (
ObservedSources, ReplySchema, UngroundedReply, enforce_reply, render_reply, validate_reply,
)
observed = ObservedSources("turn-1")
observed.observe_result(
"leave.get", "call-1", "policy",
[{"id": "annual", "days": 24, "scope": "all-staff"}],
)
ref = observed.refs()[0] # 'policy:annual@1'
schema = ReplySchema.build(observed) # give schema.schema to the model call
# The model cites the value with a marker; the host fills in the real value.
good = {"text": f"You get [[fact:{ref}#days]] days.", "citations": [{"ref": ref}], "facts": []}
print(render_reply(good, observed).text) # You get 24 days.
# A stated value that differs from the observed value is refused.
bad = {
"text": "You get 30 days.",
"citations": [{"ref": ref}],
"facts": [{"ref": ref, "field": "days", "value_json": "30"}],
}
print(validate_reply(bad, observed).mismatches)
# (Mismatch(ref='policy:annual@1', field='days', claimed='30', observed='24', kind='value_differs'),)
try:
enforce_reply(bad, observed)
except UngroundedReply:
print("refused")validate_reply returns a verdict; enforce_reply raises UngroundedReply. Money compares in integer minor units, so a claimed amount_minor must equal the observed integer. grounding_receipt records counts only, including unmarked_literals, the digit-bearing tokens in prose that the host did not fill.
Choosing between owners
| Question | Use |
|---|---|
| Need dense similarity over embeddings | vectors with SQLiteVectorIndex locally, or the adapter for the store you already run |
| Need keyword search over documents with exact citations | knowledge.SQLiteKnowledgeBase |
| Need both lanes in one ranking | Query each, then retrieval.reciprocal_rank_fusion; for a ready-made fused retriever look at retrieval_sparse |
| Need to stop the model stating values the tools never returned | grounding |
| Need the model to quote a source verbatim | knowledge.cite for a quote; the rag workflow bundles three citation gates |
| Need long-lived facts per user | user_context |
| Need role-scoped partitions of business knowledge | knowledge_partitions on top of knowledge |
| Need a policy corpus with dated, scoped paragraphs | evidence_wiki |
| Need to diversify or compress retrieved text | retrieval_advanced |
Choose a vector adapter by where your data already lives. The index contract is the same for all of them, so you can start on SQLite and swap later. vectors.parity compares any VectorIndex with a brute-force reference and reports recall per query, so measure the swap before you make it.
| Adapter | Class | Install extra |
|---|---|---|
| SQLite (exact) | vectors.sqlite.SQLiteVectorIndex | none |
| PostgreSQL | vectors.pgvector.PgVectorIndex | pgvector |
| Qdrant | vectors.qdrant.QdrantIndex | qdrant |
| Weaviate | vectors.weaviate.WeaviateIndex | none listed |
| Pinecone | vectors.pinecone.PineconeIndex | pinecone |
| Redis Search | vectors.redis_search.RedisSearchIndex | redis |
| Chroma | vectors.chroma.ChromaIndex | chroma |
| OpenSearch | vectors.opensearch.OpenSearchIndex | opensearch |
| S3 Vectors | vectors.s3_vectors.S3VectorsIndex | s3-vectors |
Embeddings clients sit beside the indexes: vectors.embeddings_openai.OpenAIEmbeddings, vectors.embeddings_bedrock.BedrockEmbeddings and vectors.embeddings_sentence_transformers.SentenceTransformerEmbeddings. They follow the Embeddings protocol, embed(texts) returning a list of vectors. Embedding generation is separate from ranking.
Failure behaviour, limits and gotchas
- Score direction differs by adapter.
SQLiteVectorIndexreturns cosine similarity, higher is closer.PgVectorIndexreturns cosine distance, lower is closer. Each adapter declares ascore_semanticsattribute; read it withscore_semantics_of(index)fromvectors.contractsbefore you compare or threshold scores. Never compare scores across backends. - The SQLite index is exact and scans every row that passes the filter. It uses NumPy when importable and pure Python otherwise. Use an approximate backend for large collections.
- Vectors are validated. A wrong dimension, a non-finite value or a vector whose norm falls outside 1e-15 to 1e15 raises
ValueError. - Writes are the caller's transaction.
upsertanddeleteon the SQLite index are not committed until you callcommiton your connection. vectorsexports no names from its package root. Import from submodules such asvectors.sqliteandvectors.contracts.- Fusion does not authorize. Filter each lane by permission before fusing. Duplicate identifiers inside one lane raise
ValueError. citechecks membership, not meaning. It proves the quote is in the retrieved passage and returns its lines. It does not prove the passage supports your claim.- Markdown ingestion needs an optional parser.
media_type="text/markdown"usesmarkdown-it-py, which theknowledgeextra installs. Plain text does not. - Grounding is strict by design.
ObservedSourcesrefuses a second observation of the same record with different data (ObservationRefused). Hidden field names can be set per turn and are not citable at any depth. - Memory is data, not authority. A recalled note cannot grant a permission. Cross-user recall returns
UserScopeDenialand reads no source.CrossUserLeak,ConsentDeniedandContextOverfloware the typed refusals. - Packs list what they drop. Omissions are reported with a reason (
budget,consent_withdrawn:category), not silently truncated. - Domain wording in
grounding. The default reply instructions and some docstrings carry wording from the travel domain where the module was first used. The checks are generic; supply your own instruction text for other domains. - Import weight. The retrieval, knowledge, grounding and user-context owners import without loading any model or vendor SDK. Vendor SDKs load only when you construct a vendor adapter.
How is this page?
Last updated on