DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(chat): parse DeepSeek DSML text tool-call markup (#666)
Bingxi Zhao (Frank)baa49d687989
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.pyindex 3983da8d5..fc40983dd 100644--- a/deeptutor/agents/chat/agent_loop.py+++ b/deeptutor/agents/chat/agent_loop.py@@ -31,6 +31,7 @@ import refrom typing import TYPE_CHECKING, Anyfrom deeptutor.agents._shared.capability_result import emit_capability_result+from deeptutor.agents.chat.dsml_tool_calls import extract_dsml_tool_calls, has_dsml_tool_callsfrom deeptutor.core.agentic.messages import assistant_message_with_tool_callsfrom deeptutor.core.agentic.tool_dispatch import DispatchOutcomefrom deeptutor.core.agentic.usage import message_content_chars, record_streamed_usage@@ -480,6 +481,11 @@ class AgentLoop:output_chars = 0finish_reason = ""think_filter = InlineThinkFilter()+ # Once a round's content channel starts carrying DeepSeek DSML tool-call+ # markup (issue #666), divert the rest of it to the thinking channel so+ # the raw markup never streams as the user-facing answer. It is parsed+ # into real tool calls after the stream completes.+ dsml_stream_active = Falsechunk_meta = merge_trace_metadata(trace_meta, {"trace_kind": "llm_chunk"})async def _emit_segments(segments: list[tuple[str, str]]) -> None:@@ -529,7 +535,12 @@ class AgentLoop:# whether to render it as narration or as the answer.# Inline <think> segments are split off to the thinking# channel so the content stream stays user-facing.- await _emit_segments(think_filter.feed(content))+ if not dsml_stream_active and has_dsml_tool_calls("".join(text_parts)):+ dsml_stream_active = True+ segments = think_filter.feed(content)+ if dsml_stream_active:+ segments = [("thinking", seg) for _, seg in segments]+ await _emit_segments(segments)for tc_delta in getattr(delta, "tool_calls", None) or []:index = int(getattr(tc_delta, "index", 0) or 0)@@ -554,7 +565,10 @@ class AgentLoop:with suppress(Exception):await close()- await _emit_segments(think_filter.flush())+ flushed = think_filter.flush()+ if dsml_stream_active:+ flushed = [("thinking", seg) for _, seg in flushed]+ await _emit_segments(flushed)text = "".join(text_parts)record_streamed_usage(self.pipeline.usage,@@ -573,6 +587,17 @@ class AgentLoop:if data.get("name")]+ # Fallback: a DeepSeek deployment without native function calling emits+ # its tool calls as DSML markup in the content channel instead of as+ # structured ``tool_calls`` (issue #666). Parse them out so the normal+ # dispatch path runs the tools, and drop the markup from ``text`` so it+ # can't leak into the conversation / answer.+ if not tool_calls:+ dsml_calls, cleaned_text = extract_dsml_tool_calls(text)+ if dsml_calls:+ tool_calls = dsml_calls+ text = cleaned_text+await self.stream.progress("",source="chat",diff --git a/deeptutor/agents/chat/dsml_tool_calls.py b/deeptutor/agents/chat/dsml_tool_calls.pynew file mode 100644index 000000000..57aa972a8--- /dev/null+++ b/deeptutor/agents/chat/dsml_tool_calls.py@@ -0,0 +1,113 @@+"""Fallback parser for DeepSeek's text-format ("DSML") tool calls.++Some DeepSeek deployments (notably local/source setups whose OpenAI-compatible+endpoint doesn't advertise native function calling) emit tool calls as markup in+the assistant *content* channel instead of as structured ``delta.tool_calls``.+The markup mirrors the ``invoke`` / ``parameter`` dialect but wraps each tag in+DeepSeek's fullwidth special-token bars, e.g.::++ <||DSML||tool_calls>+ <||DSML||invoke name="exec">+ <||DSML||parameter name="command" string="true">python -c "..."</||DSML||parameter>+ </||DSML||invoke>+ </||DSML||tool_calls>++Left unparsed, this markup streams to the user as the final answer and the tool+never runs (issue #666). :func:`extract_dsml_tool_calls` turns the markup back+into structured tool calls so the normal dispatch path executes them.++Pure functions — no I/O, no LLM. The tag prefix is matched leniently+(``<[^>]*?invoke ...>``) so the exact special-token bytes don't matter; only the+stable ``invoke name="..."`` / ``parameter name="..."`` structure does.+"""++from __future__ import annotations++import json+import re+from typing import Any++# A real DSML tool-call tag (not prose that merely mentions "tool_calls"): an+# opening ``<...invoke name="`` or any ``<...DSML...>`` tag. Used to decide+# whether the content channel is carrying tool-call markup.+DSML_SIGNAL_RE = re.compile(+ r"<[^>]*DSML[^>]*>|<[^>]*?invoke\s+name\s*=\s*\"",+ re.IGNORECASE,+)++_INVOKE_RE = re.compile(+ r"<[^>]*?invoke\s+name\s*=\s*\"(?P<name>[^\"]+)\"[^>]*>(?P<body>.*?)</[^>]*?invoke\s*>",+ re.IGNORECASE | re.DOTALL,+)+_PARAM_RE = re.compile(+ r"<[^>]*?parameter\s+name\s*=\s*\"(?P<pname>[^\"]+)\"(?P<attrs>[^>]*)>(?P<pval>.*?)</[^>]*?parameter\s*>",+ re.IGNORECASE | re.DOTALL,+)+# The ``<...tool_calls>`` open/close wrapper, stripped from the cleaned text once+# we have extracted the invokes inside it.+_TOOLCALLS_WRAP_RE = re.compile(r"</?[^>]*?tool_calls\s*>", re.IGNORECASE)+++def _looks_like_string(attrs: str) -> bool:+ normalized = attrs.replace("'", '"')+ return 'string="true"' in normalized.lower()+++def _coerce_param_value(raw: str, attrs: str) -> Any:+ if _looks_like_string(attrs):+ return raw+ # Unmarked scalars (numbers, bools, JSON objects/arrays) are parsed; on any+ # failure the raw string is kept verbatim.+ try:+ return json.loads(raw.strip())+ except Exception:+ return raw+++def has_dsml_tool_calls(text: str | None) -> bool:+ """Cheap check for whether ``text`` carries DSML tool-call markup."""+ return bool(text) and bool(DSML_SIGNAL_RE.search(text))+++def extract_dsml_tool_calls(text: str | None) -> tuple[list[dict[str, Any]], str]:+ """Parse DSML tool-call markup out of ``text``.++ Returns ``(tool_calls, cleaned_text)``. ``tool_calls`` is empty and+ ``cleaned_text is text`` when no well-formed invoke block is present, so the+ caller can treat "no calls" as "not a DSML round" and fall through+ unchanged.+ """+ if not has_dsml_tool_calls(text):+ return [], text or ""++ tool_calls: list[dict[str, Any]] = []+ spans: list[tuple[int, int]] = []+ for idx, match in enumerate(_INVOKE_RE.finditer(text)):+ name = match.group("name").strip()+ if not name:+ continue+ args: dict[str, Any] = {}+ for param in _PARAM_RE.finditer(match.group("body")):+ args[param.group("pname").strip()] = _coerce_param_value(+ param.group("pval"), param.group("attrs") or ""+ )+ tool_calls.append(+ {+ "id": f"dsml_{idx}",+ "name": name,+ "arguments": json.dumps(args, ensure_ascii=False),+ }+ )+ spans.append((match.start(), match.end()))++ if not tool_calls:+ return [], text++ cleaned = text+ for start, end in reversed(spans):+ cleaned = cleaned[:start] + cleaned[end:]+ cleaned = _TOOLCALLS_WRAP_RE.sub("", cleaned).strip()+ return tool_calls, cleaned+++__all__ = ["extract_dsml_tool_calls", "has_dsml_tool_calls", "DSML_SIGNAL_RE"]diff --git a/tests/agents/chat/test_dsml_tool_calls.py b/tests/agents/chat/test_dsml_tool_calls.pynew file mode 100644index 000000000..ed584fcf2--- /dev/null+++ b/tests/agents/chat/test_dsml_tool_calls.py@@ -0,0 +1,83 @@+"""Tests for the DeepSeek DSML text-format tool-call fallback parser (issue #666)."""++from __future__ import annotations++import json++from deeptutor.agents.chat.dsml_tool_calls import (+ extract_dsml_tool_calls,+ has_dsml_tool_calls,+)++# The exact markup from the issue report — fullwidth | special-token bars.+_ISSUE_PAYLOAD = (+ '<||DSML||tool_calls> <||DSML||invoke name="exec"> '+ '<||DSML||parameter name="command" string="true">'+ "python -c \"from pptx import Presentation; prs=Presentation(); prs.save('test.pptx')\""+ "</||DSML||parameter> </||DSML||invoke> </||DSML||tool_calls>"+)+++def test_extracts_issue_payload_into_tool_call() -> None:+ calls, cleaned = extract_dsml_tool_calls(_ISSUE_PAYLOAD)+ assert len(calls) == 1+ assert calls[0]["name"] == "exec"+ args = json.loads(calls[0]["arguments"])+ assert args["command"].startswith("python -c")+ # All markup consumed — nothing left to masquerade as the answer.+ assert cleaned == ""+++def test_multiple_invokes_and_leading_prose() -> None:+ text = (+ "Let me run two steps.\n"+ '<|DSML|invoke name="exec">'+ '<|DSML|parameter name="command" string="true">echo one</|DSML|parameter>'+ "</|DSML|invoke>"+ '<|DSML|invoke name="read_skill">'+ '<|DSML|parameter name="name" string="true">pptx</|DSML|parameter>'+ "</|DSML|invoke>"+ )+ calls, cleaned = extract_dsml_tool_calls(text)+ assert [c["name"] for c in calls] == ["exec", "read_skill"]+ assert json.loads(calls[1]["arguments"]) == {"name": "pptx"}+ # Leading prose is preserved; only the markup is stripped.+ assert cleaned == "Let me run two steps."+++def test_non_string_parameter_is_json_coerced() -> None:+ text = (+ '<|DSML|invoke name="widget">'+ '<|DSML|parameter name="count">3</|DSML|parameter>'+ '<|DSML|parameter name="label" string="true">3</|DSML|parameter>'+ "</|DSML|invoke>"+ )+ calls, _ = extract_dsml_tool_calls(text)+ args = json.loads(calls[0]["arguments"])+ assert args["count"] == 3 # unmarked scalar parsed as JSON+ assert args["label"] == "3" # string="true" kept verbatim+++def test_plain_text_is_untouched() -> None:+ text = "Here is your answer. No tools needed."+ assert has_dsml_tool_calls(text) is False+ calls, cleaned = extract_dsml_tool_calls(text)+ assert calls == []+ assert cleaned is text+++def test_prose_mentioning_tool_calls_is_not_a_false_positive() -> None:+ # Merely discussing the word must not trip detection — only a real+ # ``<...invoke name="`` / ``<...DSML...>`` tag counts.+ text = "You can trigger tool_calls by asking me to run something."+ assert has_dsml_tool_calls(text) is False+ assert extract_dsml_tool_calls(text) == ([], text)+++def test_malformed_envelope_without_close_yields_no_calls() -> None:+ # Signal present but no well-formed invoke block → treat as not-a-DSML-round+ # so the caller falls through unchanged rather than losing the text.+ text = '<|DSML|invoke name="exec"> unterminated ...'+ calls, cleaned = extract_dsml_tool_calls(text)+ assert calls == []+ assert cleaned == text