07.6 Conversational RAG
Every RAG pipeline so far in this module answers one question at a time: a user types a complete, self-contained query, the system retrieves, generates and cites. Real users don't talk that way. They say "and for contractors?", "what about the cheaper plan?", "no, I meant the EU addendum" — fragments that mean nothing without the turns before them. Conversational RAG is the set of engineering decisions that makes retrieval work across a multi-turn dialogue: rewriting each follow-up into a standalone query before it hits the index, deciding per turn whether retrieval is needed at all, carrying forward the documents and filters that are still relevant, deciding what retrieved context — and what history — goes into the next prompt, and storing all of it as session state your code owns. This lesson builds that layer: the condense step, the per-turn route decision, session state and stores, clarification and slot-filling, suggested follow-ups, and a complete docs_qa/conversation.py with tests you can run without a single API key.
What you'll learn
- Why multi-turn breaks the single-shot retrieval assumption, and the taxonomy of follow-up messages you must handle (pronouns, ellipsis, topic switches, corrections, references to earlier answers, meta-questions)
- The condense step: the prompt and schema that rewrites a follow-up into a standalone query, when to skip it, and every way it goes wrong
- How to decide per turn whether to retrieve, chat, clarify or answer from the conversation record — and what each route costs
- Carrying context forward: sticky filters and entities, re-using previous turns' retrieved chunks vs re-retrieving, and per-session retrieval caching
- What goes into turn N's context: history windows, retrieved chunks and their token cost, citation numbering across turns, cache-friendly layout, and history truncation for RAG
- Session design: the state schema, what to store per turn, store options from in-memory to Postgres, multi-user and tenant handling, and privacy/retention
- Clarification and slot-filling ("which product?"), disambiguation UX, and suggested follow-ups
- How to evaluate conversational RAG: multi-turn test sets, turn-level vs conversation-level metrics, and user simulators
- A complete, tested
docs_qa/conversation.py— session store, condense step and turn pipeline — that runs on the standard library with fakes
What you don't need
- API keys or running services. Every runnable sample is pure Python standard library with deterministic fakes; the hosted wiring is shown but labelled illustrative. Free local practice is covered where it exists.
- The internals of embeddings, vector indexes or rerankers — those are Module 06. This lesson consumes the
Retrievercontract (search(query, k, filters) -> list[Hit]) that 06.10 defined. - How to write grounding prompts or citations — 07.4 and 07.5 own those; this lesson decides what context reaches them.
- Provider API mechanics for conversation state — 03.2 owns
previous_response_id, the Conversations API, message threads andclient.chats; this lesson links to them and builds the layer above.
Setup
The runnable code in this lesson — docs_qa/conversation.py and its tests — uses only the Python standard library (3.11+) and runs anywhere, no keys and no services:
python3 conversation_demo.py # or: uv run python conversation_demo.pyIt plugs into the docs_qa package the module builds lesson by lesson. If you are working in that package (created in 07.1), the imports resolve against sibling modules: the retriever contract from 06.10, QueryPlan from 07.3, and grounded generation from 07.4. The hosted wiring in 7.4 needs the provider SDKs and Pydantic:
uv add openai anthropic google-genai pydantic python-dotenv
# or: pip install openai anthropic google-genai pydantic python-dotenvThese commands install the newest release of each package. The samples were checked against openai 3.x, anthropic 2.x, google-genai 2.x and pydantic 2.x (the versions in 07.1's Setup) as of November 2026; a newer major version may change names, so check the library's changelog if a call does not match.
Keys come from .env (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY) exactly as in 03.1. Nothing in Parts 1–6 and 8 requires them.
What you must be able to do after this lesson#
- Explain what changes when RAG meets a conversation
- Condense a follow-up question into a standalone query
- Decide when to retrieve on each turn
- Manage what history goes into the next turn
- Evaluate a conversational RAG system
Why this matters for an AI engineer#
Single-turn RAG demos fail the moment a real user has a follow-up. These are the moments in a real project where this lesson's machinery earns its keep:
| You'll hear... | You'll understand it after... |
|---|---|
| "The bot answered 'it' with the wrong document." | 1.2 The taxonomy of follow-up messages |
| "Follow-ups retrieve garbage — the query is just 'and for contractors?'." | 2.1 Why fragments retrieve badly |
| "We rewrite the question before searching." | 2.2 The condense call |
| "Sometimes the rewrite makes things worse." | 2.5 When condense goes wrong |
| "Do we really need an LLM call on every single message?" | 2.4 When to skip condensing |
| "It kept searching for 'thanks'." | 3.1 The route decision |
| "'Summarize what we discussed' shouldn't hit the index." | 3.2 Chit-chat, meta-questions and 'summarize this' |
| "The second question needs the same docs as the first." | 3.3 Fresh retrieval vs carrying context forward |
| "We're embedding the same query twice in one session." | 3.4 Retrieval caching per session |
| "The tenant filter got lost on turn 3." | 3.5 Filters that survive the conversation |
| "Resending last turn's chunks doubles the prompt cost." | 4.2 The token cost of carrying chunks forward |
| "Citation [3] means different things on different turns." | 4.3 Citation numbering across turns |
| "The prompt cache never hits in a chat." | 4.4 Cache-friendly layout |
| "Where do sessions live — memory, files, a database?" | 5.3 The session store |
| "The bot guessed which product I meant." | 6.1 Ask, don't guess |
| "How do we test a conversation, not just a question?" | Part 8: Evaluating conversational RAG |
Part 1: What changes when retrieval meets a conversation#
1.1 The single-turn assumption#
Everything in 07.1–07.5 implicitly assumes the user's message is a complete information need. That assumption is load-bearing: the query understanding stage (07.3) rewrites the query, retrieval fetches chunks for the query, the generator answers the query, and citations attach to the answer. A follow-up breaks the chain at the first link: "what about for contractors?" contains no topic, no document vocabulary and no way to know which policy "it" refers to. Embed that string and you get neighbours of conversational fragments, not of the parental-leave policy.
1.2 The taxonomy of follow-up messages#
Real follow-ups aren't one thing. Each kind needs a different response, and mistaking one for another is the root of most conversational-RAG bugs:
| Kind | Example | What it needs |
|---|---|---|
| Elliptical follow-up | "And for contractors?" after a parental-leave question | Condense into a standalone query ("parental leave for contractors"), then retrieve |
| Pronoun/reference | "Does it cover remote workers?" | Same — resolve "it" to the topic of the previous turn |
| Topic switch | "What about expenses?" | Fresh retrieval; do not carry forward the leave-policy chunks |
| Comparison/extension | "How does that compare to the old policy?" | Often needs two retrievals (new policy + old policy) or the previous turn's chunks plus new ones |
| User correction | "No, I meant the EU addendum, not the US one." | Update session state (the filter/entity), re-run the previous intent if needed |
| Clarification answer | Bot asked "which product?", user: "the Pro plan" | Fill the slot, resume the pending intent — no new topic |
| Reference to earlier answer | "Why did you say 26 weeks?" | Answerable from the conversation record or by re-retrieving the same chunk — a meta decision |
| Meta-question | "Summarize what we've covered." | Never touches the index; answered from session state |
| Chit-chat | "Thanks!" | No retrieval, minimal generation |
The first five all look like "questions" to a naive pipeline; the last four look like questions too but need completely different handling. Telling them apart is the condense step's job (Part 2) and the route decision's job (Part 3).
1.3 Anatomy of a conversational turn#
A single-shot RAG turn is query → retrieve → generate → cite. A conversational turn inserts three decisions around it:
flowchart TD
U["User message<br/>(raw text)"] --> C{"Condense:<br/>standalone query +<br/>route + slots?"}
C -->|"route = clarify"| CL["Ask one question.<br/>No retrieval."]
C -->|"route = chat / meta"| ANS["Answer from history<br/>or model knowledge.<br/>No retrieval."]
C -->|"route = retrieve"| P["QueryPlan:<br/>rewrite, expand,<br/>extract filters (07.3)"]
P --> R{"Retrieve?"}
R -->|"cache hit"| H["Session retrieval cache"]
R -->|"fresh"| RET["Retriever.search<br/>merged filters"]
RET --> CF["Carry forward:<br/>still-relevant hits<br/>from last turn"]
H --> CF
CF --> G["Generate with:<br/>session state + history<br/>+ retrieved chunks"]
ANS --> ST[("Session store:<br/>append turn record")]
CL --> ST
G --> ST
ST --> U2["Next user message"]
U2 -.->|"next turn"| CNotice what the diagram makes explicit: the model is only one box. Condensing, routing, caching, carry-forward, session storage and context assembly are all your code. The provider sees a stateless request every turn (03.2); everything that makes the conversation coherent lives in the session layer this lesson builds.
1.4 Three kinds of state#
Conflating these is the most common design error in conversational RAG. Each has a different owner, lifetime and failure mode:
| State | What it holds | Owner | Lifetime | Failure mode |
|---|---|---|---|---|
| Query state | The standalone rewrite of this turn's message, extracted filters, the route decision | Condense step + QueryPlan (07.3) |
One turn | Rewrite drift: the standalone query says something the user didn't |
| Retrieval state | Which chunks were fetched, their scores, which are "sticky" for follow-ups, the retrieval cache | This lesson (conversation.py) |
Session (with TTL) | Stale chunks: last turn's documents crowding out this turn's needs |
| Answer/history state | The transcript, previous answers, the rolling summary, session entities and sticky filters | Session store + 04.7's ConversationManager |
Session → long-term memory | History flooding the window; losing the filter that mattered |
The pipeline's job each turn is to read all three, update them, and assemble exactly the right slice into the next model call. The rest of this lesson takes each in turn.
Part 2: The condense step#
2.1 Why fragments retrieve badly#
Retrieval systems — dense, lexical or hybrid — work on vocabulary and meaning in the query text. "And for contractors?" has almost none of the vocabulary of the parental-leave policy: no "parental", no "leave", no "weeks". A dense embedder maps it into a region of embedding space populated by other conversational fragments ("what about sick pay?", "does it apply to part-timers?"); BM25 finds almost no term overlap with policy chunks. The fix is not a better index — it's giving retrieval a query that actually describes the information need. That is the condense step (also called query decontextualization, standalone-question rewriting or history-aware rewriting): an LLM call that reads the recent conversation and rewrites the latest message as a self-contained question.
06.10, 7.6 showed the retrieval-side primitive — a 10-line prompt that outputs "ONLY the query". This lesson owns the production version: a structured call that also decides the route, extracts slots and sticky filters, validates its own output, and degrades safely when the model misbehaves.
2.2 The condense call: prompt and schema#
The condense call does three jobs in one request, because they share the same input (history + latest message) and splitting them would double the cost:
- Rewrite the message into a
standalone_querythat resolves pronouns and ellipsis. - Route the turn:
retrieve,chat,metaorclarify. - Extract state: whether this is a follow-up (drives carry-forward), missing slots (drives clarification), durable filters and named entities (drive session state).
You are the query-understanding stage of a document question-answering assistant.
Rewrite the user's latest message as a standalone question that can be
understood and answered without this conversation, and decide how the turn
should be handled.
Conversation so far (most recent last):
{history}
Latest user message:
{user_text}
Return ONE JSON object, no prose:
{
"standalone_query": "<self-contained question; resolve pronouns like 'it',
'that one', 'the cheaper plan' and ellipsis like 'and for contractors?'
using the conversation. If the message is already standalone, return it
unchanged>",
"route": "retrieve" | "chat" | "meta" | "clarify",
"is_follow_up": true | false,
"clarification": null | "<one short question to ask, only when route is clarify>",
"missing_slots": ["<slot>", ...],
"sticky_filters": {},
"entities": {}
}
Route meanings:
- "retrieve": the user wants information from the document library.
- "chat": greeting, thanks, small talk, or a general-knowledge question that
needs no documents.
- "meta": about THIS conversation itself (summarize it, "what did I ask
earlier?", "go back to the pricing question").
- "clarify": too ambiguous to act on; ask exactly one short question.
"sticky_filters" holds durable constraints the user set for the rest of the
conversation (e.g. {"region": "EU"} after "only show me EU docs"); use {} when
none. "entities" maps slot names to values established this turn (e.g.
{"product": "Pulse VPN"}); use {} when none.Design notes on the schema:
routeis an enum, not prose. A free-text classification ("the user probably wants...") is unparseable half the time; a closed set makes the downstreamifexhaustive. This is the same discipline as 03.4's schema-constrained output — in production you send this as the provider's structured-output schema (OpenAItext.format, Anthropicoutput_config.format, Geminiresponse_schema) rather than parsing prose; the JSON contract is identical.standalone_queryis always populated, even forchat/meta/clarifyroutes — it doubles as the audit record of what the system thought the user meant, which is exactly what you need when debugging a bad turn (07.10 will thank you).is_follow_upis the carry-forward signal. It tells the retrieval stage whether last turn's chunks are plausibly still relevant — the difference between "and for contractors?" (yes) and "what about expenses?" (no, that's a topic switch even though it's phrased like a follow-up).sticky_filtersandentitiesare how session state gets written. Without them, "for the rest of this chat, only EU documents" is a sentence the system acknowledges and then forgets on the next turn.
2.3 Parsing it safely#
The model's JSON is an input to your code, not a guarantee. parse_condense in conversation.py (7.2) extracts a top-level JSON object with json.JSONDecoder.raw_decode — a simplified version of 03.4, 1.2's extractor: the first plausible object wins, with a preference for one containing route/standalone_query when the model emits several (if your model chatters, port 03.4's collect-all-and-let-the-schema-choose version). It then coerces every field to its declared type, validates route against the enum, and — the important part — falls back to a safe default on any failure:
def parse_condense(raw: str, user_text: str) -> CondenseResult:
data = _extract_json_object(raw) or {}
route_raw = data.get("route")
route = route_raw.strip().lower() if isinstance(route_raw, str) else ""
if route not in ROUTES:
route = "retrieve"
sq = data.get("standalone_query")
standalone = sq.strip() if isinstance(sq, str) and sq.strip() else user_text
..."Coerces to declared types" is doing real work here, because untrusted JSON is confidently wrong in specific ways: "is_follow_up": "false" is a truthy string (bool("false") is True — the exact bug that would carry last turn's chunks into a topic switch), "missing_slots": "product" is a string that iterates into ['p','r','o','d','u','c','t'], and "clarification": {"q": "which?"} would be shown to the user verbatim as "{'q': 'which?'}". _as_bool, the isinstance guards and _as_dict in 7.2 exist for precisely these shapes — the demo's checks exercise all three.
The fallback is deliberate: if the condense call returns prose, an empty string, malformed JSON or a hallucinated route, the turn degrades to "treat the raw message as a standalone retrieval question" — exactly what a single-shot pipeline would have done. Condense must never block a turn. The cost of a bad rewrite is a mediocre retrieval; the cost of an exception is a dead conversation.
Two more guards worth copying:
- Empty
standalone_query→ useuser_text. A model that returns""has told you nothing; the raw message is the best available query. - Log
rawon the turn record. When a rewrite goes wrong three turns later (the standalone query was fine but the answer contradicted it), the raw model output is the only way to tell whether the condense step or the generator drifted.
2.4 When to skip condensing#
The condense call is cheap — a small fast model (02.9, 2.5: gpt-6-luna, claude-haiku-5-5, gemini-3.8-flash tier) over a few hundred tokens of history — but "cheap" is not "free", and there are three legitimate reasons to skip it:
| Situation | Skip? | Why |
|---|---|---|
| First turn of a session | Condense still runs, but degenerates | With no history the rewrite is the identity; you still need the route decision, which the same call provides. The cost is one small call — acceptable. (Alternative: a cheaper classify-only call if profiling shows condense latency matters.) |
| Obvious trivial turns ("hi", "thanks", "bye") | Yes — deterministic fast path | is_trivial() in conversation.py pattern-matches greetings/acks and routes straight to chat with zero model calls for condense and retrieval. The answer still needs a generation call, but that's unavoidable. The list must stay conservative — when in doubt, let the model decide, because a wrongly-skipped turn produces a confidently wrong answer. |
| A pending clarification | Never skip | If the last turn asked "which product?", the user's "the Pro plan" is meaningless to a standalone rewriter and to retrieval. It must go through condense so the slot gets filled and the pending intent resumes. is_trivial() checks session.pending_clarification for exactly this reason. |
| Deployment where queries are always standalone | Yes — bypass entirely | Internal tools, API-style chat, single-question sessions. Set condense_enabled=False; every message goes to the planner as-is. You lose chit-chat routing, clarification and follow-up handling — only do this when the product genuinely has no follow-ups. |
| Caching/dedupe | Marginal | Condense results can't be cached by query text (each is unique), but identical conversations replayed in evals can reuse recorded outputs — that's what the fake-LLM test harness does. |
2.5 When condense goes wrong#
The condense step is itself an LLM call, so it inherits every failure mode in 02.10 — plus conversation-specific ones:
| Failure | What it looks like | Guard |
|---|---|---|
| Over-rewriting | User asks "what's the refund window?" (already standalone); condense rewrites it into something that drops "refund" or adds a wrong entity from history | The prompt says "if already standalone, return unchanged"; also compare standalone_query against user_text in evals — a high edit distance on standalone inputs is a prompt bug |
| Drift across turns | Turn 5's rewrite quietly inherits an entity from turn 2 that the user has since corrected | Corrections must update session.entities before the next condense; the history window fed to condense should show the correction, not just the original claim |
| Hallucinated context | Model invents a topic the conversation never had ("you asked about the Enterprise plan" when it was Pro) | entities/sticky_filters are schema-validated but not truth-validated; spot-check rewrites in evals; the raw transcript is the audit |
| Negation dropped | "Don't show me the EU policy" → standalone "show me the EU policy" | Watch for this specifically in evals — it's the highest-severity rewrite error because it inverts intent |
| Injection via history | A poisoned earlier answer instructs the rewriter to change the query | Schema validation + the fact that output is only ever a query string and filter dict limits blast radius; real defences are Module 12's |
| Latency stacking | Condense (1 call) + planner (1 call) + generator (1 call) = 3 sequential LLM calls before the first token | Condense and nothing else can start until the raw message arrives; the planner depends on condense's output. Use a small model for condense, stream the final answer, and consider merging condense+planner into one structured call if profiling demands it |
The meta-lesson: the condense step is a query rewriter, and every lesson 07.3 teaches about rewrites applies to it — measure it on your eval set, keep the original query for audit, and never let it block retrieval.
Part 3: Deciding when to retrieve — and what to retrieve#
3.1 The route decision#
The condense result's route field sends each turn down one of four paths. This is the highest-leverage decision in the whole pipeline, because every wrong route is expensive in a different way:
| Route | Trigger examples | Cost | Wrong-route symptom |
|---|---|---|---|
retrieve |
"What's the parental leave policy?", "and for contractors?" | Embed + search + (rerank) + full generation with context | Chit-chat classified as retrieve → wasted retrieval, and the generator may force an irrelevant citation |
chat |
"hi", "thanks", "what can you do?" | Generation only, no retrieval | A real question classified as chat → the model answers from priors and hallucinates policy |
meta |
"summarize this", "what did I ask earlier?", "go back" | Generation over session record | A corpus question classified as meta → answers about the conversation instead of the documents |
clarify |
"the cheaper one" with no antecedent, "tell me about it" with three candidate "its" | One short generation, no retrieval | Over-eager clarification → the bot asks "which do you mean?" when the context was actually clear; under-eager → it guesses and retrieves the wrong thing |
Two implementation notes:
- Route lives inside the condense call by default (one LLM call per turn does rewrite + route + extraction). The alternative — a separate cheap classifier — only pays off if profiling shows the combined call is too slow; see 2.4.
QueryPlan(07.3) can also redirect the turn. The planner sees filters and sub-questions the condense step doesn't, and itsroutecan sayCLARIFY(ask instead of retrieving) orSKIP_RETRIEVAL(chit-chat/general knowledge — this pipeline maps it tochat).handle_turnhonours both sources of clarification; the turn record shows which stage asked. Theplannerseam accepts a realQueryPlandirectly —plan_result_from_query_plan(7.2) mapscleaned→rewrites[0]→originalonto the single retrievalquery,filters.model_dump(exclude_none=True)ontofilters(minus the plan-side-only fieldstopic_hint,year,date_from,date_toandparty, which this corpus has no metadata to match), androuteontochat/clarify/retrieve. TwoQueryRoutes deliberately don't map:RETRIEVE_MULTIandDECOMPOSEfan out to several retrievals, which this layer's one-queryRetriever.searchcontract can't express — that's 07.3's fan-out and 07.8's territory; the adapter degrades them to a singlecleaned-query retrieval rather than dropping the plan.
3.2 Chit-chat, meta-questions and "summarize this"#
Chit-chat (route=chat) still needs a generation call — "hi!" deserves "Hi! I can answer questions about the employee handbook, help-centre articles and policies. What would you like to know?" — but it gets no retrieved context. Passing retrieved chunks to a greeting actively hurts: the generator may weld policy text onto a hello, and you pay retrieval + bigger-prompt costs for nothing.
Meta-questions (route=meta) are about this conversation, and the session record already contains everything needed:
- "What did I ask earlier?" → list the
standalone_queryof recent turns — deterministic, no model call needed (though a model can phrase it nicely). - "Summarize what we've covered." → feed the turn digests to the model and ask for a recap.
meta_answer()inconversation.pydoes exactly this, with a deterministic fallback if the call fails. - "Go back to the pricing question." → this is really a navigation request, and
meta_answerimplements it:_referenced_turnfinds the matchingTurnRecordby content-word overlap (best score wins, ties go to the most recent turn — it returnsNonerather than guessing) and the answer replays that turn's storedanswer_text, noting itshitsare still on the record for "show sources". If the user wants to continue that topic instead ("ok, and for contractors?"), that's an ordinary follow-up — condense rewrites it standalone and retrieval runs fresh; the go-back path is only for pure navigation. It's the conversational equivalent of browser history.
3.3 Fresh retrieval vs carrying context forward#
This is the central retrieval decision of conversational RAG. Three strategies, increasingly aggressive:
| Strategy | What happens on a follow-up | When it wins | When it hurts |
|---|---|---|---|
| Always fresh | Re-retrieve on the standalone query every turn; ignore last turn's hits | Topic switches, comparisons, corrections — anything where last turn's docs are wrong | Follow-ups on the same topic re-fetch chunks already in context (cost) and can lose a good chunk that ranked #7 last turn but #9 this turn |
| Carry forward + fresh | Union last turn's hits with this turn's fresh results, dedupe by id, cap the carried count | The common case: follow-ups on the same topic | Carried chunks consume context budget; stale docs can crowd out better fresh ones |
| Carry only, no fresh | Reuse last turn's retrieval entirely | Rare — only for pure acknowledgements ("tell me more about the first one") | Any topic drift silently answers about the wrong subject |
conversation.py implements the middle strategy, gated on is_follow_up from the condense step: follow-ups carry up to carry_max of last turn's hits (those not already in the fresh results); non-follow-ups get fresh retrieval only. Two subtleties:
- Scores are not comparable across queries. A hit's
scorefrom turn N-1's query means nothing next to turn N's scores — different query, different score distribution. Carried hits are appended after fresh hits, never re-ranked by stale scores. (06.10'sHitdocstring says the same: score is retriever-specific and not comparable across systems — across queries it's worse.) - Carry-forward is a recall hedge, not a ranking. Its job is to stop a good chunk from falling out of the top-k on a phrasing change ("and for contractors?" retrieves slightly different neighbours than the original question). If your reranker is strong, carried hits can also be re-scored — but only with a cross-encoder that scores (query, chunk) pairs, which is comparable across queries. That's a 07.2/06.9 decision; the default here is append, don't re-rank.
3.4 Retrieval caching per session#
Users repeat themselves: "what's the parental leave policy?" … three turns of follow-ups … "ok so how many weeks was that again?" The standalone queries differ, but the same (query, filters) pair recurs often enough that a per-session cache pays for itself:
def cache_key(query: str, filters: dict) -> str:
canon = json.dumps({"q": " ".join(query.lower().split()),
"f": _canon_filters(filters)}, sort_keys=True)
return canonDesign rules:
- Key on the planned query and the effective filters — not the raw user text. Two different phrasings that condense to the same standalone query share a cache entry; the same query under different filters must not.
- TTL, not immortality. Indexes update; a cached hit list can point at deleted or superseded chunks (07.11 owns freshness).
conversation.pyuses a per-entry timestamp andcache_ttl(default 30 minutes — tune it); on expiry the entry is replaced, not served stale. - Bound the cache.
session.cacheis capped (64 entries, oldest evicted) so a long session can't grow it without limit. - Cache the serialized hits and the carried-hit ids, not live objects. What you store is exactly what you served — the audit trail and the cache are the same data, so a cache-hit
TurnRecordreplays the samecarried_hit_idsand you can still tell carried evidence from fresh. - A cache hit is recorded on the turn (
cache_hit=True), both for cost accounting and because "why did turn 9 return identical sources to turn 4?" is a support question you'll get.
3.5 Filters that survive the conversation#
Filters are where conversational RAG has a security dimension single-turn RAG doesn't. Three sources compete to set them:
| Source | Example | Authority |
|---|---|---|
| Session sticky filters | User: "for the rest of this chat, only EU docs" → {"region": "EU"} persists |
High — but user-set, not model-set |
| Per-turn plan filters | "what's the contractor policy?" → {"doc_type": "policy", "audience": "contractor"} |
Applies to this query only |
| Tenant/ACL filters | {"tenant": "acme-corp"} from auth context |
Absolute — can never be overridden |
effective_filters() merges them in that order — sticky as defaults, per-turn overrides, tenant forced last:
def effective_filters(session: SessionState, plan_filters: dict,
required: dict | None = None) -> dict:
merged = {k: v for k, v in session.sticky_filters.items()}
merged.update(plan_filters or {})
for key in _TENANT_KEYS: # ("tenant", "acl", "user_id")
merged.pop(key, None)
if session.tenant:
merged["tenant"] = session.tenant
merged.update(required or {}) # per-request ACL filters from auth, applied last
return mergedThe critical property: tenant/acl/user_id keys are stripped from whatever the model produced, and tenant is then re-added from session.tenant — which comes from your auth layer at session creation, never from the request body or the model. acl/user_id are stripped, and nothing re-adds them unless you do: stripping removes the model's value but supplies none, so a deployment that filters on them must pass required_filters={"acl": ...} to handle_turn (computed from the authenticated request, every turn). Left out, those filters are simply absent and the search is unfiltered on that dimension. The same rule applies to the session itself: handle_turn refuses an existing session unless the caller presents exactly the tenant and user_ref it was created with, so leaving the arguments out is refused, not skipped. The condense step and the QueryPlan can propose filters, but they can never widen access — a prompt-injected document can't talk the system into searching another tenant's index (06.6, Part 3; the full ACL story is 07.2 and 07.11).
Sticky filters also need an escape hatch: conversation.py treats a sticky_filters value of null/""/{} as clearing that key — so "actually, show me all regions again" can undo "only EU docs". Without a clear path, sticky filters become sticky bugs.
3.6 The alternative: let the model write the query (search as a tool)#
Everything in Part 2 and Part 3 is the pipeline answer to follow-ups: your code condenses, routes, retrieves, then calls the generator once. There is a second architecture worth knowing, because hosted file-search tools and many agent frameworks work this way: hand the model the whole conversation and a search tool, and let it decide whether to search, with what query, and how many times (07.2, 5.3 introduced it for the retrieve-or-not decision; 03.5 owns the mechanics). The model resolves "and for contractors?" itself, because it can see the history when it writes the tool call.
| Pipeline (condense, route, retrieve, generate) | Search-as-a-tool (model loops) | |
|---|---|---|
| Who writes the standalone query | A dedicated condense call you can test, log and validate | The answering model, inside its own tool call |
| LLM calls on a typical follow-up | 2 to 3, always in the same order | 1 to N; at least two when it searches (tool call, then answer) |
| Latency shape | Predictable | Variable; each loop iteration re-sends the conversation at full input price |
| Filters and tenant scope | Merged by your code (effective_filters) before every search |
Must be enforced inside the tool implementation; never let the model pass a tenant |
| Multi-hop and comparisons | One query per turn unless you add fan-out (07.3) | Natural: it can search twice and compare |
| Debuggability | Condense output and route are explicit fields on TurnRecord |
Reconstruct from the tool-call trace; the "standalone query" is whatever it passed |
| Failure to watch | Condense drift (2.5) | Skipped searches (answers from priors), runaway loops, repeated near-identical queries |
How to choose, in our judgement (not a measured result): start with the pipeline when you need predictable cost, strict tenant filters and testable intermediate steps, which describes most support and documentation bots. Move to the tool form when questions are frequently multi-hop or exploratory, or when you are already running an agent loop (Module 08A) and retrieval is one tool among several. The two compose: keep effective_filters, the session store and TurnRecord exactly as built here, and expose handle_turn's retrieval step as the tool body, so the safety properties of Part 3 survive. Provider-hosted file search (OpenAI file_search, Gemini File Search) behaves like the tool form, and the provider can also hold the conversation state for you (03.2); what you give up is visibility into the standalone query, which 07.7 covers as part of the managed-service trade-off.
Part 4: What goes into the next turn's context#
4.1 Anatomy of turn N's context#
By the time the generator is called on turn N, five kinds of material compete for the context window. The order matters — stable material first (for caching and for instruction-following), volatile material last:
┌─ system / instructions ────────────────────────────────┐ stable across turns
│ grounding rules, citation format, persona │ → cache-friendly prefix
├─ session block (pinned) ───────────────────────────────┤
│ entities, sticky filters, rolling summary │ changes only when state does
├─ conversation summary ────────────────────────────────┤
│ condensed older turns (04.7) │
├─ recent history window ────────────────────────────────┤
│ last ~8 turns verbatim │ grows/shrinks per turn
├─ retrieved context ────────────────────────────────────┤
│ [1] chunk … [2] chunk … (this turn's hits) │ most volatile — last
├─ current question (standalone) ────────────────────────┘GenerationRequest in conversation.py carries exactly these fields: session_block, history, context_hits, question, plus source_map (the label→chunk index for this turn) and route. What the generator does with them is 07.4's job; this lesson decides what is allowed in.
4.2 The token cost of carrying chunks forward#
This is the cost nobody budgets for. A retrieved chunk averages a few hundred tokens; six chunks is ~2,000 tokens per turn, re-sent every turn the conversation continues. Over a 20-turn session that's tens of thousands of tokens of repeated context — billed at input price every time, and a growing share of the "lost in the middle" problem (02.7, 5.1).
| What to carry | Cost per turn | When it's worth it |
|---|---|---|
| Previous answers (in history) | ~100–300 tokens each | Always — they're the conversation; trim via 04.7 |
| Previous retrieved chunks | ~200–800 tokens each | Only while still relevant — that's what carry-forward + is_follow_up gate |
| Citations/hit metadata | ~20–50 tokens | Cheap; keep for provenance |
| Full retrieval results incl. losers | the most expensive mistake | Never send hits below the context cut — retrieval returns k, the context builder sends fewer (07.4, 04.6) |
The discipline: re-retrieve by default, carry forward only on evidence of continuity. is_follow_up is that evidence. A topic switch re-retrieves and the old chunks leave the context entirely — which is also what keeps the window from filling with dead documents.
4.3 Citation numbering across turns#
07.5 owns citation mechanics; conversational RAG adds one question it doesn't answer: do labels restart each turn or continue across the session?
| Scheme | How it works | Pros | Cons |
|---|---|---|---|
| Per-turn numbering | Each answer's context is [1]..[n]; the TurnRecord stores the label→hit map |
Simple; matches how users read a chat (each bubble self-contained); old turns' citations stay resolvable via stored hits |
Two turns can both cite "[1]" meaning different chunks — fine if the UI resolves per-message |
| Session-global numbering | [7] keeps meaning the same chunk all session |
Stable referent across turns ("you said [7] earlier") | Numbers grow unboundedly; chunks fall out of context but their numbers persist; confusing when context is trimmed |
conversation.py uses per-turn numbering with persisted resolution: TurnRecord.source_map stores [{"label": "[1]", "chunk_id": ..., "title": ...}] — the same label→chunk join 07.1's ContextItem.label/Citation.chunk_id and 07.5's positional [n]→sources[n-1] convention perform — and TurnRecord.hits stores the serialized chunks themselves, so a "show sources" UI can reopen turn 3's sources without re-retrieval, and without the chunk store even being consulted.
Naming matters: source_map is a resolution index, not a citation. Verified citations are 07.5's job — verify_citations consumes the ordered hits list plus the answer text and produces CitedAnswer/ClaimCitation/SourceRef; Answer.citations are built from that verified evidence at answer time, never read back from source_map. Keeping the names distinct is deliberate: when 07.11 consolidates docs_qa, three different citation-ish shapes already coexist (07.1's Citation, 07.4's Evidence/GroundedAnswer, 07.5's ClaimCitation) — a fourth under a colliding name would be an import bug. Global numbering is the right choice only if your UI exposes cross-turn citation references; decide it in 07.5's presentation layer, not here.
4.4 Cache-friendly layout#
Prompt caching (03.7, 02.7, 7.4) rewards stable prefixes. A naive conversational prompt that prepends the newest turn at the top invalidates the cache every message. The layout above is cache-aware by construction:
- System/instructions first — byte-identical every turn.
- Session block next — changes only when entities/filters/summary change, not every turn.
- Summary + history — append-mostly; 04.7, 9.1 covers the append-only discipline and where trimming breaks the cache.
- Retrieved context + question last — the volatile tail.
One conversational-specific trap: the standalone query in the question slot changes every turn even when the user is really continuing a topic. If your cache-hit rate matters, keep the raw user message visible in history (it is — history carries user_text) while the standalone rewrite lives only in the question slot; don't rewrite history itself.
4.5 Trimming history for RAG#
04.7 owns history management in depth — sliding windows, rolling summaries, pinning, ConversationManager. Conversational RAG adds three wrinkles:
- Retrieved chunks are not history. They live in the context slot, not the transcript. Trimming history (dropping old turns) does not drop their chunks — carry-forward and the retrieval cache decide chunk lifetime independently. Keep the two budgets separate in your head: transcript budget (04.7) vs evidence budget (this lesson).
history_messagescaps assistant text (1,500 characters per turn inconversation.py) — the generation-side window can't grow unboundedly either; production swaps in 04.7's token-budgetedConversationManagerfor smarter trimming.- Don't trim the turn that established a sticky filter or entity. If turn 2 said "only EU docs" and turn 18's window starts at turn 10, the model no longer sees why
region=EUis in the filters — but yoursession_blockstill showsActive filters: {"region": "EU"}, which is the durable form of that decision. This is the argument for extracting state intoentities/sticky_filters/summaryrather than relying on the transcript alone: structured state survives trimming; prose doesn't.
Part 5: Session design#
Deep-dive
5.1 The session state schema#
A session is a small document, not a transcript dump. SessionState in conversation.py is the whole schema:
| Field | Type | Purpose |
|---|---|---|
session_id |
str | Your handle — also the cache key namespace and the store key |
user_ref |
str | Pseudonymous user id (hashed — 03.2, 10.3); never an email |
tenant |
str | None | The ACL boundary; forced into every retrieval's filters |
created_at / updated_at |
float | Lifecycle and "resume where you left off" ordering |
sticky_filters |
dict | Durable user-set constraints ({"region": "EU"}) |
entities |
dict | Named things established this session ({"product": "Pulse VPN"}) — shown to the generator in the session block |
summary |
str | Rolling summary of older turns (written by the summarizer in 04.7, 2.4) |
turns |
list[TurnRecord] | The audit trail — see 5.2 |
cache |
dict | Per-session retrieval cache (3.4) |
recent_hits |
list[dict] | Last turn's served hits — the carry-forward source |
Two properties make this schema production-shaped rather than toy-shaped: everything is JSON-serializable (the store is a dict round-trip, not pickle) and the model's outputs land in typed fields (sticky_filters, entities, route) rather than being re-parsed from prose later.
5.2 What to store per turn#
TurnRecord is the audit and resume unit. For each turn it stores: the raw user_text, the standalone_query the system actually used, the route, the answer_text, the serialized hits served to the generator, the source_map label→chunk index, the filters_used, cache_hit, carried_hit_ids, followups, and a timestamp.
Why store retrieved sets, not just answers:
- Citations must resolve later. A "show sources" click on turn 3 needs turn 3's chunks; storing serialized hits makes that self-contained.
- Debugging needs the evidence. "Why did it say 26 weeks?" is answered by turn 3's
hits, not by re-running retrieval (the index may have changed since). - Evaluation needs it. Turn-level metrics (Part 8) score what was retrieved per turn — you can't compute retrieval recall after the fact if you didn't record it.
- Resume needs it. Restoring a session ("go back to the pricing question") means restoring its evidence, not just its prose.
The cost is real — serialized chunks are the biggest field — so production stores hit_ids and joins to the chunk store at render time, keeping only an excerpt inline. The lesson's JSON store keeps full hits because it's self-contained; note the trade-off in 5.3.
5.3 The session store#
Three implementations, same SessionStore protocol (get/put/delete):
| Store | Good for | Watch out for |
|---|---|---|
InMemorySessionStore |
Tests, single-process demos, eval harnesses | Dies with the process; fine because tests recreate state |
JsonFileSessionStore |
Laptops, small deployments, the lesson's demos | One file per session; atomic write (tmp + replace) so a crash can't corrupt; no queries across sessions; fine to ~thousands of sessions |
| SQLite / Postgres / Redis (production) | Real traffic, multi-instance deployments, TTL/expiry jobs, cross-session analytics | You own schema migrations, connection pooling, and the privacy lifecycle (5.5); 03.2, 5.2 shows the SQLite pattern for the transcript side — this store holds the retrieval side |
The important boundary: this store holds retrieval/session state; the transcript store (03.2's convo_store.py or your message table) holds the conversation. They can be the same database — but keep them conceptually separate, because they have different retention rules (you might keep transcripts for audit but expire retrieval caches hourly) and different writers (the transcript is appended by the API layer; session state is written by the RAG pipeline).
Concurrency is the other sharp edge. handle_turn does store.get → mutate → store.put; two rapid turns (a double-submit, two tabs) race, and last writer wins — a turn record can be silently lost. In-process, serialise per session_id (a per-session queue or lock around the read-modify-write); across instances, the production store needs optimistic concurrency — a version/etag check on put that fails the stale writer — which is 07.11's store-design territory.
5.4 Multi-user sessions, tenants and profiles#
- Session ↔ user:
session_idis not the user id. One user can hold many sessions ("refund question" vs "policy research"); a session id should be unguessable (uuid4) because it grants access to that conversation's retrieved content, andhandle_turnrefuses a turn whose statedtenantoruser_refdiffers from the stored session's (your service must pass both from its auth layer on every turn, since a caller that states nothing is not checked).user_refis the pseudonymous hash from 03.2, 10.3 — used for "list my sessions", never sent to providers as personal data. - Tenant:
session.tenantcomes from your auth layer at session creation, never from the request body or the model. It's injected intoeffective_filterson every retrieval — the model cannot see another tenant's chunks because the filter is applied before scoring (06.6, never post-filter). - Profiles/preferences: durable user preferences (language, detail level, "always cite sources") belong to long-term memory (04.7, Part 6), loaded into the session block at creation — not re-extracted every session. Session
entities/sticky_filtersare this conversation's state; user profile is across conversations. Don't conflate them. - Resuming:
store.get(session_id)returns the full state — turns, cache, recent hits, filters — so a resumed session continues exactly where it left off, including its retrieval cache (until TTL). Multi-device resume is just "samesession_id, different client".
5.5 Lifecycle, privacy and retention#
Sessions are a data store, so they inherit every obligation of one:
- Expiry: idle sessions should expire (the retrieval cache TTL is the short version; the whole session might live days). On expiry, delete — don't just stop serving.
- Deletion: "delete my data" must purge the session store and the transcript store and any provider-side state (03.2, 10.4).
- What's sensitive: session state contains retrieved document text — which may itself contain PII or confidential material — plus the user's queries. Treat
turns[].hitswith the same care as the corpus. - PII in queries: users paste customer names, order IDs, internal URLs into questions. Those land in
user_text,standalone_query,entitiesand the transcript. Hashuser_ref; don't log raw queries to third-party observability without redaction (03.10, 07.11). - Retention vs utility: the audit value of
TurnRecord.hitsconflicts with storage cost and privacy minimisation. A common compromise: keep hit ids + citation labels long-term, full chunk text for a short window. - Streaming write-point.
handle_turnis synchronous, but production answers stream (03.3, 07.4, 8.3). Write theTurnRecordwhen the stream completes; on client disconnect keepanswer_textpartial and mark the turn (apartialflag onTurnRecord, or a sentinel inanswer_text) so evals and audit know the answer was cut off — a half-answer recorded as complete poisons both.
Part 6: Clarification, slot-filling and suggested follow-ups#
Deep-dive
6.1 Ask, don't guess#
"Tell me about it." — it could be three different products discussed this session. The failure mode is a confident answer about the wrong one: retrieval runs, returns plausible chunks, the generator writes a fluent answer, and the user only discovers the mix-up when the details don't match. The clarify route exists to convert that silent failure into one cheap question.
When to clarify vs when to infer:
| Situation | Action | Why |
|---|---|---|
| One plausible referent in recent turns | Infer it (condense resolves "it") | Asking "which do you mean?" when the answer is obvious is its own UX failure |
| 2+ live candidates, no strong recency | Clarify — one question naming the candidates | "Did you mean the Pro or Enterprise plan?" beats a wrong answer |
| A required slot is missing ("the cheaper one" with no priced pair in context) | Clarify | The information literally isn't there; retrieval can't fix it |
| User seems frustrated / repeating themselves | Stop clarifying, give the best answer + caveat | Clarification loops are worse than imperfect answers |
Rules for the clarification itself: exactly one question, name the candidates concretely (slot values from session.entities and recent turns, not abstract categories), and don't retrieve — there's nothing to retrieve against yet. The turn still gets recorded with route="clarify", which sets session.pending_clarification; the next user message is then treated as a slot answer, not a new topic.
6.2 Slot-filling across turns#
Slot-filling is the conversation equivalent of a web form's dependent dropdowns: the system knows what it needs and extracts it from whatever the user says next. "Which product?" → user: "the Pro plan" → condense sees the pending clarification in history and produces standalone_query="Pro plan parental leave policy", entities={"product": "Pro plan"} — resuming the intent that was interrupted two turns ago.
Two implementation details that make it work:
- Pending state is derived, not stored separately.
session.pending_clarificationisturns[-1].route == "clarify"— the last turn record is the state. No extra flag to keep in sync. - The condense history must include the clarification question.
history_lines()feeds the last N turns including assistant answers — so the rewriter sees "assistant: Which product did you mean — Pro or Enterprise?" and knows "the Pro plan" fills that slot. If you trim history too aggressively (4.5), you can lose the pending question and the slot answer becomes a new ambiguous fragment. Keep the pending-clarification turn pinned while it's open.
6.3 Suggested follow-ups#
After a grounded answer, offering 2–3 follow-up chips ("How does this apply to contractors?", "What's the notice period?") is the cheapest engagement feature in conversational RAG — and a genuine UX feature, not decoration: it teaches users what the corpus can answer and reduces the "I don't know what to ask" problem that produces vague fragments.
suggest_followups() in conversation.py asks the model for three short questions answerable from the same library, stores them on the TurnRecord, and returns them in the TurnOutcome — and strips bullets and numbering the model adds despite the prompt, so enumerated output can't leak into the chips. Two cautions:
- Suggestions must be corpus-answerable. A suggestion the index can't satisfy sets up the next turn to fail or abstain. Evaluate them with the same retrieval harness (Part 8): run each suggestion through
retriever.searchand check it returns hits — cheap, deterministic, catches the worst suggestions. - They're optional and cost an extra call. Gate behind a flag (
suggest=True), use the cheap model, and never let a suggestion failure affect the answer —suggest_followupsreturns[]on any error.
Proactive suggestions (surfacing relevant docs before the user asks) are a different feature — closer to recommendation than RAG — and belong to Module 13A's product work, not this pipeline.
Part 7: docs_qa/conversation.py — the full turn pipeline#
Deep-dive
7.1 Design: the seams#
The module is deliberately a seam, not a monolith. Everything it can't own is injected:
| Seam | Signature | Provided by |
|---|---|---|
retriever |
search(query, k, filters) -> list[Hit] |
The 06.10 Retriever protocol — any implementation (toy, pgvector, hybrid, managed) |
llm |
(prompt: str) -> str |
A thin wrapper over your provider call — FakeLLM in tests; the condense/meta/follow-up prompts in production go through structured output (03.4) |
planner |
(standalone_query, session) -> PlanResult | QueryPlan |
07.3's plan_query — optional; a real QueryPlan (pydantic or dict) is adapted by plan_result_from_query_plan, a PlanResult passes through; without it the standalone query is used as-is |
generate |
(GenerationRequest) -> str |
07.4's generate_answer via the grounded_generator adapter — optional; without it a minimal renderer + llm is used |
store |
SessionStore protocol |
InMemorySessionStore (tests) or JsonFileSessionStore (demos/resume) |
What conversation.py owns: the condense prompt and its safe parsing, the trivial-turn fast path, route dispatch, filter merging and tenant enforcement, the retrieval cache, carry-forward, session-state updates, turn recording, and the stores. What it deliberately does not own: query rewriting/expansion (07.3), context formatting and grounding prompts (07.4), citation verification (07.5), history compaction (04.7), provider APIs (03.x).
Two seams need an explicit adapter spec, because the sibling lessons' contracts are richer than this pipeline's:
QueryPlan → PlanResult (plan_result_from_query_plan, 7.2):
QueryPlan field (07.3) |
Becomes | Notes |
|---|---|---|
cleaned → rewrites[0] → original |
PlanResult.query |
First non-empty wins; ONE retrieval string — RETRIEVE_MULTI/DECOMPOSE fan-out is out of scope for this layer (07.3 owns the fan-out, 07.8 the patterns) and degrades to a single cleaned-query retrieval |
filters: ExtractedFilters | None |
PlanResult.filters: dict |
model_dump(exclude_none=True); the plan-side-only fields (topic_hint, year, date_from, date_to, party) are dropped, as 07.3's filters_for_search does — this corpus carries no such metadata, so as equality filters they would return nothing |
clarification |
PlanResult.clarification |
Honoured only when route == CLARIFY |
route: QueryRoute |
PlanResult.route |
SKIP_RETRIEVAL→chat, CLARIFY→clarify, everything else→retrieve |
generate seam → 07.4's generate_answer (grounded_generator, 7.2) — three mismatches it bridges: GenerationRequest.context_hits are serialized dicts (what TurnRecord stores) while HitLike wants attributes (→ SimpleNamespace); generate_answer has no history/session-block parameters (→ recent history injected as real messages inside a wrapped llm_fn, session_block appended to the system message, keeping question pure for the sufficiency/coverage gates); and it returns a GenerationResult, not str (→ flattened to GroundedAnswer.answer text, full result kept on adapter.last_result for status/eval inspection — 07.4's own edge mapping turns it into Answer.text/abstained/citations).
7.2 The code#
# docs_qa/conversation.py — conversational RAG: session state, the condense
# step, and the per-turn pipeline.
#
# Pure standard library. Every model call is injected (`llm`, `generate`,
# `planner`); the retriever is the 06.10 `Retriever` protocol; hits are
# duck-typed (objects with .id/.score/.text/.metadata/.source, or dicts).
from __future__ import annotations
import json
import re
import time
import uuid
from dataclasses import dataclass, field
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable, Protocol
# --------------------------------------------------------------------------
# Hit helpers — accept a 06.10 `Hit` dataclass, a dict, or anything similar.
# --------------------------------------------------------------------------
def _hit_get(hit: Any, key: str, default: Any = None) -> Any:
if isinstance(hit, dict):
return hit.get(key, default)
return getattr(hit, key, default)
def serialize_hit(hit: Any) -> dict:
"""The JSON-safe form stored on TurnRecords and in the retrieval cache."""
return {
"id": str(_hit_get(hit, "id", "")),
"score": float(_hit_get(hit, "score", 0.0) or 0.0),
"text": str(_hit_get(hit, "text", "") or ""),
"metadata": dict(_hit_get(hit, "metadata", {}) or {}),
"source": str(_hit_get(hit, "source", "") or ""),
}
# --------------------------------------------------------------------------
# Types
# --------------------------------------------------------------------------
ROUTES = ("retrieve", "chat", "meta", "clarify")
@dataclass
class CondenseResult:
"""What the condense step decided about this turn."""
standalone_query: str
route: str = "retrieve"
is_follow_up: bool = False
clarification: str | None = None
missing_slots: list[str] = field(default_factory=list)
sticky_filters: dict = field(default_factory=dict)
entities: dict = field(default_factory=dict)
raw: dict = field(default_factory=dict) # the model's JSON, for audit
@dataclass
class TurnRecord:
"""One turn's audit + resume unit (see lesson 5.2)."""
index: int
user_text: str
standalone_query: str
route: str
answer_text: str
hits: list[dict] # serialized chunks served
hit_ids: list[str]
source_map: list[dict] # [{"label","chunk_id","title"}]
filters_used: dict
cache_hit: bool = False
carried_hit_ids: list[str] = field(default_factory=list)
followups: list[str] = field(default_factory=list)
created_at: float = 0.0
@dataclass
class SessionState:
session_id: str
user_ref: str = ""
tenant: str | None = None
created_at: float = 0.0
updated_at: float = 0.0
sticky_filters: dict = field(default_factory=dict)
entities: dict = field(default_factory=dict)
summary: str = ""
turns: list[TurnRecord] = field(default_factory=list)
cache: dict = field(default_factory=dict) # retrieval cache
recent_hits: list[dict] = field(default_factory=list)
@property
def pending_clarification(self) -> bool:
return bool(self.turns) and self.turns[-1].route == "clarify"
def history_lines(self, max_turns: int = 12) -> list[str]:
"""The condensed transcript the condense step sees (bounded)."""
lines = []
for t in self.turns[-max_turns:]:
lines.append(f"user: {t.user_text}")
if t.answer_text:
lines.append(f"assistant: {t.answer_text[:400]}")
return lines
@dataclass
class PlanResult:
"""The slice of 07.3's QueryPlan this pipeline consumes.
`route` is an optional planner override: "chat" when the plan says
SKIP_RETRIEVAL, "clarify" when it says CLARIFY. None keeps the
retrieve path. See plan_result_from_query_plan for the QueryPlan
-> PlanResult field mapping."""
query: str
filters: dict = field(default_factory=dict)
clarification: str | None = None
route: str | None = None
@dataclass
class GenerationRequest:
"""Everything the generator is allowed to see this turn."""
route: str
question: str # standalone query
context_hits: list[dict] # serialized, numbered [1]..[n]
history: list[dict] # [{"role","content"}]
session_block: str # pinned entities/filters/summary
source_map: list[dict] # label -> chunk index
@dataclass
class TurnOutcome:
session_id: str
route: str
answer_text: str
standalone_query: str
hit_ids: list[str]
cache_hit: bool
carried_hit_ids: list[str]
followups: list[str]
clarification_pending: bool
# Injectable seams (see 7.1). A planner returns a PlanResult, or a 07.3
# QueryPlan-shaped object (pydantic model or dict) — handle_turn
# normalises it via plan_result_from_query_plan before reading fields.
LLM = Callable[[str], str]
Planner = Callable[[str, SessionState], Any]
Generator = Callable[[GenerationRequest], str]
class Retriever(Protocol):
"""The 06.10 contract: one query in, ranked Hits out."""
def search(self, query: str, k: int = 10,
filters: dict | None = None) -> list[Any]: ...
# --------------------------------------------------------------------------
# 07.3 QueryPlan adaptation — the planner seam accepts a real QueryPlan
# --------------------------------------------------------------------------
def _plan_get(plan: Any, name: str, default: Any = None) -> Any:
"""plan may be a PlanResult, a 07.3 QueryPlan (pydantic), or a dict."""
if isinstance(plan, dict):
return plan.get(name, default)
return getattr(plan, name, default)
def plan_result_from_query_plan(plan: Any, fallback_query: str) -> PlanResult:
"""Adapt 07.3's QueryPlan to this pipeline's PlanResult.
Field mapping (see lesson 7.1):
query <- plan.cleaned, else plan.rewrites[0], else
plan.original — ONE retrieval string. Multi-query
fan-out (RETRIEVE_MULTI) and DECOMPOSE are
07.3/07.8's job; this layer retrieves once.
filters <- plan.filters.model_dump(exclude_none=True) for the
pydantic ExtractedFilters, a dict as-is; the
plan-side-only fields (topic_hint, year, date_from,
date_to, party) are dropped — 07.3's
filters_for_search does the same: the toy index
carries no such metadata, so as hard filters they
would return zero hits.
clarification <- plan.clarification, honoured only when
plan.route == CLARIFY.
route <- 'chat' for SKIP_RETRIEVAL, 'clarify' for CLARIFY;
RETRIEVE/RETRIEVE_FILTERED (and the multi/decompose
routes, degraded to a single query) stay 'retrieve'.
"""
route_raw = _plan_get(plan, "route")
route_val = str(getattr(route_raw, "value", route_raw) or "").lower()
cleaned = _plan_get(plan, "cleaned")
rewrites = _plan_get(plan, "rewrites") or []
first_rewrite = (rewrites[0]
if isinstance(rewrites, (list, tuple)) and rewrites
else None)
original = _plan_get(plan, "original")
query = next((q.strip() for q in (cleaned, first_rewrite, original)
if isinstance(q, str) and q.strip()), fallback_query)
filters_raw = _plan_get(plan, "filters")
if hasattr(filters_raw, "model_dump"):
filters = filters_raw.model_dump(exclude_none=True)
elif isinstance(filters_raw, dict):
filters = dict(filters_raw)
else:
filters = {}
for plan_side_only in ("topic_hint", "year", "date_from", "date_to", "party"):
filters.pop(plan_side_only, None) # not index metadata (see 07.3)
clar = _plan_get(plan, "clarification")
clarification = (clar.strip()
if route_val == "clarify" and isinstance(clar, str)
and clar.strip() else None)
out_route = {"skip_retrieval": "chat", "clarify": "clarify"}.get(route_val)
return PlanResult(query=query, filters=filters,
clarification=clarification, route=out_route)
# --------------------------------------------------------------------------
# The condense step
# --------------------------------------------------------------------------
CONDENSE_PROMPT = """\
You are the query-understanding stage of a document question-answering assistant.
Rewrite the user's latest message as a standalone question that can be
understood and answered without this conversation, and decide how the turn
should be handled.
Conversation so far (most recent last):
{history}
Latest user message:
{user_text}
Return ONE JSON object, no prose:
{
"standalone_query": "<self-contained question; resolve pronouns like 'it',
'that one', 'the cheaper plan' and ellipsis like 'and for contractors?'
using the conversation. If the message is already standalone, return it
unchanged>",
"route": "retrieve" | "chat" | "meta" | "clarify",
"is_follow_up": true | false,
"clarification": null | "<one short question to ask, only when route is clarify>",
"missing_slots": ["<slot>", ...],
"sticky_filters": {},
"entities": {}
}
Route meanings:
- "retrieve": the user wants information from the document library.
- "chat": greeting, thanks, small talk, or a general-knowledge question that
needs no documents.
- "meta": about THIS conversation itself (summarize it, "what did I ask
earlier?", "go back to the pricing question").
- "clarify": too ambiguous to act on; ask exactly one short question.
"sticky_filters" holds durable constraints the user set for the rest of the
conversation (e.g. {"region": "EU"} after "only show me EU docs"); use {} when
none. "entities" maps slot names to values established this turn (e.g.
{"product": "Pulse VPN"}); use {} when none.
"""
_DECODER = json.JSONDecoder()
def _extract_json_object(text: str) -> dict | None:
"""A plausible top-level JSON object in `text`.
Simplified vs 03.4 §1.2's collect-all extractor: we take the first
object, but prefer one that looks like condense output (has 'route'
or 'standalone_query') when the model emits several. If your model
chatters, port 03.4's collect-all-and-let-the-schema-choose version."""
fallback = None
pos = text.find("{")
while pos != -1:
try:
value, _ = _DECODER.raw_decode(text, pos)
except json.JSONDecodeError:
pos = text.find("{", pos + 1)
continue
if isinstance(value, dict):
if "route" in value or "standalone_query" in value:
return value
if fallback is None:
fallback = value
pos = text.find("{", pos + 1)
return fallback
def _as_bool(value: Any) -> bool:
"""Strict coercion for the follow-up flag. bool("false") is True —
the classic trap — so only real booleans and unambiguous 'true'-style
strings count; anything else falls back to False (no carry-forward)."""
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.strip().lower() in {"true", "yes", "1"}
if isinstance(value, int): # bool handled above (bool is int)
return value != 0
return False
def _as_dict(value: Any) -> dict:
"""Accept a real object, or a string containing one — models sometimes
emit '{"region": "EU"}' as a *string*. Anything else -> {}."""
if isinstance(value, dict):
return dict(value)
if isinstance(value, str):
try:
parsed = json.loads(value)
except json.JSONDecodeError:
return {}
return dict(parsed) if isinstance(parsed, dict) else {}
return {}
def parse_condense(raw: str, user_text: str) -> CondenseResult:
"""Validate the model's JSON. On ANY failure fall back to 'treat the raw
message as a standalone retrieval question' — condense never blocks a
turn. Every field is coerced to its declared type: untrusted model
output routinely arrives with 'false' where a boolean belongs, a bare
string where a list belongs, or an object where a string belongs."""
data = _extract_json_object(raw) or {}
route_raw = data.get("route")
route = (route_raw.strip().lower()
if isinstance(route_raw, str) else "")
if route not in ROUTES:
route = "retrieve"
sq = data.get("standalone_query")
standalone = sq.strip() if isinstance(sq, str) and sq.strip() else user_text
clar = data.get("clarification")
clarification = (clar.strip()
if isinstance(clar, str) and clar.strip() else None)
missing_raw = data.get("missing_slots")
missing = ([str(s) for s in missing_raw]
if isinstance(missing_raw, list) else [])
return CondenseResult(
standalone_query=standalone, route=route,
is_follow_up=_as_bool(data.get("is_follow_up")),
clarification=clarification,
missing_slots=missing,
sticky_filters=_as_dict(data.get("sticky_filters")),
entities=_as_dict(data.get("entities")),
raw=data)
def condense(session: SessionState, user_text: str, llm: LLM) -> CondenseResult:
hist = "\n".join(session.history_lines()) or "(no earlier turns)"
prompt = (CONDENSE_PROMPT
.replace("{history}", hist)
.replace("{user_text}", user_text))
try:
raw = llm(prompt)
except Exception:
raw = ""
return parse_condense(raw or "", user_text)
# --------------------------------------------------------------------------
# The trivial-turn fast path
# --------------------------------------------------------------------------
_TRIVIAL_RE = re.compile(
r"^\s*(hi+|hello+|hey+|yo|hiya|howdy|thanks?|thank you|thx|"
r"bye+|goodbye|see you|good (morning|afternoon|evening)|"
r"what'?s up)\s*[.!]*\s*$",
re.IGNORECASE,
)
def is_trivial(user_text: str, session: SessionState) -> bool:
"""Obvious greetings/acks skip BOTH condense and retrieval. Deliberately
conservative: 'ok', 'yes', 'sure' are NOT here — they can be real answers
to a pending question. Never fires while a clarification is open."""
return (not session.pending_clarification
and bool(_TRIVIAL_RE.match(user_text)))
# --------------------------------------------------------------------------
# Filters, cache, carry-forward
# --------------------------------------------------------------------------
_TENANT_KEYS = ("tenant", "acl", "user_id") # never settable by model output
def effective_filters(session: SessionState, plan_filters: dict,
required: dict | None = None) -> dict:
"""Sticky filters are defaults; per-turn plan filters override them;
tenant/ACL keys can never come from model output — `tenant` is forced
from session.tenant, and `required` (the acl/user_id filters your auth layer
computed for THIS request) is applied last, after the model's keys are
stripped. Stripping alone is not protection: it removes the model's `acl`
but supplies none, so a deployment that filters on acl must pass `required`."""
merged = {k: v for k, v in session.sticky_filters.items()}
merged.update(plan_filters or {})
for key in _TENANT_KEYS:
merged.pop(key, None)
if session.tenant:
merged["tenant"] = session.tenant
merged.update(required or {})
return merged
def _canon_filters(filters: dict) -> dict:
out = {}
for k in sorted(filters):
v = filters[k]
out[k] = sorted(v) if isinstance(v, (list, tuple, set)) else v
return out
def cache_key(query: str, filters: dict) -> str:
return json.dumps({"q": " ".join(query.lower().split()),
"f": _canon_filters(filters)}, sort_keys=True)
def _cache_get(session: SessionState, key: str, clock, ttl: float):
"""Returns (hits, carried_ids, hit?). carried_ids are stored in the
entry so a cache-hit TurnRecord keeps the same carry-forward audit
trail as the turn that populated it."""
e = session.cache.get(key)
if e and clock() - e["ts"] <= ttl:
return e["hits"], e.get("carried", []), True
return None, [], False
def _cache_put(session: SessionState, key: str, hits: list[dict],
carried_ids: list[str], clock,
max_entries: int = 64) -> None:
if len(session.cache) >= max_entries:
oldest = min(session.cache, key=lambda k: session.cache[k]["ts"])
session.cache.pop(oldest, None)
session.cache[key] = {"hits": hits, "carried": carried_ids, "ts": clock()}
def carry_forward(session: SessionState, fresh: list[dict], is_follow_up: bool,
max_extra: int) -> tuple[list[dict], list[str]]:
"""Last turn's hits still relevant to a follow-up, appended AFTER fresh
results. Scores aren't comparable across queries, so carried hits are
never re-ranked by stale scores — they're a recall hedge, not a ranking."""
if not is_follow_up or max_extra <= 0:
return [], []
have = {h["id"] for h in fresh}
carried, ids = [], []
for h in session.recent_hits:
if h["id"] not in have and len(carried) < max_extra:
carried.append(h)
ids.append(h["id"])
have.add(h["id"])
return carried, ids
# --------------------------------------------------------------------------
# Meta route and follow-up suggestions
# --------------------------------------------------------------------------
_SUMMARY_RE = re.compile(
r"summar|recap|what did (we|i) (talk|discuss|cover)|so far|catch me up",
re.IGNORECASE)
_GO_BACK_RE = re.compile(
r"go back|back to|return to|previous question|earlier question|"
r"last question|where were we",
re.IGNORECASE)
_GO_BACK_STOPWORDS = {
"back", "return", "previous", "earlier", "question", "topic", "that",
"this", "what", "were", "was", "about", "have", "just", "going"}
def _referenced_turn(session: SessionState,
user_text: str) -> TurnRecord | None:
"""'Go back to the pricing question' -> the TurnRecord it refers to.
Content-word overlap against each past turn's raw + standalone text;
best score wins, ties go to the most recent turn. Returns None when
nothing matches — meta answers must never guess at navigation."""
words = {w for w in re.findall(r"[a-z]{4,}", user_text.lower())}
words -= _GO_BACK_STOPWORDS
if not words:
return None
scored = []
for t in session.turns:
hay = f"{t.user_text} {t.standalone_query}".lower()
score = sum(1 for w in words if w in hay)
if score:
scored.append((score, t.index))
if not scored:
return None
scored.sort(key=lambda x: (-x[0], -x[1]))
return session.turns[scored[0][1]]
def _fallback_summary(session: SessionState) -> str:
topics = [t.standalone_query for t in session.turns[-6:]
if t.standalone_query]
if not topics:
return "This is the start of our conversation — nothing to recap yet."
return "We discussed: " + "; ".join(topics)
def meta_answer(session: SessionState, user_text: str, llm: LLM) -> str:
"""'Meta' turns are answered from the session record, never the corpus."""
if _GO_BACK_RE.search(user_text):
t = _referenced_turn(session, user_text)
if t is None:
return ("I couldn't find an earlier question matching that — "
"name the topic and I'll find it "
"(e.g. 'go back to the pricing question').")
return (f"Back to turn {t.index + 1} — \"{t.user_text}\":\n\n"
f"{t.answer_text}\n\n"
f"(Its {len(t.hits)} source chunk(s) are still on the "
"turn record if you want to revisit them.)")
if _SUMMARY_RE.search(user_text):
digest = "\n".join(
f"Q: {t.user_text}\nA: {t.answer_text[:300]}"
for t in session.turns[-10:])
prompt = ("Summarize this conversation so far in 3-5 bullet points. "
"Keep decisions, named entities and open questions.\n\n"
+ digest)
try:
return llm(prompt).strip() or _fallback_summary(session)
except Exception:
return _fallback_summary(session)
topics = [t.standalone_query for t in session.turns[-5:]
if t.standalone_query]
if topics:
return ("Earlier you asked about:\n"
+ "\n".join(f"- {q}" for q in topics))
return "This is the start of our conversation — nothing earlier to recap."
FOLLOWUP_PROMPT = """\
Suggest 3 short follow-up questions the user might ask next about this
answer, answerable from the same document library. One per line, no
numbering, under 12 words each.
Answer: {answer}
Follow-ups:"""
def suggest_followups(answer_text: str, llm: LLM, limit: int = 3) -> list[str]:
try:
raw = llm(FOLLOWUP_PROMPT.replace("{answer}", answer_text[:1500]))
except Exception:
return []
lines = []
for l in (raw or "").splitlines():
# strip bullets AND numbering — the prompt says "no numbering" but
# models add "1." anyway, and it would leak into the UI chips
l = re.sub(r"^\s*(?:[-*•]\s*|\d+[.)]\s+)", "", l).strip()
if l and not l.startswith(("{", "[")):
lines.append(l)
return lines[:limit]
# --------------------------------------------------------------------------
# Context assembly handed to the generator
# --------------------------------------------------------------------------
def session_block(session: SessionState) -> str:
"""The pinned 'where we are' block sent to the generator each turn."""
parts = []
if session.entities:
parts.append("Known entities: " + ", ".join(
f"{k}={v}" for k, v in session.entities.items()))
if session.sticky_filters:
parts.append("Active filters: " + json.dumps(
session.sticky_filters, ensure_ascii=False))
if session.summary:
parts.append("Earlier conversation summary: " + session.summary)
return "\n".join(parts)
def history_messages(session: SessionState, max_turns: int = 8,
max_answer_chars: int = 1500) -> list[dict]:
"""Generation-side history in provider message shape. Assistant text is
capped — uncapped answers would re-flood the window, the failure 4.5
warns about. Production wraps this with 04.7's ConversationManager,
which budgets by tokens rather than characters."""
msgs = []
for t in session.turns[-max_turns:]:
msgs.append({"role": "user", "content": t.user_text})
if t.answer_text:
msgs.append({"role": "assistant",
"content": t.answer_text[:max_answer_chars]})
return msgs
def render_minimal_answer_prompt(req: GenerationRequest) -> str:
"""Placeholder grounding prompt — production uses 07.4's generate.py,
which owns prompt wording, sufficiency checks and answer schemas."""
ctx = "\n\n".join(
f"[{i}] {h.get('title') or h.get('id')}\n{h.get('text', '')}"
for i, h in enumerate(req.context_hits, 1))
hist = "\n".join(f"{m['role']}: {m['content']}" for m in req.history)
return (f"{req.session_block}\n\nConversation:\n{hist}\n\n"
f"Retrieved documents:\n{ctx}\n\nQuestion: {req.question}\n\n"
"Answer using only the retrieved documents. If they don't "
"contain the answer, say so. Cite sources as [n].")
def grounded_generator(generate_answer_fn: Callable, llm_fn: Callable,
*, history_turns: int = 6, **gen_kwargs) -> Generator:
"""Adapt 07.4's `generate_answer` to this pipeline's `generate=` seam.
Bridges the three mismatches between GenerationRequest and
generate_answer(query, hits, llm, ...) -> GenerationResult:
* context_hits are *serialized dicts* (what TurnRecords store);
generate_answer's HitLike protocol wants attributes -> wrap each
in SimpleNamespace.
* generate_answer has no history/session_block parameters -> recent
history is injected as real messages inside a wrapped llm_fn and
session_block is appended to the system message, keeping `question`
pure for the sufficiency/coverage gates.
* It returns a GenerationResult, not text -> flatten to
GroundedAnswer.answer; the full result stays on
`adapter.last_result` for status/eval inspection (07.4's edge
mapping turns it into Answer.text/abstained/citations).
"""
def _gen(req: GenerationRequest) -> str:
hist = [{"role": m["role"], "content": m["content"][:400]}
for m in req.history[-history_turns * 2:]]
hits = [SimpleNamespace(**h) for h in req.context_hits]
def conv_llm(messages: list[dict]) -> str:
msgs = [dict(m) for m in messages]
if req.session_block:
if msgs and msgs[0].get("role") == "system":
msgs[0]["content"] += "\n\n" + req.session_block
else:
msgs.insert(0, {"role": "user",
"content": "Session context:\n"
+ req.session_block})
if hist and msgs:
msgs = msgs[:-1] + hist + msgs[-1:]
return llm_fn(msgs)
res = generate_answer_fn(req.question, hits, conv_llm, **gen_kwargs)
_gen.last_result = res
ans = getattr(res, "answer", None)
text = getattr(ans, "answer", "") or ""
if not text:
status = getattr(ans, "status", "")
if status == "abstained":
text = ("I don't have enough information in the retrieved "
"documents to answer that.")
elif status == "needs_clarification":
text = "Could you clarify what you'd like to know?"
return text
_gen.last_result = None
return _gen
# --------------------------------------------------------------------------
# The turn pipeline
# --------------------------------------------------------------------------
def handle_turn(store, session_id: str, user_text: str, *,
user_ref: str = "", tenant: str | None = None,
retriever: Retriever, llm: LLM,
planner: Planner | None = None,
generate: Generator | None = None,
k: int = 6, carry_max: int = 3, cache_ttl: float = 1800.0,
suggest: bool = True, condense_enabled: bool = True,
required_filters: dict | None = None,
clock=time.time) -> TurnOutcome:
session = store.get(session_id)
if session is None:
session = SessionState(session_id=session_id, user_ref=user_ref,
tenant=tenant, created_at=clock(),
updated_at=clock())
elif tenant != session.tenant or user_ref != session.user_ref:
# A session id is a lookup key, not proof of identity: never serve
# one caller's conversation (and its retrieved chunks) to another.
# The caller must present exactly the identity the session was created
# with, on EVERY turn. Omitting tenant or user_ref is a mismatch, not a
# pass: a check that is skipped when the argument is missing can be
# bypassed by leaving the argument out.
raise PermissionError("session belongs to a different user or tenant")
session.updated_at = clock()
# 1. Condense (or fast-path / bypass).
cr: CondenseResult | None = None
if is_trivial(user_text, session):
route, standalone = "chat", user_text
elif not condense_enabled:
route, standalone = "retrieve", user_text
cr = CondenseResult(standalone_query=user_text)
else:
cr = condense(session, user_text, llm)
route, standalone = cr.route, cr.standalone_query
session.entities.update(cr.entities)
for key, value in cr.sticky_filters.items():
if value in (None, "", {}):
session.sticky_filters.pop(key, None) # escape hatch
else:
session.sticky_filters[key] = value
# 2. Route dispatch.
hits: list[dict] = []
hit_ids: list[str] = []
source_map: list[dict] = []
filters_used: dict = {}
cache_hit = False
carried_ids: list[str] = []
answer_text = ""
followups: list[str] = []
if route == "clarify":
answer_text = (cr.clarification if cr else None) or (
"Could you tell me a bit more about what you're looking for?")
elif route == "meta":
answer_text = meta_answer(session, user_text, llm)
else:
# retrieve or chat
query, plan_filters = standalone, {}
if route == "retrieve" and planner is not None:
plan = planner(standalone, session)
if not isinstance(plan, PlanResult):
plan = plan_result_from_query_plan(plan, standalone)
query = plan.query or standalone
plan_filters = plan.filters
if plan.route == "clarify" or plan.clarification:
route = "clarify"
answer_text = plan.clarification or (
"Could you tell me a bit more about what you're "
"looking for?")
elif plan.route == "chat":
route = "chat"
if route == "retrieve":
filters_used = effective_filters(session, plan_filters,
required_filters)
ck = cache_key(query, filters_used)
cached, cached_carried, cache_hit = _cache_get(
session, ck, clock, cache_ttl)
if cached is not None:
served = cached
carried_ids = cached_carried # same audit trail
else:
fresh = [serialize_hit(h) for h in
retriever.search(query, k=k, filters=filters_used)]
carried, carried_ids = carry_forward(
session, fresh, bool(cr and cr.is_follow_up), carry_max)
served = fresh + carried
_cache_put(session, ck, served, carried_ids, clock)
hits = served
hit_ids = [h["id"] for h in hits]
source_map = [{"label": f"[{i}]", "chunk_id": h["id"],
"title": h["metadata"].get("title") or h["id"]}
for i, h in enumerate(hits, 1)]
session.recent_hits = hits
if route != "clarify":
req = GenerationRequest(
route=route, question=standalone, context_hits=hits,
history=history_messages(session),
session_block=session_block(session), source_map=source_map)
gen = generate or (lambda r: llm(render_minimal_answer_prompt(r)))
answer_text = (gen(req) or "").strip()
if suggest and route == "retrieve":
followups = suggest_followups(answer_text, llm)
record = TurnRecord(
index=len(session.turns), user_text=user_text,
standalone_query=standalone, route=route, answer_text=answer_text,
hits=hits, hit_ids=hit_ids, source_map=source_map,
filters_used=filters_used, cache_hit=cache_hit,
carried_hit_ids=carried_ids, followups=followups, created_at=clock())
session.turns.append(record)
store.put(session)
return TurnOutcome(
session_id=session_id, route=route, answer_text=answer_text,
standalone_query=standalone, hit_ids=hit_ids, cache_hit=cache_hit,
carried_hit_ids=carried_ids, followups=followups,
clarification_pending=route == "clarify")
# --------------------------------------------------------------------------
# Session stores
# --------------------------------------------------------------------------
class SessionStore(Protocol):
def get(self, session_id: str) -> SessionState | None: ...
def put(self, session: SessionState) -> None: ...
def delete(self, session_id: str) -> None: ...
class InMemorySessionStore:
def __init__(self) -> None:
self._sessions: dict[str, SessionState] = {}
def get(self, session_id: str) -> SessionState | None:
return self._sessions.get(session_id)
def put(self, session: SessionState) -> None:
self._sessions[session.session_id] = session
def delete(self, session_id: str) -> None:
self._sessions.pop(session_id, None)
def _turn_to_dict(t: TurnRecord) -> dict:
return {"index": t.index, "user_text": t.user_text,
"standalone_query": t.standalone_query, "route": t.route,
"answer_text": t.answer_text, "hits": t.hits,
"hit_ids": t.hit_ids, "source_map": t.source_map,
"filters_used": t.filters_used, "cache_hit": t.cache_hit,
"carried_hit_ids": t.carried_hit_ids, "followups": t.followups,
"created_at": t.created_at}
def _turn_from_dict(d: dict) -> TurnRecord:
return TurnRecord(**d)
def session_to_dict(s: SessionState) -> dict:
return {"session_id": s.session_id, "user_ref": s.user_ref,
"tenant": s.tenant, "created_at": s.created_at,
"updated_at": s.updated_at, "sticky_filters": s.sticky_filters,
"entities": s.entities, "summary": s.summary,
"turns": [_turn_to_dict(t) for t in s.turns],
"cache": s.cache, "recent_hits": s.recent_hits}
def session_from_dict(d: dict) -> SessionState:
return SessionState(
session_id=d["session_id"], user_ref=d.get("user_ref", ""),
tenant=d.get("tenant"), created_at=d.get("created_at", 0.0),
updated_at=d.get("updated_at", 0.0),
sticky_filters=d.get("sticky_filters", {}),
entities=d.get("entities", {}), summary=d.get("summary", ""),
turns=[_turn_from_dict(t) for t in d.get("turns", [])],
cache=d.get("cache", {}), recent_hits=d.get("recent_hits", []))
class JsonFileSessionStore:
"""One JSON file per session; writes are atomic (tmp + replace) so a
crash mid-write can't corrupt a session. Resume = same session_id."""
def __init__(self, directory: str | Path) -> None:
self.dir = Path(directory)
self.dir.mkdir(parents=True, exist_ok=True)
def _path(self, session_id: str) -> Path:
safe = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id)
return self.dir / f"{safe}.json"
def get(self, session_id: str) -> SessionState | None:
p = self._path(session_id)
if not p.exists():
return None
return session_from_dict(json.loads(p.read_text(encoding="utf-8")))
def put(self, session: SessionState) -> None:
p = self._path(session.session_id)
tmp = p.with_name(p.name + ".tmp")
tmp.write_text(json.dumps(session_to_dict(session),
ensure_ascii=False, indent=2),
encoding="utf-8")
tmp.replace(p)
def delete(self, session_id: str) -> None:
self._path(session_id).unlink(missing_ok=True)
def new_session_id() -> str:
return uuid.uuid4().hex7.3 Tests and a scripted demo#
conversation_demo.py — printed in full below; save it in the project root next to docs_qa/ and run python3 conversation_demo.py — runs the real pipeline against fakes: a keyword-overlap FakeRetriever, a FakeLLM that answers condense prompts by exact latest-message match, and a JsonFileSessionStore in a temp dir. The "model outputs" are canned; everything else is real code. It walks an eight-turn session — standalone question → elliptical follow-up → topic switch → trivial turn → meta question → clarify → slot answer → resume-from-disk — then runs 15 checks covering the pipeline mechanics, the parse fallbacks and the QueryPlan adapter.
"""conversation_demo.py — FakeLLM + FakeRetriever + a scripted session.
Runs the real docs_qa/conversation.py pipeline end to end with no API keys.
The 'model outputs' are canned; everything else is real code.
"""
import json
import re
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path
HERE = Path(__file__).parent
# works from the project root (next to docs_qa/) or from inside docs_qa/
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE / "docs_qa"))
from conversation import (JsonFileSessionStore, handle_turn, parse_condense,
session_from_dict, session_to_dict,
effective_filters, plan_result_from_query_plan,
SessionState)
@dataclass
class FakeHit:
id: str
score: float
text: str = ""
metadata: dict = None
source: str = "toy"
CORPUS = {
"parental": FakeHit("hb-101", 0.91, "Parental leave is 26 weeks fully paid "
"for employees with 12+ months service.",
{"title": "Leave policy", "doc_type": "handbook"}),
"contractor": FakeHit("hb-102", 0.88, "Contractors accrue 10 days of paid "
"leave per year, no notice period.",
{"title": "Leave policy", "doc_type": "handbook"}),
"expense": FakeHit("hb-201", 0.90, "Expense claims are capped at $50/day "
"for meals; receipts required over $25.",
{"title": "Expenses", "doc_type": "handbook"}),
"refund": FakeHit("cs-301", 0.86, "Refunds are issued within 5 working "
"days to the original payment method.",
{"title": "Support FAQ", "doc_type": "helpcentre"}),
}
class FakeRetriever:
"""Keyword-overlap stand-in for a real Retriever (06.10 contract)."""
def __init__(self):
self.calls = []
def search(self, query, k=10, filters=None):
self.calls.append({"query": query, "filters": filters})
words = set(query.lower().split())
scored = []
for hid, hit in CORPUS.items():
overlap = len(words & set(hit.text.lower().split()))
if filters and filters.get("tenant") not in (None, "acme"):
continue
scored.append((overlap, hit))
scored.sort(key=lambda x: -x[0])
return [h for n, h in scored[:k] if n > 0] or [CORPUS["parental"]]
def condense_json(sq, route="retrieve", follow=False, clar=None,
sticky=None, ents=None):
return json.dumps({
"standalone_query": sq, "route": route, "is_follow_up": follow,
"clarification": clar, "missing_slots": [],
"sticky_filters": sticky or {}, "entities": ents or {}})
class FakeLLM:
"""Deterministic stand-in. Condense prompts are matched on the EXACT
latest user message (extracted between the markers), so history text
can't collide with the key. Everything else uses substring rules."""
CONDENSE = {
"What is the parental leave policy?":
condense_json("What is the parental leave policy?"),
"And for contractors?":
condense_json("What is the parental leave policy for contractors?",
follow=True, ents={"audience": "contractors"}),
"What about expenses?":
condense_json("What is the expense claim policy?", follow=False),
"how many weeks was that again?":
condense_json("How many weeks of parental leave are there?",
follow=True),
"which product did you mean?":
condense_json("tell me about it", route="clarify",
clar="Which product did you mean — Pro or Enterprise?"),
"the Pro plan":
condense_json("Pro plan parental leave policy", follow=True,
ents={"product": "Pro plan"}),
"Can you summarise what we've covered?":
condense_json("summarise the conversation", route="meta"),
}
def __init__(self):
self.calls = []
def __call__(self, prompt):
self.calls.append(prompt)
m = re.search(r"Latest user message:\n(.*?)\n\nReturn ONE JSON",
prompt, flags=re.S)
if m:
return self.CONDENSE.get(m.group(1).strip(), "{}")
if "Summarize this conversation" in prompt:
return ("- Asked about parental leave\n- Moved to expenses\n"
"- Open: refund timing")
if "Suggest 3 short follow-up" in prompt:
return ("Does it apply to part-timers?\nWhat's the notice period?\n"
"How is leave accrued?")
if "Answer using only the retrieved documents" in prompt:
return "Grounded answer citing [1]."
return "(no canned reply)"
def main():
tmp = tempfile.mkdtemp(prefix="docsqa-sessions-")
store = JsonFileSessionStore(tmp)
retriever = FakeRetriever()
llm = FakeLLM()
sid = "sess-demo-1"
# The identity your auth layer produced. It must accompany EVERY turn: a call
# without it is refused for an existing session.
AUTH = dict(user_ref="u-42", tenant="acme")
print("=== turn 1: standalone question ===")
o1 = handle_turn(store, sid, "What is the parental leave policy?",
**AUTH, retriever=retriever, llm=llm, suggest=False)
print(f"route={o1.route} hits={o1.hit_ids} answer={o1.answer_text!r}")
print("\n=== turn 2: elliptical follow-up ===")
o2 = handle_turn(store, sid, "And for contractors?",
**AUTH, retriever=retriever, llm=llm, suggest=False)
print(f"route={o2.route} standalone={o2.standalone_query!r}")
print(f"hits={o2.hit_ids} carried={o2.carried_hit_ids} cache_hit={o2.cache_hit}")
print("\n=== turn 3: topic switch ===")
o3 = handle_turn(store, sid, "What about expenses?",
**AUTH, retriever=retriever, llm=llm, suggest=False)
print(f"route={o3.route} standalone={o3.standalone_query!r} hits={o3.hit_ids}")
print(f"carried={o3.carried_hit_ids} (empty = fresh retrieval only)")
print("\n=== turn 4: trivial turn (zero condense/retrieval calls) ===")
n_retr, n_llm = len(retriever.calls), len(llm.calls)
o4 = handle_turn(store, sid, "thanks!", **AUTH, retriever=retriever, llm=llm,
suggest=False)
print(f"route={o4.route} answer={o4.answer_text!r}")
print(f"retriever calls {n_retr}->{len(retriever.calls)}, "
f"llm calls {n_llm}->{len(llm.calls)} (answer call only)")
retriever_calls_after_t4 = len(retriever.calls)
print("\n=== turn 5: meta question ===")
o5 = handle_turn(store, sid, "Can you summarise what we've covered?",
**AUTH, retriever=retriever, llm=llm, suggest=False)
print(f"route={o5.route} answer={o5.answer_text!r}")
print("\n=== turn 6: clarify route ===")
o6 = handle_turn(store, sid, "which product did you mean?",
**AUTH, retriever=retriever, llm=llm, suggest=False)
print(f"route={o6.route} pending={o6.clarification_pending}")
print(f"answer={o6.answer_text!r}")
print("\n=== turn 7: slot answer resumes intent ===")
o7 = handle_turn(store, sid, "the Pro plan", **AUTH, retriever=retriever,
llm=llm, suggest=False)
print(f"route={o7.route} standalone={o7.standalone_query!r}")
print(f"entities={store.get(sid).entities}")
print("\n=== resume: new store instance, same session file ===")
store2 = JsonFileSessionStore(tmp)
s = store2.get(sid)
print(f"turns restored: {len(s.turns)}, tenant={s.tenant}, "
f"recent_hits={len(s.recent_hits)}")
o8 = handle_turn(store2, sid, "how many weeks was that again?",
**AUTH, retriever=retriever, llm=llm, suggest=False)
print(f"route={o8.route} hits={o8.hit_ids} cache_hit={o8.cache_hit}")
print("\n=== checks ===")
checks = []
checks.append(("t2 follow-up standalone rewritten",
"contractors" in o2.standalone_query))
checks.append(("t3 topic switch carried nothing",
o3.carried_hit_ids == []))
checks.append(("t4 trivial: no retrieval",
retriever_calls_after_t4 == n_retr))
checks.append(("t5 meta route", o5.route == "meta"))
checks.append(("t6 clarify pending", o6.clarification_pending))
checks.append(("t7 slot filled entities",
store.get(sid).entities.get("product") == "Pro plan"))
checks.append(("resume restored turns", len(s.turns) == 7))
sess = SessionState(session_id="x", tenant="acme",
sticky_filters={"region": "EU"})
f = effective_filters(sess, {"region": "US", "tenant": "other"})
checks.append(("tenant forced to acme", f.get("tenant") == "acme"))
checks.append(("plan filter overrides sticky", f.get("region") == "US"))
f2 = effective_filters(sess, {"acl": "everyone"}, {"acl": "staff"})
checks.append(("model acl stripped, auth acl applied", f2.get("acl") == "staff"))
for who, kwargs in (("other tenant", dict(user_ref="u-42", tenant="globex")),
("other user", dict(user_ref="u-99", tenant="acme")),
("no identity at all", {})):
try:
handle_turn(store2, sid, "hello", retriever=retriever, llm=llm,
suggest=False, **kwargs)
refused = False
except PermissionError:
refused = True
checks.append((f"session refused: {who}", refused))
bad = parse_condense("not json at all", "hello there")
checks.append(("parse fallback -> retrieve+raw text",
bad.route == "retrieve"
and bad.standalone_query == "hello there"))
# wrong-typed fields must degrade to safe defaults, not mis-parse
bad_bool = parse_condense(
'{"standalone_query": "x", "route": "retrieve", '
'"is_follow_up": "false", "missing_slots": "product"}', "u")
checks.append(("condense: 'false' string -> is_follow_up False",
bad_bool.is_follow_up is False
and bad_bool.missing_slots == []))
bad_clar = parse_condense(
'{"route": "clarify", "clarification": {"q": "which?"}}', "u")
checks.append(("condense: dict clarification dropped",
bad_clar.clarification is None))
# a 07.3 QueryPlan-shaped dict adapts through the planner seam
plan = plan_result_from_query_plan(
{"route": "skip_retrieval", "cleaned": "hi there",
"rewrites": ["hi there"], "original": "hi there",
"filters": {"doc_type": ["handbook"], "topic_hint": "leave",
"year": 2025}},
"fallback")
checks.append(("queryplan: skip_retrieval -> chat, hint/year dropped",
plan.route == "chat" and plan.query == "hi there"
and plan.filters == {"doc_type": ["handbook"]}))
plan2 = plan_result_from_query_plan(
{"route": "clarify", "clarification": "which product?",
"cleaned": "tell me about it"}, "fallback")
checks.append(("queryplan: clarify honoured",
plan2.route == "clarify"
and plan2.clarification == "which product?"))
rt = session_from_dict(session_to_dict(s))
checks.append(("json round-trip turns", len(rt.turns) == len(s.turns)))
for name, ok in checks:
print(f" {'PASS' if ok else 'FAIL'} {name}")
print(f"\n{sum(1 for _, ok in checks if ok)}/{len(checks)} checks passed")
if __name__ == "__main__":
main()Real output (python3 conversation_demo.py):
=== turn 1: standalone question ===
route=retrieve hits=['hb-101', 'hb-102', 'cs-301'] answer='Grounded answer citing [1].'
=== turn 2: elliptical follow-up ===
route=retrieve standalone='What is the parental leave policy for contractors?'
hits=['hb-101', 'hb-102', 'hb-201', 'cs-301'] carried=[] cache_hit=False
=== turn 3: topic switch ===
route=retrieve standalone='What is the expense claim policy?' hits=['hb-101', 'hb-201', 'cs-301']
carried=[] (empty = fresh retrieval only)
=== turn 4: trivial turn (zero condense/retrieval calls) ===
route=chat answer='Grounded answer citing [1].'
retriever calls 3->3, llm calls 6->7 (answer call only)
=== turn 5: meta question ===
route=meta answer='- Asked about parental leave\n- Moved to expenses\n- Open: refund timing'
=== turn 6: clarify route ===
route=clarify pending=True
answer='Which product did you mean — Pro or Enterprise?'
=== turn 7: slot answer resumes intent ===
route=retrieve standalone='Pro plan parental leave policy'
entities={'audience': 'contractors', 'product': 'Pro plan'}
=== resume: new store instance, same session file ===
turns restored: 7, tenant=acme, recent_hits=4
route=retrieve hits=['hb-101', 'hb-102', 'hb-201', 'cs-301'] cache_hit=False
=== checks ===
PASS t2 follow-up standalone rewritten
PASS t3 topic switch carried nothing
PASS t4 trivial: no retrieval
PASS t5 meta route
PASS t6 clarify pending
PASS t7 slot filled entities
PASS resume restored turns
PASS tenant forced to acme
PASS plan filter overrides sticky
PASS model acl stripped, auth acl applied
PASS session refused: other tenant
PASS session refused: other user
PASS session refused: no identity at all
PASS parse fallback -> retrieve+raw text
PASS condense: 'false' string -> is_follow_up False
PASS condense: dict clarification dropped
PASS queryplan: skip_retrieval -> chat, hint/year dropped
PASS queryplan: clarify honoured
PASS json round-trip turns
19/19 checks passedThe demo proves the mechanics end to end: the follow-up was rewritten into a standalone query, the topic switch carried nothing forward, the trivial turn made zero retrieval calls (and only one generation call), the meta question never touched the index, the clarify route set pending_clarification and the next message filled the slot into entities, a fresh store instance resumed the session from disk, and effective_filters proved the tenant can't be overridden by model-produced filters.
For unit tests, the same fakes work with InMemorySessionStore and pytest-free asserts — every check above is a plain assert you can lift into a test_*.py. The injectable seams are what make this testable without keys (03.10): FakeLLM replaces the provider, FakeRetriever replaces the index, and clock= makes TTL tests deterministic.
7.4 Wiring to providers (illustrative)#
Nothing in conversation.py is provider-specific — the seams absorb the differences. The hosted wiring is a thin adapter per provider, exactly the 03.4 conventions:
# glue.py — ILLUSTRATIVE: needs provider keys in .env.
# Wraps each provider's structured-output call as the `llm`/`generate` seams.
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
# The condense/meta/follow-up calls are small structured-output calls.
# OpenAI Responses: text.format with a JSON schema (03.4).
def openai_llm(prompt: str) -> str:
client = OpenAI()
r = client.responses.create(
model="gpt-6-luna",
instructions="Reply with the requested JSON object only.",
input=prompt,
text={"format": {"type": "json_object"}},
max_output_tokens=400)
return r.output_text
# generate= wraps 07.4's generate_answer() — it returns a
# GenerationResult, so conversation.grounded_generator flattens it to
# text and injects history/session_block (see 7.1). planner= wraps
# 07.3's plan_query() — a real QueryPlan is adapted by
# plan_result_from_query_plan.
# Anthropic: messages.parse with output_config.format (same JSON contract).
# Gemini: response_json_schema + model_validate_json (same contract).
# OpenRouter: chat.completions.parse through the openai SDK base_url.
# The four adapters differ only in HOW structured output is requested —
# the CondenseResult/PlanResult/answer contracts are identical (03.4, 03.11).Example output (illustrative — your exact output will differ): a real openai_llm("And for contractors?…") returns the same JSON shape the FakeLLM canned above, with standalone_query resolved against the real history.
7.5 What the code refuses to do#
The pipeline's guardrails are deliberate omissions:
- Condense failure never blocks a turn —
parse_condensefalls back to raw-text retrieval. - Model output can't set tenant/ACL filters —
effective_filtersstrips those keys before merging. - Sticky filters have an escape hatch —
null/""/{}clears a key. - The retrieval cache is TTL'd and bounded — no immortal stale hits.
- Carried hits are never re-ranked by stale scores — they're appended, not merged into the ranking.
- Meta/chit-chat/clarify never touch the index — the route dispatch happens before retrieval.
- Planner output is normalised before use — a 07.3
QueryPlan(or dict) goes throughplan_result_from_query_plan; onlyPlanResultfields are ever read. is_trivialis conservative — ambiguous acks ("ok", "yes") still reach the model.
Part 8: Evaluating conversational RAG#
Single-turn eval (06.10, 07.9) asks "was this question answered well?". Conversational eval asks "did the conversation work?" — a harder question with three levels:
8.1 Multi-turn test sets#
A conversational test set is a list of scripted scenarios, each a sequence of user turns with per-turn expectations. Where single-turn sets have (query, qrels), conversational sets have (turns[], expectations[]):
# A scenario: three turns exercising a first question, a follow-up and a topic switch.
SCENARIO = {
"id": "leave-policy-followups",
"turns": [
{"user": "What is the parental leave policy?",
"expect": {"route": "retrieve"}},
{"user": "And for contractors?",
"expect": {"route": "retrieve",
"standalone_contains": ["contractors"],
"must_hit": ["hb-102"]}},
{"user": "What about expenses?",
"expect": {"route": "retrieve",
"standalone_contains": ["expense"],
"standalone_not_contains": ["contractors"],
"forbidden_hit": ["hb-102"]}}, # contractor chunk must NOT carry over
],
}Sources for scenarios: real session logs (anonymised), the Module 05 user simulators (a second model plays the user with a hidden goal — 8.4), and hand-written edge cases (corrections, ambiguous referents, mid-clarification answers). Stratify by the 1.2 taxonomy — a set that's all elliptical follow-ups won't catch topic-switch bugs.
8.2 Turn-level metrics#
Each turn produces a TurnRecord — score it against expectations before judging the prose:
| Metric | What it measures | How |
|---|---|---|
| Route accuracy | Did the turn take the right path? | record.route == expected.route |
| Condense quality | Is the standalone query faithful? | standalone_contains/standalone_not_contains checks; retrieval recall on the standalone query via the 06.10 harness |
| Retrieval recall@k per turn | Did the right chunks arrive? | must_hit/forbidden_hit on record.hit_ids — pure set membership, no LLM |
| Carry-forward precision | Did carried hits help or hurt? | Compare answer quality with carry on vs off (ablation) |
| Cache hit rate | Is the session cache paying off? | record.cache_hit fraction; also a cost metric |
| Filter correctness | Did tenant/sticky filters apply? | Inspect record.filters_used; the leak check from 06.10 applies |
| Clarification correctness | Did it ask when it should, infer when it shouldn't? | Expected clarify vs actual; count over- and under-clarification separately |
The beautiful property: every one of these is computable from TurnRecord fields with pure Python — no judge model needed for the retrieval-side metrics. The LLM-judge metrics (07.9) only enter for answer quality.
8.3 Conversation-level metrics#
Turn-level metrics can all pass while the conversation still fails — the user got each answer but never resolved their goal. Conversation-level metrics:
| Metric | Definition | Catches |
|---|---|---|
| Task success | Did the conversation reach the user's goal? (hidden goal, judged or checked) | The whole pipeline, not one stage |
| Turns-to-resolution | How many user turns to succeed | Clarification loops, bad rewrites, missing carry-forward |
| Contradiction rate | Does a later answer contradict an earlier one? | Compounding errors (04.7, 1.2) |
| Constraint/fact retention | Does turn 18 still honour what turn 2 established? | History trimming, sticky-filter loss — the 04.7 Part 12 probe pattern applied to RAG |
| Abstention appropriateness | Did it say "I don't know" when the corpus couldn't answer, across the whole conversation? | Over-eager retrieval forcing citations |
| Cost/latency per resolved task | Total tokens + wall time ÷ successes | The quadratic-history tax (02.7, 6.1) made visible |
8.4 User simulators#
The 10A.2 two-model pattern maps directly: the user simulator (cheap model + persona + hidden goal) drives handle_turn, your pipeline responds, and a goal checker scores whether the conversation succeeded. For conversational RAG the simulator's personas should specifically stress the 1.2 taxonomy: the elliptical follow-upper, the topic-switcher, the corrector, the ambiguous fragmenter. Run the same scenario set through simulator variants and diff the TurnRecord metrics — that's how you find whether a condense-prompt change helped conversations, not just queries.
8.5 The eval scaffold#
# conv_eval.py — score a scripted scenario against TurnRecords. Pure local.
from conversation import handle_turn, InMemorySessionStore
def run_scenario(scenario, retriever, llm, planner=None, generate=None,
tenant="acme"):
store = InMemorySessionStore()
sid = scenario["id"]
records = []
for turn in scenario["turns"]:
out = handle_turn(store, sid, turn["user"], tenant=tenant,
retriever=retriever, llm=llm,
planner=planner, generate=generate, suggest=False)
rec = store.get(sid).turns[-1]
records.append((turn, out, rec))
return records
def _as_list(value):
"""Expectations are lists; accept a bare string too. Without this a
string such as "hb-102" is iterated character by character."""
if value is None:
return []
return [value] if isinstance(value, str) else list(value)
def score(records):
"""Turn-level metrics from TurnRecords — no judge model needed."""
results = []
for turn, out, rec in records:
exp = turn.get("expect", {})
query = rec.standalone_query.lower()
checks = {
"route": rec.route == exp.get("route", rec.route),
"must_hit": all(h in rec.hit_ids
for h in _as_list(exp.get("must_hit"))),
"forbidden_hit": not any(h in rec.hit_ids
for h in _as_list(exp.get("forbidden_hit"))),
"standalone_contains": all(s.lower() in query
for s in _as_list(exp.get("standalone_contains"))),
"standalone_not_contains": not any(s.lower() in query
for s in _as_list(exp.get("standalone_not_contains"))),
}
results.append({"turn": turn["user"], "checks": checks,
"passed": all(checks.values())})
return resultsSave the SCENARIO dict from 8.1 as scenario.py, the scaffold above as conv_eval.py, and drive it with the fakes from 7.3 (same folder as conversation_demo.py, with docs_qa/conversation.py on the path):
# run_eval.py — drive the scaffold with the fakes from conversation_demo.py (7.3).
import sys
sys.path.insert(0, "docs_qa")
from conv_eval import run_scenario, score
from conversation_demo import FakeLLM, FakeRetriever
from scenario import SCENARIO
for row in score(run_scenario(SCENARIO, FakeRetriever(), FakeLLM())):
marks = " ".join(f"{k}={'PASS' if ok else 'FAIL'}" for k, ok in row["checks"].items())
print(f"{row['turn']!r}: {marks} -> {'PASS' if row['passed'] else 'FAIL'}")'What is the parental leave policy?': route=PASS must_hit=PASS forbidden_hit=PASS standalone_contains=PASS standalone_not_contains=PASS -> PASS
'And for contractors?': route=PASS must_hit=PASS forbidden_hit=PASS standalone_contains=PASS standalone_not_contains=PASS -> PASS
'What about expenses?': route=PASS must_hit=PASS forbidden_hit=PASS standalone_contains=PASS standalone_not_contains=PASS -> PASSAn expectation that is absent from a turn (for example must_hit on turn 3) passes trivially, so read a PASS as "no violation found", not as proof of quality. And note what the helper _as_list guards against: written as a bare string, "must_hit": "hb-102" would be iterated character by character and fail every time.
The scaffold is deliberately tiny: it proves the shape — scenarios in, TurnRecords out, expectations scored per turn — and every metric in 8.2–8.3 is one more key in expect or one more function beside score. Production versions add LLM judges for answer quality (07.9), confidence intervals over scenario repetitions, and CI gating (03.10).
Failure gallery#
The ways conversational RAG specifically fails — each row is a bug that ships silently:
| Failure | What you see | Root cause | Fix |
|---|---|---|---|
| Condense drift | Turn 8 retrieves documents about a topic corrected at turn 3 | Rewrite inherits stale entities; correction didn't update session.entities/history |
Entities merge before next condense; evals check standalone_not_contains for corrected terms |
| Stale carried chunks | Follow-up answer cites last topic's doc after user switched | is_follow_up true on a topic switch, or carry_max too high |
Tune the follow-up signal; ablate carry on vs off; cap carried count |
| History flooding the window | Turn 20's prompt is 90% old turns, answer ignores new question | No token budget on history_messages/transcript |
04.7's ConversationManager + token-budgeted window (4.5) |
| Losing the filter | Tenant/region filter silently absent on turn N | Filter merged per-turn but not persisted; sticky cleared accidentally | effective_filters forces tenant; sticky_filters escape-hatch only on explicit clear; assert filters_used in tests |
| Answer contradicting earlier turns | "You said 26 weeks" vs earlier "10 days" | Compounding error — wrong claim in history re-sent as fact | Provenance: answers cite chunks; re-retrieve on challenge ("are you sure?"); constraint-retention evals (8.3) |
| Clarification loop | Bot asks "which one?" three turns running | clarify route too eager; candidates not named concretely |
One-question rule; name candidates from entities; frustration detection → best-effort answer |
| Meta question hits the index | "Summarize our chat" returns doc chunks about summaries | Route misclassified as retrieve | Route accuracy metric; meta answers come from TurnRecords only |
| Retrieval cache serving deleted docs | Citation resolves to a chunk that's gone | TTL too long / no invalidation on index update | Short TTL; invalidate session caches on reindex (07.11) |
| Negation dropped in rewrite | "Don't show EU docs" → retrieves EU docs | Condense loses negation | Eval standalone_not_contains; sticky_filters clear semantics |
| Citation label collision | "[1]" means different chunks on adjacent turns | Global vs per-turn numbering confused | Per-turn numbering + persisted TurnRecord.source_map (4.3) |
| Cost blow-up | Bill triples when chat feature ships | History re-sent + chunks carried + condense/planner/generate = 3+ calls/turn | Route gating (chat/meta skip retrieval), carry only on follow-ups, cache, cheap models for condense (4.2) |
Decision table#
| Decision | Use when | Avoid when |
|---|---|---|
| Condense every turn (default) | Any multi-turn product | Proven single-shot usage → condense_enabled=False |
| Trivial fast path | High chit-chat volume; greetings/acks | Ambiguous acks near pending questions — keep the regex conservative |
| Separate classify-then-condense | Condense latency is the bottleneck and a cheap classifier exists | Default — the combined call is simpler and one call cheaper |
| Carry-forward | is_follow_up true AND last turn's chunks plausibly still relevant |
Topic switches, corrections, comparisons needing both sides fresh |
| Always fresh retrieval | Evaluations show carry hurts precision | Same-topic follow-ups where re-retrieval loses good chunks |
| Per-session retrieval cache | Repeated queries/filters within a session; TTL acceptable | Fast-changing index; cross-session caching needs ACL scoping (07.11) |
| Sticky filters | User states a durable constraint ("only EU docs") | Per-query constraints — those belong to QueryPlan filters |
| Clarify route | 2+ live referents or a missing required slot | One obvious referent — inference is cheaper than a question |
| Meta route | Questions about the conversation itself | Anything answerable from the corpus — meta never retrieves |
| Per-turn citation numbering | Chat UI where each answer is self-contained | Cross-turn citation references needed → session-global (07.5) |
| JsonFileSessionStore | Demos, single instance, small scale | Multi-instance/production → Postgres/Redis with TTL jobs |
suggest_followups |
Engagement matters; corpus is stable | Cost-sensitive; suggestions must be corpus-answerable (eval them) |
Prompt gallery#
1. The condense prompt (2.2) — full text in the code block above; the production version sends the same JSON contract via provider structured output.
2. Meta-summary prompt (inside meta_answer):
Summarize this conversation so far in 3-5 bullet points. Keep decisions,
named entities and open questions.
Q: <turn 1 user text>
A: <turn 1 answer>
...3. Follow-up suggestion prompt (inside suggest_followups):
Suggest 3 short follow-up questions the user might ask next about this
answer, answerable from the same document library. One per line, no
numbering, under 12 words each.
Answer: {answer}
Follow-ups:Common misconceptions#
| Misconception | Reality |
|---|---|
| "The model remembers the conversation, so retrieval will too." | The model sees whatever you send; retrieval state is entirely your code. Nothing carries over unless you carry it. |
| "Just send the whole history and let the model figure it out." | History gives the model context, not the retriever. "And for contractors?" still embeds to nothing without the condense step — unless the model itself writes the search query through a tool call, which is the different architecture in 3.6. |
| "Re-retrieve everything every turn — it's simplest." | It costs a retrieval + the freshest chunks may lose a good chunk that ranked lower on the new phrasing. Carry-forward on follow-ups is a recall hedge. |
| "Condense is just query rewriting — 07.3 already covered it." | 07.3 rewrites standalone queries; the condense step additionally routes the turn, extracts slots/sticky filters/entities, and must never block a turn. Different job, different failure modes. |
| "If the JSON parse fails, retry or error." | Fall back to raw-text retrieval. A bad rewrite is a mediocre answer; a dead turn is a lost user. |
| "Sticky filters are just metadata filters." | They're session state written by the model — which is why tenant/ACL keys must be stripped from model output and forced from auth context. |
| "Citations can keep one numbering across the session." | Per-turn numbering + persisted TurnRecord.source_map is simpler and self-contained; global numbering only if the UI needs cross-turn references. |
| "Chit-chat should still retrieve 'just in case'." | It wastes retrieval and invites irrelevant citations; chat/meta/clarify routes exist precisely to skip it. |
| "The session store is just a chat log." | It holds retrieval state — hits, caches, filters, entities — which has different retention, privacy and consistency needs than the transcript. |
| "More context is always better for follow-ups." | Carried chunks cost tokens every turn and can crowd out fresh evidence; carry only on evidence of continuity. |
| "User simulators replace real users." | They test scripted goals under scripted personalities — regression coverage, not user research (10A.2, 13.4). |
Key takeaways#
- Conversational RAG is application state, not model magic. The provider sees a stateless request every turn; condense, route, retrieve, carry, cache and session storage are all your code.
- The condense step rewrites follow-ups into standalone queries and routes the turn — one cheap structured call doing three jobs, with a safe fallback that never blocks a turn.
- Route before you retrieve:
retrieve/chat/meta/clarify— every wrong route is expensive differently, and meta/chit-chat should never touch the index. - Carry context forward only on evidence (
is_follow_up): sticky filters/entities persist, previous chunks are appended (never re-ranked by stale scores), and the per-session retrieval cache is TTL'd and bounded. - Search-as-a-tool is the alternative architecture: let the model see the whole conversation and write the query itself (3.6) — more flexible for multi-hop questions, less predictable in cost and harder to debug; keep the filter and session safeguards either way.
- Tenant/ACL filters are forced from auth context — model-produced filters can narrow but never widen access.
- What goes into turn N's context is a budget decision: pinned session state + bounded history + this turn's evidence + the standalone question, ordered stable→volatile for cache friendliness.
- Session state is a typed, JSON-serializable document — turns store retrieved sets and source maps so answers, sources and evals survive restarts.
- Evaluate conversations, not just turns: scripted multi-turn scenarios, turn-level metrics computable from
TurnRecords, conversation-level metrics for task success, and user simulators for scale.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Conversational RAG | RAG that works across multi-turn dialogues, with session state owning follow-ups, retrieval and context |
| Condense step | The LLM call that rewrites a follow-up into a standalone query and decides the turn's route (also: query decontextualization) |
| Standalone query | A self-contained question needing no conversation context — what retrieval actually embeds |
Route (retrieve/chat/meta/clarify) |
The per-turn decision of whether to retrieve, chat, answer from the record, or ask a question |
is_follow_up |
Condense output flagging that the message depends on earlier turns — gates carry-forward |
| Sticky filters | Durable user-set retrieval constraints persisted in session state |
| Carry-forward | Re-using last turn's retrieved chunks on a follow-up, appended after fresh results |
| Retrieval cache | Per-session store of (query, filters) → hits, with TTL and size bound |
| Session state | The typed, JSON-serializable document (SessionState) holding a conversation's retrieval state |
TurnRecord |
One turn's audit unit: raw text, standalone query, route, answer, hits, source map, filters |
source_map |
Per-turn label→chunk resolution index on TurnRecord/GenerationRequest — not a verified citation (07.5 owns those) |
| Pending clarification | Derived state (turns[-1].route == "clarify") marking an open slot to fill |
| Slot-filling | Extracting a missing value ("the Pro plan") into session entities to resume a pending intent |
| Session block | The pinned entities/filters/summary text sent to the generator each turn |
| Trivial-turn fast path | Deterministic skip of condense+retrieval for obvious greetings/acks |
| Meta route | Answering questions about the conversation itself from TurnRecords, never the index |
| Search-as-a-tool | The alternative to the condense pipeline: the model sees the whole conversation and writes its own search queries through a tool call (3.6) |
| User simulator | A second model playing the user with a hidden goal to generate/evaluate conversations (10A.2) |
| Conversation-level metric | Metrics scoring the whole dialogue (task success, turns-to-resolution) vs per-turn metrics |
All terms are also collected in the glossary.
Exercises#
- Condense skip logic (2.4): add
"sounds good"and"ok cool"to_TRIVIAL_RE's alternation — then explain why each is risky and whatpending_clarificationguard already covers. - Carry-forward ablation (3.3): run the demo scenario with
carry_max=0vscarry_max=3on a follow-up-heavy session. Which turns changehit_ids, and what does that cost in tokens? - Filter escape (3.5): write a turn where the user says "actually show me all regions" after setting
{"region": "EU"}sticky. Trace howsticky_filtersclears and whatfilters_usedshows on theTurnRecord. - Tenant attack (3.5): craft a
sticky_filtersvalue{"tenant": "other-corp"}via a fake condense response. Proveeffective_filtersstrips it — then explain why stripping_TENANT_KEYSmust happen after the merge, not before. - Cache TTL (3.4): inject
clock=a fake that advances pastcache_ttlbetween two identical queries. Show the second call misses and re-retrieves. - Citation resolution (4.3): after the demo session, load the
TurnRecordfor turn 2 and resolvesource_map[0]["chunk_id"]back to its chunk text viarecord.hits. Write the function a "show sources" UI would call. - Eval scaffold (8.5): add
"hb-101"(the parental-leave chunk) to the topic-switch turn'sforbidden_hitand run the scaffold. It fails with the demo's toy retriever, because that retriever scores plain word overlap and stopwords such as "the" and "for" pull hb-101 in. Decide whether the retriever or the expectation is wrong, then break the condense fake so that turn 3's standalone query still contains "contractors" and watchstandalone_not_containsfail. - Clarification loop (6.1): script three consecutive ambiguous turns. Count how many
clarifyroutes fire and design the "stop clarifying" rule that would break the loop. - Cost accounting (4.2): instrument
handle_turnto sumlen(prompt)across allllmcalls per turn for a 10-turn session. Comparecondense_enabled=TruevsFalse— what does the condense call cost per turn? - Session expiry (5.5): add a
expires_attoSessionStateand astore.getthat returnsNonefor expired sessions. What happens topending_clarificationon resume-after-expiry? - Malformed condense JSON (2.3): feed
parse_condensewrong-typed fields —is_follow_up: "false"(string),missing_slots: "product"(string),clarification: {"q": "which?"}(object),entities: 42(number) — and assert each degrades to the safe default. Bonus:sticky_filtersgiven as a JSON string is accepted by_as_dict— decide whether that leniency is right for your threat model.
Hints. (1) A bare "ok" or "yes" may answer a pending clarification, and "sounds good" may precede a real question, which is why the pending-clarification guard exists. (4) Stripping before the merge would let the merged model-produced value survive; stripping after the merge removes it whatever its source, and the forced session.tenant is added last. (5) The cache entry stores a timestamp from the injected clock; once now - stored > cache_ttl the entry is replaced, so cache_hit is False on the second turn. (10) pending_clarification is derived from turns[-1], so an expired-and-deleted session loses it with everything else; a restored older snapshot could resurrect a stale open clarification.
Check yourself#
- Why does "and for contractors?" retrieve badly without the condense step?It has almost none of the topic's vocabulary — no "parental", "leave", "weeks" — so dense and lexical retrieval both land in the wrong region of the index.
- What three jobs does the condense call do in one request, and why is that cheaper than three calls?Rewrite to a standalone query, route the turn, and extract follow-up/slot/sticky-filter/entity state. They share the same input (history + message), so one call is cheaper than three.
- What does the condense fallback do when the model returns malformed JSON, and why is that the right failure mode?It falls back to treating the raw message as a standalone retrieval question — a bad rewrite is a mediocre answer, a dead turn is a lost user.
- Name the four routes and one example trigger for each.
retrieve(needs documents),chat(greeting/small talk),meta(about this conversation),clarify(too ambiguous — ask one question). - When should
is_trivialNOT skip condense even for a short message?When a clarification is pending — a short reply like "the Pro plan" is a slot answer, not a greeting, and must reach condense. - What's the difference between sticky filters and per-turn plan filters, and which wins on conflict?Sticky filters persist across the session (user-set durables); plan filters apply to this query. Per-turn plan filters override sticky on conflict; tenant is forced last.
- Why must
tenant/aclkeys be stripped from model-produced filters?Because model output — including prompt-injected document text — must never widen access; tenant/ACL come only from auth context. - When does carry-forward fire, and why are carried hits appended rather than re-ranked?On
is_follow_uptrue, up tocarry_maxof last turn's hits not already fresh. Scores aren't comparable across queries, so carried hits append rather than re-rank. - What's in the per-session retrieval cache key, and why not just the raw user text?The canonical standalone query + effective filters — not raw user text, because different phrasings can share a standalone query and different filters must not share hits.
- Which context elements go first vs last in the generation request, and why does that order matter?Stable first (system, session block, summary, history) for cache-friendly prefixes; volatile last (retrieved context, question).
- How does
pending_clarificationwork without a dedicated state field?It's derived:turns[-1].route == "clarify"— the last turn record is the state, nothing extra to sync. - What's the difference between turn-level and conversation-level metrics, with one example of each?Turn-level scores one turn's route/retrieval/answer (e.g., route accuracy); conversation-level scores the whole dialogue (e.g., task success, turns-to-resolution).
- Why store serialized hits on
TurnRecordrather than just hit IDs?So citations resolve and evals/debugging work after the index changes or the session resumes — the evidence is self-contained. - What are the three session-store options and the production trade-off?In-memory (tests), JSON file (demos/single instance), Postgres/Redis (production: multi-instance, TTL jobs, cross-session analytics).
Further resources#
- OpenAI, Conversation state:
previous_response_id, the Conversations API, and how server-side state relates to client-managed history. - Anthropic, Message threads: the beta
threadparameter — server-held conversation, 5-minute expiry, best-effort replay. - Google, generateContent quickstart:
client.chats, the client-side history helper — and Interactions API overview:previous_interaction_idserver-side chaining (both also covered in 03.2). - AskVault, Query decontextualization: a production write-up of the condense step — including skip rules for first turns, greetings and one-word messages.
- Lesson 04.7: the
ConversationManagerand history-management machinery this lesson's session layer sits beside. - Lesson 10A.2, Part 13: the two-model user-simulator pattern used for conversational eval.
- Lesson 06.10, 7.6: the retrieval-side standalone-query primitive this lesson productionises.
← 07.5 — Citations and Attribution | Module 07 overview | 07.7 — Managed RAG: Provider Tools, Platforms and Frameworks →