The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): keep the Mistral tool-id rule beside its only consumer
kshitijk4poorc5fc0958b49f
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 15a3f3f5430..f0eb59cb49b 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -11,7 +11,6 @@ import hashlibimport jsonimport loggingimport re-import stringfrom functools import partialfrom typing import Any, Callable, Iterable, NamedTuple@@ -465,10 +464,10 @@ __all__ = ["_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",+ "deterministic_call_id", "matches_reasoning_echo_family", "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",+ "route_reasoning_carriers","sanitize_outbound_kwargs", "stale_thinking_reaches_wire", "strip_images_for_rejecting_model","tool_call_id_variants", "tool_result_id_variants", "uniquify_tool_call_ids",]@@ -507,41 +506,6 @@ 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}$`` ("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", "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 ""), "mistral.ai"):- return True- model_lower = (model or "").lower()- return any(marker in model_lower for marker in _MISTRAL_MODEL_MARKERS)---def mistral_compliant_tool_id(raw: Any) -> str:- """Return ``raw`` when it is already 9 alphanumeric characters, else a stable substitute."""- text = raw.strip() if isinstance(raw, str) else ""- if _MISTRAL_TOOL_ID_RE.fullmatch(text):- return text- number = int.from_bytes(hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest()[:8], "big")- chars = []- for _ in range(9):- number, rem = divmod(number, 62)- chars.append(_MISTRAL_ID_ALPHABET[rem])- return "".join(chars)--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 66a33e11a14..1bb9fcb2b9d 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -4,8 +4,11 @@ Messages/tools are already OpenAI-shaped, so convert_* are near-identity; theprovider-specific work lives in build_kwargs (max_tokens, reasoning, extra_body)."""+import hashlibimport json-from typing import Any, Callable+import re+import string+from typing import Anyfrom urllib.parse import urlparsefrom agent.reasoning_effort import (@@ -13,12 +16,7 @@ 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 (- coalesce_tool_call_id,- mistral_compliant_tool_id,- normalize_finish_reason as _normalize_finish_reason,- route_requires_mistral_tool_ids,-)+from agent.message_sanitization import coalesce_tool_call_id, normalize_finish_reason as _normalize_finish_reasonfrom agent.moonshot_schema import is_moonshot_model, sanitize_moonshot_toolsfrom agent.prompt_builder import DEVELOPER_ROLE_MODELSfrom agent.transports.base import ProviderTransport@@ -404,9 +402,43 @@ def _finish_kwargs(api_kwargs: dict[str, Any], sanitized: list, params: dict, *,return api_kwargs+# 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 another+# provider's id is rejected on replay. Ids are mapped on the wire copy only: stored history stays+# byte-stable, and one source id always becomes the same 9 characters so the cache prefix holds.+_MISTRAL_TOOL_ID_RE = re.compile(r"^[A-Za-z0-9]{9}$")+_MISTRAL_ID_ALPHABET = string.digits + string.ascii_uppercase + string.ascii_lowercase+# Hosts/providers mirror the Mistral row of message_sanitization._REASONING_CARRIER_ROUTES; the+# model markers catch Mistral models served elsewhere (Ollama Cloud, vLLM, NIM, LM Studio).+_MISTRAL_MODEL_MARKERS = (+ "mistral", "magistral", "mixtral", "devstral", "codestral", "ministral", "pixtral", "voxtral",+)+++def _route_requires_mistral_tool_ids(provider: str | None, model: str | None, base_url: str | None) -> bool:+ from utils import base_url_host_matches++ if (provider or "").strip().lower() == "mistral" or base_url_host_matches(str(base_url or ""), "mistral.ai"):+ return True+ model_lower = (model or "").lower()+ return any(marker in model_lower for marker in _MISTRAL_MODEL_MARKERS)+++def _mistral_tool_id(key: str) -> str:+ """``key`` when already 9 alphanumeric characters, else a stable base62 digest of it."""+ if _MISTRAL_TOOL_ID_RE.fullmatch(key):+ return key+ number = int.from_bytes(hashlib.sha256(key.encode("utf-8", "surrogatepass")).digest()[:8], "big")+ chars = []+ for _ in range(9):+ number, rem = divmod(number, 62)+ chars.append(_MISTRAL_ID_ALPHABET[rem])+ return "".join(chars)++def _sanitize_message(msg: Any, strip_extra_content: bool, strip_reasoning: frozenset = frozenset(),- native_reasoning_details_type: str | None = None, map_tool_id: Callable[[str], str] | None = None,+ native_reasoning_details_type: str | None = None, *, mistral_tool_ids: bool = False,) -> dict | None:"""Sanitized copy of ``msg``, or None when nothing needs stripping.@@ -419,8 +451,9 @@ 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.+ ``mistral_tool_ids`` maps the call ``id`` and the result ``tool_call_id`` through+ ``_mistral_tool_id`` from the pairing key the result writers use (``coalesce_tool_call_id``:+ ``call_id`` first, call half of a composite ``call|item`` id), so each pair stays matched."""if not isinstance(msg, dict):return None@@ -442,13 +475,12 @@ 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"]:+ remapped = False+ if mistral_tool_ids and msg.get("role") == "tool":+ result_key = coalesce_tool_call_id({"id": msg.get("tool_call_id")})+ if result_key and (mapped := _mistral_tool_id(result_key)) != msg["tool_call_id"]:out_msg["tool_call_id"] = mapped- mapped_result_id = True+ remapped = Trueif kept_details:out_msg["reasoning_details"] = kept_detailstool_calls = msg.get("tool_calls")@@ -465,8 +497,8 @@ def _sanitize_message(strip_extra_content or not _has_replayable_thought_signature(tc["extra_content"])):keys.append("extra_content")- key = coalesce_tool_call_id(tc) if map_tool_id else ""- mapped = map_tool_id(key) if key else None+ key = coalesce_tool_call_id(tc) if mistral_tool_ids else ""+ mapped = _mistral_tool_id(key) if key else Noneif keys or (mapped is not None and mapped != tc.get("id")):if copied_tool_calls is None:copied_tool_calls = list(tool_calls)@@ -475,7 +507,7 @@ def _sanitize_message(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 mapped_result_id or copied_tool_calls is not None else None+ return out_msg if strip_keys or remapped or copied_tool_calls is not None else Noneclass ChatCompletionsTransport(ProviderTransport):@@ -503,10 +535,9 @@ 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- 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))+ mistral_ids = _route_requires_mistral_tool_ids(provider, kwargs.get("model"), kwargs.get("base_url"))+ sanitized_pairs = [(m, _sanitize_message(m, strip_extra_content, strip_reasoning, native_type,+ mistral_tool_ids=mistral_ids))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 e0bf4b0494c..1802c9cb87d 100644--- a/tests/agent/test_mistral_tool_ids.py+++ b/tests/agent/test_mistral_tool_ids.py@@ -12,8 +12,11 @@ import reimport pytest-from agent.message_sanitization import mistral_compliant_tool_id, route_requires_mistral_tool_ids-from agent.transports.chat_completions import ChatCompletionsTransport+from agent.transports.chat_completions import (+ ChatCompletionsTransport,+ _mistral_tool_id,+ _route_requires_mistral_tool_ids,+)_BAD_ID = "call_04c3699a572b"_NATIVE_ID = "c9Abb5ZtX"@@ -68,12 +71,12 @@ def _wire(model, base_url="https://ollama.com/v1"):],)def test_route_gate(provider, model, base_url, required):- assert route_requires_mistral_tool_ids(provider, model, base_url) is required+ assert _route_requires_mistral_tool_ids(provider, model, base_url) is requireddef 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"+ assert _mistral_tool_id(_NATIVE_ID) == _NATIVE_ID+ assert _mistral_tool_id(_BAD_ID) == "uzvbkiH61"messages, sent = _wire("mistral-large-4")call_ids = [tc["id"] for tc in sent[0]["tool_calls"]]diff --git a/tests/providers/test_e2e_wiring.py b/tests/providers/test_e2e_wiring.pyindex 98eeceff3cf..1d292d2287e 100644--- a/tests/providers/test_e2e_wiring.py+++ b/tests/providers/test_e2e_wiring.py@@ -61,9 +61,10 @@ class TestNvidiaProfileWiring:ollama_num_ctx=None,)+ # A Mistral model on NIM gets 9-character tool ids (both sides map identically).assert kwargs["messages"][2] == {"role": "tool",- "tool_call_id": "call_1",+ "tool_call_id": kwargs["messages"][1]["tool_calls"][0]["id"],"content": "ok",}assert msgs[2]["name"] == "terminal"