rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
364591b
·
1 Parent(s): 26023b8

feat(fact-find): KI-070 — single-LLM-call fact-find replaces 3-layer template stitching

Browse files

Real-user feedback on 2026-05-15 flagged the fact-find flow as robotic and
templated because it WAS three stitched layers: hardcoded canonical prompts
in needs_finder.GRAPH, per-turn paraphrase in question_paraphraser.py, and
acknowledger rotation (_pick_opener / _family_aware_opener) in the
orchestrator. Replace all three with ONE LLM call per turn that produces a
natural conversational reply plus a machine-readable <FF>...</FF> trailer
declaring captured fields, the slot it's driving toward, and whether
fact-find is complete.

New: backend/fact_find_brain.py
- drive_fact_find(user_text, session, chat_history, session_id)
-> FactFindOutcome(reply_text, captured_updates, slot_driving,
fact_find_complete, ambiguous)
- System prompt encodes the 9-slot schema, conversation rules, and
strict trailer-block format with 5 worked examples.
- _parse_ff_block + _strip_ff_block split the trailer from the reply.
- _validate_capture runs each LLM-emitted value through
fact_find_normalizer._validate before commit.
- Slot-not-progressing safeguard: if the same slot_driving appears in
3 consecutive turns, force next_question() to pick a different slot.
- Hard 12s timeout. On timeout / malformed JSON / no trailer → ambiguous
fallback using the canonical next_question.prompt_en.

Modified: backend/orchestrator.py
- Old fact-find branch (~lines 580-900, 348 lines) gutted. Replaced
with ~95 lines calling drive_fact_find + applying captured updates +
re-upserting profile chunk + persisting named profile.
- Deleted: _pick_opener, _family_aware_opener, _NEUTRAL_OPENERS_EN,
_FAMILY_*_OPENERS_EN, _contains_self_introduction, _SELF_INTRO_RE,
_NON_NAME_TOKENS, hashlib import.
- Kept: should_route_to_fact_find, greeting / intent-restart detector,
_format_known_profile_summary (welcome-back), KI-063 shown-policy
logging.

Deleted: backend/question_paraphraser.py — entirely superseded by the
single-LLM-call brain (which natively varies wording per turn without
needing a separate paraphrase pass).

Modified: backend/needs_finder.py
- next_question now documented as fallback / completeness-API helper
only. GRAPH + readback_summary kept (used by fact_find_brain
canonical fallback + /api/profile/completeness hint).

Verification:
- py_compile on all changed files: clean.
- tests/test_routing_regression.py: 15/15 pass (4 KI-018 + 4 KI-025 +
7 others). should_route_to_fact_find unchanged.
- Inline smoke tests of _parse_ff_block (valid / missing / malformed)
and drive_fact_find against a stub LLM with canned <FF> output:
all pass — captured_updates, slot_driving, complete parsed
correctly + <FF> trailer stripped from user-facing reply.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

backend/fact_find_brain.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """KI-070 — Single-LLM-call fact-find brain.
2
+
3
+ Replaces three stitched layers that previously drove fact-find:
4
+ 1. `backend/needs_finder.GRAPH` — hardcoded canonical question prompts
5
+ 2. `backend/question_paraphraser.py` — per-turn LLM paraphrase pass
6
+ 3. `backend/orchestrator._pick_opener` + `_family_aware_opener` —
7
+ acknowledger rotation prepended to each canonical question
8
+
9
+ Real-user testing on 2026-05-15 flagged the result as robotic + templated.
10
+ The fix is to do the whole job in ONE LLM call per turn that produces a
11
+ natural conversational reply AND tags which slots were captured / which
12
+ slot it's driving toward / whether fact-find is complete — all in a single
13
+ machine-parsable trailer block.
14
+
15
+ Public entry:
16
+ async def drive_fact_find(user_text, session, chat_history, session_id)
17
+ -> FactFindOutcome
18
+
19
+ Reliability guardrails:
20
+ 1. JSON-block-must-parse — if `<FF>...</FF>` is missing or invalid,
21
+ return `ambiguous=true` so the orchestrator emits a soft canonical
22
+ fallback (`next_question` then prompt_en).
23
+ 2. Capture validation — each captured value goes through
24
+ `fact_find_normalizer._validate` before commit. Validation failure
25
+ drops only that field; others still apply.
26
+ 3. Slot-not-progressing safeguard — if the SAME `slot_driving` appears
27
+ in 3 consecutive turns, force `next_question(profile)` to pick a
28
+ different slot. State is held on the SessionState (`_ff_brain_history`).
29
+ 4. Hard timeout 12 seconds. Timeout → ambiguous=True + the canonical
30
+ `next_question.prompt_en` as a fallback reply.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import asyncio
36
+ import json
37
+ import logging
38
+ import re
39
+ import time
40
+ from dataclasses import dataclass, field
41
+ from typing import Any, Optional
42
+
43
+ from backend.providers.base import ChatMessage
44
+ from backend.providers.nvidia_nim_llm import get_fast_brain_llm
45
+
46
+
47
+ # ----------------------------------------------------------------------------
48
+ # Outcome dataclass
49
+ # ----------------------------------------------------------------------------
50
+
51
+ @dataclass
52
+ class FactFindOutcome:
53
+ reply_text: str
54
+ captured_updates: dict[str, Any] = field(default_factory=dict)
55
+ slot_driving: Optional[str] = None
56
+ fact_find_complete: bool = False
57
+ ambiguous: bool = False
58
+
59
+
60
+ # ----------------------------------------------------------------------------
61
+ # System prompt — the ENTIRE behavioural contract lives here. Keep tight.
62
+ # ----------------------------------------------------------------------------
63
+
64
+ _SYSTEM_PROMPT = """You are an insurance advisor having a natural conversation with someone considering a health policy in India. Be warm, brief, consultative — NOT closing-pitchy. Speak like a trusted Independent Financial Advisor, not a call-centre script.
65
+
66
+ You need to capture these 9 facts before recommending. Don't ask them all at once — weave them into the conversation based on what the user just said.
67
+
68
+ SLOTS YOU NEED TO FILL (field name : type : allowed values : why it matters)
69
+ - name : string (1-50 chars) : for personalisation + saving their profile so they don't repeat fact-find next visit
70
+ - age : int 18-99 : drives premium, eligibility, renewability
71
+ - dependents : enum {self, self+spouse, self+spouse+kids, self+kids, self+parents, self+spouse+parents, self+spouse+kids+parents} : drives policy structure (parent-specific plans often win when parents are on)
72
+ - income_band : enum {under_5L, 5L-10L, 10L-25L, 25L+} : drives sum-insured sizing
73
+ - existing_cover_inr : int >= 0 (0 if first-time buyer or no employer plan) : drives whether to recommend top-up vs full base plan
74
+ - primary_goal : enum {first_buy, upgrade, compare_specific, tax_planning} : drives whether to grade on price / breadth / claim experience / tax savings
75
+ - location_tier : enum {metro, tier1, tier2, tier3} : drives premium + cashless hospital density
76
+ - parents_age_max : int 30-99 (only relevant when dependents includes parents) : drives whether parent-specific plans should be included
77
+ - health_conditions : list of lowercase canonical names like ["diabetes", "hypertension", "thyroid", "asthma", "heart", "cancer"] (empty list = no conditions) : drives PED waiting + insurer fit. Honesty here protects the user's future claim.
78
+ - budget_band : enum {under_15k, 15k_30k, 30k_60k, 60k+} : drives policy shortlist
79
+
80
+ CONVERSATION RULES
81
+ 1. Reply naturally. Don't say "Got it." or "Noted." every turn. Don't apologise robotically. Don't number your questions.
82
+ 2. Acknowledge what the user just told you — reflect it back briefly so they feel heard.
83
+ 3. Ask for at most ONE missing slot per reply, woven into the conversation.
84
+ 4. If the user supplied multiple facts in one message (e.g., "I'm Rohit, 29, in Mumbai"), capture them ALL — don't re-ask for what they just volunteered.
85
+ 5. If they go off-topic, give a brief honest answer, then steer back.
86
+ 6. If they say "show me policies", "let me see options", "that's enough", "skip the questions" — set complete=true and slot_driving=null. Don't keep fact-finding forever.
87
+ 7. When the profile feels complete enough to recommend (at minimum age + dependents + income + primary_goal captured), proactively summarise the captured profile + ask if they want a policy suggestion. Set complete=true.
88
+ 8. Indian English is fine — "₹", "lakh", "metro/tier-2 city" are natural. Never use markdown bold or italics — the reply is read aloud by TTS too.
89
+ 9. BFSI compliance: do not promise specific premium quotes, do not pressure-close. Light, advisory tone.
90
+ 10. On health conditions — be straight: hiding a condition lowers premium today but turns into a denied claim later. Encourage honesty without lecturing.
91
+
92
+ OUTPUT FORMAT (strict)
93
+ After your natural reply, on a NEW LINE, emit exactly one machine-readable trailer:
94
+ <FF>{"captured": {<field>: <value>, ...}, "slot_driving": "<slot_field_or_null>", "complete": <true_or_false>}</FF>
95
+
96
+ The <FF> block is INVISIBLE to the user — the backend strips it before sending.
97
+
98
+ Strict requirements for the <FF> block:
99
+ - Captured values MUST match the slot schema (enums exact, ints parsed as JSON numbers, strings trimmed, list as JSON array). Missing slots = omit them; do NOT emit null values for fields you didn't capture this turn.
100
+ - `slot_driving` MUST be the FIELD NAME (e.g., "income_band"), not the canonical-question id. Use null when fact-find is complete OR when the user has steered to a different intent.
101
+ - `complete` MUST be a JSON boolean (true / false), no quotes.
102
+ - If the user's latest message yielded no new facts, emit "captured": {} (empty object, not omitted).
103
+ - Emit the <FF> block exactly once and at the END. Nothing after </FF>.
104
+
105
+ EXAMPLES OF GOOD REPLIES (reply line + trailer)
106
+
107
+ User: "Hi, I'm Rohit, 29, looking to buy my first health policy."
108
+ Bot reply: Hi Rohit — nice to meet you. First health policy is a good place to start. To shape the right options for you, who else would you want covered apart from yourself — spouse, kids, parents, or just you for now?
109
+ <FF>{"captured": {"name": "Rohit", "age": 29, "primary_goal": "first_buy"}, "slot_driving": "dependents", "complete": false}</FF>
110
+
111
+ User: "Just me and my wife. We're both in Bangalore."
112
+ Bot reply: Got that — you and your spouse, based in Bangalore (so metro hospital network is a big advantage for cashless). What income band are you in roughly — under ₹5L, ₹5-10L, ₹10-25L, or ₹25L+? Helps me suggest the right sum-insured size.
113
+ <FF>{"captured": {"dependents": "self+spouse", "location_tier": "metro"}, "slot_driving": "income_band", "complete": false}</FF>
114
+
115
+ User: "Around 18 lakh."
116
+ Bot reply: That puts you in the ₹10-25L band — gives us comfortable room on sum-insured. Do either of you have any pre-existing conditions — diabetes, BP, thyroid, anything chronic? Be straight here: it protects your future claim.
117
+ <FF>{"captured": {"income_band": "10L-25L"}, "slot_driving": "health_conditions", "complete": false}</FF>
118
+
119
+ User: "Just show me some policies already."
120
+ Bot reply: Fair enough — let me put together a shortlist based on what you've shared so far: age 29, covering you and your spouse, metro, income ₹10-25L, first-time buyer. Want me to suggest 2-3 policies that fit, or do you have specific insurers in mind to compare?
121
+ <FF>{"captured": {}, "slot_driving": null, "complete": true}</FF>
122
+
123
+ User: "What's the waiting period for PED usually?"
124
+ Bot reply: Most policies in India have a 24-36 month waiting period for pre-existing diseases — IRDAI caps the maximum, and a few insurers offer shorter waits as a premium upgrade. Happy to dig into a specific policy if you have one in mind. Meanwhile, what budget range are you comfortable with annually — under ₹15k, ₹15-30k, ₹30-60k, or ₹60k+?
125
+ <FF>{"captured": {}, "slot_driving": "budget_band", "complete": false}</FF>
126
+ """
127
+
128
+
129
+ # ----------------------------------------------------------------------------
130
+ # Parser for <FF>...</FF> trailer
131
+ # ----------------------------------------------------------------------------
132
+
133
+ _FF_BLOCK_RE = re.compile(r"<FF>\s*(\{.*?\})\s*</FF>", re.DOTALL)
134
+
135
+
136
+ def _parse_ff_block(text: str) -> Optional[dict]:
137
+ """Extract + parse the <FF>...</FF> JSON trailer from an LLM reply.
138
+
139
+ Returns the parsed dict on success, None when the trailer is missing,
140
+ malformed, or fails JSON parse. The caller should treat None as
141
+ `ambiguous=True` and fall through to the canonical fallback.
142
+ """
143
+ if not text:
144
+ return None
145
+ m = _FF_BLOCK_RE.search(text)
146
+ if not m:
147
+ return None
148
+ raw_json = m.group(1).strip()
149
+ try:
150
+ data = json.loads(raw_json)
151
+ except json.JSONDecodeError:
152
+ return None
153
+ if not isinstance(data, dict):
154
+ return None
155
+ return data
156
+
157
+
158
+ def _strip_ff_block(text: str) -> str:
159
+ """Remove the <FF>...</FF> trailer (and any trailing whitespace) so the
160
+ user-facing reply doesn't leak the schema tag."""
161
+ if not text:
162
+ return text
163
+ cleaned = _FF_BLOCK_RE.sub("", text).strip()
164
+ # Remove any orphaned partial tags too — defensive against LLMs that emit
165
+ # an opening <FF> without a close, or a malformed inner block.
166
+ cleaned = re.sub(r"<FF>.*$", "", cleaned, flags=re.DOTALL).strip()
167
+ cleaned = re.sub(r"</FF>", "", cleaned).strip()
168
+ return cleaned
169
+
170
+
171
+ # ----------------------------------------------------------------------------
172
+ # Schema map — field name → validator schema in fact_find_normalizer terms
173
+ # ----------------------------------------------------------------------------
174
+ #
175
+ # The slot prompt promises enum values like "self+spouse" and "10L-25L", and
176
+ # `fact_find_normalizer._FIELD_SCHEMA` already encodes those. Reuse it. Note
177
+ # that the orchestrator's Profile fields are keyed by the FIELD NAME (e.g.,
178
+ # `income_band`), not the canonical question id (`income_band`), and those
179
+ # happen to match for most slots — exceptions handled below.
180
+
181
+ # Slot field → canonical-question id (for marking `profile.asked` so
182
+ # `next_question` doesn't re-pick the same slot).
183
+ FIELD_TO_QUESTION_ID: dict[str, str] = {
184
+ "name": "name",
185
+ "age": "age",
186
+ "dependents": "dependents",
187
+ "income_band": "income_band",
188
+ "existing_cover_inr": "existing_cover",
189
+ "primary_goal": "primary_goal",
190
+ "location_tier": "location",
191
+ "parents_age_max": "parents_age",
192
+ "health_conditions": "health_conditions",
193
+ "budget_band": "budget",
194
+ }
195
+
196
+
197
+ def _validate_capture(field_name: str, value: Any) -> Any:
198
+ """Run `value` through the fact_find_normalizer schema for the matching
199
+ field. Returns the validated value (possibly coerced) or None when the
200
+ value fails validation."""
201
+ if value is None:
202
+ return None
203
+ # Name is free-text — apply the profile_store name validator.
204
+ if field_name == "name":
205
+ try:
206
+ from backend.profile_store import is_valid_name
207
+ v = str(value).strip()
208
+ return v if is_valid_name(v) else None
209
+ except Exception:
210
+ return None
211
+
212
+ # Translate field name → fact_find_normalizer question id for schema lookup.
213
+ qid = FIELD_TO_QUESTION_ID.get(field_name)
214
+ if qid is None:
215
+ # Unknown slot — drop.
216
+ return None
217
+
218
+ try:
219
+ from backend.fact_find_normalizer import _FIELD_SCHEMA, _validate
220
+ except Exception:
221
+ return value # if validator import fails, trust the LLM
222
+
223
+ schema = _FIELD_SCHEMA.get(qid)
224
+ if schema is None:
225
+ return value
226
+
227
+ # Try the strict validator first.
228
+ validated = _validate(value, schema)
229
+ if validated is not None:
230
+ return validated
231
+
232
+ # Last resort — for ints, accept strings that parse cleanly.
233
+ t = schema.get("type")
234
+ if t == "int":
235
+ try:
236
+ iv = int(str(value).strip())
237
+ except (TypeError, ValueError):
238
+ return None
239
+ if iv < schema.get("min", 0) or iv > schema.get("max", 1_000_000_000):
240
+ return None
241
+ return iv
242
+ if t == "list" and isinstance(value, str):
243
+ # LLM may emit a comma-separated string; coerce.
244
+ items = [x.strip().lower() for x in value.split(",") if x.strip()]
245
+ return items
246
+ return None
247
+
248
+
249
+ # ----------------------------------------------------------------------------
250
+ # Slot-not-progressing safeguard
251
+ # ----------------------------------------------------------------------------
252
+
253
+ def _bump_brain_history(session, slot_driving: Optional[str]) -> int:
254
+ """Record `slot_driving` on the session and return how many consecutive
255
+ turns the same slot has been driven. Stored on the session under
256
+ `_ff_brain_history` as a list[str] capped at 8."""
257
+ if not hasattr(session, "_ff_brain_history"):
258
+ session._ff_brain_history = []
259
+ history: list[Optional[str]] = session._ff_brain_history
260
+ history.append(slot_driving)
261
+ if len(history) > 8:
262
+ del history[: len(history) - 8]
263
+ # Count run-length of the most recent slot at the tail.
264
+ if not slot_driving:
265
+ return 0
266
+ n = 0
267
+ for s in reversed(history):
268
+ if s == slot_driving:
269
+ n += 1
270
+ else:
271
+ break
272
+ return n
273
+
274
+
275
+ # ----------------------------------------------------------------------------
276
+ # Public entry
277
+ # ----------------------------------------------------------------------------
278
+
279
+ _TIMEOUT_S = 12.0
280
+
281
+
282
+ async def drive_fact_find(
283
+ user_text: str,
284
+ session,
285
+ chat_history: Optional[list[dict]],
286
+ session_id: Optional[str],
287
+ ) -> FactFindOutcome:
288
+ """Single LLM call per fact-find turn.
289
+
290
+ Returns a FactFindOutcome the orchestrator applies to session state.
291
+
292
+ Behaviour:
293
+ - Calls `get_fast_brain_llm()` with a system prompt that defines the
294
+ slot schema, conversation rules, and trailer-block format.
295
+ - Parses the trailer `<FF>...</FF>` JSON to learn what was captured,
296
+ which slot the brain is driving toward, and whether fact-find is
297
+ complete.
298
+ - Validates each captured value through `fact_find_normalizer`.
299
+ - On timeout / malformed JSON / no trailer → ambiguous=True and a
300
+ canonical-question fallback reply.
301
+ """
302
+ t0 = time.time()
303
+ # Build current profile JSON (only set fields) so the prompt sees what we
304
+ # already know.
305
+ profile = session.profile
306
+ profile_snapshot: dict[str, Any] = {}
307
+ for field_name in (
308
+ "name", "age", "dependents", "income_band", "existing_cover_inr",
309
+ "primary_goal", "location_tier", "parents_age_max", "health_conditions",
310
+ "budget_band",
311
+ ):
312
+ v = getattr(profile, field_name, None)
313
+ if v not in (None, "", []):
314
+ profile_snapshot[field_name] = v
315
+
316
+ system_with_state = _SYSTEM_PROMPT + (
317
+ "\n\nCURRENT PROFILE (already captured; do NOT re-ask for these):\n"
318
+ + json.dumps(profile_snapshot, ensure_ascii=False)
319
+ )
320
+
321
+ # Build messages: system + last ~10 chat history turns + user_text
322
+ messages: list[ChatMessage] = [ChatMessage(role="system", content=system_with_state)]
323
+ if chat_history:
324
+ for turn in chat_history[-10:]:
325
+ role = turn.get("role")
326
+ content = turn.get("content")
327
+ if role in ("user", "assistant") and content:
328
+ messages.append(ChatMessage(role=role, content=content))
329
+ messages.append(ChatMessage(role="user", content=user_text or ""))
330
+
331
+ # Hard 12-second timeout. The fast-brain chain already has its own budget
332
+ # but we wrap with asyncio.wait_for as a belt-and-braces stop.
333
+ llm = get_fast_brain_llm()
334
+ try:
335
+ result = await asyncio.wait_for(
336
+ llm.chat(messages=messages, temperature=0.6, max_tokens=420),
337
+ timeout=_TIMEOUT_S,
338
+ )
339
+ except asyncio.TimeoutError:
340
+ logging.warning(
341
+ "fact_find_brain timeout (session=%s, %.1fs)", session_id, time.time() - t0
342
+ )
343
+ return _canonical_fallback(profile, reason="timeout")
344
+ except Exception as e:
345
+ logging.warning(
346
+ "fact_find_brain LLM call failed (session=%s): %s: %s",
347
+ session_id, type(e).__name__, str(e)[:200],
348
+ )
349
+ return _canonical_fallback(profile, reason="llm_error")
350
+
351
+ raw = (result.text or "").strip()
352
+ parsed = _parse_ff_block(raw)
353
+ if parsed is None:
354
+ logging.info(
355
+ "fact_find_brain trailer missing/malformed (session=%s, raw=%r)",
356
+ session_id, raw[:200],
357
+ )
358
+ return _canonical_fallback(profile, reason="no_trailer")
359
+
360
+ reply_text = _strip_ff_block(raw)
361
+ if not reply_text.strip():
362
+ return _canonical_fallback(profile, reason="empty_reply")
363
+
364
+ captured_raw = parsed.get("captured") or {}
365
+ if not isinstance(captured_raw, dict):
366
+ captured_raw = {}
367
+ slot_driving_raw = parsed.get("slot_driving")
368
+ if slot_driving_raw in ("", "null", "None"):
369
+ slot_driving_raw = None
370
+ complete_raw = bool(parsed.get("complete", False))
371
+
372
+ # Validate each capture; drop fields that fail.
373
+ captured: dict[str, Any] = {}
374
+ for field_name, raw_value in captured_raw.items():
375
+ validated = _validate_capture(field_name, raw_value)
376
+ if validated is None:
377
+ logging.info(
378
+ "fact_find_brain dropped invalid capture (session=%s, field=%s, raw=%r)",
379
+ session_id, field_name, raw_value,
380
+ )
381
+ continue
382
+ captured[field_name] = validated
383
+
384
+ # Slot-not-progressing safeguard — if same slot has been driven 3 turns
385
+ # in a row, force the orchestrator to pick a different slot.
386
+ repeat_count = _bump_brain_history(session, slot_driving_raw)
387
+ if repeat_count >= 3 and slot_driving_raw and not complete_raw:
388
+ try:
389
+ from backend.needs_finder import next_question
390
+ alt = next_question(profile)
391
+ if alt and alt.field != slot_driving_raw:
392
+ logging.info(
393
+ "fact_find_brain stuck on slot=%s for %d turns → forcing %s",
394
+ slot_driving_raw, repeat_count, alt.field,
395
+ )
396
+ slot_driving_raw = alt.field
397
+ except Exception:
398
+ pass
399
+
400
+ return FactFindOutcome(
401
+ reply_text=reply_text,
402
+ captured_updates=captured,
403
+ slot_driving=slot_driving_raw,
404
+ fact_find_complete=complete_raw,
405
+ ambiguous=False,
406
+ )
407
+
408
+
409
+ def _canonical_fallback(profile, *, reason: str) -> FactFindOutcome:
410
+ """Produce a deterministic, on-rails fallback reply when the LLM brain
411
+ times out or returns unparseable output. Uses the canonical needs_finder
412
+ question for the next missing slot so the user always sees a coherent
413
+ next step."""
414
+ try:
415
+ from backend.needs_finder import next_question
416
+ q = next_question(profile)
417
+ except Exception:
418
+ q = None
419
+ if q is not None:
420
+ reply = q.prompt_en
421
+ slot = q.field
422
+ return FactFindOutcome(
423
+ reply_text=reply,
424
+ captured_updates={},
425
+ slot_driving=slot,
426
+ fact_find_complete=False,
427
+ ambiguous=True,
428
+ )
429
+ # Nothing left to ask — gentle hand-off.
430
+ reply = (
431
+ "Let me know a bit about yourself — your age, who you'd want covered "
432
+ "(just you, family, parents), and your annual income band — and I'll "
433
+ "tailor the options for you."
434
+ )
435
+ return FactFindOutcome(
436
+ reply_text=reply,
437
+ captured_updates={},
438
+ slot_driving=None,
439
+ fact_find_complete=False,
440
+ ambiguous=True,
441
+ )
backend/needs_finder.py CHANGED
@@ -175,7 +175,15 @@ def is_field_set(profile: Profile, field_name: str) -> bool:
175
 
176
 
177
  def next_question(profile: Profile, language: str = "en") -> Optional[Question]:
178
- """Return the next question to ask, or None if we have enough to recommend."""
 
 
 
 
 
 
 
 
179
  if profile.free_form_session:
180
  return None
181
 
 
175
 
176
 
177
  def next_question(profile: Profile, language: str = "en") -> Optional[Question]:
178
+ """Return the next question to ask, or None if we have enough to recommend.
179
+
180
+ KI-070 (2026-05-15) — the orchestrator no longer drives fact-find via this
181
+ function; the new `backend/fact_find_brain.py` single-LLM-call brain
182
+ handles question phrasing natively. This is now used as a fallback
183
+ (canonical reply when the brain times out / emits malformed JSON), as a
184
+ slot-not-progressing safeguard, and by `/api/profile/completeness` to
185
+ surface "next question hint" to the frontend.
186
+ """
187
  if profile.free_form_session:
188
  return None
189
 
backend/orchestrator.py CHANGED
@@ -12,7 +12,6 @@ For each user turn:
12
 
13
  from __future__ import annotations
14
 
15
- import hashlib
16
  import re
17
  import time
18
  from dataclasses import dataclass, field
@@ -150,159 +149,15 @@ def pick_brain(intent: str, language: str) -> BrainPick:
150
  return BrainPick(get_fast_brain_llm(), f"v4-flash::{intent}")
151
 
152
 
153
- # ---------- conversational acknowledgers (KI-056, 2026-05-15) ----------
154
  #
155
- # Previous behaviour: every fact-find continuation turn started with the
156
- # literal "Got it. " — three turns in a row with the same opener felt robotic
157
- # and triggered user feedback. We now rotate through a small set of natural
158
- # acknowledgers (deterministic per session+turn so the wording is stable on
159
- # replay) AND, when the user's message mentions family, swap in a
160
- # family-aware opener that explicitly acknowledges the disclosure.
161
-
162
- _FAMILY_DISCLOSURE_RE = re.compile(
163
- r"\b(wife|husband|spouse|partner|kids?|children|child|parents?|family)\b",
164
- re.IGNORECASE,
165
- )
166
-
167
- # Plain rotation — when nothing special is going on. Trailing space included so
168
- # callers can concatenate directly; `""` lets some turns skip the opener
169
- # entirely and go straight into the next question.
170
- _NEUTRAL_OPENERS_EN: tuple[str, ...] = (
171
- "Thanks for that. ",
172
- "Noted. ",
173
- "Helpful — ",
174
- "Right, ",
175
- "OK. ",
176
- "Got it. ",
177
- "Makes sense. ",
178
- "",
179
- )
180
-
181
- # Family-aware variants — picked when the user's message references a spouse,
182
- # kids, or parents. The bot should signal that it actually heard the family
183
- # mention rather than mechanically advancing.
184
- _FAMILY_OPENERS_EN: tuple[str, ...] = (
185
- "Understood — for you and your family, then. ",
186
- "Noted — covering your family. ",
187
- "OK, family coverage to think about. ",
188
- )
189
- _SPOUSE_OPENERS_EN: tuple[str, ...] = (
190
- "Understood — for you and your spouse, then. ",
191
- "Noted — covering you and your spouse. ",
192
- "OK, that means two people on the policy. ",
193
- )
194
- _KIDS_OPENERS_EN: tuple[str, ...] = (
195
- "Noted — covering your kids too. ",
196
- "OK, family-floater territory then. ",
197
- )
198
- _PARENTS_OPENERS_EN: tuple[str, ...] = (
199
- "Noted — your parents in the mix as well. ",
200
- "OK, parent coverage to factor in. ",
201
- )
202
-
203
-
204
- def _family_aware_opener(user_text: str, fallback: str) -> Optional[str]:
205
- """Pick a family-aware acknowledger if `user_text` mentions a spouse,
206
- kids, or parents; otherwise return None so the caller uses `fallback`.
207
-
208
- KI-056 (2026-05-15). The opener picked here is intentionally more
209
- specific than the neutral rotation so the user feels heard when they
210
- volunteer family information mid-flow.
211
- """
212
- if not user_text:
213
- return None
214
- t = user_text.lower()
215
- has_spouse = bool(re.search(r"\b(wife|husband|spouse|partner)\b", t))
216
- has_kids = bool(re.search(r"\b(kids?|children|child)\b", t))
217
- has_parents = bool(re.search(r"\bparents?\b", t))
218
- has_family_word = "family" in t
219
- if not (has_spouse or has_kids or has_parents or has_family_word):
220
- return None
221
- # Pick the most specific variant available — order matters.
222
- if has_spouse and (has_kids or has_parents):
223
- pool = _FAMILY_OPENERS_EN
224
- elif has_spouse:
225
- pool = _SPOUSE_OPENERS_EN
226
- elif has_kids:
227
- pool = _KIDS_OPENERS_EN
228
- elif has_parents:
229
- pool = _PARENTS_OPENERS_EN
230
- else: # has_family_word only
231
- pool = _FAMILY_OPENERS_EN
232
- # Deterministic pick based on the fallback string so two consecutive calls
233
- # with similar context don't collide on the same variant.
234
- idx = (sum(ord(c) for c in (fallback or "x")) % len(pool))
235
- return pool[idx]
236
-
237
-
238
- _SELF_INTRO_RE = re.compile(
239
- # KI-062 (2026-05-15) — widened from 1-2 words to 1-4 words so full
240
- # names like "Rohit Sar" or "Anjali Devi Kumar" get captured.
241
- r"\b(?:i'?m|i\s+am|this\s+is|my\s+name\s+is|name\s+is|call\s+me|name'?s)\s+"
242
- r"([a-zA-Z][a-zA-Z'\-]{1,30}"
243
- r"(?:\s+[a-zA-Z][a-zA-Z'\-]{1,30}){0,3})\b",
244
- re.IGNORECASE,
245
- )
246
-
247
- # KI-059 (2026-05-15) — leading greeting tokens to ignore so "Hi this is X"
248
- # and "Hello, my name is X" reach the introduction phrase.
249
- _GREETING_LEAD = re.compile(
250
- r"^\s*(?:hi|hello|hey|namaste|yo|hola)[,!.\s]+",
251
- re.IGNORECASE,
252
- )
253
-
254
-
255
- # KI-069 (2026-05-15) — words that follow "this is" / "I'm" / "I am" but
256
- # are NOT names. Without this guard KI-059 mis-fired on natural feedback
257
- # like "this is correct" / "I'm good" / "I am sure" and routed users back
258
- # to the name slot. Lowercase comparison.
259
- _NON_NAME_TOKENS: frozenset[str] = frozenset({
260
- # Confirmatory adjectives
261
- "correct", "right", "fine", "good", "okay", "ok", "alright", "great",
262
- "true", "perfect", "accurate", "exactly", "yes", "yeah", "yep", "sure",
263
- # Negations / wrong-flag
264
- "wrong", "incorrect", "no", "false", "off", "bad", "mistaken",
265
- # Common adjectives / nouns mistaken for names
266
- "first", "second", "third", "last", "next", "another", "the", "a", "an",
267
- "my", "your", "his", "her", "their", "our", "this", "that", "these",
268
- "happy", "sad", "tired", "busy", "ready", "done", "new", "old",
269
- # Common stop-words that sneak through capitalisation rules
270
- "looking", "buying", "shopping", "interested", "trying", "thinking",
271
- "here", "there",
272
- })
273
-
274
-
275
- def _contains_self_introduction(text: str) -> bool:
276
- """True if the message volunteers a name via "I'm X" / "this is X" /
277
- "my name is X" / "call me X" — with or without a greeting prefix.
278
-
279
- KI-059 (2026-05-15) — original detector.
280
- KI-069 (2026-05-15) — tightened to avoid false positives:
281
- 1. The captured token must NOT be in the non-name blocklist
282
- (catches "this is correct" / "I'm good" / "first, show me ...").
283
- 2. The captured name must start with an UPPERCASE letter in the
284
- ORIGINAL text. Real names get capitalized in chat input even
285
- after voice transcription; adjectives don't.
286
- """
287
- if not text:
288
- return False
289
- stripped_original = _GREETING_LEAD.sub("", text.strip())
290
- m = _SELF_INTRO_RE.search(stripped_original)
291
- if not m:
292
- return False
293
- captured = m.group(1).strip()
294
- if not captured:
295
- return False
296
- # First word of the captured span is the strongest "is this a name?" signal.
297
- first_word = captured.split()[0]
298
- if first_word.lower() in _NON_NAME_TOKENS:
299
- return False
300
- # Names are typically capitalised in user input (chat AND voice STT).
301
- # If the first character isn't uppercase, the captured span is almost
302
- # certainly an adjective/adverb, not a name.
303
- if not first_word[0].isupper():
304
- return False
305
- return True
306
 
307
 
308
  # KI-061 (2026-05-15) — human-readable summaries for the welcome-back
@@ -381,35 +236,6 @@ def _format_missing_slots(profile) -> list[str]:
381
  return missing
382
 
383
 
384
- def _pick_opener(
385
- user_text: str,
386
- session_id: Optional[str],
387
- turn_idx: int,
388
- slot_just_filled: Optional[str],
389
- ) -> str:
390
- """Choose a natural-language acknowledger for the bot's next reply.
391
-
392
- KI-056 (2026-05-15). Replaces the hardcoded literal "Got it. " opener
393
- that appeared on every fact-find continuation turn. The opener varies
394
- deterministically by (session_id, turn_idx) so the same user gets a
395
- different acknowledger each turn — but two replays of the same session
396
- produce the same wording (testable).
397
-
398
- If the user's message contains a spouse/family/parents disclosure, the
399
- opener swaps to a family-aware variant that explicitly acknowledges it,
400
- so the user feels heard rather than ignored.
401
- """
402
- # Family-aware override takes precedence over the neutral rotation.
403
- fam = _family_aware_opener(user_text, fallback=f"{session_id}:{turn_idx}:{slot_just_filled or ''}")
404
- if fam is not None:
405
- return fam
406
- # Deterministic neutral rotation. Hash (session_id, turn_idx, slot)
407
- # so each turn rotates and different sessions decorrelate.
408
- seed = f"{session_id or 'anon'}|{turn_idx}|{slot_just_filled or ''}"
409
- h = int(hashlib.sha1(seed.encode("utf-8")).hexdigest()[:8], 16)
410
- return _NEUTRAL_OPENERS_EN[h % len(_NEUTRAL_OPENERS_EN)]
411
-
412
-
413
  # ---------- main entrypoint ----------
414
 
415
  @dataclass
@@ -468,7 +294,6 @@ async def handle_turn(
468
  # specific question), interpret the user's message as that answer and emit
469
  # the next question — regardless of whether intent_classifier thinks it's a
470
  # fact-find phrase. This is what fixes "39 years old" being misrouted to RAG.
471
- from backend.needs_finder import next_question, record_answer
472
  from backend.session_state import get_session
473
  session = get_session(session_id or "anonymous")
474
 
@@ -562,391 +387,110 @@ async def handle_turn(
562
  )
563
 
564
  if treat_as_fact_find:
565
- # KI-045 (2026-05-14) — natural-conversation classifier. Previously
566
- # EVERY user message during fact-find got parsed as an answer to the
567
- # awaiting slot. The bot couldn't gracefully handle off-topic asides,
568
- # mid-flow questions, or volunteered profile information. Now we
569
- # classify the user's message first; only "direct_answer" continues
570
- # into the existing normalizer flow.
571
- #
572
- # Heuristic-only (no LLM call — keeps latency negligible):
573
- #
574
- # • question → message ends with "?" AND has 4+ words AND no
575
- # obvious slot-answer pattern. User is asking
576
- # something off-topic; we exit fact-find and let
577
- # the QA brain answer.
578
- # • intent_change → explicit phrases like "never mind", "actually
579
- # let me ask", "wait, can you...", "forget the
580
- # profile, just tell me...". User is steering
581
- # away; we exit fact-find.
582
- # • otherwise → direct_answer (existing normalizer flow).
583
- #
584
- # In all non-answer cases we keep the awaiting slot pinned so when
585
- # the user returns to fact-find next turn, we pick up where we
586
- # left off — and we flip `session.free_form_session = True` so the
587
- # rest of handle_turn routes to retrieval + brain, not back here.
588
- if session.awaiting_question_id and session.awaiting_question_id != "name":
589
- _t = user_text.lower().strip()
590
- _intent_change_phrases = (
591
- "never mind", "forget the profile", "forget profile",
592
- "actually let me ask", "wait, can you", "wait can you",
593
- "wait, tell me", "skip this", "skip that question",
594
- "let's switch", "lets switch", "stop asking",
595
- "i have a question", "just tell me",
596
- )
597
- _looks_intent_change = any(p in _t for p in _intent_change_phrases)
598
- _ends_q = _t.endswith("?") or _t.rstrip(".!").endswith("?")
599
- _wordy_q = _ends_q and len(_t.split()) >= 4
600
- # Don't misclassify enum-answer questions like "spouse?" /
601
- # "diabetes?" (short, often a clarification request)
602
- _looks_off_topic_q = _wordy_q and not any(
603
- kw in _t for kw in (
604
- "yes", "no", "self", "spouse", "kids", "parents",
605
- "diabetes", "bp", "thyroid", "lakh", "lac",
606
- )
607
- )
608
- if _looks_intent_change or _looks_off_topic_q:
609
- # Exit fact-find: let the rest of handle_turn route to the
610
- # QA / brain path. Keep awaiting_question_id pinned so we
611
- # remember where we were for next turn. Flip free-form so
612
- # the should_route_to_fact_find guard returns False on the
613
- # follow-up turn.
614
- session.free_form_session = True
615
- session._flush()
616
- # Fall out of the fact-find branch entirely — the user's
617
- # message is treated as a regular QA turn from here.
618
- treat_as_fact_find = False # noqa: F841 — re-checked below
619
-
620
- # If we just exited fact-find via the classifier, skip the answer
621
- # handling block + the question-emission tail; let execution fall
622
- # through to the QA / retrieval path below.
623
 
624
- if treat_as_fact_find:
625
- # If we were awaiting an answer, normalize + record it before picking next Q.
626
- # Uses backend/fact_find_normalizer.py to map free-text → schema enums.
627
- #
628
- # Two safety nets:
629
- # (1) Keyword fast-path inside normalize_answer() handles ~80% of
630
- # answers without needing the NIM LLM (no rate-limit risk).
631
- # (2) Re-ask cap (`_reask_count` on the session) — after 2 consecutive
632
- # failures on the same question we GIVE UP, skip that question,
633
- # and proceed to the next. Better to have an incomplete profile
634
- # than an infinite reask loop.
635
- ambiguous_or_failed = False
636
- # Telemetry: KI-019 (2026-05-14) — populate this dict whenever the
637
- # slot-filler successfully captures a normalized answer so the API
638
- # response's `profile_updates` field reflects fact-find captures (it
639
- # previously only reflected free-form mode captures, which made the
640
- # 100-persona audit appear to show age captured for only 12/100 when
641
- # the slot-filler was actually working — see readback summaries in
642
- # `needs_finder::fact_find_complete` turns).
643
- fact_find_profile_updates: dict = {}
644
- # KI-040 — named-profile return-visit detection. Set when we resolve
645
- # a name and find a stored profile for that name; used at the bottom
646
- # of this branch to emit a "Welcome back" message instead of the
647
- # next slot's question.
648
- returning_visitor_greeting: Optional[str] = None
649
-
650
- # KI-059 (2026-05-15) — opening-turn name capture. If the user
651
- # volunteered a name in their FIRST message ("Hi this is Rohit",
652
- # "I'm Anjali", "My name is Ravi") before we asked, route it into
653
- # the name-slot handler below so the existing extract + save +
654
- # welcome-back logic fires — instead of asking "what should I
655
- # call you?" right after they told us. Pre-condition: not yet
656
- # awaiting any slot, no name on the profile, and not in
657
- # free-form session.
658
- if (not session.awaiting_question_id
659
- and not session.profile.name
660
- and not session.free_form_session
661
- and _contains_self_introduction(user_text)):
662
- session.set_awaiting("name")
663
-
664
- if session.awaiting_question_id:
665
- from backend.fact_find_normalizer import is_valid_answer, normalize_answer
666
- qid = session.awaiting_question_id
667
- # KI-040 — special handling for the name slot: free-text, no enum.
668
- if qid == "name":
669
- from backend.profile_store import is_valid_name, load_profile, save_profile
670
- raw_name = user_text.strip().strip(".,!?")
671
- # KI-059 — strip a leading greeting + comma so "Hi, this is
672
- # Rohit" / "Hello I'm Anjali" reduces to the introduction
673
- # phrase the next loop expects.
674
- for greet in ("hi there ", "hello there ", "hey there ",
675
- "hi, ", "hello, ", "hey, ",
676
- "hi ", "hello ", "hey ", "namaste ", "yo "):
677
- if raw_name.lower().startswith(greet):
678
- raw_name = raw_name[len(greet):].strip()
679
- break
680
- # Tolerate "I'm Rohit" / "My name is Rohit" / "call me Rohit"
681
- for prefix in ("i'm ", "i am ", "my name is ", "name is ", "call me ", "this is "):
682
- if raw_name.lower().startswith(prefix):
683
- raw_name = raw_name[len(prefix):].strip()
684
- break
685
- # Capitalize a sensible display form
686
- if raw_name and not any(c.isupper() for c in raw_name):
687
- raw_name = " ".join(w.capitalize() for w in raw_name.split())
688
- if is_valid_name(raw_name):
689
- session.update_profile_field("name", raw_name)
690
- fact_find_profile_updates["name"] = raw_name
691
- if qid not in session.profile.asked:
692
- session.profile.asked.append(qid)
693
- session.set_awaiting(None)
694
- if hasattr(session, "_reask_counts"):
695
- session._reask_counts.pop(qid, None)
696
- # Look up an existing profile for this name. If found,
697
- # MERGE its fields into the current empty session so the
698
- # user doesn't repeat the 9-question walk.
699
- stored = load_profile(raw_name)
700
- if stored is not None and any(
701
- getattr(stored, f, None) not in (None, [], "")
702
- for f in ("age", "dependents", "income_band", "primary_goal")
703
- ):
704
- for field_name in (
705
- "age", "dependents", "income_band", "existing_cover_inr",
706
- "primary_goal", "location_tier", "parents_to_insure",
707
- "parents_age_max", "parents_has_ped", "health_conditions",
708
- "budget_band",
709
- ):
710
- val = getattr(stored, field_name, None)
711
- if val not in (None, [], ""):
712
- session.update_profile_field(field_name, val)
713
- fact_find_profile_updates[field_name] = val
714
- # Mark all stored slots as already-asked so next_question
715
- # skips them.
716
- for slot_id in ("age", "dependents", "income_band",
717
- "existing_cover", "primary_goal", "location",
718
- "parents_age", "health_conditions", "budget"):
719
- if slot_id not in session.profile.asked:
720
- session.profile.asked.append(slot_id)
721
- session.free_form_session = True
722
- session._flush()
723
- # KI-061 (2026-05-15) — personalized welcome-back:
724
- # summarize what's on file, call out helpful gaps,
725
- # offer next step. So the returning visitor sees
726
- # the bot remembers them precisely, and any missing
727
- # info can be filled before recommending.
728
- known_summary = _format_known_profile_summary(stored)
729
- missing_labels = _format_missing_slots(stored)
730
- parts = [f"Welcome back, {raw_name}!"]
731
- if known_summary:
732
- parts.append(
733
- f"Here's what I have on file from your last visit: {known_summary}."
734
- )
735
- if missing_labels:
736
- if len(missing_labels) == 1:
737
- gap_phrase = missing_labels[0]
738
- elif len(missing_labels) == 2:
739
- gap_phrase = " and ".join(missing_labels)
740
- else:
741
- gap_phrase = ", ".join(missing_labels[:-1]) + f", and {missing_labels[-1]}"
742
- parts.append(
743
- f"We never got around to {gap_phrase} — happy to fill that in "
744
- "so I can grade policies more precisely, or you can jump straight "
745
- "to a recommendation or any specific question."
746
- )
747
- else:
748
- parts.append(
749
- "Looks like we have everything we need — want me to suggest some "
750
- "policies that fit, or do you have a specific question in mind?"
751
- )
752
- returning_visitor_greeting = " ".join(parts)
753
- else:
754
- # New visitor — record an initial profile so subsequent
755
- # turns persist; orchestrator will continue to next slot.
756
- save_profile(raw_name, session.profile, session_id=session_id)
757
- else:
758
- ambiguous_or_failed = True
759
- elif not is_valid_answer(user_text):
760
- ambiguous_or_failed = True
761
- else:
762
- try:
763
- normalized = await normalize_answer(qid, user_text)
764
- except Exception:
765
- normalized = None
766
- if normalized is None:
767
- ambiguous_or_failed = True
768
- else:
769
- # Apply the normalized value to the right Profile field.
770
- q_obj = next((q for q in __import__('backend.needs_finder', fromlist=['GRAPH']).GRAPH if q.id == qid), None)
771
- if q_obj is not None:
772
- session.update_profile_field(q_obj.field, normalized)
773
- fact_find_profile_updates[q_obj.field] = normalized
774
- if qid not in session.profile.asked:
775
- session.profile.asked.append(qid)
776
- session.set_awaiting(None)
777
- # Reset re-ask counter on success
778
- if hasattr(session, "_reask_counts"):
779
- session._reask_counts.pop(qid, None)
780
- # KI-040 — persist the updated profile to JSON store
781
- # so next-visit lookup-by-name has the latest data.
782
- if session.profile.name:
783
- try:
784
- from backend.profile_store import save_profile
785
- save_profile(session.profile.name, session.profile, session_id=session_id)
786
- except Exception:
787
- pass
788
- else:
789
- ambiguous_or_failed = True
790
-
791
- # ---- Re-ask cap (safety against infinite loops) ----
792
- if ambiguous_or_failed:
793
- if not hasattr(session, "_reask_counts"):
794
- session._reask_counts = {}
795
- session._reask_counts[qid] = session._reask_counts.get(qid, 0) + 1
796
- if session._reask_counts[qid] >= 2:
797
- # Give up on this question; mark it asked so next_question moves on.
798
- if qid not in session.profile.asked:
799
- session.profile.asked.append(qid)
800
- session.set_awaiting(None)
801
- ambiguous_or_failed = False # no longer a reask situation
802
-
803
- # KI-056 (2026-05-15) — opportunistic dependents capture from any
804
- # free-text fact-find turn. If the user mentioned spouse / kids /
805
- # parents while answering an UNRELATED slot ("my wife also doesn't
806
- # have anything" in response to existing_cover), pre-fill the
807
- # dependents slot so we don't waste a turn asking again later.
808
- # Only fires when the slot is still empty — never overwrites an
809
- # explicit user-provided answer to the dependents question.
810
- if session.profile.dependents in (None, ""):
811
- from backend.needs_finder import infer_dependents_from_text
812
- inferred = infer_dependents_from_text(user_text)
813
- if inferred:
814
- session.update_profile_field("dependents", inferred)
815
- fact_find_profile_updates["dependents"] = inferred
816
- if "dependents" not in session.profile.asked:
817
- session.profile.asked.append("dependents")
818
-
819
- # KI-040 — returning-visitor short-circuit. If we recognised the user's
820
- # name and loaded their stored profile, skip directly to the greeting
821
- # without picking another fact-find question.
822
- if returning_visitor_greeting:
823
- return TurnResult(
824
- reply_text=returning_visitor_greeting,
825
- citations=[],
826
- retrieved_chunk_ids=[],
827
- brain_used="needs_finder::welcome_back",
828
- intent="fact_find",
829
- language=language,
830
- latency_ms=int((time.time() - t0) * 1000),
831
- raw_reply=returning_visitor_greeting,
832
- faithfulness_passed=True,
833
- blocked=False,
834
- profile_updates=fact_find_profile_updates,
835
- )
836
 
837
- # If the answer didn't normalize, pick the SAME question again (re-ask
838
- # with a gentle clarifier) instead of moving on with garbage — UNLESS
839
- # the cap above just kicked in, in which case we move on.
840
- if ambiguous_or_failed and session.awaiting_question_id:
841
- q = next((qq for qq in __import__('backend.needs_finder', fromlist=['GRAPH']).GRAPH if qq.id == session.awaiting_question_id), None)
842
- else:
843
- q = next_question(session.profile, language=language)
844
-
845
- if q is not None:
846
- session.set_awaiting(q.id)
847
- if ambiguous_or_failed:
848
- opener_en = "Sorry, I didn't catch that. Let me ask again — "
849
- opener_hi = "माफ़ कीजिए, समझ नहीं आया। दोबारा पूछता हूँ — "
850
- elif in_fact_find_continuation:
851
- # KI-056 (2026-05-15) — dynamic acknowledger. Replaces the
852
- # literal "Got it. " that previously appeared at the start of
853
- # every continuation turn. Family disclosures get an explicit
854
- # acknowledgement; neutral turns rotate through 8 variants
855
- # deterministic on (session_id, turn_idx, slot).
856
- opener_en = _pick_opener(
857
- user_text=user_text,
858
- session_id=session_id,
859
- turn_idx=len(session.profile.asked),
860
- slot_just_filled=session.awaiting_question_id or None,
861
- )
862
- opener_hi = "ठीक है। "
863
- else:
864
- opener_en = "Happy to help. " if not user_text.lower().strip().startswith(("hi", "hello")) else "Hi! "
865
- opener_hi = "मदद के लिए तैयार हूँ। "
866
-
867
- # KI-032 — Per-turn LLM paraphrase + verifier so the bot stops
868
- # asking the same 9 hardcoded questions with the same wording in
869
- # every session. English only for now; the indic branch keeps
870
- # the canonical Hindi text. Re-ask flows ALSO skip paraphrase —
871
- # we want the literal "let me ask again" to read the canonical
872
- # so the user has a stable anchor.
873
- question_text_en = q.prompt_en
874
- if language != "indic" and not ambiguous_or_failed:
875
- try:
876
- from backend.question_paraphraser import paraphrase_question
877
- paraphrased = await paraphrase_question(
878
- canonical=q.prompt_en,
879
- slot_id=q.id,
880
- session_id=session_id,
881
- recent_user_text=user_text,
882
- )
883
- if paraphrased:
884
- question_text_en = paraphrased
885
- except Exception:
886
- # Paraphraser must never block fact-find; on any failure
887
- # we silently keep the canonical wording.
888
- pass
889
-
890
- reply = (opener_hi + q.prompt_hi) if language == "indic" else (opener_en + question_text_en)
891
- if ambiguous_or_failed:
892
- brain_tag = "needs_finder::reask_clarify"
893
- else:
894
- brain_tag = "needs_finder::fact_find_continue" if in_fact_find_continuation else "needs_finder::fact_find_start"
895
  else:
896
- # Fact-find complete — produce a profile readback + invite next step.
897
- # CRITICAL (KI-012): flip free_form_session=True so subsequent turns
898
- # don't re-enter the fact-find branch and repeat the readback.
899
- #
900
- # KI-015 — explicitly invite corrections in the readback message
901
- # before recommending. Real user testing surfaced that the bot
902
- # captured age=30 when user said 31, and the readback only said
903
- # "Want me to suggest…" — no explicit "correct me if wrong" prompt.
904
- # Corrections in the next turn flow through the conversational
905
- # profile-update extractor (free-form mode), so the bot WILL
906
- # absorb "actually I'm 31" — but the user has to know they can
907
- # say that. This message tells them.
908
- from backend.needs_finder import readback_summary
909
  session.set_awaiting(None)
 
 
 
 
910
  session.free_form_session = True
911
  session._flush()
912
- summary = readback_summary(session.profile)
913
- # KI-056 (2026-05-15) — dynamic readback opener. Picks a varied
914
- # acknowledger so the completion turn doesn't always start with
915
- # "Got it — here's what I've understood:".
916
- readback_opener = _pick_opener(
917
- user_text=user_text,
918
- session_id=session_id,
919
- turn_idx=len(session.profile.asked),
920
- slot_just_filled="__readback__",
921
- ).rstrip()
922
- if not readback_opener:
923
- readback_opener = "Here's what I've understood:"
924
- else:
925
- readback_opener = f"{readback_opener} Here's what I've understood:"
926
- # KI-068 (2026-05-15) — dropped the `**bold**` wrapper which was
927
- # leaking as literal asterisks in the chat panel + getting read by
928
- # TTS as "asterisk asterisk".
929
- reply = (
930
- f"{readback_opener} {summary}. "
931
- f"If anything's wrong, just tell me — e.g., \"actually I'm 31\", or "
932
- f"\"I want to cover my parents too\". "
933
- f"Otherwise — want me to suggest 2-3 policies that fit your profile, "
934
- f"or do you have a specific policy in mind to dig into?"
935
- )
936
- brain_tag = "needs_finder::fact_find_complete"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
937
 
938
  return TurnResult(
939
- reply_text=reply,
940
  citations=[],
941
  retrieved_chunk_ids=[],
942
  brain_used=brain_tag,
943
  intent="fact_find",
944
  language=language,
945
  latency_ms=int((time.time() - t0) * 1000),
946
- raw_reply=reply,
947
  faithfulness_passed=True,
948
  blocked=False,
949
- profile_updates=fact_find_profile_updates, # KI-019 telemetry fix
950
  )
951
 
952
  # User explicitly asked a specific question — leave fact-find mode if they were in one.
 
12
 
13
  from __future__ import annotations
14
 
 
15
  import re
16
  import time
17
  from dataclasses import dataclass, field
 
149
  return BrainPick(get_fast_brain_llm(), f"v4-flash::{intent}")
150
 
151
 
152
+ # ---------- welcome-back greeting helpers ----------
153
  #
154
+ # KI-070 (2026-05-15) — the conversational acknowledger rotation
155
+ # (_pick_opener / _family_aware_opener / _NEUTRAL_OPENERS_EN etc.) and the
156
+ # self-introduction regex (_SELF_INTRO_RE / _NON_NAME_TOKENS /
157
+ # _contains_self_introduction) were removed alongside the 3-layer fact-find
158
+ # stitching. The single-LLM-call `drive_fact_find` brain now produces natural
159
+ # acknowledgers AND extracts names natively from any free-text message —
160
+ # making the rule-based helpers redundant.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
 
163
  # KI-061 (2026-05-15) — human-readable summaries for the welcome-back
 
236
  return missing
237
 
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  # ---------- main entrypoint ----------
240
 
241
  @dataclass
 
294
  # specific question), interpret the user's message as that answer and emit
295
  # the next question — regardless of whether intent_classifier thinks it's a
296
  # fact-find phrase. This is what fixes "39 years old" being misrouted to RAG.
 
297
  from backend.session_state import get_session
298
  session = get_session(session_id or "anonymous")
299
 
 
387
  )
388
 
389
  if treat_as_fact_find:
390
+ # KI-070 (2026-05-15) — single-LLM-call fact-find brain replaces the
391
+ # 3-layer stitching of (hardcoded canonical prompts + per-turn
392
+ # paraphraser + acknowledger rotation). One model call now produces
393
+ # the natural reply AND a machine-readable trailer describing what
394
+ # was captured, which slot it's driving toward, and whether
395
+ # fact-find is complete.
396
+ from backend.fact_find_brain import (
397
+ FIELD_TO_QUESTION_ID,
398
+ drive_fact_find,
399
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
400
 
401
+ outcome = await drive_fact_find(
402
+ user_text=user_text,
403
+ session=session,
404
+ chat_history=chat_history,
405
+ session_id=session_id,
406
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
 
408
+ # Apply captured updates to profile + mark matching slot ids as asked
409
+ # so the orchestrator's downstream `next_question` (used in the
410
+ # canonical fallback + completeness API) doesn't double-ask.
411
+ fact_find_profile_updates: dict = {}
412
+ for field_name, value in outcome.captured_updates.items():
413
+ if value in (None, "", []):
414
+ continue
415
+ session.update_profile_field(field_name, value)
416
+ fact_find_profile_updates[field_name] = value
417
+ matching_slot = FIELD_TO_QUESTION_ID.get(field_name)
418
+ if matching_slot and matching_slot not in session.profile.asked:
419
+ session.profile.asked.append(matching_slot)
420
+
421
+ # Track slot_driving so subsequent turns know where we are. The new
422
+ # brain produces FIELD names (e.g., "income_band"); translate to the
423
+ # canonical question id (e.g., "income_band") via FIELD_TO_QUESTION_ID
424
+ # so the rest of the orchestrator (which keys on question ids) stays
425
+ # consistent.
426
+ if outcome.slot_driving:
427
+ slot_qid = FIELD_TO_QUESTION_ID.get(outcome.slot_driving, outcome.slot_driving)
428
+ session.set_awaiting(slot_qid)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  else:
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  session.set_awaiting(None)
431
+
432
+ # If the brain decided fact-find is complete, flip free-form so
433
+ # subsequent turns route to retrieval+brain (not back here).
434
+ if outcome.fact_find_complete:
435
  session.free_form_session = True
436
  session._flush()
437
+
438
+ # KI-063 — opportunistic profile-chunk re-upsert if any field changed
439
+ # so this turn's downstream retrieval (when complete=true triggers a
440
+ # follow-up recommendation) sees the latest profile.
441
+ if fact_find_profile_updates:
442
+ try:
443
+ from backend.profile_rag import upsert_profile_chunk
444
+ p = session.profile
445
+ await upsert_profile_chunk(session_id or "anonymous", {
446
+ "age": p.age,
447
+ "dependents": p.dependents,
448
+ "income_band": p.income_band,
449
+ "existing_cover_inr": p.existing_cover_inr,
450
+ "primary_goal": p.primary_goal,
451
+ "location_tier": p.location_tier,
452
+ "parents_to_insure": p.parents_to_insure,
453
+ "parents_age_max": p.parents_age_max,
454
+ "parents_has_ped": p.parents_has_ped,
455
+ "budget_band": p.budget_band,
456
+ "health_conditions": p.health_conditions,
457
+ })
458
+ except Exception as e:
459
+ import logging
460
+ logging.warning(
461
+ "fact_find_brain profile-chunk upsert failed (session=%s): %s: %s",
462
+ session_id, type(e).__name__, str(e)[:200],
463
+ )
464
+
465
+ # KI-040 / KI-062 — named-profile persistence preserved. If the brain
466
+ # captured (or already has) a name on the profile, write the merged
467
+ # profile to disk so the next visit can welcome the user back.
468
+ if session.profile.name:
469
+ try:
470
+ from backend.profile_store import save_profile
471
+ save_profile(session.profile.name, session.profile, session_id=session_id)
472
+ except Exception:
473
+ pass
474
+
475
+ if outcome.ambiguous:
476
+ brain_tag = "fact_find_brain::fallback"
477
+ elif outcome.fact_find_complete:
478
+ brain_tag = "fact_find_brain::complete"
479
+ else:
480
+ brain_tag = "fact_find_brain::continue"
481
 
482
  return TurnResult(
483
+ reply_text=outcome.reply_text,
484
  citations=[],
485
  retrieved_chunk_ids=[],
486
  brain_used=brain_tag,
487
  intent="fact_find",
488
  language=language,
489
  latency_ms=int((time.time() - t0) * 1000),
490
+ raw_reply=outcome.reply_text,
491
  faithfulness_passed=True,
492
  blocked=False,
493
+ profile_updates=fact_find_profile_updates,
494
  )
495
 
496
  # User explicitly asked a specific question — leave fact-find mode if they were in one.
backend/question_paraphraser.py DELETED
@@ -1,193 +0,0 @@
1
- """LLM-driven per-turn paraphrasing for the fact-find question graph.
2
-
3
- Real-user testing on 2026-05-14 flagged the bot as "mechanical and robotic":
4
- the 9 fact-find questions (backend/needs_finder.py::GRAPH) are hardcoded
5
- strings asked in fixed order with fixed wording. This module wraps each
6
- canonical question with a fast NIM/Groq paraphrase pass + a verifier that
7
- rejects any paraphrase which drifts off-slot, so the worst case degrades
8
- gracefully to the canonical text (no UX regression).
9
-
10
- Caching: a module-level dict keyed by (session_id, slot_id) holds the
11
- paraphrase across the lifetime of a session. Each slot is therefore
12
- LLM-paraphrased AT MOST ONCE per session → max 9 paraphrase calls per
13
- 30-turn audit persona, even though the orchestrator can call this
14
- function on every fact-find turn.
15
-
16
- KI-032 (2026-05-14).
17
- """
18
-
19
- from __future__ import annotations
20
-
21
- import json
22
- import logging
23
- import re
24
- from typing import Optional
25
-
26
- from backend.providers.base import ChatMessage
27
- from backend.providers.nvidia_nim_llm import FAST_BRAIN_CHAIN, NimChainLLM
28
-
29
- # Slot IDs match Question.id in needs_finder.GRAPH — keep this in lock-step.
30
- ALLOWED_SLOTS = frozenset({
31
- "age", "dependents", "income_band", "existing_cover", "primary_goal",
32
- "location", "parents_age", "health_conditions", "budget",
33
- })
34
-
35
-
36
- _PARAPHRASER_SYSTEM = """You are rewriting fact-find questions for a health insurance bot in India.
37
-
38
- The bot asks 9 fixed questions about the customer's age, dependents, income,
39
- existing insurance, goals, city, parents' health, own pre-existing conditions,
40
- and budget. Your job is to rephrase the next question so it sounds warm and
41
- conversational instead of robotic — without changing what's being asked.
42
-
43
- NON-NEGOTIABLE CONSTRAINTS:
44
- 1. The paraphrase must ask about the SAME piece of information (same slot).
45
- 2. Preserve any educational context the original explains ("this matters
46
- because…"). Rewrite the explanation in your own words, but keep its
47
- meaning.
48
- 3. Warm and conversational, not verbose. 1-3 sentences max.
49
- 4. Must end with a question mark.
50
- 5. Indian English is fine — "₹", "lakh", "metro/tier-2 city" are OK.
51
- 6. Do NOT add new questions or ask for additional information beyond the slot.
52
-
53
- OUTPUT — strict JSON with exactly two fields, NO code fences, NO commentary:
54
- {"paraphrase": "...", "asks_about_slot": "<slot_id>"}
55
-
56
- Valid slot IDs: age | dependents | income_band | existing_cover | primary_goal | location | parents_age | health_conditions | budget
57
- """
58
-
59
-
60
- _USER_TEMPLATE = (
61
- "ORIGINAL CANONICAL: {original}\n"
62
- "SLOT: {slot_id}\n"
63
- "USER'S MOST RECENT MESSAGE (for tone calibration): {recent_user_text}\n\n"
64
- "Rewrite the question now. Return strict JSON only."
65
- )
66
-
67
-
68
- # (session_id, slot_id) → cached paraphrase string. None means "tried + failed,
69
- # fall back to canonical for this session" so we don't retry the LLM each turn.
70
- _PARAPHRASE_CACHE: dict[tuple[str, str], Optional[str]] = {}
71
-
72
-
73
- def clear_session_cache(session_id: str) -> int:
74
- """Drop all cached paraphrases for one session. Called from
75
- session_state.reset_session() so a "Start fresh" click produces fresh
76
- paraphrase wording. Returns count of dropped keys."""
77
- keys = [k for k in _PARAPHRASE_CACHE.keys() if k[0] == session_id]
78
- for k in keys:
79
- _PARAPHRASE_CACHE.pop(k, None)
80
- return len(keys)
81
-
82
-
83
- def _parse_json_lenient(raw: str) -> Optional[dict]:
84
- raw = raw.strip()
85
- if not raw:
86
- return None
87
- # Strip code fences some models add despite instructions
88
- if raw.startswith("```"):
89
- raw = re.sub(r"^```(?:json)?\s*", "", raw)
90
- raw = re.sub(r"\s*```\s*$", "", raw)
91
- try:
92
- return json.loads(raw)
93
- except Exception:
94
- pass
95
- # Last-resort: pull the first balanced {...}
96
- m = re.search(r"\{.*\}", raw, flags=re.DOTALL)
97
- if not m:
98
- return None
99
- try:
100
- return json.loads(m.group(0))
101
- except Exception:
102
- return None
103
-
104
-
105
- async def paraphrase_question(
106
- canonical: str,
107
- slot_id: str,
108
- session_id: Optional[str] = None,
109
- recent_user_text: str = "",
110
- *,
111
- total_budget_s: float = 6.0,
112
- ) -> Optional[str]:
113
- """LLM-rewrite the canonical fact-find question + verify it still targets
114
- `slot_id`. Returns the paraphrase if it passes the verifier, None otherwise.
115
-
116
- Callers should fall back to the canonical text on None.
117
-
118
- Result is cached per (session_id, slot_id) so the LLM is only called once
119
- per slot per session. A None result is also cached so we don't keep
120
- retrying a flaky model mid-session.
121
- """
122
- if slot_id not in ALLOWED_SLOTS:
123
- return None
124
-
125
- cache_key = (session_id or "_anon", slot_id)
126
- if cache_key in _PARAPHRASE_CACHE:
127
- return _PARAPHRASE_CACHE[cache_key]
128
-
129
- user_msg = _USER_TEMPLATE.format(
130
- original=canonical,
131
- slot_id=slot_id,
132
- recent_user_text=(recent_user_text or "(no prior message yet)")[:300],
133
- )
134
-
135
- llm = NimChainLLM(
136
- chain=FAST_BRAIN_CHAIN,
137
- timeout=4.0,
138
- role="paraphraser",
139
- total_budget_s=total_budget_s,
140
- )
141
-
142
- try:
143
- res = await llm.chat(
144
- messages=[
145
- ChatMessage(role="system", content=_PARAPHRASER_SYSTEM),
146
- ChatMessage(role="user", content=user_msg),
147
- ],
148
- temperature=0.7,
149
- max_tokens=200,
150
- response_format={"type": "json_object"},
151
- )
152
- except Exception as e:
153
- logging.info("paraphraser LLM call failed slot=%s err=%s — falling back",
154
- slot_id, type(e).__name__)
155
- _PARAPHRASE_CACHE[cache_key] = None
156
- return None
157
-
158
- data = _parse_json_lenient(res.text or "")
159
- if not data:
160
- logging.info("paraphraser JSON unparseable slot=%s — falling back", slot_id)
161
- _PARAPHRASE_CACHE[cache_key] = None
162
- return None
163
-
164
- paraphrase = (data.get("paraphrase") or "").strip()
165
- claimed_slot = (data.get("asks_about_slot") or "").strip()
166
-
167
- # ---- Verifier ---------------------------------------------------------
168
- if claimed_slot != slot_id:
169
- logging.info("paraphraser slot drift slot=%s claimed=%s — falling back",
170
- slot_id, claimed_slot)
171
- _PARAPHRASE_CACHE[cache_key] = None
172
- return None
173
- # KI-036 (2026-05-14) — strict end-position "?" check + reject malformed
174
- # punctuation patterns. Previous lenient `"?" in paraphrase` let outputs
175
- # like "...have their own insurance options.?" through, producing
176
- # awkward double-punctuation in production.
177
- para_stripped = paraphrase.rstrip()
178
- if not para_stripped.endswith("?"):
179
- logging.info("paraphraser doesn't end with '?' slot=%s — falling back", slot_id)
180
- _PARAPHRASE_CACHE[cache_key] = None
181
- return None
182
- if any(bad in para_stripped for bad in (".?", "?.", "??", "!?", "?!", ",?")):
183
- logging.info("paraphraser malformed punctuation slot=%s — falling back", slot_id)
184
- _PARAPHRASE_CACHE[cache_key] = None
185
- return None
186
- if not (30 <= len(paraphrase) <= 500):
187
- logging.info("paraphraser length oob slot=%s len=%d — falling back",
188
- slot_id, len(paraphrase))
189
- _PARAPHRASE_CACHE[cache_key] = None
190
- return None
191
-
192
- _PARAPHRASE_CACHE[cache_key] = paraphrase
193
- return paraphrase