Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 37 additions & 5 deletions src/freehand/runtime/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,29 @@ def _post(agent: Any, url: str, headers: dict[str, str], body: dict[str, Any], r
_MISTRAL_MODELS = ("mistral", "codestral", "devstral", "ministral", "pixtral")


def _split_content(value: Any) -> tuple[str, str]:
"""(text, thinking) of a Chat Completions `content`. Mistral reasoning models send a list of parts instead of a
string: {"type": "text", "text": ...} and {"type": "thinking", "thinking": [{"type": "text", "text": ...}]}.
The thinking goes to the reasoning, like `reasoning_content` from other services."""
if isinstance(value, str):
return value, ""
if not isinstance(value, list):
return "", ""
text, thinking = [], []
for part in value:
if isinstance(part, str):
text.append(part)
elif isinstance(part, dict) and part.get("type") == "thinking":
inner = part.get("thinking")
if isinstance(inner, str):
thinking.append(inner)
elif isinstance(inner, list):
thinking.extend(str(p.get("text") or "") for p in inner if isinstance(p, dict))
elif isinstance(part, dict) and isinstance(part.get("text"), str):
text.append(part["text"])
return "".join(text), "".join(thinking)


def _chat_target(api_base: Any, model: Any) -> tuple[str, str, str]:
host = (urllib.parse.urlparse(str(api_base or "")).hostname or "").lower()
raw = str(model or "").lower()
Expand Down Expand Up @@ -976,11 +999,12 @@ def send(self, agent: Any, token: str | None, kind: str) -> dict[str, Any]:
def from_json(self, data: dict[str, Any]) -> dict[str, Any]:
choice = (data.get("choices") or [{}])[0]
msg = choice.get("message") or {}
out: dict[str, Any] = {"role": "assistant", "content": msg.get("content") or ""}
text, thought = _split_content(msg.get("content"))
out: dict[str, Any] = {"role": "assistant", "content": text}
if msg.get("tool_calls"):
out["tool_calls"] = msg["tool_calls"]
if msg.get("reasoning_content") or msg.get("reasoning"):
out["reasoning_content"] = msg.get("reasoning_content") or msg.get("reasoning")
if msg.get("reasoning_content") or msg.get("reasoning") or thought:
out["reasoning_content"] = msg.get("reasoning_content") or msg.get("reasoning") or thought
if msg.get("reasoning_details"):
out["reasoning_details"] = msg["reasoning_details"]
return {"output": out, "usage": self.usage(data.get("usage") or {}), "model": data.get("model"),
Expand Down Expand Up @@ -1041,8 +1065,16 @@ def read_stream(self, lines: Any, agent: Any) -> dict[str, Any]:
reasoning += piece
agent._on_stream("response.reasoning_summary_text.delta", {"delta": piece})
if delta.get("content"):
content += delta["content"]
agent._on_stream("response.output_text.delta", {"delta": delta["content"]})
text, thought = _split_content(delta["content"])
if thought:
if not started_reasoning:
started_reasoning = True
agent._on_stream("response.reasoning_summary_part.added", {})
reasoning += thought
agent._on_stream("response.reasoning_summary_text.delta", {"delta": thought})
if text:
content += text
agent._on_stream("response.output_text.delta", {"delta": text})
for tc in delta.get("tool_calls") or []:
slot = calls.setdefault(int(tc.get("index", len(calls))),
{"id": None, "type": "function", "function": {"name": "", "arguments": ""}})
Expand Down
25 changes: 25 additions & 0 deletions tests/test_provider_conformance.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,31 @@ def test_chat_stream_raises_on_mid_stream_vendor_error_or_truncated_eof():
providers.Chat().read_stream(io.BytesIO(b'data: {"choices": [{"delta": {"content": "half"}}]}\n\n'), agent)


def test_mistral_list_content_splits_thinking_from_text():
# Mistral reasoning models stream `content` as a list of parts; thinking parts nest their text one level deeper.
def frame(delta, finish=None):
return b"data: " + json.dumps({"choices": [{"delta": delta, "finish_reason": finish}]}).encode() + b"\n\n"
chunks = [
frame({"role": "assistant", "content": ""}),
frame({"content": [{"type": "thinking", "thinking": [{"type": "text", "text": "Let me "}]}]}),
frame({"content": [{"type": "thinking", "thinking": [{"type": "text", "text": "check."}]}]}),
frame({"content": [{"type": "text", "text": "Hel"}]}),
frame({"content": "lo"}, "stop"),
b"data: [DONE]\n\n",
]
agent = _dummy_agent("mistral-large-4", "https://api.mistral.ai/v1")
msg = providers.Chat().read_stream(io.BytesIO(b"".join(chunks)), agent)["output"]
assert msg["content"] == "Hello"
assert msg["reasoning_content"] == "Let me check."
kinds = [k for k, _ in agent._events]
assert kinds.count("response.reasoning_summary_text.delta") == 2
assert kinds.count("response.output_text.delta") == 2

out = providers.Chat().from_json({"choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": [
{"type": "thinking", "thinking": [{"type": "text", "text": "hmm"}]}, {"type": "text", "text": "done"}]}}]})
assert out["output"]["content"] == "done" and out["output"]["reasoning_content"] == "hmm"


@pytest.mark.parametrize("model", ["MiniMax-M4", "MiniMax-M3.1-Flash"])
@pytest.mark.parametrize("host", ["api.minimax.io", "api.minimax.cn", "api.minimaxi.com"])
@pytest.mark.parametrize("effort", ["low", "medium", "high", "xhigh", "max", "off", "none", None])
Expand Down