Bounded retrieve-assemble-answer workflows with citation contracts and evidence routing
Explicit RAG composition where applications own sources, prompts, token budgets, and routing policy, with deterministic retrieval, claim gates, and persisted conversation runs.
recohut_kit.rag is the kit’s bounded retrieval-augmented generation layer. Applications supply vector indexes, embeddings, sparse retrievers, prompts, context limits, entity vocabularies, and routing policy. The package wires retrieve-and-assemble steps, checks citations against supplied passages, grades evidence into discrete states, and persists turns through the conversation store. The package root is a marker only: import the submodules you need; nothing is re-exported from recohut_kit.rag itself.
Two lanes dominate the design. recohut_kit.rag.chat is a deterministic assistant workflow with one retrieval pass, prompt budgeting, and a single cited answer per question—not an autonomous tool loop. recohut_kit.rag.cited_turn runs a fixed multi-step cited-answer pipeline (resolve follow-up, entity-coverage retrieval, draft and validate claims, freshness check, assess, route, optional bounded fallback) where the model appears only at named structured-generation steps; no step chooses the next step. Supporting modules also index corpora, compare RAG with whole-post stuffing, pack prompts under token ceilings, fetch allowlisted fallback pages, start one disposable Redis Stack container, and serve local static fixtures on loopback.
Purpose
Retrieval finds candidate evidence, then the application assembles material for a model call. The package does not decide by itself whether an answer is true; the caller provides the relevant data and bounded contracts.
The layer owns explicit composition for RAG: vector retrieval with score transforms and embedding-identity checks, rank-ordered prompt assembly under declared context limits, structured claim drafting with three deterministic citation gates, per-turn evidence snapshots, entity-first sparse retrieval, evidence-state assessment, and caller-owned routing including optional official-source fallback. It persists runs and receipts in ConversationStore and refuses to infer tenant policy from similarity scores or conversation text.
Callers pass a Chunker; fallback does not crawl or follow links; CitedRagTurn is not an agent; release-gate compare lives in recohut_kit.evals, which this package does not implement. It does not load embedding models or discover Redis servers you did not start. Quote membership in claims is not semantic entailment.
Public API
Import paths follow recohut_kit.rag.<module>. Install the knowledge-answering extra for RagChat.ask, comparison, draft_claims, resolve_followup, and the Pydantic schemas those workflows use.
recohut_kit.rag.chat
| Name | Kind | What it does |
|---|---|---|
RagChat | class | One question per ask: retrieve, assemble prompt, cited answer, persist turn and receipts |
retrieve | function | Embed the question, query the index, filter by minimum_score, build ScoredPassage rows |
ChatTurn | dataclass | Frozen record of one completed ask (answer, citations, retrieval, budget, usage, prompt) |
RetrievalReceipt | dataclass | Collection, k, hit counts, native scores, timing, prefilter flag |
RecordedClient | class | Wraps FormattedTextClient and collects UsageReceipt per generation |
resolve_score_transform | function | Maps index score semantics to higher-is-better relevance for thresholding |
identity_score | function | Default transform when scores are already higher-is-better |
embedding_identity_of | function | Reads embedding_identity, identity, or model_identity from an embeddings object |
verify_embedding_binding | function | Checks recorded integer width and compares a recorded identity with the explicit query identity or the adapter identity |
recohut_kit.rag.prompt_budget
| Name | Kind | What it does |
|---|---|---|
assemble_prompt | function | Pack a rank prefix under context_limit_tokens, and raise ContextBudgetExceeded when the fixed prompt and bounded history do not fit |
render_prompt | function | JSON wire text matching answer_from_passages input shape |
ScoredPassage | dataclass | Passage plus relevance score for ordering |
BudgetReceipt | dataclass | Included and excluded passage ids, token estimates, reserves |
PromptAssembly | dataclass | Prompt, instructions, question, passages, and budget receipt |
ContextBudgetExceeded | exception | Raised before generation when instructions and history exceed the budget |
recohut_kit.rag.corpus
| Name | Kind | What it does |
|---|---|---|
index_posts | function | Chunk supplied posts, embed, upsert to a collection, retire stale chunk ids |
CorpusReceipt | dataclass | Counts of posts, chunks, tokens, embedding identity, elapsed time |
recohut_kit.rag.comparison
| Name | Kind | What it does |
|---|---|---|
compare_contexts | async function | Run the chunked RAG and whole-post arms, and take one separate LLMGrader judgement for each arm that actually generates an answer |
ComparisonArm | dataclass | One arm’s answer, passage count, token fields, latency, groundedness, refused, and full_input_exceeded_limit |
comparison_rows | function | Table rows for persistence without raw usage receipts |
recohut_kit.rag.claims
| Name | Kind | What it does |
|---|---|---|
draft_claims | function | Structured claim generation with bounded correction rounds over fixed passages |
validate_claims | function | Gates: passage supplied, verbatim quote, version agreement |
ContractReport | dataclass | Per-claim verdicts; supported and rejected views |
ClaimVerdict | dataclass | One claim’s status and citation verdicts |
CitationVerdict | dataclass | Per-citation gate outcomes |
DraftedClaims | dataclass | Answer, generations, correction reasons, usage receipts |
passage_digest | function | SHA-256 of passage text for evidence snapshots |
VersionOf | type alias | Caller function mapping a passage to a product version or None |
QuoteMatch | type alias | "exact" or "whitespace" quote matching mode |
Claim, ClaimCitation, ClaimedAnswer | Pydantic models | Lazy-loaded structured claim schema |
recohut_kit.rag.entity_retrieval
| Name | Kind | What it does |
|---|---|---|
EntityCoverageRetriever | class | Per-entity retrieval first, then BM25 fill, with coverage report. Entity results can exceed total_k. |
EntityVocabulary | dataclass | Caller-supplied entities with unique canonical names |
Entity | dataclass | Canonical name, aliases, optional document-id filter |
find_entities | function | Vocabulary entities mentioned in text, by first mention order |
EntityCoverage | dataclass | Entity to passage ids plus uncovered entity names |
EntityRetrieval | dataclass | Hits, entities, coverage, per-entity id map |
measure_coverage | function | Coverage from a hit list and entity list |
passages_from_hits | function | Build Passage rows from retriever hit metadata |
recohut_kit.rag.evidence_states
| Name | Kind | What it does |
|---|---|---|
assess | function | Map ContractReport and optional coverage to one of four evidence states |
route | function | Apply RoutingPolicy to an assessment (clarify, answer, fallback, refuse) |
EvidenceAssessment | dataclass | State, reasons, claim counts, entities, missing facts |
RoutingPolicy | dataclass | Application-owned answer, clarify, fallback, and refuse rules |
Decision | dataclass | Chosen action, reason, optional clarify question or fallback plan |
FallbackPlan | dataclass | Entities to target on a fallback attempt |
recohut_kit.rag.followup
| Name | Kind | What it does |
|---|---|---|
resolve_followup | function | One structured call turning a follow-up into standalone query, entities, version hint |
TurnEvidence | dataclass | Immutable snapshot of passage ids, digests, and versions for one turn |
TurnEvidenceLedger | class | Persist and read turn evidence via the conversation store |
require_fresh_citations | function | Re-mark claims citing passages outside the current turn snapshot |
ScriptedResolver | class | FormattedTextClient replaying fixed JSON for regression lanes |
ResolvedQuery | Pydantic model | Lazy-loaded resolution schema |
recohut_kit.rag.fallback
| Name | Kind | What it does |
|---|---|---|
acquire | function | Fetch at most max_pages allowlisted canonical pages for the normalised entities |
FallbackSource | dataclass | Base URL, host allowlist, entity to path map, optional version |
FallbackAcquisition | dataclass | Terms, pages, passages, unmapped and over-cap entity lists |
normalize_fallback_terms | function | Keep vocabulary canonical names; drop unrecognized free text |
FallbackHostRefused | exception | Host outside the explicit allowlist |
recohut_kit.rag.cited_turn
| Name | Kind | What it does |
|---|---|---|
CitedRagTurn | class | Runs the full cited pipeline per ask with optional FallbackLane |
CitedTurnResult | dataclass | Standalone query, entities, state, decision, claims, evidence, receipts |
TurnPrompts | dataclass | Instructions and prompt versions for resolve and draft steps |
FallbackLane | dataclass | Fallback source, fetcher, output directory, page cap |
SupportedClaim | dataclass | Supported claim text, version, citations |
recohut_kit.rag.redis_runtime and recohut_kit.rag.local_site
| Name | Kind | What it does |
|---|---|---|
docker_available | function | Read-only check that the Docker daemon responds |
OwnedRedis | class | Start and remove one disposable Redis Stack container with generated password |
StaticSite | class | Loopback http.server for local static fixtures |
How it composes
Modules import other kit packages explicitly; nothing is hidden behind the recohut_kit.rag package root.
| Module | Kit dependencies (from imports) |
|---|---|
chat | conversations.sqlite_store, json, knowledge, knowledge_answering, providers.contracts, providers.structured, usage, vectors.contracts, rag.prompt_budget |
prompt_budget | governed_retrieval, knowledge |
corpus | documents.chunking.contracts, knowledge, vectors.contracts, rag.chat (embedding_identity_of) |
comparison | documents.chunking.answering, evals.judge, json, knowledge, knowledge_answering, providers.structured, usage, rag.chat, rag.prompt_budget |
claims | _lazy_build, knowledge, providers.contracts, providers.structured, usage; optional pydantic |
entity_retrieval | knowledge, retrieval_sparse, vectors.contracts |
evidence_states | rag.claims, rag.entity_retrieval |
followup | _lazy_build, conversations.sqlite_store, evals.codec, json, knowledge, providers.contracts, providers.structured, usage, rag.claims; optional pydantic |
fallback | documents.html, documents.web_snapshot, knowledge, rag.entity_retrieval |
cited_turn | conversations.sqlite_store, documents.web_snapshot, json, knowledge, providers.structured, usage, and internal rag.claims, entity_retrieval, evidence_states, fallback, followup |
redis_runtime | json, local_containers |
local_site | http_deadline |
Internal recohut_kit.rag.* imports tie the cited-turn lane together; chat and comparison share prompt_budget, and corpus reuses embedding identity helpers from chat.
Minimal usage example
Install uv pip install '.[knowledge-answering,connectors]' from your Kit checkout. The follow-up helper loads the Kit evaluation and connector modules, which require HTTPX. A scripted response proposes two claims. The example verifies an exact quote, rejects the second citation, and applies the default routing policy.
import json
from recohut_kit.knowledge import Passage
from recohut_kit.rag.claims import draft_claims, validate_claims
from recohut_kit.rag.evidence_states import RoutingPolicy, assess, route
from recohut_kit.rag.followup import ScriptedResolver
passage = Passage("p1", "returns-policy-v1", "returns-policy-v1", "c1", 1,
"Returns are accepted within 30 days.")
reply = json.dumps({
"claims": [
{
"text": "The return window is 30 days.",
"applies_to_version": "v1",
"citations": [{"passage_id": "p1", "quote": passage.text, "version": "v1"}],
},
{
"text": "The return window is 60 days.",
"applies_to_version": "v1",
"citations": [{"passage_id": "p1", "quote": "within 60 days", "version": "v1"}],
},
],
"proposed_state": "supported",
"clarifying_question": None,
})
def version_of(source: Passage) -> str:
return source.document_id.rsplit("-", 1)[-1]
draft = draft_claims(
ScriptedResolver([reply]), (passage,), "What is the return window?",
instructions="Cite the policy.", prompt_version="returns-v1",
)
report = validate_claims(draft.answer, (passage,), version_of=version_of)
assert [item.status for item in report.verdicts] == ["supported", "quote_mismatch"]
assessment = assess(report, coverage=None, required_version="v1")
assert assessment.state == "partial"
assert route(assessment, RoutingPolicy()).action == "refuse"Limits and gotchas
- Package root exports nothing. Import
recohut_kit.rag.chat,recohut_kit.rag.claims, and the other modules directly. - Run outcomes.
RagChatadmits a fresh run per call.CitedRagTurnincludes rejected and stale claims in the evidence assessment and persists its routed answer, clarification, or refusal as a completed run. Exceptions during turn processing mark the run failed and propagate. Errors writing the initial user message or the final run result propagate from storage. - Embedding identity. A recorded integer width is checked against the query vector width. Identity checks use explicit
embedding_identityfirst and fall back to the adapter identity. The comparison requires identity metadata on both sides. - Score direction. Non-cosine lower-is-better indexes require an explicit
score_transform; otherwiseresolve_score_transformraisesValueError. - Retrieval metadata. Hits must carry nonempty
textmetadata (vector lane) ordocument_idandtext(sparse lane).index_postsneeds the backend to honourpost_idmetadata filters for stale chunk deletion. - Prompt budget.
RagChatusesassemble_promptto omit overflow passages and recordBudgetCutreceipts. Fixed instructions plus bounded history that exceed the budget raiseContextBudgetExceeded.CitedRagTurnpasses retrieved passages into its draft step without this token budget. Set retrieval bounds at the host.total_klimits BM25 fill and preserves per-entity hits. - Claim gates.
validate_claimschecks passage membership, verbatim quote (optional whitespace folding), and version agreement via caller-ownedversion_of.version_unstateddoes not triggerdraft_claimscorrection loops. - Fresh citations only.
require_fresh_citationsmarks supported claimsstale_citationwhen they cite passages outside the currentTurnEvidencesnapshot or when digests differ. - Fallback is bounded and allowlisted.
acquirerefuses hosts outsideFallbackSource.allowed_hosts, caps pages per acquisition, and uses explicit page URLs. The fetcher’s allowlist must be a subset of the source’s. Use trusted DNS for the allowed hosts, including redirect targets. - Policy wiring. If
RoutingPolicy.fallback_configuredis true,CitedRagTurnrequires aFallbackLane; otherwise construction raises. - Optional extras. Pydantic loads lazily for claim and follow-up models. Comparison’s semantic judgements use
LLMGraderfromrecohut_kit.evals.judge. - Local fixtures.
OwnedRedis.startstarts an owned Redis container when Docker is already available;StaticSitebinds an ephemeral loopback port at construction.
Verification
The example checks citation verdicts and routing with a scripted response. See Verify the examples.
How is this page?
Last updated on