Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix(chat): preserve ask-user protocol across fallbacks and history

Bingxi Zhao (Frank)11c0a1ed6855
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index 4d0a51680..5ed3c3917 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -30,6 +30,7 @@ from __future__ import annotations
import asyncio
from contextlib import suppress
from dataclasses import dataclass, field
+import json
import logging
import re
from typing import TYPE_CHECKING, Any
@@ -907,6 +908,37 @@ class AgentLoop:
tool_calls = dsml_calls
text = cleaned_text
+ if forced_tool_choice and tool_choice == "ask_user" and not tool_calls:
+ # A few OpenAI-compatible providers either reject tool schemas or
+ # accept ``tool_choice`` and then ignore it. Ask Questions is an
+ # explicit UI mode, so preserve its contract by turning the
+ # model's buffered question into a local ask_user card instead of
+ # silently degrading to an ordinary prose answer.
+ question = clean_thinking_tags(text, self.pipeline.binding, self.pipeline.model).strip()
+ if not question:
+ question = self.pipeline._t(
+ "notices.ask_questions_fallback_prompt",
+ default="What is the most important goal or constraint I should account for?",
+ )
+ tool_calls = [
+ {
+ "id": new_call_id("ask-user-fallback"),
+ "name": "ask_user",
+ "arguments": json.dumps(
+ {
+ "questions": [
+ {
+ "id": "clarification",
+ "prompt": question,
+ "allow_free_text": True,
+ }
+ ]
+ },
+ ensure_ascii=False,
+ ),
+ }
+ ]
+
truncated_round = call_kind == "agent_loop_round" and _finish_was_truncated(finish_reason)
completion_metadata: dict[str, Any] = {
"trace_kind": "call_status",
@@ -963,10 +995,6 @@ class AgentLoop:
try:
return await self.client.chat.completions.create(**kwargs)
except Exception as exc:
- if "stream_options" in kwargs and is_stream_options_unsupported(exc):
- retry_kwargs = dict(kwargs)
- retry_kwargs.pop("stream_options", None)
- return await self.client.chat.completions.create(**retry_kwargs)
if kwargs.get("tools") and is_tool_schema_unsupported(exc):
# Capture the provider's raw rejection body. Without it there is
# no way to tell *which* parameter/shape a new model family
@@ -996,6 +1024,10 @@ class AgentLoop:
retry_kwargs.pop("tool_choice", None)
self.tool_schemas = None
return await self.client.chat.completions.create(**retry_kwargs)
+ if "stream_options" in kwargs and is_stream_options_unsupported(exc):
+ retry_kwargs = dict(kwargs)
+ retry_kwargs.pop("stream_options", None)
+ return await self.client.chat.completions.create(**retry_kwargs)
if is_image_input_unsupported(exc) and should_degrade_to_text(
self.pipeline.binding,
self.pipeline.model,
diff --git a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
index d763ddf9a..321a3c103 100644
--- a/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/en/agentic_chat.yaml
@@ -129,6 +129,7 @@ notices:
provider_stream_interrupted: "The model provider interrupted this response. Please retry."
context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."
tool_schema_fallback: "Provider rejected native tool schemas; retrying without tools."
+ ask_questions_fallback_prompt: "What is the most important goal or constraint I should account for?"
image_fallback: "Model does not support image input; retrying without images."
empty_final_response: "I could not produce a useful response from the model output. Please try again or narrow the request."
empty_finish_nudged: "The round produced only internal reasoning; asked the model to continue."
diff --git a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
index 29adb43ff..fb1e3d0e4 100644
--- a/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
+++ b/deeptutor/agents/chat/prompts/zh/agentic_chat.yaml
@@ -97,6 +97,7 @@ notices:
provider_stream_interrupted: "模型服务中断了本次回答,请重试。"
context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"
tool_schema_fallback: "服务方拒绝了原生工具 schema;将不带工具重试。"
+ ask_questions_fallback_prompt: "我最需要了解的目标或限制条件是什么?"
image_fallback: "当前模型不支持图片输入;将去除图片后重试。"
empty_final_response: "未能从模型输出中得到有效回答。请重试或缩小问题范围。"
empty_finish_nudged: "模型这一轮只有内部推理,已提示其继续执行。"
diff --git a/deeptutor/services/session/ask_user_trace.py b/deeptutor/services/session/ask_user_trace.py
index af580ba51..e4f82b718 100644
--- a/deeptutor/services/session/ask_user_trace.py
+++ b/deeptutor/services/session/ask_user_trace.py
@@ -55,11 +55,19 @@ def select_ask_user_events(raw_events: str | None) -> list[dict[str, Any]]:
return []
-def extract_ask_user_clarifications(message: dict[str, Any]) -> str:
- """Render a message's resolved ask_user exchanges as plain context text."""
-
+def extract_ask_user_clarification_blocks(
+ message: dict[str, Any],
+) -> list[tuple[int, str]]:
+ """Return resolved clarifications with their assistant-content boundary.
+
+ ``ask_user`` replies arrive inside one persisted assistant row. New rows
+ record how many user-facing assistant characters existed at each reply so
+ later context can preserve ``assistant -> user -> assistant`` chronology.
+ Older rows have no boundary and safely fall back to zero: their persisted
+ content is normally the post-reply final answer.
+ """
pending_questions: dict[str, str] = {}
- exchanges: list[tuple[str, str]] = []
+ blocks: list[tuple[int, str]] = []
for event in message.get("events") or []:
if not isinstance(event, dict):
continue
@@ -79,6 +87,7 @@ def extract_ask_user_clarifications(message: dict[str, Any]) -> str:
if not metadata.get("ask_user_resolved"):
continue
answers = metadata.get("answers") or []
+ exchanges: list[tuple[str, str]] = []
resolved = False
for answer in answers:
if not isinstance(answer, dict):
@@ -94,18 +103,31 @@ def extract_ask_user_clarifications(message: dict[str, Any]) -> str:
if preview:
question_text = next(iter(pending_questions.values()), "User clarification")
exchanges.append((question_text, preview))
+ if exchanges:
+ try:
+ content_offset = max(0, int(metadata.get("assistant_content_offset") or 0))
+ except (TypeError, ValueError):
+ content_offset = 0
+ lines = [
+ "[Earlier ask_user clarification — treat these answers as user-provided context]"
+ ]
+ for question, answer in exchanges:
+ lines.extend((f"- Question: {question}", f" User answer: {answer}"))
+ blocks.append((content_offset, "\n".join(lines)))
pending_questions = {}
- if not exchanges:
- return ""
- lines = ["[Earlier ask_user clarification — treat these answers as user-provided context]"]
- for question, answer in exchanges:
- lines.extend((f"- Question: {question}", f" User answer: {answer}"))
- return "\n".join(lines)
+ return blocks
+
+
+def extract_ask_user_clarifications(message: dict[str, Any]) -> str:
+ """Render all of a message's resolved ask_user exchanges as context text."""
+
+ return "\n\n".join(text for _, text in extract_ask_user_clarification_blocks(message))
__all__ = [
"extract_ask_user_clarifications",
+ "extract_ask_user_clarification_blocks",
"filter_ask_user_events",
"select_ask_user_events",
]
diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.py
index 058a5b93e..be26c211b 100644
--- a/deeptutor/services/session/context_builder.py
+++ b/deeptutor/services/session/context_builder.py
@@ -14,7 +14,10 @@ from deeptutor.services.llm.context_window import (
resolve_effective_context_window,
)
-from .ask_user_trace import extract_ask_user_clarifications
+from .ask_user_trace import (
+ extract_ask_user_clarification_blocks,
+ extract_ask_user_clarifications,
+)
from .protocol import SessionStoreProtocol
#: When the summarizer's output lands within this fraction of its hard token
@@ -57,6 +60,29 @@ def trim_incomplete_tail(text: str) -> str:
return text.rstrip()
+def expand_message_context(message: dict[str, Any]) -> list[dict[str, str]]:
+ """Expand one stored row into its true assistant/user chronology."""
+ role = str(message.get("role", "user"))
+ content = str(message.get("content", "") or "")
+ blocks = extract_ask_user_clarification_blocks(message)
+ if role != "assistant" or not blocks:
+ return [{"role": role, "content": content}] if content.strip() else []
+
+ expanded: list[dict[str, str]] = []
+ cursor = 0
+ for raw_offset, clarification in blocks:
+ offset = min(len(content), max(cursor, raw_offset))
+ prefix = content[cursor:offset]
+ if prefix.strip():
+ expanded.append({"role": "assistant", "content": prefix})
+ expanded.append({"role": "user", "content": clarification})
+ cursor = offset
+ suffix = content[cursor:]
+ if suffix.strip():
+ expanded.append({"role": "assistant", "content": suffix})
+ return expanded
+
+
def format_messages_as_transcript(messages: list[dict[str, Any]]) -> str:
lines: list[str] = []
role_map = {
@@ -65,14 +91,9 @@ def format_messages_as_transcript(messages: list[dict[str, Any]]) -> str:
"system": "System",
}
for item in messages:
- # User clarifications answered an ask_user card *before* the assistant
- # answer was produced, so render them before the row's own content.
- clarification = extract_ask_user_clarifications(item)
- if clarification:
- lines.append(f"User: {clarification}")
- content = str(item.get("content", "") or "").strip()
- if content:
- role = role_map.get(str(item.get("role", "user")), "User")
+ for expanded in expand_message_context(item):
+ content = expanded["content"].strip()
+ role = role_map.get(expanded["role"], "User")
lines.append(f"{role}: {content}")
return "\n\n".join(lines)
@@ -173,18 +194,9 @@ class ContextBuilder:
if cleaned_summary:
history.append({"role": "system", "content": cleaned_summary})
for item in messages:
- role = item.get("role")
- content = str(item.get("content", "") or "")
- # Resolved ask_user clarifications happened *before* the assistant
- # produced this row's answer, so they must precede the row's own
- # content in history. Otherwise later turns see the answer first
- # and the user's clarification second, and the model wrongly
- # assumes the answer came before the user supplied the context.
- clarification = extract_ask_user_clarifications(item)
- if clarification:
- history.append({"role": "user", "content": clarification})
- if role in {"user", "assistant"} and content.strip():
- history.append({"role": role, "content": content})
+ for expanded in expand_message_context(item):
+ if expanded["role"] in {"user", "assistant"}:
+ history.append(expanded)
return history
async def _append_event(
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index 012ec0a2d..96df1a6eb 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -111,6 +111,16 @@ def _assemble_persisted_answer(
)
+def _stamp_ask_user_content_offset(
+ payload_event: dict[str, Any],
+ assistant_content: str,
+) -> None:
+ """Attach the replay boundary to a persisted ask_user resolution event."""
+ metadata = payload_event.get("metadata")
+ if isinstance(metadata, dict) and metadata.get("ask_user_resolved"):
+ metadata.setdefault("assistant_content_offset", len(assistant_content))
+
+
def _clip_text(value: str, limit: int = 4000) -> str:
text = str(value or "").strip()
if len(text) <= limit:
@@ -1921,6 +1931,10 @@ class TurnRuntimeManager:
continue
payload_event = await self._publish_live_event(execution, event)
if payload_event.get("type") not in {"done", "session"}:
+ # A card reply lives inside this assistant row. Persist
+ # the exact user-facing answer boundary so future context
+ # can replay assistant -> user -> assistant in order.
+ _stamp_ask_user_content_offset(payload_event, _persisted_answer())
assistant_events.append(payload_event)
if _should_capture_assistant_content(event):
call_id = (event.metadata or {}).get("call_id")
diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py
index fce384656..f501e0a6a 100644
--- a/tests/agents/chat/test_agent_loop.py
+++ b/tests/agents/chat/test_agent_loop.py
@@ -1387,6 +1387,73 @@ async def test_initial_tool_choice_only_forces_first_round_and_hides_preamble(
assert _contents(events) == ["Completed with the added context."]
+async def test_ask_questions_uses_a_card_when_provider_rejects_tool_schemas(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ class _PausingRegistry(_Registry):
+ async def execute(self, name: str, **kwargs):
+ self.executed.append({"name": name, "kwargs": kwargs})
+ return ToolResult(
+ content="Asked the user.",
+ success=True,
+ pause_for_user={"questions": kwargs["questions"]},
+ )
+
+ class _SchemaRejectingClient:
+ def __init__(self) -> None:
+ self.calls: list[dict[str, Any]] = []
+
+ class _Completions:
+ def __init__(self, parent: _SchemaRejectingClient) -> None:
+ self.parent = parent
+
+ async def create(self, **kwargs):
+ self.parent.calls.append(kwargs)
+ if len(self.parent.calls) == 1:
+ raise ValueError("unsupported parameter: tools")
+ content = (
+ "Which outcome matters most?"
+ if len(self.parent.calls) == 2
+ else "Completed after clarification."
+ )
+ return _async_llm_stream([_llm_chunk(content=content)])
+
+ self.chat = SimpleNamespace(completions=_Completions(self))
+
+ registry = _PausingRegistry()
+ client = _SchemaRejectingClient()
+ pipeline = AgenticChatPipeline(language="en", initial_tool_choice="ask_user")
+ pipeline.registry = registry
+ monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["ask_user"])
+ monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
+
+ async def _waiter():
+ return {"text": "Accuracy"}
+
+ events = await _run(
+ pipeline,
+ UnifiedContext(
+ session_id="s1",
+ user_message="Help with this task",
+ metadata={"wait_for_user_reply": _waiter},
+ ),
+ )
+
+ assert "tools" in client.calls[0]
+ assert "tools" not in client.calls[1]
+ assert [item["name"] for item in registry.executed] == ["ask_user"]
+ assert registry.executed[0]["kwargs"]["questions"] == [
+ {
+ "id": "clarification",
+ "prompt": "Which outcome matters most?",
+ "allow_free_text": True,
+ }
+ ]
+ assert _contents(events) == ["Completed after clarification."]
+ assert any(event.metadata.get("tool_schema_fallback") for event in events)
+
+
@pytest.mark.asyncio
async def test_ask_user_pause_resumes_and_streams_interleaved(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/services/session/test_context_builder.py b/tests/services/session/test_context_builder.py
index 533346a29..23fd96d44 100644
--- a/tests/services/session/test_context_builder.py
+++ b/tests/services/session/test_context_builder.py
@@ -260,9 +260,11 @@ class TestBuildHistory:
assert len(history) == 1
def test_resolved_ask_user_answers_are_rehydrated_as_user_context(self) -> None:
+ before = "I can help, but one detail matters."
+ after = "I adapted the explanation."
message = {
"role": "assistant",
- "content": "I adapted the explanation.",
+ "content": before + after,
"events": [
{
"type": "tool_result",
@@ -281,6 +283,7 @@ class TestBuildHistory:
"type": "progress",
"metadata": {
"ask_user_resolved": True,
+ "assistant_content_offset": len(before),
"answers": [
{"questionId": "level", "text": "High-school calculus"},
{"questionId": "goal", "text": "Understand the intuition"},
@@ -296,9 +299,12 @@ class TestBuildHistory:
history = ContextBuilder(store=MagicMock())._build_history("", [message])
assert history == [
+ {"role": "assistant", "content": before},
{"role": "user", "content": clarification},
- {"role": "assistant", "content": "I adapted the explanation."},
+ {"role": "assistant", "content": after},
]
+ transcript = format_messages_as_transcript([message])
+ assert transcript.index(before) < transcript.index(clarification) < transcript.index(after)
# ---------------------------------------------------------------------------
diff --git a/tests/services/session/test_turn_runtime.py b/tests/services/session/test_turn_runtime.py
index 136020955..110373c47 100644
--- a/tests/services/session/test_turn_runtime.py
+++ b/tests/services/session/test_turn_runtime.py
@@ -14,6 +14,7 @@ from deeptutor.services.session.turn_runtime import (
_format_followup_question_context,
_narration_marker_call_id,
_should_capture_assistant_content,
+ _stamp_ask_user_content_offset,
)
# ---------------------------------------------------------------------------
@@ -131,6 +132,14 @@ class TestAssemblePersistedAnswer:
assert _assemble_persisted_answer(segments, {"search-round"}) == "Answer."
+def test_ask_user_resolution_records_the_current_answer_boundary() -> None:
+ event = {"type": "progress", "metadata": {"ask_user_resolved": True}}
+
+ _stamp_ask_user_content_offset(event, "Visible teaching before the card.")
+
+ assert event["metadata"]["assistant_content_offset"] == 33
+
+
# ---------------------------------------------------------------------------
# _clip_text
# ---------------------------------------------------------------------------
diff --git a/web/app/(workspace)/home/[[...sessionId]]/page.tsx b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
index 63d2ce132..f3acd46da 100644
--- a/web/app/(workspace)/home/[[...sessionId]]/page.tsx
+++ b/web/app/(workspace)/home/[[...sessionId]]/page.tsx
@@ -276,7 +276,6 @@ const CAPABILITIES: CapabilityDef[] = [
"videogen",
],
defaultTools: [],
- loopEngine: true,
},
{
value: "deep_question",