DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix: rehydrate ask_user answers into later-turn context
SeleiXi81e983045233
diff --git a/deeptutor/services/session/ask_user_trace.py b/deeptutor/services/session/ask_user_trace.pynew file mode 100644index 000000000..af580ba51--- /dev/null+++ b/deeptutor/services/session/ask_user_trace.py@@ -0,0 +1,111 @@+"""Recover resolved ``ask_user`` exchanges from persisted assistant rows.++Card replies resume the same backend turn, so they are stored in the assistant+message's event trace rather than as standalone user messages. Rehydrate them+into future model context or later turns would forget the answers and could ask+the same questions again.+"""++from __future__ import annotations++import json+from typing import Any++#: Raw-text probe run before parsing a stored trace. An assistant row can hold+#: a thousand streamed content deltas, and only the rare row that paused on+#: ``ask_user`` is worth the JSON parse.+_RESOLVED_MARKER = '"ask_user_resolved"'+++def _ask_user_payload(metadata: dict[str, Any]) -> dict[str, Any] | None:+ tool_metadata = metadata.get("tool_metadata")+ payload = (+ tool_metadata.get("ask_user") if isinstance(tool_metadata, dict) else None+ ) or metadata.get("ask_user")+ return payload if isinstance(payload, dict) else None+++def _is_ask_user_event(event: dict[str, Any]) -> bool:+ metadata = event.get("metadata")+ if not isinstance(metadata, dict):+ return False+ if metadata.get("ask_user_resolved"):+ return True+ return event.get("type") == "tool_result" and _ask_user_payload(metadata) is not None+++def filter_ask_user_events(events: Any) -> list[dict[str, Any]]:+ """Keep only the ask_user exchanges of an already-parsed event trace.++ Context building never needs the streamed deltas, so the caller keeps only+ these events instead of holding a full trace per message in memory.+ """+ if not isinstance(events, list):+ return []+ return [event for event in events if isinstance(event, dict) and _is_ask_user_event(event)]+++def select_ask_user_events(raw_events: str | None) -> list[dict[str, Any]]:+ """Filter a stored ``events_json`` blob down to its ask_user exchanges."""+ if not raw_events or _RESOLVED_MARKER not in raw_events:+ return []+ try:+ return filter_ask_user_events(json.loads(raw_events))+ except (TypeError, ValueError):+ return []+++def extract_ask_user_clarifications(message: dict[str, Any]) -> str:+ """Render a message's resolved ask_user exchanges as plain context text."""++ pending_questions: dict[str, str] = {}+ exchanges: list[tuple[str, str]] = []+ for event in message.get("events") or []:+ if not isinstance(event, dict):+ continue+ metadata = event.get("metadata") or {}+ if not isinstance(metadata, dict):+ continue+ if event.get("type") == "tool_result":+ ask_user = _ask_user_payload(metadata)+ if ask_user is None:+ continue+ pending_questions = {+ str(question.get("id") or ""): str(question.get("prompt") or "").strip()+ for question in ask_user.get("questions") or []+ if isinstance(question, dict) and str(question.get("prompt") or "").strip()+ }+ continue+ if not metadata.get("ask_user_resolved"):+ continue+ answers = metadata.get("answers") or []+ resolved = False+ for answer in answers:+ if not isinstance(answer, dict):+ continue+ question_id = str(answer.get("questionId") or answer.get("question_id") or "")+ answer_text = str(answer.get("text") or "").strip()+ question_text = pending_questions.get(question_id, question_id).strip()+ if question_text and answer_text:+ exchanges.append((question_text, answer_text))+ resolved = True+ if not resolved:+ preview = str(metadata.get("reply_preview") or "").strip()+ if preview:+ question_text = next(iter(pending_questions.values()), "User clarification")+ exchanges.append((question_text, preview))+ 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)+++__all__ = [+ "extract_ask_user_clarifications",+ "filter_ask_user_events",+ "select_ask_user_events",+]diff --git a/deeptutor/services/session/context_builder.py b/deeptutor/services/session/context_builder.pyindex b386869c8..8dd033c3e 100644--- a/deeptutor/services/session/context_builder.py+++ b/deeptutor/services/session/context_builder.py@@ -14,6 +14,7 @@ from deeptutor.services.llm.context_window import (resolve_effective_context_window,)+from .ask_user_trace import extract_ask_user_clarificationsfrom .protocol import SessionStoreProtocol#: When the summarizer's output lands within this fraction of its hard token@@ -56,64 +57,6 @@ def trim_incomplete_tail(text: str) -> str:return text.rstrip()-def extract_ask_user_clarifications(message: dict[str, Any]) -> str:- """Recover resolved ask_user exchanges from a persisted assistant row.-- Card replies resume the same backend turn, so they are stored in the- assistant message's event trace rather than as standalone user messages.- Rehydrate them into future model context or later turns would forget the- answers and could ask the same questions again.- """-- pending_questions: dict[str, str] = {}- exchanges: list[tuple[str, str]] = []- for event in message.get("events") or []:- if not isinstance(event, dict):- continue- metadata = event.get("metadata") or {}- if not isinstance(metadata, dict):- continue- if event.get("type") == "tool_result":- tool_metadata = metadata.get("tool_metadata") or {}- ask_user = (- tool_metadata.get("ask_user") if isinstance(tool_metadata, dict) else None- ) or metadata.get("ask_user")- if not isinstance(ask_user, dict):- continue- pending_questions = {- str(question.get("id") or ""): str(question.get("prompt") or "").strip()- for question in ask_user.get("questions") or []- if isinstance(question, dict) and str(question.get("prompt") or "").strip()- }- continue- if not metadata.get("ask_user_resolved"):- continue- answers = metadata.get("answers") or []- resolved = False- for answer in answers:- if not isinstance(answer, dict):- continue- question_id = str(answer.get("questionId") or answer.get("question_id") or "")- answer_text = str(answer.get("text") or "").strip()- question_text = pending_questions.get(question_id, question_id).strip()- if question_text and answer_text:- exchanges.append((question_text, answer_text))- resolved = True- if not resolved:- preview = str(metadata.get("reply_preview") or "").strip()- if preview:- question_text = next(iter(pending_questions.values()), "User clarification")- exchanges.append((question_text, preview))- 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)--def format_messages_as_transcript(messages: list[dict[str, Any]]) -> str:lines: list[str] = []role_map = {diff --git a/deeptutor/services/session/pocketbase_store.py b/deeptutor/services/session/pocketbase_store.pyindex 42e11902b..ae1b53a6e 100644--- a/deeptutor/services/session/pocketbase_store.py+++ b/deeptutor/services/session/pocketbase_store.py@@ -30,6 +30,8 @@ import timefrom typing import Anyimport uuid+from .ask_user_trace import filter_ask_user_events+logger = logging.getLogger(__name__)_VALID_ID = re.compile(r"^[a-zA-Z0-9_-]+$")@@ -436,7 +438,12 @@ class PocketBaseSessionStore:_ = leaf_message_idmessages = await self.get_messages(session_id)return [- {"id": m["id"], "role": m["role"], "content": m["content"] or ""}+ {+ "id": m["id"],+ "role": m["role"],+ "content": m["content"] or "",+ "events": filter_ask_user_events(m.get("events")),+ }for m in messagesif m["role"] in ("user", "assistant", "system")]diff --git a/deeptutor/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pyindex f89eef81e..36696b1c6 100644--- a/deeptutor/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -19,6 +19,8 @@ import uuidfrom deeptutor.services.path_service import get_path_service+from .ask_user_trace import select_ask_user_events+def _json_dumps(value: Any) -> str:# default=str: a single non-serializable object inside an event payload@@ -1345,7 +1347,7 @@ class SQLiteSessionStore:if leaf_message_id is None:rows = conn.execute("""- SELECT id, role, content+ SELECT id, role, content, events_jsonFROM messagesWHERE session_id = ?AND role IN ('user', 'assistant', 'system')@@ -1358,6 +1360,7 @@ class SQLiteSessionStore:"id": row["id"],"role": row["role"],"content": row["content"] or "",+ "events": select_ask_user_events(row["events_json"]),}for row in rows]@@ -1369,7 +1372,7 @@ class SQLiteSessionStore:while current is not None and safety > 0:row = conn.execute("""- SELECT id, role, content, parent_message_id+ SELECT id, role, content, events_json, parent_message_idFROM messagesWHERE id = ? AND session_id = ?AND role IN ('user', 'assistant', 'system')@@ -1383,6 +1386,7 @@ class SQLiteSessionStore:"id": row["id"],"role": row["role"],"content": row["content"] or "",+ "events": select_ask_user_events(row["events_json"]),})parent = row["parent_message_id"]diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.pyindex 1941935a9..aeaa2e891 100644--- a/tests/services/session/test_sqlite_store.py+++ b/tests/services/session/test_sqlite_store.py@@ -333,3 +333,51 @@ def test_delete_last_turn_leaves_prefix_intact(store: SQLiteSessionStore) -> Nonassert remaining[0]["parent_message_id"] is Noneassert remaining[1]["parent_message_id"] == remaining[0]["id"]assert remaining[1]["id"] == a1+# ── Context messages ──────────────────────────────────────────────+++_ASK_USER_EVENTS = [+ {"type": "content", "content": "streamed delta", "metadata": {}},+ {+ "type": "tool_result",+ "metadata": {+ "tool_metadata": {"ask_user": {"questions": [{"id": "level", "prompt": "Your level?"}]}}+ },+ },+ {+ "type": "progress",+ "metadata": {+ "ask_user_resolved": True,+ "answers": [{"questionId": "level", "text": "Beginner"}],+ },+ },+]+++def _add_ask_user_turn(store: SQLiteSessionStore, session_id: str) -> None:+ asyncio.run(store.add_message(session_id, "user", "Plan my study"))+ asyncio.run(+ store.add_message(session_id, "assistant", "Here is a plan", events=_ASK_USER_EVENTS)+ )+++def test_context_messages_carry_ask_user_events(store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ _add_ask_user_turn(store, session["id"])++ messages = asyncio.run(store.get_messages_for_context(session["id"]))++ assert [m["role"] for m in messages] == ["user", "assistant"]+ # Streamed deltas are dropped; only the ask_user exchange survives, so a+ # later turn can see which questions the learner already answered.+ assert [e["type"] for e in messages[1]["events"]] == ["tool_result", "progress"]+++def test_branch_context_messages_carry_ask_user_events(store: SQLiteSessionStore) -> None:+ session = asyncio.run(store.create_session())+ _add_ask_user_turn(store, session["id"])+ leaf = asyncio.run(store.add_message(session["id"], "user", "Still not right"))++ messages = asyncio.run(store.get_messages_for_context(session["id"], leaf_message_id=leaf))++ assert [e["type"] for e in messages[1]["events"]] == ["tool_result", "progress"]