Skip to Content
Recodocs

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.

9 min read

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

NameKindWhat it does
RagChatclassOne question per ask: retrieve, assemble prompt, cited answer, persist turn and receipts
retrievefunctionEmbed the question, query the index, filter by minimum_score, build ScoredPassage rows
ChatTurndataclassFrozen record of one completed ask (answer, citations, retrieval, budget, usage, prompt)
RetrievalReceiptdataclassCollection, k, hit counts, native scores, timing, prefilter flag
RecordedClientclassWraps FormattedTextClient and collects UsageReceipt per generation
resolve_score_transformfunctionMaps index score semantics to higher-is-better relevance for thresholding
identity_scorefunctionDefault transform when scores are already higher-is-better
embedding_identity_offunctionReads embedding_identity, identity, or model_identity from an embeddings object
verify_embedding_bindingfunctionChecks recorded integer width and compares a recorded identity with the explicit query identity or the adapter identity

recohut_kit.rag.prompt_budget

NameKindWhat it does
assemble_promptfunctionPack a rank prefix under context_limit_tokens, and raise ContextBudgetExceeded when the fixed prompt and bounded history do not fit
render_promptfunctionJSON wire text matching answer_from_passages input shape
ScoredPassagedataclassPassage plus relevance score for ordering
BudgetReceiptdataclassIncluded and excluded passage ids, token estimates, reserves
PromptAssemblydataclassPrompt, instructions, question, passages, and budget receipt
ContextBudgetExceededexceptionRaised before generation when instructions and history exceed the budget

recohut_kit.rag.corpus

NameKindWhat it does
index_postsfunctionChunk supplied posts, embed, upsert to a collection, retire stale chunk ids
CorpusReceiptdataclassCounts of posts, chunks, tokens, embedding identity, elapsed time

recohut_kit.rag.comparison

NameKindWhat it does
compare_contextsasync functionRun the chunked RAG and whole-post arms, and take one separate LLMGrader judgement for each arm that actually generates an answer
ComparisonArmdataclassOne arm’s answer, passage count, token fields, latency, groundedness, refused, and full_input_exceeded_limit
comparison_rowsfunctionTable rows for persistence without raw usage receipts

recohut_kit.rag.claims

NameKindWhat it does
draft_claimsfunctionStructured claim generation with bounded correction rounds over fixed passages
validate_claimsfunctionGates: passage supplied, verbatim quote, version agreement
ContractReportdataclassPer-claim verdicts; supported and rejected views
ClaimVerdictdataclassOne claim’s status and citation verdicts
CitationVerdictdataclassPer-citation gate outcomes
DraftedClaimsdataclassAnswer, generations, correction reasons, usage receipts
passage_digestfunctionSHA-256 of passage text for evidence snapshots
VersionOftype aliasCaller function mapping a passage to a product version or None
QuoteMatchtype alias"exact" or "whitespace" quote matching mode
Claim, ClaimCitation, ClaimedAnswerPydantic modelsLazy-loaded structured claim schema

recohut_kit.rag.entity_retrieval

NameKindWhat it does
EntityCoverageRetrieverclassPer-entity retrieval first, then BM25 fill, with coverage report. Entity results can exceed total_k.
EntityVocabularydataclassCaller-supplied entities with unique canonical names
EntitydataclassCanonical name, aliases, optional document-id filter
find_entitiesfunctionVocabulary entities mentioned in text, by first mention order
EntityCoveragedataclassEntity to passage ids plus uncovered entity names
EntityRetrievaldataclassHits, entities, coverage, per-entity id map
measure_coveragefunctionCoverage from a hit list and entity list
passages_from_hitsfunctionBuild Passage rows from retriever hit metadata

recohut_kit.rag.evidence_states

NameKindWhat it does
assessfunctionMap ContractReport and optional coverage to one of four evidence states
routefunctionApply RoutingPolicy to an assessment (clarify, answer, fallback, refuse)
EvidenceAssessmentdataclassState, reasons, claim counts, entities, missing facts
RoutingPolicydataclassApplication-owned answer, clarify, fallback, and refuse rules
DecisiondataclassChosen action, reason, optional clarify question or fallback plan
FallbackPlandataclassEntities to target on a fallback attempt

recohut_kit.rag.followup

NameKindWhat it does
resolve_followupfunctionOne structured call turning a follow-up into standalone query, entities, version hint
TurnEvidencedataclassImmutable snapshot of passage ids, digests, and versions for one turn
TurnEvidenceLedgerclassPersist and read turn evidence via the conversation store
require_fresh_citationsfunctionRe-mark claims citing passages outside the current turn snapshot
ScriptedResolverclassFormattedTextClient replaying fixed JSON for regression lanes
ResolvedQueryPydantic modelLazy-loaded resolution schema

recohut_kit.rag.fallback

NameKindWhat it does
acquirefunctionFetch at most max_pages allowlisted canonical pages for the normalised entities
FallbackSourcedataclassBase URL, host allowlist, entity to path map, optional version
FallbackAcquisitiondataclassTerms, pages, passages, unmapped and over-cap entity lists
normalize_fallback_termsfunctionKeep vocabulary canonical names; drop unrecognized free text
FallbackHostRefusedexceptionHost outside the explicit allowlist

recohut_kit.rag.cited_turn

NameKindWhat it does
CitedRagTurnclassRuns the full cited pipeline per ask with optional FallbackLane
CitedTurnResultdataclassStandalone query, entities, state, decision, claims, evidence, receipts
TurnPromptsdataclassInstructions and prompt versions for resolve and draft steps
FallbackLanedataclassFallback source, fetcher, output directory, page cap
SupportedClaimdataclassSupported claim text, version, citations

recohut_kit.rag.redis_runtime and recohut_kit.rag.local_site

NameKindWhat it does
docker_availablefunctionRead-only check that the Docker daemon responds
OwnedRedisclassStart and remove one disposable Redis Stack container with generated password
StaticSiteclassLoopback 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.

ModuleKit dependencies (from imports)
chatconversations.sqlite_store, json, knowledge, knowledge_answering, providers.contracts, providers.structured, usage, vectors.contracts, rag.prompt_budget
prompt_budgetgoverned_retrieval, knowledge
corpusdocuments.chunking.contracts, knowledge, vectors.contracts, rag.chat (embedding_identity_of)
comparisondocuments.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_retrievalknowledge, retrieval_sparse, vectors.contracts
evidence_statesrag.claims, rag.entity_retrieval
followup_lazy_build, conversations.sqlite_store, evals.codec, json, knowledge, providers.contracts, providers.structured, usage, rag.claims; optional pydantic
fallbackdocuments.html, documents.web_snapshot, knowledge, rag.entity_retrieval
cited_turnconversations.sqlite_store, documents.web_snapshot, json, knowledge, providers.structured, usage, and internal rag.claims, entity_retrieval, evidence_states, fallback, followup
redis_runtimejson, local_containers
local_sitehttp_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. RagChat admits a fresh run per call. CitedRagTurn includes 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_identity first 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; otherwise resolve_score_transform raises ValueError.
  • Retrieval metadata. Hits must carry nonempty text metadata (vector lane) or document_id and text (sparse lane). index_posts needs the backend to honour post_id metadata filters for stale chunk deletion.
  • Prompt budget. RagChat uses assemble_prompt to omit overflow passages and record BudgetCut receipts. Fixed instructions plus bounded history that exceed the budget raise ContextBudgetExceeded. CitedRagTurn passes retrieved passages into its draft step without this token budget. Set retrieval bounds at the host. total_k limits BM25 fill and preserves per-entity hits.
  • Claim gates. validate_claims checks passage membership, verbatim quote (optional whitespace folding), and version agreement via caller-owned version_of. version_unstated does not trigger draft_claims correction loops.
  • Fresh citations only. require_fresh_citations marks supported claims stale_citation when they cite passages outside the current TurnEvidence snapshot or when digests differ.
  • Fallback is bounded and allowlisted. acquire refuses hosts outside FallbackSource.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_configured is true, CitedRagTurn requires a FallbackLane; otherwise construction raises.
  • Optional extras. Pydantic loads lazily for claim and follow-up models. Comparison’s semantic judgements use LLMGrader from recohut_kit.evals.judge.
  • Local fixtures. OwnedRedis.start starts an owned Redis container when Docker is already available; StaticSite binds 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