Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(local-models): recover Qwen-style tool calls, hide think blocks, fall back when the server rejects tools (#941)

Ruben Lütke250838dce6f2
diff --git a/dodaios/agent_runtimes/provider_errors.py b/dodaios/agent_runtimes/provider_errors.py
index 9b1eab9306..ecd60af31c 100644
--- a/dodaios/agent_runtimes/provider_errors.py
+++ b/dodaios/agent_runtimes/provider_errors.py
@@ -31,6 +31,8 @@ import re
from dataclasses import dataclass
from typing import Final
+from dodaios.brain.tools_rejection import TOOLS_UNSUPPORTED_PHRASES, tools_rejection_hint
+
log = logging.getLogger(__name__)
#: Error codes providers use for an empty balance or a spent quota.
@@ -103,14 +105,9 @@ _OVERFLOW_PHRASES: Final[tuple[str, ...]] = (
)
_MODEL_MISSING_CODES: Final[frozenset[str]] = frozenset({"model_not_found"})
-_TOOLS_UNSUPPORTED_PHRASES: Final[tuple[str, ...]] = (
- "does not support tools",
- "tools are not supported",
- "tool use is not supported",
- "does not support function calling",
- "function calling is not enabled",
- "tool calling is not supported",
-)
+#: One list with the brains' tool-less retry (llama.cpp ``--jinja``, vLLM
+#: ``--enable-auto-tool-choice``, Ollama "does not support tools").
+_TOOLS_UNSUPPORTED_PHRASES: Final[tuple[str, ...]] = TOOLS_UNSUPPORTED_PHRASES
_TOOL_SCHEMA_CODES: Final[frozenset[str]] = frozenset(
{"invalid_function_parameters", "invalid_tool_schema"}
)
@@ -250,12 +247,17 @@ def classify(provider: str, exc: BaseException, model: str = "") -> Refusal | No
f"{model or 'the model'}'s context window on {_label(provider)}. Compress "
"or shorten the conversation and send it again.",
)
- if status in (400, 422) and any(phrase in text for phrase in _TOOLS_UNSUPPORTED_PHRASES):
+ # llama.cpp answered a tools request without ``--jinja`` with HTTP 500 in
+ # older builds; the phrases are specific enough to accept that status too.
+ if status in (400, 422, 500, None) and any(
+ phrase in text for phrase in _TOOLS_UNSUPPORTED_PHRASES
+ ):
return Refusal(
400,
"tools_unsupported",
f"{model or 'This model'} on {_label(provider)} cannot call tools, which the "
- "agent needs. Choose a model with tool support in the agent's settings.",
+ "agent needs. Choose a model with tool support in the agent's settings. "
+ f"{tools_rejection_hint(text) or ''}".rstrip(),
)
if status in (400, 422) and (
codes & _TOOL_SCHEMA_CODES or any(phrase in text for phrase in _TOOL_SCHEMA_PHRASES)
diff --git a/dodaios/brain/stream_markup.py b/dodaios/brain/stream_markup.py
new file mode 100644
index 0000000000..d945677ecf
--- /dev/null
+++ b/dodaios/brain/stream_markup.py
@@ -0,0 +1,288 @@
+"""Strip model markup out of a streamed answer before anyone sees or hears it.
+
+Local reasoning models (Qwen, DeepSeek-R1 distills, Gemma-based coders) write
+their chain of thought into the answer as ``<think>…</think>``, and a server
+that does not parse tool calls returns them as ``<tool_call>{…}</tool_call>``
+or ``[TOOL_CALLS][…]`` text. Left in the stream, the chat shows the reasoning,
+TTS reads it aloud, and a tool call turns into an empty reply once the voice
+scrubber removes the tag.
+
+:class:`StreamMarkupFilter` is the single place this is handled for every
+OpenAI-compatible transport. It is fed the raw ``delta.content`` chunks and
+returns only the visible answer, while recovered tool calls (offered tools
+only — see :func:`dodaios.brain.tool_call_recovery.extract_tagged_tool_calls`)
+are collected for the transport to emit as structured calls.
+
+It copes with tags split across chunks (a partial marker at the end of a chunk
+is held back until the next one decides it), an unclosed ``<think>`` (hidden
+to the end), and a stray ``</think>`` with no opener — some Qwen chat templates
+put the opening tag into the PROMPT, so the reply starts mid-thought. The text
+before such a closer is reasoning; once a model is seen doing this, its next
+replies are held back until the closer (or the end) so nothing leaks.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from .tool_call_recovery import (
+ MISTRAL_TOOL_CALLS,
+ TOOL_CALL_CLOSE,
+ TOOL_CALL_OPEN,
+ extract_tagged_tool_calls,
+)
+
+log = logging.getLogger(__name__)
+
+THINK_OPEN = "<think>"
+THINK_CLOSE = "</think>"
+
+_TEXT_MARKERS = (THINK_OPEN, THINK_CLOSE, TOOL_CALL_OPEN, MISTRAL_TOOL_CALLS)
+
+#: How much of a reply from a model of unknown habit is held back while
+#: waiting to see whether it opens with reasoning that ends in a bare
+#: ``</think>``. Only local providers ask for this, and only until the model
+#: has answered once without any think markup.
+PREFIX_HOLD_CHARS = 1500
+
+# (endpoint, model) -> "implicit" (reply starts inside a think block) or
+# "plain". Process lifetime; a wrong "plain" is corrected by the next stray
+# closer, a wrong "implicit" only costs streaming latency.
+_THINK_HABIT: dict[tuple[str, str], str] = {}
+
+
+def reset_think_habits() -> None:
+ """Forget what was learned about models (tests)."""
+ _THINK_HABIT.clear()
+
+
+def _partial_marker_suffix(buffer: str, markers: tuple[str, ...]) -> int:
+ """Length of the longest buffer suffix that could start one of ``markers``."""
+ lowered = buffer.lower()
+ longest = 0
+ for marker in markers:
+ marker = marker.lower()
+ for size in range(min(len(marker) - 1, len(lowered)), 0, -1):
+ if lowered.endswith(marker[:size]):
+ longest = max(longest, size)
+ break
+ return longest
+
+
+class StreamMarkupFilter:
+ """Incremental filter: ``feed`` chunks, then ``finish``; read ``calls``."""
+
+ def __init__(
+ self,
+ tools: Any = None,
+ *,
+ habit_key: tuple[str, str] | None = None,
+ hold_unknown_prefix: bool = False,
+ ) -> None:
+ self._tools = tools
+ self._habit_key = habit_key
+ habit = _THINK_HABIT.get(habit_key) if habit_key else None
+ # "prefix": the reply may begin inside a think block whose opener was
+ # in the prompt. Held back until a closer, the end, or the bound.
+ if habit == "implicit":
+ self._state = "prefix"
+ self._prefix_limit: int | None = None
+ elif habit is None and hold_unknown_prefix:
+ self._state = "prefix"
+ self._prefix_limit = PREFIX_HOLD_CHARS
+ else:
+ self._state = "text"
+ self._prefix_limit = None
+ self._buffer = ""
+ self._emitted_fences = 0
+ self._strip_leading = False
+ self._saw_think = False
+ self._saw_stray_close = False
+ self._emitted_any = False
+ self.calls: list[dict[str, Any]] = []
+
+ # -- public -----------------------------------------------------------
+
+ def feed(self, chunk: str) -> str:
+ if not chunk:
+ return ""
+ self._buffer += chunk
+ return self._drain(final=False)
+
+ def finish(self) -> str:
+ out = self._drain(final=True)
+ self._learn()
+ return out
+
+ # -- internals --------------------------------------------------------
+
+ def _emit(self, text: str) -> str:
+ if self._strip_leading:
+ text = text.lstrip()
+ if not text:
+ return ""
+ self._strip_leading = False
+ if text:
+ self._emitted_fences += text.count("```")
+ self._emitted_any = True
+ return text
+
+ def _in_fence(self, pending: str = "") -> bool:
+ return (self._emitted_fences + pending.count("```")) % 2 == 1
+
+ def _drain(self, *, final: bool) -> str:
+ out: list[str] = []
+ while True:
+ progressed = getattr(self, f"_step_{self._state}")(out, final)
+ if not progressed:
+ break
+ return "".join(out)
+
+ def _step_prefix(self, out: list[str], final: bool) -> bool:
+ lowered = self._buffer.lower()
+ close = lowered.find(THINK_CLOSE)
+ opener = lowered.find(THINK_OPEN)
+ if opener != -1 and (close == -1 or opener < close):
+ # An explicit opener after all: the normal think path handles it.
+ self._state = "text"
+ return True
+ if close != -1:
+ self._saw_think = True
+ self._saw_stray_close = True
+ self._buffer = self._buffer[close + len(THINK_CLOSE):]
+ self._strip_leading = True
+ self._state = "text"
+ return True
+ limit = self._prefix_limit
+ if final or (limit is not None and len(self._buffer) > limit):
+ # No closer: this reply did not start inside a think block.
+ self._state = "text"
+ return True
+ return False
+
+ def _step_text(self, out: list[str], final: bool) -> bool:
+ lowered = self._buffer.lower()
+ hits = [
+ (index, marker)
+ for marker in _TEXT_MARKERS
+ if (index := lowered.find(marker.lower())) != -1
+ ]
+ if not hits:
+ if final:
+ out.append(self._emit(self._buffer))
+ self._buffer = ""
+ return False
+ keep = _partial_marker_suffix(self._buffer, _TEXT_MARKERS)
+ ready = self._buffer[: len(self._buffer) - keep] if keep else self._buffer
+ out.append(self._emit(ready))
+ self._buffer = self._buffer[len(ready):]
+ return False
+ index, marker = min(hits)
+ before = self._buffer[:index]
+ rest = self._buffer[index + len(marker):]
+ tool_marker = marker in (TOOL_CALL_OPEN, MISTRAL_TOOL_CALLS)
+ if tool_marker and self._in_fence(before):
+ # Markup inside a code block is an example, not a call.
+ out.append(self._emit(before + self._buffer[index: index + len(marker)]))
+ self._buffer = rest
+ return True
+ out.append(self._emit(before))
+ if marker == THINK_OPEN:
+ self._saw_think = True
+ self._buffer = rest
+ self._state = "think"
+ elif marker == THINK_CLOSE:
+ # A closer with no opener: whatever reasoning preceded it was
+ # already handed on (it could not be known as such); drop the tag
+ # and remember the habit so the next reply is held back.
+ self._saw_think = True
+ self._saw_stray_close = True
+ self._buffer = rest
+ self._strip_leading = True
+ elif marker == TOOL_CALL_OPEN:
+ self._buffer = self._buffer[index:]
+ self._state = "tool_tag"
+ else:
+ self._buffer = self._buffer[index:]
+ self._state = "mistral"
+ return True
+
+ def _step_think(self, out: list[str], final: bool) -> bool:
+ close = self._buffer.lower().find(THINK_CLOSE)
+ if close == -1:
+ if final:
+ # Unclosed reasoning (cut off by the token limit): never shown.
+ self._buffer = ""
+ return False
+ keep = _partial_marker_suffix(self._buffer, (THINK_CLOSE,))
+ self._buffer = self._buffer[len(self._buffer) - keep:] if keep else ""
+ return False
+ self._buffer = self._buffer[close + len(THINK_CLOSE):]
+ self._strip_leading = True
+ self._state = "text"
+ return True
+
+ def _step_tool_tag(self, out: list[str], final: bool) -> bool:
+ close = self._buffer.lower().find(TOOL_CALL_CLOSE)
+ if close == -1 and not final:
+ return False
+ end = len(self._buffer) if close == -1 else close + len(TOOL_CALL_CLOSE)
+ block = self._buffer[:end]
+ self._buffer = self._buffer[end:]
+ self._state = "text"
+ calls, remaining = extract_tagged_tool_calls(block, self._tools)
+ if calls:
+ self.calls.extend(calls)
+ self._strip_leading = True
+ elif remaining == block:
+ # Not a call at all (prose about the tag): keep it as text.
+ out.append(self._emit(block))
+ else:
+ log.warning(
+ "stream_markup: dropped a text tool call naming no offered tool"
+ )
+ self._strip_leading = True
+ return True
+
+ def _step_mistral(self, out: list[str], final: bool) -> bool:
+ # ``[TOOL_CALLS]`` has no closing tag; it runs to the end of the reply.
+ if not final:
+ return False
+ block = self._buffer
+ self._buffer = ""
+ self._state = "text"
+ calls, remaining = extract_tagged_tool_calls(block, self._tools)
+ self.calls.extend(calls)
+ if remaining == block:
+ out.append(self._emit(block))
+ elif remaining:
+ out.append(self._emit(remaining))
+ elif not calls:
+ log.warning(
+ "stream_markup: dropped a text tool call naming no offered tool"
+ )
+ return False
+
+ def _learn(self) -> None:
+ if self._habit_key is None:
+ return
+ if self._saw_stray_close:
+ if _THINK_HABIT.get(self._habit_key) != "implicit":
+ log.info(
+ "stream_markup: %s starts its replies inside a think block; "
+ "holding its replies back until the reasoning ends.",
+ self._habit_key[1],
+ )
+ _THINK_HABIT[self._habit_key] = "implicit"
+ elif self._habit_key not in _THINK_HABIT and (self._emitted_any or self._saw_think):
+ _THINK_HABIT[self._habit_key] = "plain"
+
+
+__all__ = [
+ "PREFIX_HOLD_CHARS",
+ "THINK_CLOSE",
+ "THINK_OPEN",
+ "StreamMarkupFilter",
+ "reset_think_habits",
+]
diff --git a/dodaios/brain/tool_call_recovery.py b/dodaios/brain/tool_call_recovery.py
index 5d626dd784..52708829d6 100644
--- a/dodaios/brain/tool_call_recovery.py
+++ b/dodaios/brain/tool_call_recovery.py
@@ -224,9 +224,16 @@ def _call_identity(call: dict[str, Any]) -> str:
)
-def extract_leaked_tool_calls(text: str) -> list[dict[str, Any]]:
+def extract_leaked_tool_calls(text: str, tools: Any = None) -> list[dict[str, Any]]:
"""Parse explicit text-serialized tool calls into normal loop call records.
+ With ``tools`` (the tools offered this round), chat-template markup —
+ Qwen/Hermes ``<tool_call>{...}</tool_call>`` and Mistral ``[TOOL_CALLS]`` —
+ is recovered first, limited to offered tool names (see
+ :func:`extract_tagged_tool_calls`). Without ``tools`` only the explicit
+ JSON envelopes below count, since a bare ``{"name": ...}`` cannot be told
+ from a quoted sample unless its name is known to be real.
+
An envelope may sit anywhere in the response — alone, after prose, before
prose, between two sentences, or inside a ```json fence. Every envelope
found in the text is returned, in document order, with identical calls
@@ -245,6 +252,10 @@ def extract_leaked_tool_calls(text: str) -> list[dict[str, Any]]:
4. Prose — the text outside the envelopes must be short and free of
example vocabulary ("for example", "z. B.", "schema", "json", …).
"""
+ if tools and text and has_tool_markup(text):
+ tagged, _remaining = extract_tagged_tool_calls(text, tools)
+ if tagged:
+ return tagged
if not text or not any(marker in text.lower() for marker in _CALL_MARKERS):
return []
@@ -291,4 +302,255 @@ def extract_leaked_tool_calls(text: str) -> list[dict[str, Any]]:
return unique
-__all__ = ["extract_leaked_tool_calls"]
+# ---------------------------------------------------------------------------
+# Chat-template tool markup (Qwen / Hermes ``<tool_call>``, Mistral
+# ``[TOOL_CALLS]``).
+#
+# A local server that does not parse tool calls (llama.cpp without
+# ``--jinja``, LM Studio with an unknown template, an Ollama model whose
+# template lacks a tool parser) hands the model's raw markup back as text. The
+# markup is a template token, not prose, so it is a far stronger signal than a
+# bare JSON envelope — but it carries no ``type`` wrapper, so the gates are
+# different: the call must name a tool that was actually OFFERED this round,
+# and markup inside a code fence is documentation, never a call.
+# ---------------------------------------------------------------------------
+
+TOOL_CALL_OPEN = "<tool_call>"
+TOOL_CALL_CLOSE = "</tool_call>"
+MISTRAL_TOOL_CALLS = "[TOOL_CALLS]"
+_MISTRAL_ARGS = "[ARGS]"
+
+_TAGGED_BLOCK_RE = re.compile(
+ r"<tool_call>(.*?)(?:</tool_call>|\Z)", re.DOTALL | re.IGNORECASE
+)
+# Qwen3-Coder's XML flavour: <function=name><parameter=key>value</parameter></function>
+_XML_FUNCTION_RE = re.compile(
+ r"<function=([^>\s]+)\s*>(.*?)(?:</function>|\Z)", re.DOTALL
+)
+_XML_PARAMETER_RE = re.compile(
+ r"<parameter=([^>\s]+)\s*>(.*?)</parameter>", re.DOTALL
+)
+_MISTRAL_NAME_RE = re.compile(r"\s*([A-Za-z0-9_.\-/]+)\s*\[ARGS\]")
+
+
+def has_tool_markup(text: str) -> bool:
+ """Whether ``text`` contains a chat-template tool-call marker."""
+ lowered = (text or "").lower()
+ return TOOL_CALL_OPEN in lowered or MISTRAL_TOOL_CALLS.lower() in lowered
+
+
+def _offered(tools: Any) -> dict[str, dict[str, Any] | None]:
+ """``{name: input_schema}`` from schemas, a mapping, or plain names."""
+ offered: dict[str, dict[str, Any] | None] = {}
+ if not tools:
+ return offered
+ if isinstance(tools, dict):
+ return {str(k): (v if isinstance(v, dict) else None) for k, v in tools.items()}
+ for tool in tools:
+ if isinstance(tool, str):
+ offered[tool] = None
+ elif isinstance(tool, dict):
+ fn = tool.get("function") if isinstance(tool.get("function"), dict) else tool
+ name = fn.get("name")
+ if isinstance(name, str) and name:
+ schema = fn.get("input_schema", fn.get("parameters"))
+ offered[name] = schema if isinstance(schema, dict) else None
+ return offered
+
+
+def _bare_call(block: Any, offered: dict[str, dict[str, Any] | None]) -> dict[str, Any] | None:
+ """``{"name": ..., "arguments": ...}`` (or a wrapped form) → call record."""
+ if not isinstance(block, dict):
+ return None
+ call = block
+ for key in ("function", "function_call"):
+ if isinstance(block.get(key), dict):
+ call = block[key]
+ break
+ name = call.get("name")
+ if not isinstance(name, str) or name.strip() not in offered:
+ return None
+ arguments = _MISSING
+ for key in ("arguments", "parameters", "input", "args"):
+ if key in call:
+ arguments = call[key]
+ break
+ decoded = {} if arguments is _MISSING else _decode_arguments(arguments)
+ if decoded is None:
+ return None
+ return _record(name.strip(), decoded, block.get("id") or call.get("id"))
+
+
+def _record(name: str, arguments: dict[str, Any], call_id: Any = None) -> dict[str, Any]:
+ fingerprint = json.dumps(
+ [name, arguments], sort_keys=True, separators=(",", ":"), default=str
+ ).encode("utf-8")
+ return {
+ "id": str(call_id or f"leaked_{sha256(fingerprint).hexdigest()[:12]}"),
+ "name": name,
+ "input": arguments,
+ }
+
+
+def _xml_value(raw: str, schema: dict[str, Any] | None, key: str) -> Any:
+ """A Qwen3-Coder parameter value, typed by the tool's schema when known."""
+ value = raw.strip("\n")
+ declared = None
+ if schema and isinstance(schema.get("properties"), dict):
+ prop = schema["properties"].get(key)
+ if isinstance(prop, dict):
+ declared = prop.get("type")
+ if declared == "string":
+ return value
+ try:
+ return json.loads(value)
+ except (json.JSONDecodeError, ValueError):
+ # Not JSON: the value is plain text, which is what the template
+ # writes for every string argument.
+ return value
+
+
+def _calls_in_payload(
+ payload: str, offered: dict[str, dict[str, Any] | None]
+) -> tuple[list[dict[str, Any]], bool]:
+ """Calls inside one ``<tool_call>`` body, and whether it was call-shaped.
+
+ Call-shaped means the body WAS an attempted call (JSON with a ``name``, or
+ a ``<function=…>`` block) even when the name is not offered — the caller
+ hides such markup instead of showing it as an answer.
+ """
+ body = payload.strip()
+ xml = list(_XML_FUNCTION_RE.finditer(body))
+ if xml:
+ calls = []
+ for match in xml:
+ name = match.group(1).strip()
+ if name not in offered:
+ continue
+ schema = offered[name]
+ arguments = {
+ p.group(1).strip(): _xml_value(p.group(2), schema, p.group(1).strip())
+ for p in _XML_PARAMETER_RE.finditer(match.group(2))
+ }
+ calls.append(_record(name, arguments))
+ return calls, True
+ calls = []
+ shaped = False
+ for start, end in _json_spans(body):
+ try:
+ candidate = json.loads(body[start:end])
+ except (json.JSONDecodeError, ValueError):
+ # Not JSON at all: not a call, the caller keeps the text.
+ continue
+ blocks = candidate if isinstance(candidate, list) else [candidate]
+ for block in blocks:
+ if isinstance(block, dict) and (
+ "name" in block or "function" in block or "function_call" in block
+ ):
+ shaped = True
+ call = _bare_call(block, offered)
+ if call is not None:
+ calls.append(call)
+ return calls, shaped
+
+
+def _mistral_calls(
+ tail: str, offered: dict[str, dict[str, Any] | None]
+) -> tuple[list[dict[str, Any]], int]:
+ """Calls right after a ``[TOOL_CALLS]`` marker, and how much text they used."""
+ stripped = tail.lstrip()
+ lead = len(tail) - len(stripped)
+ if stripped[:1] in ("[", "{"):
+ spans = _json_spans(stripped)
+ if not spans or spans[0][0] != 0:
+ return [], 0
+ end = spans[0][1]
+ try:
+ candidate = json.loads(stripped[:end])
+ except (json.JSONDecodeError, ValueError):
+ # A truncated or malformed array executes nothing.
+ return [], 0
+ blocks = candidate if isinstance(candidate, list) else [candidate]
+ calls = [c for c in (_bare_call(b, offered) for b in blocks) if c is not None]
+ return calls, lead + end
+ # v11+ tokenizer: ``name[ARGS]{...}``
+ match = _MISTRAL_NAME_RE.match(tail)
+ if not match:
+ return [], 0
+ rest = tail[match.end():]
+ spans = _json_spans(rest)
+ if not spans or rest[: spans[0][0]].strip():
+ return [], 0
+ try:
+ arguments = json.loads(rest[spans[0][0]: spans[0][1]])
+ except (json.JSONDecodeError, ValueError):
+ # Malformed arguments: refuse rather than guess.
+ return [], 0
+ name = match.group(1)
+ if name not in offered or not isinstance(arguments, dict):
+ return [], match.end() + spans[0][1]
+ return [_record(name, arguments)], match.end() + spans[0][1]
+
+
+def _fenced(text: str, index: int) -> bool:
+ """Whether ``index`` sits inside a ``` code fence."""
+ return text.count("```", 0, index) % 2 == 1
+
+
+def extract_tagged_tool_calls(
+ text: str, tools: Any
+) -> tuple[list[dict[str, Any]], str]:
+ """Recover chat-template tool markup; return ``(calls, remaining_text)``.
+
+ ``tools`` are the tools OFFERED this round (schemas, ``{name: schema}``, or
+ names). Only calls naming one of them are returned. Call-shaped markup is
+ removed from the remaining text whether or not it named an offered tool —
+ it is never an answer a person should see or hear. Markup inside a code
+ fence, and markup whose body is not a call at all, stay as text.
+ """
+ if not text or not has_tool_markup(text):
+ return [], text
+ offered = _offered(tools)
+ calls: list[dict[str, Any]] = []
+ pieces: list[str] = []
+ cursor = 0
+ for match in _TAGGED_BLOCK_RE.finditer(text):
+ if _fenced(text, match.start()):
+ continue
+ found, shaped = _calls_in_payload(match.group(1), offered)
+ if not shaped:
+ continue
+ calls.extend(found)
+ pieces.append(text[cursor: match.start()])
+ cursor = match.end()
+ pieces.append(text[cursor:])
+ remaining = "".join(pieces)
+
+ marker = remaining.upper().find(MISTRAL_TOOL_CALLS)
+ while marker != -1 and not _fenced(remaining, marker):
+ tail = remaining[marker + len(MISTRAL_TOOL_CALLS):]
+ found, used = _mistral_calls(tail, offered)
+ if not used:
+ break
+ calls.extend(found)
+ remaining = remaining[:marker] + tail[used:]
+ marker = remaining.upper().find(MISTRAL_TOOL_CALLS)
+
+ unique: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for call in calls:
+ identity = _call_identity(call)
+ if identity not in seen:
+ seen.add(identity)
+ unique.append(call)
+ return unique, (remaining.strip() if remaining != text else text)
+
+
+__all__ = [
+ "MISTRAL_TOOL_CALLS",
+ "TOOL_CALL_CLOSE",
+ "TOOL_CALL_OPEN",
+ "extract_leaked_tool_calls",
+ "extract_tagged_tool_calls",
+ "has_tool_markup",
+]
diff --git a/dodaios/brain/tool_use_loop.py b/dodaios/brain/tool_use_loop.py
index 278d009d7c..8370e085b6 100644
--- a/dodaios/brain/tool_use_loop.py
+++ b/dodaios/brain/tool_use_loop.py
@@ -1064,7 +1064,10 @@ class ToolUseLoop:
# normal executor, risk, confirmation, telemetry, and synthesis
# path. This is shared by native, plugin, skill, and MCP tools.
if not deadline_forced and tools_payload:
- recovered_calls = extract_leaked_tool_calls(agg.text)
+ # The offered schemas let chat-template markup (Qwen
+ # ``<tool_call>``, Mistral ``[TOOL_CALLS]``) be recovered for
+ # the tools that really exist this round.
+ recovered_calls = extract_leaked_tool_calls(agg.text, tools_payload)
if recovered_calls:
structured_signatures = {
_tool_call_signature(call) for call in agg.tool_calls
diff --git a/dodaios/brain/tools_rejection.py b/dodaios/brain/tools_rejection.py
new file mode 100644
index 0000000000..4b43a7b7c8
--- /dev/null
+++ b/dodaios/brain/tools_rejection.py
@@ -0,0 +1,80 @@
+"""Recognise a model server that refuses a request because it carries tools.
+
+Local OpenAI-compatible servers only accept tool definitions when they were
+started for it, and each says so in its own words:
+
+* llama.cpp ``llama-server`` without ``--jinja``:
+ "tools param requires --jinja flag" (older builds: "Unsupported param: tools").
+* vLLM without ``--enable-auto-tool-choice``: '"auto" tool choice requires
+ --enable-auto-tool-choice and --tool-call-parser to be set'.
+* Ollama, for a model whose template has no tool support:
+ "registry.ollama.ai/library/<model> does not support tools".
+
+The phrases live here once so the voice/chat brains (which retry the turn
+without tools) and the agent gateway (which explains the refusal to an agent
+runtime) can never disagree about what counts as a tools refusal. Matching is
+loose on purpose: every phrase is specific to tool support, so a false match
+costs one tool-less answer, never a wrong action.
+"""
+
+from __future__ import annotations
+
+from typing import Final
+
+#: Lower-case fragments that only appear when a server refuses tools.
+TOOLS_UNSUPPORTED_PHRASES: Final[tuple[str, ...]] = (
+ # Ollama, and several gateways
+ "does not support tools",
+ "tools are not supported",
+ "tool use is not supported",
+ "does not support function calling",
+ "function calling is not enabled",
+ "tool calling is not supported",
+ # llama.cpp llama-server
+ "tools param requires --jinja",
+ "tool_choice param requires --jinja",
+ "unsupported param: tools",
+ # vLLM
+ "--enable-auto-tool-choice",
+ "enable-auto-tool-choice",
+ "--tool-call-parser",
+)
+
+_LLAMA_CPP_HINT: Final = (
+ "llama.cpp: start llama-server with --jinja so it accepts tool definitions."
+)
+_VLLM_HINT: Final = (
+ "vLLM: start the server with --enable-auto-tool-choice --tool-call-parser <parser> "
+ "(hermes for Qwen models)."
+)
+_TEMPLATE_HINT: Final = (
+ "The model's chat template declares no tool support; pick a model with tool "
+ "calling to let it act."
+)
+_GENERIC_HINT: Final = (
+ "The model server refused tool definitions; enable tool calling on the server "
+ "or pick a model with tool support."
+)
+
+
+def is_tools_rejection(message: str) -> bool:
+ """Whether an error text says the server cannot take tools."""
+ text = (message or "").lower()
+ return any(phrase in text for phrase in TOOLS_UNSUPPORTED_PHRASES)
+
+
+def tools_rejection_hint(message: str) -> str | None:
+ """The fix for a tools refusal (naming the missing server flag), else ``None``."""
+ text = (message or "").lower()
+ if not is_tools_rejection(text):
+ return None
+ if "jinja" in text or "unsupported param: tools" in text:
+ return _LLAMA_CPP_HINT
+ if "tool-choice" in text or "tool-call-parser" in text:
+ return _VLLM_HINT
+ if "does not support tools" in text:
+ return _TEMPLATE_HINT
+ return _GENERIC_HINT
+
+
+__all__ = ["TOOLS_UNSUPPORTED_PHRASES", "is_tools_rejection", "tools_rejection_hint"]
diff --git a/dodaios/plugins/brain/_openai_base.py b/dodaios/plugins/brain/_openai_base.py
index 19fdce53e3..6d7b465b0c 100644
--- a/dodaios/plugins/brain/_openai_base.py
+++ b/dodaios/plugins/brain/_openai_base.py
@@ -16,6 +16,8 @@ from typing import Any
import httpx
+from dodaios.brain.stream_markup import StreamMarkupFilter
+from dodaios.brain.tools_rejection import tools_rejection_hint
from dodaios.core.protocols import BrainDelta, BrainMessage, BrainRequest
from . import _agent_profile
@@ -526,6 +528,8 @@ async def stream_complete(
supports_vision: bool = True,
assistant_tool_call_extra_content: dict[str, Any] | None = None,
send_temperature: bool | None = None,
+ tools_fallback: bool = False,
+ hold_think_prefix: bool = False,
) -> AsyncIterator[BrainDelta]:
"""Streaming run against OpenAI-compatible Chat-Completions.
@@ -533,6 +537,20 @@ async def stream_complete(
that chose no temperature sends none); ``True`` always sends it — a
provider's own per-model temperature setting.
+ ``tools_fallback`` (local servers): a server that refuses the request
+ because it carries tools (llama.cpp without ``--jinja``, vLLM without
+ ``--enable-auto-tool-choice``, an Ollama model without tool support) is
+ asked once more without them, and the endpoint+model is remembered so
+ later turns do not pay the refusal again.
+
+ The streamed text passes through :class:`StreamMarkupFilter`: ``<think>``
+ reasoning never reaches the caller, and tool calls the server returned as
+ chat-template text (``<tool_call>``, ``[TOOL_CALLS]``) become structured
+ calls for the tools offered in ``req``. ``hold_think_prefix`` (local
+ servers) additionally holds the start of a reply from a model of unknown
+ habit back until it is clear the reply does not open mid-reasoning.
+ ``reasoning_content`` / ``reasoning`` delta fields are never read.
+
`supports_vision` is passed through to the message builder — when `False`,
`BrainMessage.images` are dropped and a WARN is logged.
@@ -595,12 +613,30 @@ async def stream_complete(
# OpenRouter call that carried the reasoning opt-out.
kwargs["extra_body"] = dict(extra_body)
- # Accumulator for tool-call partials (OpenAI streams per tool_call index)
- tool_buffer: dict[int, dict[str, Any]] = {}
+ # Accumulator for tool-call partials (OpenAI streams per tool_call index;
+ # a server that omits the index is keyed by the call id instead).
+ tool_buffer: dict[Any, dict[str, Any]] = {}
+ last_tool_key: Any = None
# A model the server already declared Responses-only skips the doomed
# Chat-Completions round-trip for the rest of the process lifetime.
responses_cache_key = (str(getattr(client, "base_url", "") or ""), model)
+ if tools_fallback and "tools" in kwargs and responses_cache_key in _TOOLS_REFUSED_CACHE:
+ kwargs.pop("tools", None)
+ kwargs.pop("tool_choice", None)
+ # Tools the model saw this round, under the (sanitized) names it saw.
+ offered_tools: dict[str, Any] = {}
+ for tool in req.tools or ():
+ tool_name = str(tool.get("name") or "")
+ if tool_name:
+ schema = tool.get("input_schema", tool.get("parameters"))
+ offered_tools[name_map.get(tool_name, tool_name)] = schema
+ offered_tools.setdefault(tool_name, schema)
+ markup = StreamMarkupFilter(
+ offered_tools,
+ habit_key=responses_cache_key,
+ hold_unknown_prefix=hold_think_prefix,
+ )
if responses_cache_key in _RESPONSES_ONLY_CACHE and _client_supports_responses(
client
):
@@ -615,7 +651,7 @@ async def stream_complete(
_sdk_optional_kwargs = ("stream_options", "reasoning_effort")
stream = None
use_responses = False
- for _ in range(len(_sdk_optional_kwargs) + 1):
+ for _ in range(len(_sdk_optional_kwargs) + 2):
try:
stream = await _create_with_token_param_retry(client, kwargs)
break
@@ -633,6 +669,26 @@ async def stream_complete(
)
kwargs.pop(offender, None)
except Exception as exc: # noqa: BLE001 — inspect for the transport verdict
+ hint = (
+ tools_rejection_hint(_error_text(exc))
+ if tools_fallback and "tools" in kwargs
+ else None
+ )
+ if hint is not None:
+ # The server cannot take tool definitions. Answering without
+ # tools beats failing every turn; remember it for this
+ # endpoint+model and say which server flag would fix it.
+ _TOOLS_REFUSED_CACHE.add(responses_cache_key)
+ log.warning(
+ "model server at %s refused tools for %s — answering without "
+ "tools from now on. %s",
+ responses_cache_key[0] or "the configured endpoint",
+ model,
+ hint,
+ )
+ kwargs.pop("tools", None)
+ kwargs.pop("tool_choice", None)
+ continue
if _is_responses_only_rejection(exc) and _client_supports_responses(
client
):
@@ -651,6 +707,41 @@ async def stream_complete(
return
if stream is None: # pragma: no cover -- loop always breaks or raises
raise RuntimeError("openai stream creation retry loop exhausted")
+ def _completed_calls() -> list[dict[str, Any]]:
+ calls = []
+ for position, (key, buf) in enumerate(tool_buffer.items()):
+ try:
+ parsed = json.loads(buf["arguments"]) if buf["arguments"] else {}
+ except json.JSONDecodeError as exc:
+ raise ValueError(
+ "The provider returned incomplete tool arguments.",
+ ) from exc
+ if not isinstance(parsed, dict):
+ raise ValueError("The provider returned non-object tool arguments.")
+ fallback_id = f"call_{key}" if isinstance(key, int) else f"call_{position}"
+ calls.append({
+ "id": buf["id"] or fallback_id,
+ "name": reverse_name_map.get(buf["name"], buf["name"]),
+ "input": parsed,
+ })
+ return calls
+
+ def _recovered_calls() -> list[dict[str, Any]]:
+ """Tool calls the server returned as chat-template text."""
+ recovered = [
+ {**call, "name": reverse_name_map.get(call["name"], call["name"])}
+ for call in markup.calls
+ ]
+ markup.calls.clear()
+ if recovered:
+ log.warning(
+ "recovered %d tool call(s) the server returned as text: %s",
+ len(recovered),
+ ", ".join(call["name"] for call in recovered),
+ )
+ return recovered
+
+ finished = False
async for chunk in stream:
# Text-Content
choices = getattr(chunk, "choices", None) or []
@@ -659,16 +750,32 @@ async def stream_complete(
if delta is None:
continue
+ # Only ``content`` is the answer. ``reasoning_content`` /
+ # ``reasoning`` (vLLM, LM Studio, Ollama, DeepSeek) are the
+ # model's thoughts and are deliberately never read.
content = getattr(delta, "content", None)
if content:
- yield BrainDelta(content=content)
+ visible = markup.feed(content)
+ if visible:
+ yield BrainDelta(content=visible)
tool_calls = getattr(delta, "tool_calls", None) or []
for tc in tool_calls:
- idx = getattr(tc, "index", 0) or 0
- slot = tool_buffer.setdefault(idx, {"id": "", "name": "", "arguments": ""})
- if getattr(tc, "id", None):
- slot["id"] = tc.id
+ idx = getattr(tc, "index", None)
+ call_id = getattr(tc, "id", None)
+ if isinstance(idx, int):
+ key: Any = idx
+ elif call_id:
+ # No index (some local servers): the id names the call.
+ key = f"id:{call_id}"
+ else:
+ # A continuation fragment without index or id belongs to
+ # the call that is being streamed.
+ key = last_tool_key if last_tool_key is not None else 0
+ last_tool_key = key
+ slot = tool_buffer.setdefault(key, {"id": "", "name": "", "arguments": ""})
+ if call_id:
+ slot["id"] = call_id
fn = getattr(tc, "function", None)
if fn is not None:
if getattr(fn, "name", None):
@@ -678,31 +785,27 @@ async def stream_complete(
finish = getattr(choice, "finish_reason", None)
if finish:
+ finished = True
+ tail = markup.finish()
+ if tail:
+ yield BrainDelta(content=tail)
if tool_buffer and finish not in {"tool_calls", "stop"}:
# Preserve the stop reason so the caller can retry with a
# larger budget; no partial tool arguments may execute.
tool_buffer.clear()
+ markup.calls.clear()
yield BrainDelta(finish_reason=finish)
continue
# Finalize tool calls if present
- completed_calls = []
- for idx, buf in sorted(tool_buffer.items()):
- try:
- parsed = json.loads(buf["arguments"]) if buf["arguments"] else {}
- except json.JSONDecodeError as exc:
- raise ValueError(
- "The provider returned incomplete tool arguments.",
- ) from exc
- if not isinstance(parsed, dict):
- raise ValueError("The provider returned non-object tool arguments.")
- completed_calls.append({
- "id": buf["id"] or f"call_{idx}",
- "name": reverse_name_map.get(buf["name"], buf["name"]),
- "input": parsed,
- })
+ completed_calls = _completed_calls()
+ tool_buffer.clear()
+ if not completed_calls and finish in {"stop", "tool_calls"}:
+ completed_calls = _recovered_calls()
+ if completed_calls:
+ finish = "tool_calls"
+ markup.calls.clear()
for call in completed_calls:
yield BrainDelta(tool_call=call)
- tool_buffer.clear()
yield BrainDelta(finish_reason=finish)
# Usage info (OpenAI delivers this in the last chunk)
@@ -724,6 +827,40 @@ async def stream_complete(
usage_payload["cache_hit_tokens"] = cached
yield BrainDelta(usage=usage_payload)
+ if not finished:
+ # Some local servers close the stream without ever sending a
+ # finish_reason. The text held back for a split tag, the tool-call
+ # fragments, and any text-format calls must not be lost with it.
+ tail = markup.finish()
+ if tail:
+ yield BrainDelta(content=tail)
+ try:
+ completed_calls = _completed_calls()
+ except ValueError:
+ # The stream broke off inside the arguments: never execute a
+ # partial call; report it like a cut-off answer.
+ log.warning("stream ended inside tool-call arguments; dropping the call")
+ tool_buffer.clear()
+ yield BrainDelta(finish_reason="length")
+ return
+ if not completed_calls:
+ completed_calls = _recovered_calls()
+ for call in completed_calls:
+ yield BrainDelta(tool_call=call)
+ if completed_calls:
+ yield BrainDelta(finish_reason="tool_calls")
+
+
+def _error_text(exc: Exception) -> str:
+ """An API error's message plus its response body, for phrase matching."""
+ body = getattr(exc, "body", None)
+ return f"{exc} {body if body is not None else ''}"
+
+
+# (base_url, model) pairs whose server refused tool definitions — answered
+# without tools for the rest of the process (``tools_fallback`` callers only).
+_TOOLS_REFUSED_CACHE: set[tuple[str, str]] = set()
+
_UNSUPPORTED_ERROR_MARKERS = (
"unsupported_parameter",
diff --git a/dodaios/plugins/brain/local_openai.py b/dodaios/plugins/brain/local_openai.py
index cb42b54a6c..cc9b33d47b 100644
--- a/dodaios/plugins/brain/local_openai.py
+++ b/dodaios/plugins/brain/local_openai.py
@@ -239,7 +239,18 @@ class LocalOpenAIBrain:
root = self._resolve_root()
stated = await self._guard_window(req, root, model)
reported: int | None = None
- stream = stream_complete(client, model, req, supports_vision=self.supports_vision)
+ # A server that was not started for tool calling (llama.cpp without
+ # --jinja, vLLM without --enable-auto-tool-choice) refuses requests
+ # with tools; the streamer then answers without them and says which
+ # flag is missing. Local reasoning models may open a reply mid-thought.
+ stream = stream_complete(
+ client,
+ model,
+ req,
+ supports_vision=self.supports_vision,
+ tools_fallback=True,
+ hold_think_prefix=True,
+ )
try:
first = True
async for delta in stream:
diff --git a/dodaios/plugins/brain/ollama.py b/dodaios/plugins/brain/ollama.py
index cf51b6d7d0..c63f4fa1d4 100644
--- a/dodaios/plugins/brain/ollama.py
+++ b/dodaios/plugins/brain/ollama.py
@@ -496,8 +496,17 @@ class OllamaBrain:
# Invariant at this point: either the request carries no images, or the
# model just negotiated declares ``vision`` — so the streamer may encode
# them.
+ # ``tools_fallback``: the capability probe fails open, so a model
+ # without tool support can still reach the server with tools; its
+ # "does not support tools" refusal is then answered without them.
stream = stream_complete(
- client, call.run_model, req, supports_vision=True, send_temperature=send_temperature
+ client,
+ call.run_model,
+ req,
+ supports_vision=True,
+ send_temperature=send_temperature,
+ tools_fallback=True,
+ hold_think_prefix=True,
)
reported: int | None = None
try:
diff --git a/tests/unit/brain/test_local_model_stream_paths.py b/tests/unit/brain/test_local_model_stream_paths.py
new file mode 100644
index 0000000000..a40e5f5ab2
--- /dev/null
+++ b/tests/unit/brain/test_local_model_stream_paths.py
@@ -0,0 +1,334 @@
+"""Local models end to end through the OpenAI-compatible streamer.
+
+A user running Dodaios on local models only (a Qwen-based coder via Ollama /
+LM Studio / llama.cpp) hit three failures at once:
+
+1. Tool calls the server returned as ``<tool_call>`` text never ran — the
+ person got an empty reply.
+2. ``<think>`` reasoning was shown in the chat and read aloud.
+3. A server started without tool support (llama.cpp without ``--jinja``,
+ vLLM without ``--enable-auto-tool-choice``) failed every turn.
+
+These tests drive the real ``stream_complete`` with a fake SDK client, and the
+real ``ToolUseLoop`` on top of it, so the recovered call is proven to EXECUTE.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import AsyncIterator
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from dodaios.agent_runtimes.provider_errors import classify
+from dodaios.brain import stream_markup
+from dodaios.brain.tool_use_loop import ToolUseLoop
+from dodaios.brain.tools_rejection import tools_rejection_hint
+from dodaios.core.protocols import BrainDelta, BrainMessage, BrainRequest, ToolResult
+from dodaios.plugins.brain import _openai_base
+from dodaios.plugins.brain._openai_base import stream_complete
+
+_LLAMA_CPP_NO_JINJA = "Error code: 500 - {'error': {'code': 500, 'message': 'tools param requires --jinja flag', 'type': 'server_error'}}" # noqa: E501
+_VLLM_NO_AUTO = (
+ "Error code: 400 - {'object': 'error', 'message': '\"auto\" tool choice requires "
+ "--enable-auto-tool-choice and --tool-call-parser to be set', 'type': 'BadRequestError'}"
+)
+_OLLAMA_NO_TOOLS = (
+ "Error code: 400 - {'error': {'message': 'registry.ollama.ai/library/gemma3:4b does "
+ "not support tools', 'type': 'api_error'}}"
+)
+
+
[email protected](autouse=True)
+def _fresh_process_state(monkeypatch):
+ stream_markup.reset_think_habits()
+ monkeypatch.setattr(_openai_base, "_TOOLS_REFUSED_CACHE", set())
+ monkeypatch.setattr(_openai_base, "_PARAM_ADAPTATION_CACHE", {})
+ yield
+ stream_markup.reset_think_habits()
+
+
+def _chunk(content: str | None = None, *, finish: str | None = None,
+ tool_calls: list[Any] | None = None, **extra: Any) -> Any:
+ delta = SimpleNamespace(content=content, tool_calls=tool_calls, **extra)
+ return SimpleNamespace(
+ choices=[SimpleNamespace(delta=delta, finish_reason=finish)], usage=None
+ )
+
+
+def _fragment(*, index: Any = None, call_id: str | None = None, name: str | None = None,
+ arguments: str | None = None) -> Any:
+ return SimpleNamespace(
+ index=index, id=call_id, function=SimpleNamespace(name=name, arguments=arguments)
+ )
+
+
+class _Stream:
+ def __init__(self, chunks: list[Any]) -> None:
+ self._chunks = list(chunks)
+
+ def __aiter__(self) -> _Stream:
+ return self
+
+ async def __anext__(self) -> Any:
+ if not self._chunks:
+ raise StopAsyncIteration
+ return self._chunks.pop(0)
+
+
+class _Client:
+ """``client.chat.completions.create`` raising queued errors, then streaming."""
+
+ base_url = "http://localhost:8080/v1/"
+
+ def __init__(self, rounds: list[list[Any]], errors: list[Exception] | None = None) -> None:
+ self.calls: list[dict[str, Any]] = []
+ self._rounds = list(rounds)
+ self._errors = list(errors or [])
+ self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create))
+
+ async def _create(self, **kwargs: Any) -> _Stream:
+ self.calls.append(kwargs)
+ if self._errors:
+ raise self._errors.pop(0)
+ return _Stream(self._rounds.pop(0) if self._rounds else [])
+
+
+_OPEN_APP = {
+ "name": "open_app",
+ "description": "Open an application.",
+ "input_schema": {"type": "object", "properties": {"app": {"type": "string"}}},
+}
+
+
+def _req(tools: tuple[dict[str, Any], ...] = (_OPEN_APP,)) -> BrainRequest:
+ return BrainRequest(messages=(BrainMessage(role="user", content="open spotify"),),
+ tools=tools)
+
+
+async def _collect(client: _Client, req: BrainRequest | None = None, **kw: Any) -> list[BrainDelta]:
+ return [d async for d in stream_complete(client, "qwen", req or _req(), **kw)]
+
+
+def _text(deltas: list[BrainDelta]) -> str:
+ return "".join(d.content or "" for d in deltas)
+
+
+def _calls(deltas: list[BrainDelta]) -> list[dict[str, Any]]:
+ return [d.tool_call for d in deltas if d.tool_call]
+
+
+# ── 1. text-format tool calls become real calls ─────────────────────────────
+
+
+async def test_qwen_tool_call_text_becomes_a_structured_call() -> None:
+ client = _Client([[
+ _chunk("<think>The user wants Spotify.</think>\n"),
+ _chunk('<tool_call>\n{"name": "open_app", "arguments": '),
+ _chunk('"{\\"app\\": \\"spotify\\"}"}\n</tool_call>'),
+ _chunk(finish="stop"),
+ ]])
+ deltas = await _collect(client)
+ assert _text(deltas) == ""
+ assert [(c["name"], c["input"]) for c in _calls(deltas)] == [("open_app", {"app": "spotify"})]
+ assert deltas[-1].finish_reason == "tool_calls"
+
+
+async def test_unknown_tool_in_text_never_becomes_a_call() -> None:
+ client = _Client([[
+ _chunk('<tool_call>{"name": "format_disk", "arguments": {}}</tool_call>'),
+ _chunk(finish="stop"),
+ ]])
+ deltas = await _collect(client)
+ assert _calls(deltas) == []
+ assert deltas[-1].finish_reason == "stop"
+
+
+class _Executor:
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ async def execute(self, tool: Any, args: dict[str, Any], **_: Any) -> ToolResult:
+ self.calls.append((tool.name, args))
+ return ToolResult(success=True, output="Spotify is open.")
+
+
+class _OpenApp:
+ name = "open_app"
+ description = "Open an application."
+ schema: dict[str, Any] = {"type": "object", "properties": {"app": {"type": "string"}}}
+
+
+class _StreamerBrain:
+ """A brain whose rounds run through the real OpenAI-compatible streamer."""
+
+ def __init__(self, client: _Client) -> None:
+ self._client = client
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ async for delta in stream_complete(
+ self._client, "qwen", req, tools_fallback=True, hold_think_prefix=True
+ ):
+ yield delta
+
+
+async def test_recovered_call_is_executed_by_the_tool_loop() -> None:
+ client = _Client([
+ [
+ _chunk("Okay, Spotify.</think>"),
+ _chunk('<tool_call>{"name": "open_app", "arguments": {"app": "spotify"}}'),
+ _chunk("</tool_call>", finish="stop"),
+ ],
+ [_chunk("<think>done</think>Spotify is open now.", finish="stop")],
+ ])
+ executor = _Executor()
+ loop = ToolUseLoop(_StreamerBrain(client), {"open_app": _OpenApp()}, executor) # type: ignore[arg-type]
+
+ result = await loop.run([], user_utterance="open spotify")
+
+ assert executor.calls == [("open_app", {"app": "spotify"})]
+ assert result.text == "Spotify is open now."
+ assert "<" not in result.text
+
+
+class _RawTextBrain:
+ """A transport that hands raw template text through (no streamer filter)."""
+
+ def __init__(self) -> None:
+ self.rounds = 0
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ self.rounds += 1
+ if self.rounds == 1:
+ yield BrainDelta(
+ content='[TOOL_CALLS][{"name": "open_app", "arguments": {"app": "x"}}]'
+ )
+ else:
+ yield BrainDelta(content="Done.")
+ yield BrainDelta(finish_reason="stop")
+
+
+async def test_loop_recovers_mistral_text_from_any_transport() -> None:
+ executor = _Executor()
+ loop = ToolUseLoop(_RawTextBrain(), {"open_app": _OpenApp()}, executor) # type: ignore[arg-type]
+ result = await loop.run([], user_utterance="open x")
+ assert executor.calls == [("open_app", {"app": "x"})]
+ assert result.text == "Done."
+
+
+# ── 2. reasoning is never streamed ──────────────────────────────────────────
+
+
+async def test_reasoning_fields_and_think_blocks_never_reach_the_caller() -> None:
+ client = _Client([[
+ _chunk(None, reasoning_content="private thought"),
+ _chunk(None, reasoning="more private thought"),
+ _chunk("<thi"),
+ _chunk("nk>inline thought</th"),
+ _chunk("ink>\n\nHello!"),
+ _chunk(finish="stop"),
+ ]])
+ assert _text(await _collect(client, _req(tools=()))) == "Hello!"
+
+
+# ── stream ends without finish_reason; fragments without an index ──────────
+
+
+async def test_tool_fragments_are_finalized_when_the_stream_just_ends() -> None:
+ client = _Client([[
+ _chunk(tool_calls=[_fragment(index=0, call_id="c1", name="open_app", arguments='{"app"')]),
+ _chunk(tool_calls=[_fragment(index=0, arguments=': "spotify"}')]),
+ ]])
+ deltas = await _collect(client)
+ assert _calls(deltas) == [{"id": "c1", "name": "open_app", "input": {"app": "spotify"}}]
+ assert deltas[-1].finish_reason == "tool_calls"
+
+
+async def test_fragments_without_index_are_keyed_by_id() -> None:
+ client = _Client([[
+ _chunk(tool_calls=[_fragment(call_id="a", name="open_app", arguments='{"app": ')]),
+ _chunk(tool_calls=[_fragment(arguments='"one"}')]),
+ _chunk(tool_calls=[_fragment(call_id="b", name="open_app", arguments='{"app": "two"}')]),
+ _chunk(finish="tool_calls"),
+ ]])
+ calls = _calls(await _collect(client))
+ assert [(c["id"], c["input"]) for c in calls] == [("a", {"app": "one"}), ("b", {"app": "two"})]
+
+
+async def test_a_stream_cut_inside_arguments_runs_nothing() -> None:
+ client = _Client([[
+ _chunk(tool_calls=[
+ _fragment(index=0, call_id="c1", name="open_app", arguments='{"app": "sp'),
+ ]),
+ ]])
+ deltas = await _collect(client)
+ assert _calls(deltas) == []
+ assert deltas[-1].finish_reason == "length"
+
+
+async def test_held_back_partial_tag_is_flushed_when_the_stream_just_ends() -> None:
+ client = _Client([[_chunk("a < b and c <")]])
+ assert _text(await _collect(client, _req(tools=()))) == "a < b and c <"
+
+
+# ── 3. servers that refuse tools ────────────────────────────────────────────
+
+
+ ("error", "flag"),
+ [
+ (_LLAMA_CPP_NO_JINJA, "--jinja"),
+ (_VLLM_NO_AUTO, "--enable-auto-tool-choice"),
+ (_OLLAMA_NO_TOOLS, "tool support"),
+ ],
+)
+async def test_a_tools_refusal_is_retried_once_without_tools(
+ error: str, flag: str, caplog: pytest.LogCaptureFixture
+) -> None:
+ client = _Client([[_chunk("Hi.", finish="stop")], [_chunk("Again.", finish="stop")]],
+ errors=[RuntimeError(error)])
+ with caplog.at_level(logging.WARNING):
+ deltas = await _collect(client, tools_fallback=True)
+ assert _text(deltas) == "Hi."
+ assert "tools" in client.calls[0] and "tools" not in client.calls[1]
+ assert flag in caplog.text
+ # Remembered: the next turn does not pay the refusal again.
+ await _collect(client, tools_fallback=True)
+ assert len(client.calls) == 3 and "tools" not in client.calls[2]
+
+
+async def test_cloud_callers_keep_the_refusal() -> None:
+ client = _Client([[_chunk("Hi.", finish="stop")]], errors=[RuntimeError(_LLAMA_CPP_NO_JINJA)])
+ with pytest.raises(RuntimeError, match="--jinja"):
+ await _collect(client)
+
+
+async def test_other_errors_are_not_mistaken_for_a_tools_refusal() -> None:
+ client = _Client([[_chunk("Hi.", finish="stop")]], errors=[RuntimeError("model crashed")])
+ with pytest.raises(RuntimeError, match="model crashed"):
+ await _collect(client, tools_fallback=True)
+ assert len(client.calls) == 1
+
+
+class _StatusError(Exception):
+ def __init__(self, message: str, status: int) -> None:
+ super().__init__(message)
+ self.status_code = status
+
+
+ ("error", "status"),
+ [(_LLAMA_CPP_NO_JINJA, 500), (_VLLM_NO_AUTO, 400), (_OLLAMA_NO_TOOLS, 400)],
+)
+def test_agent_gateway_explains_the_refusal_with_the_server_flag(error: str, status: int) -> None:
+ refusal = classify("local-openai", _StatusError(error, status), "qwen")
+ assert refusal is not None and refusal.code == "tools_unsupported"
+ assert tools_rejection_hint(error) in refusal.message
+
+
+def test_hint_names_the_flag() -> None:
+ assert "--jinja" in (tools_rejection_hint(_LLAMA_CPP_NO_JINJA) or "")
+ assert "--enable-auto-tool-choice" in (tools_rejection_hint(_VLLM_NO_AUTO) or "")
+ assert tools_rejection_hint("Error code: 400 - context length exceeded") is None
diff --git a/tests/unit/brain/test_stream_markup.py b/tests/unit/brain/test_stream_markup.py
new file mode 100644
index 0000000000..072eb7192a
--- /dev/null
+++ b/tests/unit/brain/test_stream_markup.py
@@ -0,0 +1,91 @@
+"""``<think>`` reasoning never reaches the chat or the voice.
+
+Local reasoning models (Qwen, DeepSeek-R1 distills) write their thoughts into
+``delta.content``. The streamer used to pass every chunk straight on, so the
+chat showed the reasoning and TTS read it aloud. These tests pin the filter
+that sits in the one OpenAI-compatible streamer every local provider uses.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from dodaios.brain import stream_markup
+from dodaios.brain.stream_markup import PREFIX_HOLD_CHARS, StreamMarkupFilter
+
+
[email protected](autouse=True)
+def _fresh_habits():
+ stream_markup.reset_think_habits()
+ yield
+ stream_markup.reset_think_habits()
+
+
+def _run(chunks: list[str], **kwargs) -> str:
+ flt = StreamMarkupFilter([], **kwargs)
+ return "".join(flt.feed(c) for c in chunks) + flt.finish()
+
+
+def test_a_think_block_is_removed() -> None:
+ assert _run(["<think>The user greets me.</think>\n\nHello!"]) == "Hello!"
+
+
+def test_tags_split_across_chunks_are_still_removed() -> None:
+ chunks = ["<th", "ink>reas", "oning</thi", "nk>", "\n\nHel", "lo!"]
+ assert _run(chunks) == "Hello!"
+
+
+def test_one_character_chunks() -> None:
+ text = "Hi. <think>hidden</think>There."
+ assert _run(list(text)) == "Hi. There."
+
+
+def test_unclosed_think_at_the_start_is_never_shown() -> None:
+ assert _run(["<think>Let me think about this", " for a long time"]) == ""
+
+
+def test_stray_closer_is_dropped_and_learned() -> None:
+ key = ("http://localhost:8080/v1", "qwen3")
+ # Cloud-style call without a prefix hold: the reasoning before the stray
+ # closer cannot be known in time, but the tag never shows.
+ first = _run(["Okay, the user wants hi.", "</think>", "Hi!"], habit_key=key)
+ assert "</think>" not in first and first.endswith("Hi!")
+ # From now on this model's replies are held back until the closer.
+ assert _run(["Thinking again.", "</think>\n", "Hello."], habit_key=key) == "Hello."
+
+
+def test_local_provider_holds_the_start_of_an_unknown_model() -> None:
+ key = ("http://localhost:1234/v1", "ornith")
+ out = _run(["The user asks", " for the time.", "</think>", "It is noon."],
+ habit_key=key, hold_unknown_prefix=True)
+ assert out == "It is noon."
+
+
+def test_a_plain_model_is_released_after_its_first_reply() -> None:
+ key = ("http://localhost:1234/v1", "plain")
+ flt = StreamMarkupFilter([], habit_key=key, hold_unknown_prefix=True)
+ assert flt.feed("Hello there.") == "" # held: habit unknown
+ assert flt.finish() == "Hello there."
+ # Learned "plain": the next reply streams immediately.
+ assert StreamMarkupFilter([], habit_key=key, hold_unknown_prefix=True).feed("Hi") == "Hi"
+
+
+def test_the_prefix_hold_is_bounded() -> None:
+ flt = StreamMarkupFilter([], habit_key=("u", "m"), hold_unknown_prefix=True)
+ long = "x" * (PREFIX_HOLD_CHARS + 10)
+ assert flt.feed(long) == long
+
+
+def test_ordinary_angle_brackets_and_brackets_pass_through() -> None:
+ text = "If a < b and [x] then <b>bold</b>."
+ assert _run([text]) == text
+
+
+def test_tool_markup_becomes_a_call_not_text() -> None:
+ tools = [{"name": "open_app", "input_schema": {}}]
+ flt = StreamMarkupFilter(tools)
+ out = flt.feed('<think>open it</think>Opening. <tool_call>{"name": "open_app", ')
+ out += flt.feed('"arguments": {"app": "spotify"}}</tool_')
+ out += flt.feed("call>") + flt.finish()
+ assert out == "Opening. "
+ assert [(c["name"], c["input"]) for c in flt.calls] == [("open_app", {"app": "spotify"})]
diff --git a/tests/unit/brain/test_tagged_tool_call_recovery.py b/tests/unit/brain/test_tagged_tool_call_recovery.py
new file mode 100644
index 0000000000..e5877c82b1
--- /dev/null
+++ b/tests/unit/brain/test_tagged_tool_call_recovery.py
@@ -0,0 +1,121 @@
+"""Chat-template tool markup a local server returned as text is recovered.
+
+A Qwen / Hermes model behind a server that does not parse tool calls (llama.cpp
+without ``--jinja``, an unknown LM Studio template) writes
+``<tool_call>{"name": ..., "arguments": ...}</tool_call>``; Mistral writes
+``[TOOL_CALLS][...]``. Before this fix the recovery only knew JSON envelopes
+with a ``type`` wrapper, the voice scrubber then removed the tag, and the
+person got an empty reply while nothing ran.
+
+The tag is a template token, so it is a strong signal — but it carries no
+``type``, so the gate is different: only a tool OFFERED this round may run,
+and markup inside a code fence is documentation.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from dodaios.brain.tool_call_recovery import (
+ extract_leaked_tool_calls,
+ extract_tagged_tool_calls,
+)
+
+_TOOLS: list[dict[str, Any]] = [
+ {
+ "name": "open_app",
+ "description": "",
+ "input_schema": {"type": "object", "properties": {"app": {"type": "string"}}},
+ },
+ {
+ "name": "set_volume",
+ "description": "",
+ "input_schema": {"type": "object", "properties": {"level": {"type": "integer"}}},
+ },
+]
+
+
+def _calls(text: str, tools: Any = _TOOLS) -> list[tuple[str, dict[str, Any]]]:
+ return [(c["name"], c["input"]) for c in extract_tagged_tool_calls(text, tools)[0]]
+
+
+_QWEN = '{"name": "open_app", "arguments": {"app": "spotify"}}'
+
+
+ ("label", "text"),
+ [
+ ("object arguments", f"<tool_call>{_QWEN}</tool_call>"),
+ (
+ "arguments as a JSON string",
+ '<tool_call>{"name": "open_app", '
+ '"arguments": "{\\"app\\": \\"spotify\\"}"}</tool_call>',
+ ),
+ ("newlines inside the tag", f"<tool_call>\n{_QWEN}\n</tool_call>"),
+ ("prose before", f"Opening it.\n<tool_call>{_QWEN}</tool_call>"),
+ ("missing close tag at the end", f"<tool_call>{_QWEN}"),
+ ("OpenAI function wrapper", f'<tool_call>{{"type": "function", "function": {_QWEN}}}'
+ "</tool_call>"),
+ (
+ "Qwen3-Coder XML",
+ "<tool_call>\n<function=open_app>\n<parameter=app>\nspotify\n</parameter>\n</function>\n</tool_call>",
+ ),
+ ("Mistral array", '[TOOL_CALLS][{"name": "open_app", "arguments": {"app": "spotify"}}]'),
+ ("Mistral v11 name[ARGS]", '[TOOL_CALLS]open_app[ARGS]{"app": "spotify"}'),
+ ],
+)
+def test_template_markup_is_recovered(label: str, text: str) -> None:
+ assert _calls(text) == [("open_app", {"app": "spotify"})], label
+
+
+def test_several_tagged_calls_all_run_in_order() -> None:
+ text = (
+ '<tool_call>{"name": "open_app", "arguments": {"app": "spotify"}}</tool_call>\n'
+ '<tool_call>{"name": "set_volume", "arguments": {"level": 30}}</tool_call>'
+ )
+ assert _calls(text) == [("open_app", {"app": "spotify"}), ("set_volume", {"level": 30})]
+
+
+def test_xml_parameters_are_typed_by_the_schema() -> None:
+ text = (
+ "<tool_call><function=set_volume><parameter=level>30</parameter></function></tool_call>"
+ "<tool_call><function=open_app><parameter=app>42</parameter></function></tool_call>"
+ )
+ # An integer field decodes; a string field keeps "42" as text.
+ assert _calls(text) == [("set_volume", {"level": 30}), ("open_app", {"app": "42"})]
+
+
+def test_a_tool_that_was_not_offered_never_runs_and_is_hidden() -> None:
+ text = 'Sure. <tool_call>{"name": "delete_everything", "arguments": {}}</tool_call>'
+ calls, remaining = extract_tagged_tool_calls(text, _TOOLS)
+ assert calls == []
+ assert remaining == "Sure."
+
+
+def test_markup_in_a_code_fence_is_an_example() -> None:
+ text = '```\n<tool_call>{"name": "open_app", "arguments": {"app": "x"}}</tool_call>\n```'
+ calls, remaining = extract_tagged_tool_calls(text, _TOOLS)
+ assert calls == []
+ assert remaining == text
+
+
+def test_a_tag_around_prose_is_left_alone() -> None:
+ text = "Qwen writes calls between <tool_call> and </tool_call> tags."
+ assert extract_tagged_tool_calls(text, _TOOLS) == ([], text)
+
+
+def test_malformed_arguments_run_nothing() -> None:
+ assert _calls('<tool_call>{"name": "open_app", "arguments": "{broken"}</tool_call>') == []
+
+
+def test_without_offered_tools_nothing_runs() -> None:
+ assert _calls('<tool_call>{"name": "open_app", "arguments": {}}</tool_call>', tools=[]) == []
+
+
+def test_loop_entry_point_recovers_tags_only_with_offered_tools() -> None:
+ text = '<tool_call>{"name": "open_app", "arguments": {"app": "spotify"}}</tool_call>'
+ assert [c["name"] for c in extract_leaked_tool_calls(text, _TOOLS)] == ["open_app"]
+ # Callers that pass no tool list keep the old, envelope-only behaviour.
+ assert extract_leaked_tool_calls(text) == []