rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
2a58c28
·
1 Parent(s): 58e3c82

feat(single_brain): wire view_context → ACTIVE POLICY DIVE-IN block (KI-330)

Browse files

Root cause caught in 2026-05-27 multi-PDF e2e audit. On 3 of 5 uploads,
asking "What are the waiting periods on this policy?" got back "Before I
pull your recommendations, just a couple more (you can skip any):" —
single_brain pivoted to profile-building / recommendation flow instead
of answering about the just-uploaded policy.

Triple root cause:
1. ChatRequest.view_context declared since launch but NEVER CONSUMED
anywhere on the backend (truly dead code).
2. single_brain.handle_turn signature didn't accept it.
3. Frontend set view_context.active_policy_id only when a marketplace
card was clicked (openPolicy modal); never on a just-uploaded PDF.

Fix:
- backend/single_brain.py: handle_turn(..., view_context=None);
_system_instruction(..., view_context=None);
new _build_active_policy_block() that appends an ACTIVE POLICY
DIVE-IN block to the system instruction when view_context.
active_policy_id is set. Block tells the model: answer the
question via retrieve_policies + get_policy_facts on that pid,
do NOT pivot to "pull your recommendations" unless the user
explicitly asks for one, profile-building only when the question
LITERALLY requires a missing fact.
- backend/main.py: pass req.view_context through to handle_turn.
- frontend/src/app/page.tsx: new activeUploadPid state, set when the
upload's card-bearing message lands inline in chat, plumbed into
view_context.active_policy_id (openPolicy from a clicked card
still takes priority).

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

backend/main.py CHANGED
@@ -927,6 +927,12 @@ async def chat(req: ChatRequest, request: Request):
927
  session=_sb_session,
928
  user_text=req.user_text,
929
  chat_history=req.chat_history,
 
 
 
 
 
 
930
  ),
931
  timeout=45.0,
932
  )
 
927
  session=_sb_session,
928
  user_text=req.user_text,
929
  chat_history=req.chat_history,
930
+ # KI-330 (2026-05-27) — pipe view_context through so
931
+ # single_brain can build an ACTIVE POLICY DIVE-IN
932
+ # block when the frontend tells us the user is
933
+ # focused on a specific policy. Field was declared
934
+ # on ChatRequest since launch but never consumed.
935
+ view_context=req.view_context or None,
936
  ),
937
  timeout=45.0,
938
  )
backend/single_brain.py CHANGED
@@ -744,9 +744,55 @@ def _build_contents(
744
  # is NOT cross-session and never reads disk.
745
 
746
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747
  def _system_instruction(
748
  profile, is_returning_user: bool = False, shortlist_block: str = "",
749
  reconstruct_from_history: bool = False,
 
750
  ) -> dict:
751
  """Bake the profile snapshot into the system prompt so each turn the
752
  LLM knows what's already captured. Returned in Gemini's expected
@@ -812,9 +858,14 @@ def _system_instruction(
812
  "now captured, proceed straight to retrieve_policies and "
813
  "recommendations. The user must never perceive any loss."
814
  )
 
 
 
 
815
  text = (
816
  SYSTEM_PROMPT + extra + reconstruct_block
817
  + (shortlist_block or "")
 
818
  )
819
  return {"parts": [{"text": text}]}
820
 
@@ -1805,6 +1856,7 @@ async def handle_turn(
1805
  session,
1806
  user_text: str,
1807
  chat_history: Optional[list[dict]] = None,
 
1808
  ) -> TurnResult:
1809
  """Single-LLM turn handler — replaces orchestrator.handle_turn behaviour
1810
  when USE_SINGLE_BRAIN is enabled.
@@ -1812,6 +1864,13 @@ async def handle_turn(
1812
  Returns a TurnResult whose shape matches orchestrator.TurnResult.
1813
  Raises SingleBrainError on unrecoverable Gemini failure so the api.py
1814
  caller falls through to the legacy orchestrator.
 
 
 
 
 
 
 
1815
  """
1816
  t0 = time.time()
1817
 
@@ -1912,6 +1971,7 @@ async def handle_turn(
1912
  is_returning_user=is_returning_user,
1913
  shortlist_block=_shortlist_block,
1914
  reconstruct_from_history=_reconstruct_from_history,
 
1915
  )
1916
 
1917
  # Bug #108 + #110 — if the user explicitly declines the pricing /
 
744
  # is NOT cross-session and never reads disk.
745
 
746
 
747
+ def _build_active_policy_block(view_context: Optional[dict]) -> str:
748
+ """KI-330 (2026-05-27) — when the frontend tells us the user is
749
+ actively viewing / has just uploaded a specific policy
750
+ (view_context.active_policy_id), tell the model to ANSWER ABOUT IT
751
+ using retrieve_policies + get_policy_facts. Do NOT pivot to the
752
+ profile-building / recommendation flow.
753
+
754
+ Origin: 2026-05-27 multi-PDF e2e audit. On 3 of 5 uploads, asking
755
+ "What are the waiting periods on this policy?" got back "Before I
756
+ pull your recommendations, just a couple more (you can skip any):"
757
+ — the model didn't realise it was in deep-dive-on-this-policy mode
758
+ because the view_context field on /api/chat (declared in
759
+ ChatRequest since launch) had never actually been consumed
760
+ anywhere on the backend.
761
+ """
762
+ if not view_context:
763
+ return ""
764
+ pid = (view_context or {}).get("active_policy_id") or ""
765
+ if not pid:
766
+ return ""
767
+ return (
768
+ "\n\n═══════════ ACTIVE POLICY DIVE-IN MODE ═══════════\n"
769
+ f"The user is currently focused on policy_id={pid} "
770
+ "(either just uploaded that PDF or opened that card). For this "
771
+ "turn:\n"
772
+ " 1. If the user's question is ABOUT that policy "
773
+ "(waiting periods, coverage, exclusions, claim ratio, room "
774
+ "rent, sub-limits, AYUSH, network hospitals, premium, anything "
775
+ "policy-specific) — answer it directly using "
776
+ "retrieve_policies(query=user_text, policy_filter_ids=["
777
+ f"'{pid}']) AND/OR get_policy_facts(policy_ids=['{pid}']). "
778
+ "Cite the policy.\n"
779
+ " 2. Do NOT pivot to 'let me pull your recommendations' or "
780
+ "'a few quick pricing inputs' on this turn unless the user "
781
+ "EXPLICITLY asks for recommendations. The user is dive-in mode.\n"
782
+ " 3. Profile-building is allowed only if the user's question "
783
+ "REQUIRES a profile fact you don't have (e.g. they ask 'is this "
784
+ "worth it for my age' and age is missing — then ask for that "
785
+ "one fact AFTER answering the policy-specific part).\n"
786
+ " 4. If retrieve_policies returns nothing relevant, say so "
787
+ "honestly ('I can't see that detail in this policy's wording') "
788
+ "— never invent."
789
+ )
790
+
791
+
792
  def _system_instruction(
793
  profile, is_returning_user: bool = False, shortlist_block: str = "",
794
  reconstruct_from_history: bool = False,
795
+ view_context: Optional[dict] = None,
796
  ) -> dict:
797
  """Bake the profile snapshot into the system prompt so each turn the
798
  LLM knows what's already captured. Returned in Gemini's expected
 
858
  "now captured, proceed straight to retrieve_policies and "
859
  "recommendations. The user must never perceive any loss."
860
  )
861
+ # KI-330 (2026-05-27) — active-policy dive-in block. See
862
+ # _build_active_policy_block for full rationale. Goes LAST so it has
863
+ # the strongest recency bias in the system instruction.
864
+ active_policy_block = _build_active_policy_block(view_context)
865
  text = (
866
  SYSTEM_PROMPT + extra + reconstruct_block
867
  + (shortlist_block or "")
868
+ + active_policy_block
869
  )
870
  return {"parts": [{"text": text}]}
871
 
 
1856
  session,
1857
  user_text: str,
1858
  chat_history: Optional[list[dict]] = None,
1859
+ view_context: Optional[dict] = None,
1860
  ) -> TurnResult:
1861
  """Single-LLM turn handler — replaces orchestrator.handle_turn behaviour
1862
  when USE_SINGLE_BRAIN is enabled.
 
1864
  Returns a TurnResult whose shape matches orchestrator.TurnResult.
1865
  Raises SingleBrainError on unrecoverable Gemini failure so the api.py
1866
  caller falls through to the legacy orchestrator.
1867
+
1868
+ `view_context` is the frontend-supplied snapshot of what the user is
1869
+ looking at (`{active_view, active_policy_id, filters}`) — wired
1870
+ through 2026-05-27 (KI-330) so the system_instruction can include
1871
+ an ACTIVE POLICY DIVE-IN block when the user is focused on a
1872
+ specific policy (just-uploaded PDF or opened card). See
1873
+ _build_active_policy_block for the full rationale.
1874
  """
1875
  t0 = time.time()
1876
 
 
1971
  is_returning_user=is_returning_user,
1972
  shortlist_block=_shortlist_block,
1973
  reconstruct_from_history=_reconstruct_from_history,
1974
+ view_context=view_context,
1975
  )
1976
 
1977
  # Bug #108 + #110 — if the user explicitly declines the pricing /
frontend/src/app/page.tsx CHANGED
@@ -202,6 +202,12 @@ export default function Page() {
202
  // this so ambient noise / TTS playback during the 30-60s extraction
203
  // window can no longer fire an unprompted chat turn.
204
  const [extractionInFlight, setExtractionInFlight] = useState<boolean>(false);
 
 
 
 
 
 
205
  // KI-027 (2026-05-14) — voice UX simplification. The legacy `handsFree`
206
  // mode (its own VAD auto-cutoff + post-turn mic re-open loop) has been
207
  // removed. We now have exactly two voice paths, mutually exclusive:
@@ -867,7 +873,11 @@ export default function Page() {
867
  signal: controller.signal,
868
  view_context: {
869
  active_view,
870
- active_policy_id: openPolicy?.policy_id,
 
 
 
 
871
  },
872
  onRetry: (attempt) => {
873
  // Show transient "warming up" hint while postChat retries the
@@ -1560,6 +1570,9 @@ export default function Page() {
1560
  ],
1561
  },
1562
  );
 
 
 
1563
  // Choice prompt fires AFTER the card, not before — that was the
1564
  // race the previous flow exhibited.
1565
  pushAssistant(t("upload.chat_choice"));
 
202
  // this so ambient noise / TTS playback during the 30-60s extraction
203
  // window can no longer fire an unprompted chat turn.
204
  const [extractionInFlight, setExtractionInFlight] = useState<boolean>(false);
205
+ // KI-330 (2026-05-27) — once an uploaded PDF's card lands inline in
206
+ // chat, that policy_id becomes the "active focus" so the chat brain's
207
+ // ACTIVE POLICY DIVE-IN block fires on subsequent turns and answers
208
+ // questions about THIS policy instead of pivoting to recommendations.
209
+ // Cleared when the user navigates away (marketplace / profile builder).
210
+ const [activeUploadPid, setActiveUploadPid] = useState<string | null>(null);
211
  // KI-027 (2026-05-14) — voice UX simplification. The legacy `handsFree`
212
  // mode (its own VAD auto-cutoff + post-turn mic re-open loop) has been
213
  // removed. We now have exactly two voice paths, mutually exclusive:
 
873
  signal: controller.signal,
874
  view_context: {
875
  active_view,
876
+ // KI-330 (2026-05-27) — when an uploaded PDF's card has just
877
+ // landed AND the user hasn't opened a different policy modal,
878
+ // make the upload the active focus so the brain enters DIVE-IN
879
+ // mode. openPolicy (a clicked marketplace card) takes priority.
880
+ active_policy_id: openPolicy?.policy_id || activeUploadPid || undefined,
881
  },
882
  onRetry: (attempt) => {
883
  // Show transient "warming up" hint while postChat retries the
 
1570
  ],
1571
  },
1572
  );
1573
+ // KI-330 (2026-05-27) — flag THIS upload as the dive-in target
1574
+ // so subsequent chat turns ground in this policy via view_context.
1575
+ setActiveUploadPid(r.policy_id);
1576
  // Choice prompt fires AFTER the card, not before — that was the
1577
  // race the previous flow exhibited.
1578
  pushAssistant(t("upload.chat_choice"));