Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(provider): parse DeepSeek DSML tool calls

Haozhe Wud6bf209303ed
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.py
index 9bc8d27e8..02535034d 100644
--- a/agent/src/providers/chat.py
+++ b/agent/src/providers/chat.py
@@ -5,7 +5,9 @@ ChatLLM is designed specifically for the AgentLoop ReAct cycle.
from __future__ import annotations
+import html
import os
+import re
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional
@@ -118,6 +120,89 @@ def _redact_provider_error(message: str) -> str:
return redacted
+_DSML_BAR = r"(?:\|\||||)"
+_DSML_TAG = rf"{_DSML_BAR}\s*DSML\s*{_DSML_BAR}"
+_DSML_TOOL_CALLS_RE = re.compile(
+ rf"<\s*{_DSML_TAG}\s*tool_calls\s*>(?P<body>.*?)"
+ rf"</\s*{_DSML_TAG}\s*tool_calls\s*>",
+ re.DOTALL,
+)
+_DSML_INVOKE_RE = re.compile(
+ rf"<\s*{_DSML_TAG}\s*invoke\b(?P<attrs>[^>]*)>(?P<body>.*?)"
+ rf"</\s*{_DSML_TAG}\s*invoke\s*>",
+ re.DOTALL,
+)
+_DSML_PARAMETER_RE = re.compile(
+ rf"<\s*{_DSML_TAG}\s*parameter\b(?P<attrs>[^>]*)>(?P<body>.*?)"
+ rf"</\s*{_DSML_TAG}\s*parameter\s*>",
+ re.DOTALL,
+)
+_DSML_ATTR_RE = re.compile(r"""([A-Za-z_][\w:-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')""")
+_DSML_PREFIXES = ("<||dsml||tool_calls", "<||dsml||tool_calls")
+
+
+def _parse_dsml_attrs(raw: str) -> dict[str, str]:
+ """Parse attributes from a DSML tag."""
+ attrs: dict[str, str] = {}
+ for match in _DSML_ATTR_RE.finditer(raw):
+ attrs[match.group(1)] = html.unescape(match.group(2) or match.group(3) or "")
+ return attrs
+
+
+def _is_possible_dsml_tool_call_prefix(content: str) -> bool:
+ """Return True while buffered stream text could still be a DSML call."""
+ compact = re.sub(r"\s+", "", content.lstrip()[:80]).lower()
+ if not compact:
+ return True
+ return any(prefix.startswith(compact) or compact.startswith(prefix) for prefix in _DSML_PREFIXES)
+
+
+def _parse_dsml_tool_calls(content: Any) -> list[ToolCallRequest]:
+ """Parse DeepSeek-style DSML tool calls embedded as assistant content.
+
+ Some OpenAI-compatible relays/models return tool calls as a textual DSML
+ block rather than LangChain ``AIMessage.tool_calls``. Treat only pure DSML
+ tool-call payloads as executable so examples embedded in normal prose never
+ cross into the tool path.
+ """
+ if not isinstance(content, str):
+ return []
+
+ stripped = content.strip()
+ blocks = list(_DSML_TOOL_CALLS_RE.finditer(stripped))
+ if not blocks:
+ return []
+
+ outside = _DSML_TOOL_CALLS_RE.sub("", stripped).strip()
+ if outside not in {"", "/"}:
+ return []
+
+ tool_calls: list[ToolCallRequest] = []
+ for block in blocks:
+ for invoke in _DSML_INVOKE_RE.finditer(block.group("body")):
+ invoke_attrs = _parse_dsml_attrs(invoke.group("attrs"))
+ name = invoke_attrs.get("name", "").strip()
+ if not name:
+ continue
+
+ arguments: dict[str, Any] = {}
+ for param in _DSML_PARAMETER_RE.finditer(invoke.group("body")):
+ param_attrs = _parse_dsml_attrs(param.group("attrs"))
+ param_name = param_attrs.get("name", "").strip()
+ if param_name:
+ arguments[param_name] = html.unescape(param.group("body")).strip()
+
+ tool_calls.append(
+ ToolCallRequest(
+ id=f"dsml_call_{len(tool_calls) + 1}",
+ name=name,
+ arguments=arguments,
+ )
+ )
+
+ return tool_calls
+
+
class ChatLLM:
"""LLM chat client with function calling support.
@@ -184,18 +269,32 @@ class ChatLLM:
llm = self._llm.bind_tools(tools) if tools else self._llm
config = {"timeout": timeout} if timeout else {}
accumulated = None
+ pending_text = ""
+ possible_dsml_text = True
for chunk in llm.stream(messages, config=config):
if should_cancel and should_cancel():
break
if chunk.content and on_text_chunk:
- on_text_chunk(chunk.content)
+ if possible_dsml_text:
+ pending_text += chunk.content
+ if _is_possible_dsml_tool_call_prefix(pending_text):
+ pass
+ else:
+ possible_dsml_text = False
+ on_text_chunk(pending_text)
+ pending_text = ""
+ else:
+ on_text_chunk(chunk.content)
reasoning = getattr(chunk, "additional_kwargs", {}).get("reasoning_content")
if reasoning and not chunk.content and on_reasoning_chunk:
on_reasoning_chunk(reasoning)
accumulated = chunk if accumulated is None else accumulated + chunk
if accumulated is None:
return LLMResponse(content="", tool_calls=[], finish_reason="stop")
- return self._parse_response(accumulated)
+ response = self._parse_response(accumulated)
+ if pending_text and not (response.has_tool_calls and response.content == ""):
+ on_text_chunk(pending_text)
+ return response
except Exception as exc:
provider = os.getenv("LANGCHAIN_PROVIDER", "openai").strip().lower() or "openai"
model = self.model_name or os.getenv("LANGCHAIN_MODEL_NAME", "").strip() or "(unset)"
@@ -254,21 +353,29 @@ class ChatLLM:
thought_signatures_by_id, thought_signatures_by_index = (
ChatLLM._tool_call_thought_signature_maps(ai_message)
)
+ native_tool_calls = [
+ ToolCallRequest(
+ id=tc["id"],
+ name=tc["name"],
+ arguments=tc["args"],
+ thought_signature=thought_signatures_by_id.get(str(tc["id"]))
+ or thought_signatures_by_index.get(index),
+ )
+ for index, tc in enumerate(ai_message.tool_calls)
+ ]
+ dsml_tool_calls = [] if native_tool_calls else _parse_dsml_tool_calls(ai_message.content)
+ tool_calls = native_tool_calls or dsml_tool_calls
+
return LLMResponse(
- content=ai_message.content,
- tool_calls=[
- ToolCallRequest(
- id=tc["id"],
- name=tc["name"],
- arguments=tc["args"],
- thought_signature=thought_signatures_by_id.get(str(tc["id"]))
- or thought_signatures_by_index.get(index),
- )
- for index, tc in enumerate(ai_message.tool_calls)
- ],
+ content="" if dsml_tool_calls else ai_message.content,
+ tool_calls=tool_calls,
reasoning_content=ai_message.additional_kwargs.get("reasoning_content"),
- finish_reason=_dedupe_finish_reason(
- ai_message.response_metadata.get("finish_reason", "stop")
+ finish_reason=(
+ "tool_calls"
+ if dsml_tool_calls
+ else _dedupe_finish_reason(
+ ai_message.response_metadata.get("finish_reason", "stop")
+ )
),
usage_metadata=usage,
)
diff --git a/agent/tests/test_agent_loop_dsml_tool_calls.py b/agent/tests/test_agent_loop_dsml_tool_calls.py
new file mode 100644
index 000000000..06a16f80e
--- /dev/null
+++ b/agent/tests/test_agent_loop_dsml_tool_calls.py
@@ -0,0 +1,99 @@
+"""Regression tests for DSML textual tool calls in the ReAct loop."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any
+
+from src.agent.loop import AgentLoop
+from src.agent.tools import BaseTool, ToolRegistry
+from src.memory.persistent import PersistentMemory
+from src.providers.chat import ChatLLM
+
+
+class _Chunk:
+ """Minimal LangChain AIMessageChunk stand-in."""
+
+ def __init__(self, content: str) -> None:
+ self.content = content
+ self.tool_calls: list[dict[str, Any]] = []
+ self.additional_kwargs: dict[str, Any] = {}
+ self.response_metadata = {"finish_reason": "stop"}
+ self.usage_metadata = None
+
+ def __add__(self, other: "_Chunk") -> "_Chunk":
+ return _Chunk(f"{self.content}{other.content}")
+
+
+class _ScriptedStreamingLLM:
+ """Return one scripted response per stream_chat call."""
+
+ def __init__(self, responses: list[str]) -> None:
+ self._responses = responses
+
+ def bind_tools(self, tools: list[dict[str, Any]]) -> "_ScriptedStreamingLLM":
+ return self
+
+ def stream(self, messages: list[dict[str, Any]], config: dict[str, Any] | None = None):
+ yield _Chunk(self._responses.pop(0))
+
+
+class _EchoProbeTool(BaseTool):
+ """Safe test tool proving DSML calls reach the normal tool executor."""
+
+ name = "echo_probe"
+ description = "Echo a marker for DSML tool-call regression tests."
+ parameters = {
+ "type": "object",
+ "properties": {"marker": {"type": "string"}},
+ "required": ["marker"],
+ }
+ repeatable = True
+ is_readonly = False
+
+ def execute(self, **kwargs: Any) -> str:
+ return json.dumps({"status": "ok", "marker": kwargs.get("marker")})
+
+
+def _chat_llm(fake_llm: _ScriptedStreamingLLM) -> ChatLLM:
+ client = ChatLLM.__new__(ChatLLM)
+ client.model_name = "deepseek-v4-pro"
+ client._llm = fake_llm
+ return client
+
+
+def test_agent_loop_executes_dsml_textual_tool_call(tmp_path: Path) -> None:
+ """A pure DSML response must execute as a tool call instead of final text."""
+ dsml = (
+ '<||DSML||tool_calls>'
+ '<||DSML||invoke name="echo_probe">'
+ '<||DSML||parameter name="marker" string="true">ran-dsml</||DSML||parameter>'
+ "</||DSML||invoke>"
+ "</||DSML||tool_calls>"
+ )
+ registry = ToolRegistry()
+ registry.register(_EchoProbeTool())
+ memory = PersistentMemory(memory_dir=tmp_path / "memory")
+ events: list[tuple[str, dict[str, Any]]] = []
+ agent = AgentLoop(
+ registry=registry,
+ llm=_chat_llm(_ScriptedStreamingLLM([dsml, "final answer"])),
+ event_callback=lambda event_type, payload: events.append((event_type, payload)),
+ max_iterations=2,
+ persistent_memory=memory,
+ )
+ agent.memory.run_dir = str(tmp_path / "run")
+
+ result = agent.run("use the probe")
+
+ assert result["status"] == "success"
+ assert result["content"] == "final answer"
+ assert any(
+ event_type == "tool_call" and payload["tool"] == "echo_probe"
+ for event_type, payload in events
+ )
+ assert any(
+ event_type == "tool_result" and payload["tool"] == "echo_probe"
+ for event_type, payload in events
+ )
diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.py
index a6a1e0c58..963e850b5 100644
--- a/agent/tests/test_chat_llm_streaming.py
+++ b/agent/tests/test_chat_llm_streaming.py
@@ -84,6 +84,68 @@ def test_reasoning_only_chunks_emit_progress_without_final_answer_text() -> None
assert response.reasoning_content == "thinking more"
+def test_parse_dsml_tool_call_content_as_structured_tool_call() -> None:
+ """DeepSeek-style DSML content must drive the ReAct tool path (#261)."""
+ content = (
+ '<||DSML||tool_calls> '
+ '<||DSML||invoke name="bash"> '
+ '<||DSML||parameter name="command" string="true">'
+ "python -c \"print('vibe-dsml-ok')\""
+ "</||DSML||parameter> "
+ "</||DSML||invoke> "
+ "</||DSML||tool_calls>/"
+ )
+
+ response = ChatLLM._parse_response(_FakeChunk(content=content))
+
+ assert response.content == ""
+ assert len(response.tool_calls) == 1
+ assert response.tool_calls[0].id == "dsml_call_1"
+ assert response.tool_calls[0].name == "bash"
+ assert response.tool_calls[0].arguments == {
+ "command": "python -c \"print('vibe-dsml-ok')\""
+ }
+ assert response.finish_reason == "tool_calls"
+
+
+def test_parse_dsml_tool_call_requires_pure_tool_call_payload() -> None:
+ """Do not execute DSML examples embedded inside normal assistant text."""
+ content = (
+ "Here is the syntax:\n"
+ '<||DSML||tool_calls><||DSML||invoke name="bash">'
+ '<||DSML||parameter name="command">pwd</||DSML||parameter>'
+ "</||DSML||invoke></||DSML||tool_calls>"
+ )
+
+ response = ChatLLM._parse_response(_FakeChunk(content=content))
+
+ assert response.content == content
+ assert response.tool_calls == []
+ assert response.finish_reason == "stop"
+
+
+def test_stream_dsml_tool_call_content_is_not_emitted_as_text() -> None:
+ """DSML tool-call payloads should not flash as assistant text in CLI/UI."""
+ content = (
+ '<||DSML||tool_calls>'
+ '<||DSML||invoke name="bash">'
+ '<||DSML||parameter name="command">pwd</||DSML||parameter>'
+ "</||DSML||invoke>"
+ "</||DSML||tool_calls>"
+ )
+ fake = _FakeStreamingLLM([_FakeChunk(content=content)])
+ text_chunks: list[str] = []
+
+ response = _client(fake).stream_chat(
+ [{"role": "user", "content": "hi"}],
+ on_text_chunk=text_chunks.append,
+ )
+
+ assert text_chunks == []
+ assert response.content == ""
+ assert response.tool_calls[0].name == "bash"
+
+
def test_should_cancel_stops_stream_early() -> None:
"""A should_cancel predicate breaks the chunk loop; later chunks are dropped."""
fake = _FakeStreamingLLM([