The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): keep composite tool ids paired on Mistral routes
kshitijk4poor0c1bfb7dfb47
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex b18cdfb2bd9..15a3f3f5430 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -460,40 +460,17 @@ def _looks_like_corrupt_image_rejection(error_body: str) -> bool:__all__ = [- "_SURROGATE_RE",- "_escape_invalid_chars_in_json_strings",- "_repair_tool_call_arguments",- "_sanitize_messages_non_ascii",- "_sanitize_messages_surrogates",- "_sanitize_structure_non_ascii",- "_sanitize_structure_surrogates",- "_sanitize_surrogates",- "_sanitize_tools_non_ascii",- "_strip_images_from_messages",- "_strip_non_ascii",- "apply_reasoning_content_policy",- "close_interrupted_tool_sequence",- "coalesce_tool_call_id",- "coerce_tool_name",- "deterministic_call_id",- "matches_reasoning_echo_family",- "mistral_compliant_tool_id",- "needs_reasoning_echo",- "normalize_provider_tool_call_ids",- "reapply_reasoning_echo",- "reasoning_echo_family",- "reasoning_replay_route",- "record_reasoning_field_rejection",- "rejected_reasoning_carriers",- "rewrite_mistral_tool_call_ids",- "route_reasoning_carriers",- "route_requires_mistral_tool_ids",- "sanitize_outbound_kwargs",- "stale_thinking_reaches_wire",- "strip_images_for_rejecting_model",- "tool_call_id_variants",- "tool_result_id_variants",- "uniquify_tool_call_ids",+ "_SURROGATE_RE", "_escape_invalid_chars_in_json_strings", "_repair_tool_call_arguments",+ "_sanitize_messages_non_ascii", "_sanitize_messages_surrogates", "_sanitize_structure_non_ascii",+ "_sanitize_structure_surrogates", "_sanitize_surrogates", "_sanitize_tools_non_ascii",+ "_strip_images_from_messages", "_strip_non_ascii", "apply_reasoning_content_policy",+ "close_interrupted_tool_sequence", "coalesce_tool_call_id", "coerce_tool_name",+ "deterministic_call_id", "matches_reasoning_echo_family", "mistral_compliant_tool_id", "needs_reasoning_echo",+ "normalize_provider_tool_call_ids", "reapply_reasoning_echo", "reasoning_echo_family",+ "reasoning_replay_route", "record_reasoning_field_rejection", "rejected_reasoning_carriers",+ "route_reasoning_carriers", "route_requires_mistral_tool_ids",+ "sanitize_outbound_kwargs", "stale_thinking_reaches_wire", "strip_images_for_rejecting_model",+ "tool_call_id_variants", "tool_result_id_variants", "uniquify_tool_call_ids",]@@ -530,20 +507,23 @@ def deterministic_call_id(fn_name: str, arguments: str, index: int = 0) -> str:return f"call_{hashlib.sha256(seed.encode('utf-8', errors='replace')).hexdigest()[:12]}"-# Mistral's validator accepts only ``^[A-Za-z0-9]{9}$``. A split tool_call batch-# stores ``call_`` + 12 hex, and replaying that id is HTTP 400 ("Unexpected tool-# call id"). Map on the wire copy only: stored history stays byte-stable, and the-# same source id always becomes the same 9 characters so the prefix does not drift.+# Mistral's validator accepts only ``^[A-Za-z0-9]{9}$`` ("Tool call id was ... but must be a-z,+# A-Z, 0-9, with a length of 9"); ``call_`` + 12 hex from a split tool_call batch or any other+# provider's id is rejected on replay. ChatCompletionsTransport maps ids on the wire copy only:+# stored history stays byte-stable, and one source id always becomes the same 9 characters so+# the prompt-cache prefix does not drift._MISTRAL_TOOL_ID_RE = re.compile(r"^[A-Za-z0-9]{9}$")_MISTRAL_ID_ALPHABET = string.digits + string.ascii_uppercase + string.ascii_lowercase-_MISTRAL_MODEL_MARKERS = ("mistral", "devstral", "codestral", "ministral", "pixtral")+_MISTRAL_MODEL_MARKERS = (+ "mistral", "magistral", "mixtral", "devstral", "codestral", "ministral", "pixtral", "voxtral",+)def route_requires_mistral_tool_ids(provider: Any, model: Any, base_url: Any) -> bool:"""True when this chat-completions route enforces Mistral's 9-character tool ids."""from utils import base_url_host_matches- if (provider or "").strip().lower() == "mistral" or base_url_host_matches(str(base_url or ""), "api.mistral.ai"):+ if (provider or "").strip().lower() == "mistral" or base_url_host_matches(str(base_url or ""), "mistral.ai"):return Truemodel_lower = (model or "").lower()return any(marker in model_lower for marker in _MISTRAL_MODEL_MARKERS)@@ -562,55 +542,6 @@ def mistral_compliant_tool_id(raw: Any) -> str:return "".join(chars)-def _rewrite_mistral_tool_call(tool_call: dict) -> dict:- updates = {}- for key in ("id", "call_id"):- current = tool_call.get(key)- if not isinstance(current, str):- continue- updated = mistral_compliant_tool_id(current)- if updated != current:- updates[key] = updated- return {**tool_call, **updates} if updates else tool_call---def _rewrite_mistral_tool_ids_message(message: Any) -> Any:- if not isinstance(message, dict):- return message- role = message.get("role")- if role == "tool":- current = message.get("tool_call_id")- if not isinstance(current, str):- return message- updated = mistral_compliant_tool_id(current)- return {**message, "tool_call_id": updated} if updated != current else message- if role != "assistant":- return message- calls = message.get("tool_calls")- if not isinstance(calls, list):- return message- copied = None- for index, tool_call in enumerate(calls):- if not isinstance(tool_call, dict):- continue- rewritten = _rewrite_mistral_tool_call(tool_call)- if rewritten is not tool_call:- if copied is None:- copied = list(calls)- copied[index] = rewritten- return {**message, "tool_calls": copied} if copied is not None else message---def rewrite_mistral_tool_call_ids(- messages: list, *, provider: Any = None, model: Any = None, base_url: Any = None,-) -> list:- """Wire copy whose tool ids satisfy Mistral. Other routes and already-valid ids pass through."""- if not messages or not route_requires_mistral_tool_ids(provider, model, base_url):- return messages- rewritten = [_rewrite_mistral_tool_ids_message(message) for message in messages]- return messages if all(new is old for new, old in zip(rewritten, messages)) else rewritten--def _expand_tool_id_variants(values: tuple[Any, ...]) -> frozenset[str]:"""Every wire spelling of one tool-call identifier: Responses bridges may expose the pairingid and response-item id separately or as ``call_id|response_item_id``; all alias ONE call."""diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex b6093ba9e05..66a33e11a14 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -5,7 +5,7 @@ provider-specific work lives in build_kwargs (max_tokens, reasoning, extra_body)"""import json-from typing import Any+from typing import Any, Callablefrom urllib.parse import urlparsefrom agent.reasoning_effort import (@@ -13,7 +13,12 @@ from agent.reasoning_effort import (clamp_reasoning_config, kimi_supported_efforts, requested_effort, tokenhub_effort,)from agent.message_metadata import MESSAGE_UID-from agent.message_sanitization import normalize_finish_reason as _normalize_finish_reason+from agent.message_sanitization import (+ coalesce_tool_call_id,+ mistral_compliant_tool_id,+ normalize_finish_reason as _normalize_finish_reason,+ route_requires_mistral_tool_ids,+)from agent.moonshot_schema import is_moonshot_model, sanitize_moonshot_toolsfrom agent.prompt_builder import DEVELOPER_ROLE_MODELSfrom agent.transports.base import ProviderTransport@@ -401,7 +406,7 @@ def _finish_kwargs(api_kwargs: dict[str, Any], sanitized: list, params: dict, *,def _sanitize_message(msg: Any, strip_extra_content: bool, strip_reasoning: frozenset = frozenset(),- native_reasoning_details_type: str | None = None,+ native_reasoning_details_type: str | None = None, map_tool_id: Callable[[str], str] | None = None,) -> dict | None:"""Sanitized copy of ``msg``, or None when nothing needs stripping.@@ -414,6 +419,8 @@ def _sanitize_message(On a route that reads ``reasoning_details``, private ``<provider>.native_assistant`` carriers still go only to theprofile that declared that exact type: another provider's signed replay is meaningless (orrejected) elsewhere, and stored history keeps it for a return to the original provider.+ ``map_tool_id`` (Mistral routes) rewrites the pairing id on both sides of a call/result pair+ from the same key, ``coalesce_tool_call_id``, so a composite ``call|item`` id stays paired."""if not isinstance(msg, dict):return None@@ -435,6 +442,13 @@ def _sanitize_message(if msg.get("role") == "tool" and "name" in msg:strip_keys.append("name")out_msg = {k: v for k, v in msg.items() if k not in strip_keys}+ mapped_result_id = False+ result_key = coalesce_tool_call_id({"id": msg.get("tool_call_id")}) if map_tool_id and msg.get("role") == "tool" else ""+ if result_key:+ mapped = map_tool_id(result_key)+ if mapped != msg["tool_call_id"]:+ out_msg["tool_call_id"] = mapped+ mapped_result_id = Trueif kept_details:out_msg["reasoning_details"] = kept_detailstool_calls = msg.get("tool_calls")@@ -451,13 +465,17 @@ def _sanitize_message(strip_extra_content or not _has_replayable_thought_signature(tc["extra_content"])):keys.append("extra_content")- if keys:+ key = coalesce_tool_call_id(tc) if map_tool_id else ""+ mapped = map_tool_id(key) if key else None+ if keys or (mapped is not None and mapped != tc.get("id")):if copied_tool_calls is None:copied_tool_calls = list(tool_calls)copied_tool_calls[tc_idx] = {k: v for k, v in tc.items() if k not in keys}+ if mapped is not None:+ copied_tool_calls[tc_idx]["id"] = mappedif copied_tool_calls is not None:out_msg["tool_calls"] = copied_tool_calls- return out_msg if strip_keys or copied_tool_calls is not None else None+ return out_msg if strip_keys or mapped_result_id or copied_tool_calls is not None else Noneclass ChatCompletionsTransport(ProviderTransport):@@ -478,10 +496,6 @@ class ChatCompletionsTransport(ProviderTransport):"""profile = kwargs.get("provider_profile")provider = getattr(profile, "name", None) or kwargs.get("provider")- from agent.message_sanitization import rewrite_mistral_tool_call_ids- messages = rewrite_mistral_tool_call_ids(- messages, provider=provider, model=kwargs.get("model"), base_url=kwargs.get("base_url"),- )strip_extra_content = not _model_consumes_thought_signature(kwargs.get("model"), kwargs.get("base_url"), provider)native_type = getattr(profile, "native_reasoning_details_type", None) or Nonecarriers = _wire_reasoning_carriers(provider, kwargs.get("base_url"))@@ -489,7 +503,10 @@ class ChatCompletionsTransport(ProviderTransport):# A profile declaring a native carrier type consumes replayed details by contract.carriers = carriers | {"reasoning_details"}strip_reasoning = frozenset({"reasoning_content", "reasoning", "reasoning_details"}) - carriers- sanitized_pairs = [(m, _sanitize_message(m, strip_extra_content, strip_reasoning, native_type))+ map_tool_id = (mistral_compliant_tool_id+ if route_requires_mistral_tool_ids(provider, kwargs.get("model"), kwargs.get("base_url"))+ else None)+ sanitized_pairs = [(m, _sanitize_message(m, strip_extra_content, strip_reasoning, native_type, map_tool_id))for m in messages]if all(s is None for _, s in sanitized_pairs):return messagesdiff --git a/tests/agent/test_mistral_tool_ids.py b/tests/agent/test_mistral_tool_ids.pyindex 820f4168d95..e0bf4b0494c 100644--- a/tests/agent/test_mistral_tool_ids.py+++ b/tests/agent/test_mistral_tool_ids.py@@ -12,11 +12,7 @@ import reimport pytest-from agent.message_sanitization import (- mistral_compliant_tool_id,- rewrite_mistral_tool_call_ids,- route_requires_mistral_tool_ids,-)+from agent.message_sanitization import mistral_compliant_tool_id, route_requires_mistral_tool_idsfrom agent.transports.chat_completions import ChatCompletionsTransport_BAD_ID = "call_04c3699a572b"@@ -33,17 +29,28 @@ def _pair():{"id": _NATIVE_ID, "type": "function", "function": {"name": "tool_call", "arguments": "{}"}},{"id": _BAD_ID, "call_id": _BAD_ID, "type": "function","function": {"name": "tool_call", "arguments": "{}"}},+ # Composite Responses-bridge id (uniquify_tool_call_ids writes these); its result+ # carries only the call half (tool_dispatch_helpers._normalize_tool_call_id).+ {"id": "call_abc|fc_123", "call_id": "call_abc", "type": "function",+ "function": {"name": "tool_call", "arguments": "{}"}},],},{"role": "tool", "tool_call_id": _NATIVE_ID, "content": "windows"},{"role": "tool", "tool_call_id": _BAD_ID, "content": "capture"},+ {"role": "tool", "tool_call_id": "call_abc", "content": "bridge"},]-def test_split_id_maps_to_one_stable_mistral_id():- assert mistral_compliant_tool_id(_BAD_ID) == "uzvbkiH61"- assert mistral_compliant_tool_id(_NATIVE_ID) == _NATIVE_ID- assert mistral_compliant_tool_id(_BAD_ID) == mistral_compliant_tool_id(_BAD_ID)+def _wire(model, base_url="https://ollama.com/v1"):+ import model_tools # registers provider profiles+ import providers++ messages = _pair()+ kwargs = ChatCompletionsTransport().build_kwargs(+ model=model, messages=messages, tools=None,+ provider_profile=providers.get_provider_profile("ollama-cloud"), base_url=base_url,+ )+ return messages, kwargs["messages"]@pytest.mark.parametrize(@@ -52,7 +59,10 @@ def test_split_id_maps_to_one_stable_mistral_id():("ollama-cloud", "mistral-large-4", "https://ollama.com/v1", True),("ollama-cloud", "devstral-2", "https://ollama.com/v1", True),("mistral", "codestral-latest", "https://api.mistral.ai/v1", True),+ ("custom", "anything", "https://codestral.mistral.ai/v1", True),("custom", "pixtral-large", "https://example.invalid/v1", True),+ ("custom", "magistral-small", "http://localhost:8000/v1", True),+ ("custom", "mixtral-8x22b", "http://localhost:8000/v1", True),("ollama-cloud", "glm-5.3-flash", "https://ollama.com/v1", False),("openrouter", "anthropic/claude-sonnet-4", "https://openrouter.ai/api/v1", False),],@@ -61,46 +71,24 @@ def test_route_gate(provider, model, base_url, required):assert route_requires_mistral_tool_ids(provider, model, base_url) is required-def test_rewrite_pairs_both_sides_and_leaves_history():- messages = _pair()- rewritten = rewrite_mistral_tool_call_ids(- messages, provider="ollama-cloud", model="mistral-large-4", base_url="https://ollama.com/v1",- )- assistant_ids = [tc["id"] for tc in rewritten[0]["tool_calls"]]- result_ids = [rewritten[1]["tool_call_id"], rewritten[2]["tool_call_id"]]-- assert assistant_ids[0] == _NATIVE_ID- assert _MISTRAL_ID.fullmatch(assistant_ids[1])- assert assistant_ids[1] == "uzvbkiH61"- assert rewritten[0]["tool_calls"][1]["call_id"] == assistant_ids[1]- assert result_ids == assistant_ids- assert messages[0]["tool_calls"][1]["id"] == _BAD_ID- assert messages[2]["tool_call_id"] == _BAD_ID+def test_mistral_wire_pairs_every_call_with_its_result_and_leaves_history():+ assert mistral_compliant_tool_id(_NATIVE_ID) == _NATIVE_ID+ assert mistral_compliant_tool_id(_BAD_ID) == "uzvbkiH61"+ messages, sent = _wire("mistral-large-4")+ call_ids = [tc["id"] for tc in sent[0]["tool_calls"]]+ result_ids = [m["tool_call_id"] for m in sent[1:]]-def test_non_mistral_route_is_unchanged():- messages = _pair()- rewritten = rewrite_mistral_tool_call_ids(- messages, provider="ollama-cloud", model="glm-5.3-flash", base_url="https://ollama.com/v1",- )- assert rewritten is messages+ assert call_ids[:2] == [_NATIVE_ID, "uzvbkiH61"]+ assert all(_MISTRAL_ID.fullmatch(i) for i in call_ids)+ assert result_ids == call_ids+ assert all("call_id" not in tc for tc in sent[0]["tool_calls"])+ assert messages[0]["tool_calls"][1]["id"] == _BAD_ID+ assert messages[0]["tool_calls"][2]["id"] == "call_abc|fc_123"+ assert messages[2]["tool_call_id"] == _BAD_ID-def test_ollama_cloud_profile_sends_the_rewritten_id():- import model_tools # registers provider profiles- import providers-- profile = providers.get_provider_profile("ollama-cloud")- messages = _pair()- kwargs = ChatCompletionsTransport().build_kwargs(- model="mistral-large-4",- messages=messages,- tools=None,- provider_profile=profile,- base_url="https://ollama.com/v1",- )- sent_ids = [tc["id"] for tc in kwargs["messages"][0]["tool_calls"]]- assert sent_ids[1] == "uzvbkiH61"- assert "call_id" not in kwargs["messages"][0]["tool_calls"][1]- assert kwargs["messages"][2]["tool_call_id"] == sent_ids[1]- assert messages[2]["tool_call_id"] == _BAD_ID+def test_non_mistral_route_keeps_ids():+ _, sent = _wire("glm-5.3-flash")+ assert [tc["id"] for tc in sent[0]["tool_calls"]] == [_NATIVE_ID, _BAD_ID, "call_abc|fc_123"]+ assert [m["tool_call_id"] for m in sent[1:]] == [_NATIVE_ID, _BAD_ID, "call_abc"]