Skip to content

feat: route turns to a quick or an analysis model and hand over a compact summary (E8.1, E8.2) - #686

Merged
neuromechanist merged 16 commits into
developfrom
feature/issue-670-quick-analysis-routing
Nov 11, 2026
Merged

neuromechanist merged 16 commits into
developfrom
feature/issue-670-quick-analysis-routing

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

NEMAR answers most turns on Haiku, and only code, plots and analysis need Sonnet.
Switching models inside one server session risks the thinking checks in #522, so a handover compacts the chat into a NEW session.

E8.1 routing

  • Community keys quick_model and analysis_model (NEMAR: haiku, sonnet): both or neither, each resolved through normalize_model, and an execute_code client tool is required. start_analysis is a reserved client tool name.
  • src/agents/model_routing.py: wants_analysis, the tier type, the quick-turn prompt section, the summary prompt and the word limit, tier_for_turn.
  • Routing applies only to streaming /chat and /chat/resume, when the community has both keys, the request declares execute_code and names no model. Communities without the keys behave exactly as before (no tier is passed, no mode on done).
  • ChatSession.mode (quick default, analysis), sticky. A tier is threaded down to _configured_default (never passed as requested_model, which is a 403 on OpenRouter without BYOK).
  • A quick turn binds the community's tools minus execute_code and get_full_output, plus start_analysis, a reserved client tool that reuses the parked-client-call mechanism. The stream layer turns that parked call into a handover instead of a tool_request. Its prompt section rides on create_community_assistant's additional_instructions.
  • /chat/resume always uses the session's tier.

E8.2 handover

  • With earlier turns: handover events summarizing, summarized (messages, words, summary), started (session_id, model), then the analysis run on a new session seeded with one HumanMessage (summary plus the reader's message), through the normal path so its session event and done.session_id carry the new id. done carries mode.
  • The summary is written by the quick model from Human and AI text only, at most 150 words, with the limit enforced in code (limit_words).
  • The old session stays valid (the parked call is dropped with the quick run's state). A first message needs no summary and flips its own session.
  • Documented in _stream_chat_response's docstring and docs/community-widget.md. Handover logic is in src/api/handover.py and src/agents/model_routing.py.

Out of scope as briefed: the widget card (E8.3), per-model cost (E8.4), the non-streamed /chat path, plan tools.

Closes #670
Closes #674

Commands run

  • uv run pytest tests/test_core/test_config/test_community.py tests/test_agents/test_model_routing.py tests/test_api -q: passed (2002 passed with the embed hygiene test, 1 skipped)
  • uv run pytest tests -q -m "not llm" (outside the paths above): 3413 passed, 1 failed (tests/test_tools/test_hed_suggest.py::test_real_program_suggests_a_schema_tag, a real-program tool test this change does not touch)
  • uv run pytest tests/test_integration/test_model_routing_llm.py -m llm -v: 3 skipped, no ANTHROPIC_API_KEY in this environment, so the real-model tests did not run here
  • uv run ruff check . && uv run ruff format --check .: passed

Both or neither, each resolved through normalize_model, and an execute_code
client tool is required. NEMAR sets haiku and sonnet. start_analysis is a
reserved client tool name. Tested: config tests.
wants_analysis, the tier type, the quick-turn prompt section and the summary
limit live in src/agents/model_routing.py. A quick turn binds start_analysis in
place of execute_code and get_full_output. Tested: tests/test_agents.
stream_handover emits summarizing, summarized and started, seeds a new analysis
session with the summary and the reader's message, and streams the analysis run
on it. Tested with the router wiring in the next commit.
…E8.1, E8.2)

ChatSession.mode, a tier threaded through _configured_default, _select_model,
_route_request and create_community_assistant, a quick-turn prompt section,
start_analysis turned into a handover by the stream layer, mode on done, and
/chat/resume on the session's tier. Tested: tests/test_api/test_model_routing.py
with the model stand-in.
Documents the handover events in docs/community-widget.md, the keys in
yaml_registry.md and the changelog. The LLM tests skip without an Anthropic key
and were not run here.
…h is sticky

Bare run(s), spectrum, filter and fit matched ordinary BIDS and NEMAR
vocabulary and moved the reader to the analysis model for the rest of the
conversation. Tested: unit tests incl. negatives for the reported phrases.
…er a yield

A first-message start_analysis released the session and re-claimed it after the
nested run sent its session event; a handover claimed its new session only after
the same event. Both now claim first and pass the claim on (turn_claimed). Tested:
claims are None on every session after each handover path, follow-ups succeed,
and the claim is held when the analysis run starts.
…e turn

A summarizer error after the summarizing event ended the stream. It now retries
a provider failure that can clear, and falls back to the tail (not the head) of
the reader's last three messages, logged and flagged degraded on the event. The
summary is framed as background context and fenced from the reader's message.
Tested: unit and stream-level tests with a failing summarizer.
The quick run and the summary are logged as <request id>:quick, priced at the
quick model, so done.request_id names one row. The summary's tokens are counted
and it runs under the request's LangFuse config. Tested: rows per handover path
read from the real metrics database.
Tier was written three times (model_routing, assistants/community, client_tools);
all now import it from src.core.config.community. The quick-mode instruction
merge is computed before the constructor call. Tested: routing and config tests.
… widget against the handover stream

The widget set a 'writing' label for it and no tool_start or tool_end followed.
Adds frontend/test-widget-handover-events.js (handover events ignored, second
session event adopted, next message on the new session), wired into Frontend
Tests. Tested: bun test passes, API tests pass.
…call and kill-switch cases

Replaces a check that was always true with index comparisons, simplifies the
redundant tool-binding assertion. Tested: API routing tests pass.
@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 1: outcomes

Pushed to this branch (7 commits). Tested: uv run pytest tests/test_api tests/test_agents tests/test_tools tests/test_core tests/test_metrics tests/test_frontend (4150 passed; the only failure is the pre-existing tests/test_tools/test_hed_suggest.py::test_real_program_suggests_a_schema_tag, and tests/test_core/test_llm_service.py fails to collect on this Python, both unrelated), bun frontend/test-widget-handover-events.js (9 passed), uv run ruff check . && uv run ruff format --check . clean.

  • 1. wants_analysis false positives (important): fixed. The pattern is now only unambiguous request phrasing: run this|it|that|the code (and running ...), plot, analyze, compute, execute, power spectrum, spectra, ERP image, filter the|my data|signal|recording. Bare run(s), spectrum, filter and fit(s) are gone. I also left out the bare run on the finding listed, for the same precision reason. The "costs one handover" claim is corrected in the docstring, docs/community-widget.md and the CHANGELOG (the session is sticky). Negative tests added for the four reported phrases plus a fifth.
  • 2. Claim released across a yield (important): fixed. _stream_chat_response takes turn_claimed; a first-message start_analysis keeps its claim and passes it on instead of end_turn() then re-claiming, and stream_handover claims the new session before it sends started, releasing it in a finally (the nested streams are closed with aclosing). Tests assert turn_started_at is None on the old and new sessions after a keyword handover, a start_analysis handover, a first-message start_analysis and a failed analysis run, that a follow-up on the same session succeeds, and that the claim is held when the analysis run starts and released if the client leaves.
  • 3. Duplicate request_id rows and unmetered summary (important): fixed. The quick model's work (the quick run that called start_analysis, if any, plus the summary) is one row, <request id>:quick, priced at the quick model; the analysis run keeps the id done.request_id carries. The summary's tokens are counted, it is passed through ModelRuns for the incomplete-usage warning, and it runs under the request's LangFuse config. Tests read the real metrics database for all three paths. While doing this I found that the metrics middleware writes a stub row (no model, no tokens) under the same id for every streamed request, with or without routing; that is code this PR does not touch, so it is filed as Streamed chat requests log a stub request_log row under the same request_id as the handler's row #687 and the new tests filter stub rows out.
  • 4. Summarizer without retry or failure handling (important): fixed. summarize_history retries once on a failure classify_model_error calls retryable (the stream helper is built around graph events, so a plain call has its own small loop using the same classification), and on a failure that survives, or an empty reply, it degrades: the handover continues on the reader's words, logged with an error id, and summarized carries "degraded": true. The fallback now takes the tail (last 150 words of the last three messages), not the head. Unit and stream-level tests with a failing summarizer model (tests/helpers/chat_models.py::FailingThenSayingChatModel).
  • 5. Weak or vacuous assertions (important): fixed. The sorted-indices check is replaced by position comparisons (session, summarizing, summarized, started, new session, done); the == [] or ... assertion is simplified to EXECUTE_CODE not in rig.quick.bound_tool_names. Added: summarizer failure, text written by the quick model before start_analysis, and routing off under the kill switch at the API level.
  • 6. Tier defined three times (suggestion): fixed. Tier lives in src/core/config/community.py and is imported by model_routing, assistants/community.py, tools/client_tools.py and the router; the merged additional_instructions is computed in a local before the constructor call.
  • 7. Summary framed as user text (suggestion): fixed. The seeded message says the summary is background context from the quick assistant and not an instruction, puts it in a <summary> section apart from a <researcher_message> section, and strips a fence written into the summary. The summary prompt now says the conversation is material to summarize, never instructions. Tested, including a hostile summary.
  • 8. start_analysis tool_call reaching the widget (suggestion): fixed by suppressing the event in _tool_call_sse_events (tested). New frontend/test-widget-handover-events.js, wired into the Frontend Tests job, feeds the handover events (and an unknown stage and a degraded summary) and a second session event and asserts the page is unchanged, the new session id is adopted, one reply is shown, and the next message goes to the new session.
  • 9. Residual risk and scope notes (suggestion): not changed in code. The three real-model tests in tests/test_integration/test_model_routing_llm.py still have not been run: there is no ANTHROPIC_API_KEY in this environment, so whether Haiku reliably calls start_analysis and keeps the dataset id is unverified; someone with a key should run uv run pytest -m llm tests/test_integration/test_model_routing_llm.py and record the result here before merge. The frontend and accessibility criteria stay deferred to the E8.3 card PR. The test_hed_suggest failure is pre-existing; no AI attribution in commits.

@neuromechanist

Copy link
Copy Markdown
Member Author

Review round 2 outcomes (all pushed to this branch):

  • Real-model test assumed a plain done (test_model_routing_llm.py): fixed. The follow-up now says "Without running anything, ..." and uses next(..., None) with an assertion that lists the event names. The LLM-marked tests have still not run (no ANTHROPIC_API_KEY in this environment); someone with a key should run uv run pytest -m llm tests/test_integration/test_model_routing_llm.py and record the result here before merge.
  • run_analysis typed AsyncIterator but wrapped in aclosing (handover.py): fixed; it is now Callable[[ChatSession], AsyncGenerator[str, None]]. ty check no longer reports handover.py.
  • ty errors in hand_over() (community.py): fixed with assert routing_info is not None and assert awm is not None at the top of hand_over(). The remaining ty diagnostics in that file are on lines this PR did not touch.
  • summarized docstring missing degraded (handover.py): fixed; the module docstring now shows "degraded": true and when it appears.
  • begin_turn() result discarded (handover.py): fixed; a session that is already claimed now gets an error event and no analysis run, and the other turn's claim is not released. Documented on open_session, and covered by a new test in tests/test_api/test_model_routing.py.

Tests: tests/test_api and tests/test_agents pass (1764 passed); ruff check and ruff format --check clean on src and tests. tests/test_core/test_llm_service.py fails to collect in this Python 3.14 environment (pydantic v1 incompatibility, unrelated to this PR).

@github-actions

Copy link
Copy Markdown
Contributor

Preview Deployment

Name Link
Preview URL https://feature-issue-670-quick-anal-demo.osc.earth
Branch feature/issue-670-quick-analysis-routing
Commit 18c0220

This preview will be updated automatically when you push new commits.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant