DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: three defects on the paths this week's PRs touched
Bingxi Zhao (Frank)97574b5236e5
diff --git a/deeptutor/agents/research/utils/citation_manager.py b/deeptutor/agents/research/utils/citation_manager.pyindex a88f0bf1c..f797e4e81 100644--- a/deeptutor/agents/research/utils/citation_manager.py+++ b/deeptutor/agents/research/utils/citation_manager.py@@ -304,7 +304,7 @@ class CitationManager:if tool_type_lower in ("rag", "rag_naive", "rag_hybrid"):citation_info = self._extract_rag_citation(- citation_id, "rag", raw_answer, tool_trace+ citation_id, "rag", raw_answer, tool_trace, tool_metadata)elif tool_type_lower == "web_search":citation_info = self._extract_web_citation(@@ -330,9 +330,22 @@ class CitationManager:return Falsedef _extract_rag_citation(- self, citation_id: str, tool_type: str, raw_answer: str, tool_trace: Any+ self,+ citation_id: str,+ tool_type: str,+ raw_answer: str,+ tool_trace: Any,+ tool_metadata: dict[str, Any] | None = None,) -> dict[str, Any]:- """Extract citation information for RAG retrieval with source documents"""+ """Extract citation information for RAG retrieval with source documents.++ Prefers the structured ``ToolResult.metadata`` for the same reason+ :meth:`_extract_web_citation` does: ``raw_answer`` is the textual+ answer surfaced to the LLM, not a JSON payload, so parsing it usually+ yields no sources at all. Every RAG pipeline normalises what it+ retrieved into ``metadata["sources"]`` (see ``tools/builtin``), which+ is already the shape ``_rag_source_payload`` reads.+ """citation_info = {"citation_id": citation_id,"tool_type": tool_type,@@ -343,9 +356,14 @@ class CitationManager:}try:- # Parse raw_answer to extract source information- answer_data = parse_json_response(raw_answer)- source_documents, kb_name = _rag_source_payload(answer_data)+ source_documents, kb_name = _rag_source_payload(tool_metadata)+ if not source_documents:+ # No metadata (older traces, or a tool that only returns text):+ # fall back to parsing the answer, which is what this did before+ # the structured payload reached here.+ documents, answer_kb_name = _rag_source_payload(parse_json_response(raw_answer))+ source_documents = documents+ kb_name = kb_name or answer_kb_namesources = [source_infofor index, document in enumerate(source_documents[:5])diff --git a/deeptutor/services/llm/provider_core/openai_responses/parsing.py b/deeptutor/services/llm/provider_core/openai_responses/parsing.pyindex 35b8cfeba..7d26b1943 100644--- a/deeptutor/services/llm/provider_core/openai_responses/parsing.py+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py@@ -43,6 +43,11 @@ class _ToolCallBuffers:SSE and SDK consumers share the same correlation rules."""+ #: Stands in for the output-item id when a provider omits one. It is not an+ #: identity — several calls in one response can carry it — so it is never+ #: registered as a lookup key (see :meth:`add`).+ PLACEHOLDER_ITEM_ID = "fc_0"+def __init__(self) -> None:self._by_identity: dict[str, _ToolCallBuffer] = {}@@ -50,13 +55,17 @@ class _ToolCallBuffers:self,*,call_id: str,- item_id: str,+ item_id: str | None,name: str,arguments: str,) -> None:- buffer = _ToolCallBuffer(call_id, item_id, name, arguments)+ buffer = _ToolCallBuffer(call_id, item_id or self.PLACEHOLDER_ITEM_ID, name, arguments)self._by_identity[call_id] = buffer- self._by_identity[item_id] = buffer+ # Only a real id becomes an alias. Aliasing the placeholder would let+ # the *next* call that omits its item id resolve to this buffer and be+ # dispatched under this call's tool name, with this call's arguments.+ if item_id and item_id != self.PLACEHOLDER_ITEM_ID:+ self._by_identity[item_id] = bufferdef get(self,@@ -173,7 +182,7 @@ async def consume_sse(continuetool_call_buffers.add(call_id=call_id,- item_id=item.get("id") or "fc_0",+ item_id=item.get("id"),name=item.get("name") or "",arguments=item.get("arguments") or "",)@@ -200,12 +209,15 @@ async def consume_sse(call_id = item.get("call_id")if not call_id:continue- item_id = item.get("id") or "fc_0"- buf = tool_call_buffers.get(call_id=call_id, item_id=item_id)+ # Look up by the ids this item actually carries; the+ # placeholder is only a fallback for the id we report back.+ raw_item_id = item.get("id")+ buf = tool_call_buffers.get(call_id=call_id, item_id=raw_item_id)tool_calls.append(_build_tool_call(call_id=call_id,- item_id=buf.item_id if buf else item_id,+ item_id=(buf.item_id if buf else raw_item_id)+ or _ToolCallBuffers.PLACEHOLDER_ITEM_ID,name=(buf.name if buf else "") or item.get("name") or "",arguments=(buf.arguments if buf else "") or item.get("arguments") or "{}",)@@ -253,7 +265,7 @@ def parse_response_output(response: Any) -> LLMResponse:reasoning_content = (reasoning_content or "") + summary["text"]elif item_type == "function_call":call_id = item.get("call_id") or ""- item_id = item.get("id") or "fc_0"+ item_id = item.get("id") or _ToolCallBuffers.PLACEHOLDER_ITEM_IDargs_raw = item.get("arguments") or "{}"tool_calls.append(_build_tool_call(@@ -309,7 +321,7 @@ async def consume_sdk_stream(continuetool_call_buffers.add(call_id=call_id,- item_id=getattr(item, "id", None) or "fc_0",+ item_id=getattr(item, "id", None),name=getattr(item, "name", None) or "",arguments=getattr(item, "arguments", None) or "",)@@ -336,12 +348,13 @@ async def consume_sdk_stream(call_id = getattr(item, "call_id", None)if not call_id:continue- item_id = getattr(item, "id", None) or "fc_0"- buf = tool_call_buffers.get(call_id=call_id, item_id=item_id)+ raw_item_id = getattr(item, "id", None)+ buf = tool_call_buffers.get(call_id=call_id, item_id=raw_item_id)tool_calls.append(_build_tool_call(call_id=call_id,- item_id=buf.item_id if buf else item_id,+ item_id=(buf.item_id if buf else raw_item_id)+ or _ToolCallBuffers.PLACEHOLDER_ITEM_ID,name=(buf.name if buf else "") or getattr(item, "name", None) or "",arguments=(buf.arguments if buf else "")or getattr(item, "arguments", None)diff --git a/deeptutor/services/llm/reasoning_params.py b/deeptutor/services/llm/reasoning_params.pyindex b6df2ca7e..66d50a5c1 100644--- a/deeptutor/services/llm/reasoning_params.py+++ b/deeptutor/services/llm/reasoning_params.py@@ -29,6 +29,13 @@ _PROVIDER_REASONING_PATTERNS = {_PROVIDER_DEFAULT_OFF_PATTERNS: dict[str, tuple[str, ...]] = {"gemini": ("gemini-2.5", "gemini-3"),}+# Models matched above that cannot turn thinking off at all: they reject+# ``reasoning_effort="none"`` with a 400, and "minimal" is the lowest level+# they accept (#734). Kept beside the patterns it narrows so adding a family+# to one table is an obvious prompt to check the other.+_MINIMAL_NOT_OFF_PATTERNS: dict[str, tuple[str, ...]] = {+ "gemini": ("gemini-3", "gemini-2.5-pro"),+}_CUSTOM_MODEL_THINKING_STYLES: tuple[tuple[tuple[str, ...], str], ...] = ((("qwen3", "qwen-3", "qwq", "qwen-plus"), "enable_thinking"),(("deepseek-v4-pro", "deepseek-reasoner"), "thinking_type"),@@ -74,10 +81,7 @@ def default_reasoning_effort_for(provider: str | None, model: str | None) -> strprovider_name = (provider or "").strip().lower()off_patterns = _PROVIDER_DEFAULT_OFF_PATTERNS.get(provider_name)if off_patterns and _matches(model or "", off_patterns):- _m = (model or "").lower()- # Gemini 3 and 2.5 Pro reject reasoning_effort="none";- # "minimal" is the lowest valid level for those families.- if "gemini-3" in _m or "gemini-2.5-pro" in _m:+ if _matches(model or "", _MINIMAL_NOT_OFF_PATTERNS.get(provider_name, ())):return "minimal"return "none"return Nonediff --git a/tests/agents/research/test_citation_manager.py b/tests/agents/research/test_citation_manager.pyindex f28e76fe7..08b7c87af 100644--- a/tests/agents/research/test_citation_manager.py+++ b/tests/agents/research/test_citation_manager.py@@ -56,3 +56,50 @@ def test_rag_citation_preserves_object_payload_metadata(tmp_path) -> None:assert citation["sources"][0]["content_preview"] == "A source chunk"assert citation["sources"][0]["chunk_id"] == "chunk-1"assert citation["sources"][0]["score"] == 0.9+++def test_rag_citation_prefers_the_structured_tool_metadata(tmp_path) -> None:+ """``raw_answer`` is the prose shown to the model, not a JSON payload.++ Every RAG pipeline normalises what it retrieved into ``metadata["sources"]``,+ and that is what reaches the citation manager as ``tool_metadata`` — so a+ perfectly ordinary textual answer must still produce source links.+ """+ manager = CitationManager("research-metadata", cache_dir=tmp_path)+ metadata = {+ "answer": "RAG grounds an answer in retrieved documents.",+ "kb_name": "lecture-notes",+ "sources": [+ {+ "title": "Retrieval-Augmented Generation",+ "content": "Ground an answer in retrieved documents.",+ "source": "rag.pdf",+ "page": 3,+ "score": 0.91,+ }+ ],+ }++ citation = manager._extract_rag_citation(+ "CIT-1-01",+ "rag",+ "RAG grounds an answer in retrieved documents.",+ _trace(),+ metadata,+ )++ assert citation["kb_name"] == "lecture-notes"+ assert citation["total_sources"] == 1+ assert citation["sources"][0]["source_file"] == "rag.pdf"+ assert citation["sources"][0]["page"] == 3+++def test_rag_citation_falls_back_to_the_answer_without_metadata(tmp_path) -> None:+ """Traces recorded before metadata reached this extractor still resolve."""+ manager = CitationManager("research-fallback", cache_dir=tmp_path)+ raw_answer = json.dumps({"kb_name": "kb", "sources": [{"title": "T", "content": "C"}]})++ citation = manager._extract_rag_citation("CIT-1-02", "rag", raw_answer, _trace(), None)++ assert citation["kb_name"] == "kb"+ assert citation["total_sources"] == 1diff --git a/tests/services/llm/test_openai_responses_parsing.py b/tests/services/llm/test_openai_responses_parsing.pyindex 44bb1fcba..c2d5bfe92 100644--- a/tests/services/llm/test_openai_responses_parsing.py+++ b/tests/services/llm/test_openai_responses_parsing.py@@ -99,3 +99,47 @@ async def test_sdk_arguments_can_be_correlated_by_item_id() -> None:assert len(tool_calls) == 1assert tool_calls[0].id == "call_1|fc_1"assert tool_calls[0].arguments == {"topic": "geometry"}+++async def test_a_call_without_an_item_id_does_not_inherit_another_calls_identity() -> None:+ """The placeholder item id is not an identity, and must never resolve one.++ A provider that omits ``item.id`` on function-call items makes every call+ carry the same stand-in. If that stand-in were registered as a lookup key,+ a ``done`` event for a call that was never announced would find the+ previous call's buffer — and the tool would be dispatched under the wrong+ name with the wrong arguments.+ """+ events = [+ {+ "type": "response.output_item.added",+ "item": {"type": "function_call", "call_id": "call_1", "name": "delete_kb"},+ },+ {+ "type": "response.function_call_arguments.done",+ "call_id": "call_1",+ "arguments": '{"kb":"secret"}',+ },+ {+ "type": "response.output_item.done",+ "item": {"type": "function_call", "call_id": "call_1", "name": "delete_kb"},+ },+ # Never announced with an ``added`` event, and carries no item id.+ {+ "type": "response.output_item.done",+ "item": {+ "type": "function_call",+ "call_id": "call_2",+ "name": "list_kb",+ "arguments": '{"scope":"mine"}',+ },+ },+ ]++ _, tool_calls, _ = await consume_sse(_SSEFixture(events))++ assert [(call.name, call.arguments) for call in tool_calls] == [+ ("delete_kb", {"kb": "secret"}),+ ("list_kb", {"scope": "mine"}),+ ]diff --git a/web/lib/iframe-html.ts b/web/lib/iframe-html.tsindex a40cbaea7..894e88d84 100644--- a/web/lib/iframe-html.ts+++ b/web/lib/iframe-html.ts@@ -155,10 +155,16 @@ const BRIDGE_SCRIPT =}}- if (document.readyState === "loading") {- document.addEventListener("DOMContentLoaded", startHeightObservers, { once: true });- } else {+ // Gate on document.body, not readyState. This script is injected just+ // before </body>, so the body already exists while readyState is still+ // "loading" — and deferred scripts (the KaTeX tags injectKaTeX adds) must+ // all run before DOMContentLoaded fires. Waiting for that event means a+ // blocked or slow CDN leaves the observers unattached and every+ // visualization frozen at the iframe's initial height.+ if (document.body) {startHeightObservers();+ } else {+ document.addEventListener("DOMContentLoaded", startHeightObservers, { once: true });}window.addEventListener("load", scheduleHeightReport);})();