Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: normalize replayed tool-call ids for external providers (#9116)
Nilay851bcb05c03c
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.pyindex 488d7346d34..811ac947a31 100644--- a/studio/backend/core/inference/studio_tool_loop.py+++ b/studio/backend/core/inference/studio_tool_loop.py@@ -548,7 +548,15 @@ class _Turn:# Never replayed upstream: the conversation carries the# de-duplicated id, which is the whole point of the rename.normalized["stream_id"] = normalized["id"]- normalized["id"] = f"{normalized['id']}_{self.round}_{position}"+ # The renamed id is itself stored and replayed, so a single-shot+ # rename collides again on the next request. Counting up over a+ # finite ledger terminates and leaves the first attempt as is.+ renamed = f"{normalized['id']}_{self.round}_{position}"+ attempt = 0+ while renamed in seen:+ attempt += 1+ renamed = f"{normalized['id']}_{self.round}_{position}_{attempt}"+ normalized["id"] = renamedseen.add(normalized["id"])out.append(normalized)return out@@ -662,6 +670,27 @@ def _is_usage_only(payload: dict[str, Any]) -> bool:return "usage" in payload and isinstance(choices, list) and not choices+def _replayed_call_ids(conversation: list[dict[str, Any]]) -> set[str]:+ """Every tool-call id already in the history this run starts from.++ The healer restarts its counter every request, so a freshly minted call_0+ collides with a stripped call_0 replayed from history inside one upstream+ body. Seeding the ledger makes calls() rename the new one as it does any+ repeat within a run.+ """+ taken: set[str] = set()+ for message in conversation:+ if not isinstance(message, dict):+ continue+ for call in message.get("tool_calls") or []:+ if isinstance(call, dict) and isinstance(call.get("id"), str) and call["id"]:+ taken.add(call["id"])+ result_id = message.get("tool_call_id")+ if isinstance(result_id, str) and result_id:+ taken.add(result_id)+ return taken++def _append_user_turn(conversation: list[dict[str, Any]], content: str) -> None:"""Append a user turn, merging into a trailing one so roles keep alternating.@@ -781,7 +810,7 @@ async def stream_with_studio_tools(max_reprompts = MAX_ACT_REPROMPTSlast_reprompt_text = ""provider_turns = 0- used_call_ids: set[str] = set()+ used_call_ids: set[str] = _replayed_call_ids(conversation)spent_budget_passes = 0fruitless_turns = 0# One provider call per possible execution, plus headroom for the no-op,diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex a597d743d72..948229db2ee 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -12475,6 +12475,81 @@ def _extract_content_parts(messages: list) -> tuple[str, list[dict], "Optional[s# content_part type._INPUT_DOCUMENT_PROVIDERS = frozenset({"anthropic", "openai"})+# The frontend stores tool-call ids as "<provider id>:<uuid4>" (chat-adapter.ts mints them+# for part identity), which strict providers reject on replay: OpenAI caps call ids at 64+# chars and the minted form is 66. #8913.+_MINTED_TOOL_CALL_ID_SUFFIX = _re.compile(+ r":[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"+)++# Mistral rejects any replayed tool-call id not matching ^[a-zA-Z0-9]{9}$+# ("Tool call id was ... but must be a-z, A-Z, 0-9, with a length of 9").+_MISTRAL_TOOL_CALL_ID = _re.compile(r"[a-zA-Z0-9]{9}")++# Anthropic states the charset in its 400: "tool_use.id: String should match pattern+# '^[a-zA-Z0-9_-]+$'". No length cap is documented or observed, so this is charset only.+# A colon is not in the set, and two stored shapes carry one in under 64 chars so the >64+# branch never caught them: the duplicate-base fallback below, which keeps the whole+# "call_0:<uuid>", and the frontend's "<sandbox>:<thread>:<approval>" confirmation ids.+# Anthropic cannot originate either (its own ids are server-tool ids _filter_tool_calls+# drops), so the path is a history replayed after switching an existing chat to Anthropic.+_ANTHROPIC_TOOL_CALL_ID = _re.compile(r"[a-zA-Z0-9_-]+")+_ANTHROPIC_TOOL_CALL_ID_ILLEGAL = _re.compile(r"[^a-zA-Z0-9_-]")+++def _replay_tool_call_id_map(+ originals: "set[str]", provider_type: Optional[str] = None+) -> dict[str, str]:+ """Map stored tool-call ids to replay ids.++ The suffix-stripped base when exactly one distinct original claims it, else+ the full stored value: backend ids like "call_0" restart every response, so+ the minted uuid suffix is the only cross-response uniqueness. Then per+ provider: Mistral takes only 9-char alphanumeric ids, Anthropic only+ [a-zA-Z0-9_-] (sanitized prefix plus sha256 tail), everything else+ hash-shortens past 64 chars (same scheme as+ openai_codex_client._codex_call_id, so call/output pairs stay paired).++ Every branch hashes the whole pre-mapping value, not the truncated prefix,+ so ids sharing a prefix stay distinct, and is a no-op on its own output, so+ replaying an already-normalized history does not drift the ids again."""+ bases = {v: _MINTED_TOOL_CALL_ID_SUFFIX.sub("", v) for v in originals}+ claims: dict[str, int] = {}+ for base in bases.values():+ claims[base] = claims.get(base, 0) + 1+ out = {}+ for value, base in bases.items():+ replay = base if claims[base] == 1 else value+ if provider_type == "mistral":+ if not _MISTRAL_TOOL_CALL_ID.fullmatch(replay):+ replay = _hashlib.sha256(replay.encode("utf-8")).hexdigest()[:9]+ elif provider_type == "anthropic" and not _ANTHROPIC_TOOL_CALL_ID.fullmatch(replay):+ # Sanitizing alone would collide "a:b" and "a_b" onto one id, pairing the+ # wrong result with the wrong call: a silent wrong answer, worse than the 400+ # this avoids. The sha256 tail is over the unsanitized value so the mapping+ # stays injective; the prefix is readability only. 31 + 1 + 32 is 64, as below.+ digest = _hashlib.sha256(replay.encode("utf-8")).hexdigest()[:32]+ sanitized = _ANTHROPIC_TOOL_CALL_ID_ILLEGAL.sub("_", replay)[:31]+ replay = f"{sanitized}_{digest}"+ elif len(replay) > 64:+ digest = _hashlib.sha256(replay.encode("utf-8")).hexdigest()[:32]+ replay = f"{replay[:31]}_{digest}"+ out[value] = replay+ return out+++def _replay_tool_call_ids(tool_calls: Any, replay_ids: dict[str, str]) -> Any:+ if not isinstance(tool_calls, list):+ return tool_calls+ out = []+ for tc in tool_calls:+ if isinstance(tc, dict) and isinstance(tc.get("id"), str):+ fixed = replay_ids.get(tc["id"], tc["id"])+ if fixed != tc["id"]:+ tc = {**tc, "id": fixed}+ out.append(tc)+ return out+def _build_external_messages(messages: list,@@ -12785,6 +12860,20 @@ def _build_external_messages(if emit_extra_content and msg.role == "assistant" and msg.extra_content:entry["extra_content"] = msg.extra_contentresult.append(entry)+ originals = {+ tc["id"]+ for entry in result+ if isinstance(entry.get("tool_calls"), list)+ for tc in entry["tool_calls"]+ if isinstance(tc, dict) and isinstance(tc.get("id"), str)+ } | {entry["tool_call_id"] for entry in result if isinstance(entry.get("tool_call_id"), str)}+ if originals:+ replay_ids = _replay_tool_call_id_map(originals, provider_type)+ for entry in result:+ if entry.get("tool_calls"):+ entry["tool_calls"] = _replay_tool_call_ids(entry["tool_calls"], replay_ids)+ if isinstance(entry.get("tool_call_id"), str):+ entry["tool_call_id"] = replay_ids.get(entry["tool_call_id"], entry["tool_call_id"])return resultdiff --git a/studio/backend/tests/test_external_tool_call_id_replay.py b/studio/backend/tests/test_external_tool_call_id_replay.pynew file mode 100644index 00000000000..86eb892d5ab--- /dev/null+++ b/studio/backend/tests/test_external_tool_call_id_replay.py@@ -0,0 +1,164 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Replayed tool-call ids must fit provider limits (#8913).++The frontend stores them as "<provider id>:<uuid4>" (66 chars for OpenAI), and a+provider that validates ids rejects the whole request, permanently breaking the chat.+"""++import re++from models.inference import ChatMessage+from routes.inference import _build_external_messages++MINTED = "call_AbCdEfGhIjKlMnOpQrStUvWx:071e73c8-5d38-4d4c-821a-62fe32c7a54a"+ORIGINAL = "call_AbCdEfGhIjKlMnOpQrStUvWx"+++def _history(tool_call_id):+ return [+ ChatMessage.model_validate(+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": tool_call_id,+ "type": "function",+ "function": {"name": "python", "arguments": "{}"},+ }+ ],+ }+ ),+ ChatMessage.model_validate({"role": "tool", "tool_call_id": tool_call_id, "content": "ok"}),+ ]+++def _replayed_ids(tool_call_id, provider_type = "openai"):+ out = _build_external_messages(+ _history(tool_call_id), supports_vision = True, provider_type = provider_type+ )+ assistant = next(m for m in out if m.get("tool_calls"))+ tool = next(m for m in out if m["role"] == "tool")+ return assistant["tool_calls"][0]["id"], tool["tool_call_id"]+++def test_minted_frontend_id_is_restored_to_provider_id():+ call_id, output_id = _replayed_ids(MINTED)+ assert call_id == ORIGINAL+ assert output_id == ORIGINAL+++def test_oversized_foreign_id_is_shortened_symmetrically():+ long_id = "x" * 80+ call_id, output_id = _replayed_ids(long_id)+ assert call_id == output_id+ assert len(call_id) == 64+ assert call_id.startswith("x" * 31)+++def test_short_ids_pass_through_unchanged():+ call_id, output_id = _replayed_ids("call_xyz")+ assert call_id == "call_xyz"+ assert output_id == "call_xyz"+++def test_replay_applies_on_generic_chat_completions_providers():+ call_id, output_id = _replayed_ids(MINTED, provider_type = "deepseek")+ assert call_id == ORIGINAL+ assert output_id == ORIGINAL+++def test_mistral_maps_foreign_ids_to_nine_alnum_chars():+ for foreign in (MINTED, "tool_call_0", "toolu_01A09q90qw90lq917835lq9", "x" * 80):+ call_id, output_id = _replayed_ids(foreign, provider_type = "mistral")+ assert call_id == output_id+ assert re.fullmatch(r"[a-zA-Z0-9]{9}", call_id)+++def test_colliding_bases_keep_the_full_stored_ids():+ a = "call_0:071e73c8-5d38-4d4c-821a-62fe32c7a54a"+ b = "call_0:11111111-2222-4333-8444-555555555555"+ out = _build_external_messages(+ _history(a) + _history(b), supports_vision = True, provider_type = "openai"+ )+ call_ids = [m["tool_calls"][0]["id"] for m in out if m.get("tool_calls")]+ output_ids = [m["tool_call_id"] for m in out if m["role"] == "tool"]+ assert call_ids == output_ids == [a, b]+++def test_mistral_colliding_bases_stay_distinct():+ a = "call_0:071e73c8-5d38-4d4c-821a-62fe32c7a54a"+ b = "call_0:11111111-2222-4333-8444-555555555555"+ out = _build_external_messages(+ _history(a) + _history(b), supports_vision = True, provider_type = "mistral"+ )+ call_ids = [m["tool_calls"][0]["id"] for m in out if m.get("tool_calls")]+ output_ids = [m["tool_call_id"] for m in out if m["role"] == "tool"]+ assert call_ids == output_ids+ assert call_ids[0] != call_ids[1]+ assert all(re.fullmatch(r"[a-zA-Z0-9]{9}", cid) for cid in call_ids)+++def test_mistral_native_ids_pass_through_unchanged():+ call_id, output_id = _replayed_ids(+ "AbCdEfGhI:071e73c8-5d38-4d4c-821a-62fe32c7a54a", provider_type = "mistral"+ )+ assert call_id == "AbCdEfGhI"+ assert output_id == "AbCdEfGhI"+++# Anthropic states its charset in the 400 it raises: "tool_use.id: String should match+# pattern '^[a-zA-Z0-9_-]+$'". A colon is not in it, and the two stored shapes carrying+# one (the duplicate-base fallback, and "<sandbox>:<thread>:<approval>" confirmation ids)+# are both under 64 chars, so the length branch never touched them.+ANTHROPIC_ID = re.compile(r"[a-zA-Z0-9_-]+")+++def test_anthropic_rejects_nothing_it_would_have_rejected():+ call_id, output_id = _replayed_ids("sandboxsess:threadid:approvalid", provider_type = "anthropic")+ assert call_id == output_id+ assert ANTHROPIC_ID.fullmatch(call_id), call_id+++def test_anthropic_colliding_bases_stay_legal_and_distinct():+ a = "call_0:071e73c8-5d38-4d4c-821a-62fe32c7a54a"+ b = "call_0:11111111-2222-4333-8444-555555555555"+ out = _build_external_messages(+ _history(a) + _history(b), supports_vision = True, provider_type = "anthropic"+ )+ call_ids = [m["tool_calls"][0]["id"] for m in out if m.get("tool_calls")]+ output_ids = [m["tool_call_id"] for m in out if m["role"] == "tool"]+ assert call_ids == output_ids+ assert call_ids[0] != call_ids[1]+ assert all(ANTHROPIC_ID.fullmatch(cid) for cid in call_ids), call_ids+++def test_anthropic_legal_ids_pass_through_unchanged():+ # Only ids Anthropic would already have refused may change, so a chat that works+ # today keeps byte-identical ids.+ for legal in ("toolu_01A1B2C3D4E5F6G7H8I9J0K1", "call_abc123", "a-b_c"):+ call_id, output_id = _replayed_ids(legal, provider_type = "anthropic")+ assert call_id == output_id == legal+++def test_anthropic_sanitizing_alone_would_collide():+ # "pre:fix" and "pre_fix" both sanitize to "pre_fix", a silent mispairing, so the+ # sha256 tail over the unsanitized value is what keeps the map injective.+ out = _build_external_messages(+ _history("pre:fix") + _history("pre_fix"),+ supports_vision = True,+ provider_type = "anthropic",+ )+ call_ids = [m["tool_calls"][0]["id"] for m in out if m.get("tool_calls")]+ assert len(set(call_ids)) == 2, call_ids+++def test_replay_is_idempotent_for_every_provider():+ # A normalized id replayed again on turn three must not drift, or the call and its+ # result stop matching.+ for provider in ("openai", "anthropic", "mistral", "gemini", "deepseek", None):+ once, _ = _replayed_ids(MINTED, provider_type = provider)+ twice, paired = _replayed_ids(once, provider_type = provider)+ assert twice == once == paired, (provider, once, twice)diff --git a/studio/backend/tests/test_external_tool_edge_cases.py b/studio/backend/tests/test_external_tool_edge_cases.pyindex d1b9ac7d273..b6cf1669031 100644--- a/studio/backend/tests/test_external_tool_edge_cases.py+++ b/studio/backend/tests/test_external_tool_edge_cases.py@@ -684,6 +684,102 @@ def test_healed_ids_are_unique_across_turns(executed):assert len(ids) == len(set(ids)), ids+def _healed_history(*call_ids):+ """A chat whose earlier turns already ran a healed call, as the route replays it.++ The replay normalization strips the stored "<backend id>:<uuid4>" back to the+ bare base, so this is the shape run.messages arrives in on the next request.+ """+ out = [{"role": "user", "content": "search something"}]+ for call_id in call_ids:+ out.append(+ {+ "role": "assistant",+ "content": "",+ "tool_calls": [+ {+ "id": call_id,+ "type": "function",+ "function": {"name": "web_search", "arguments": '{"query": "a"}'},+ }+ ],+ }+ )+ out.append({"role": "tool", "tool_call_id": call_id, "content": "ok"})+ out.append({"role": "user", "content": "now search again"})+ return out+++def _replayed_ids(transport):+ final = transport.requests[-1]["messages"]+ calls = [call["id"] for m in final if m.get("tool_calls") for call in m["tool_calls"]]+ results = [m["tool_call_id"] for m in final if m.get("role") == "tool"]+ return calls, results+++def test_healed_ids_do_not_collide_with_replayed_history(executed):+ """The healer restarts at call_0 on a history that already replays a call_0.++ The counter behind the healer's ids is per request, not per chat, so a+ history normalized down to a bare call_0 lands in the same upstream body as+ the newly minted one. The ledger only catches that if it is seeded from the+ replayed history.+ """+ heal = '<tool_call>{"name": "web_search", "arguments": {"query": "b"}}</tool_call>'+ transport = FakeTransport(+ [+ [_sse({"content": heal}), _sse(finish = "stop"), _DONE],+ _answer_turn(),+ ]+ )+ _run(transport, messages = _healed_history("call_0"))++ calls, results = _replayed_ids(transport)+ assert calls == results, (calls, results)+ assert len(calls) == len(set(calls)), calls+ assert "call_0" in calls, calls+++def test_history_rename_does_not_collide_again_on_the_next_request(executed):+ """The id the rename mints comes back as history, so it must not repeat.++ Renaming to "<id>_<round>_<position>" once is not enough: the client stores+ that id too, so the next request replays both call_0 and call_0_1_0 and a+ single-shot rename lands on the call_0_1_0 already in the body.+ """+ heal = '<tool_call>{"name": "web_search", "arguments": {"query": "c"}}</tool_call>'+ transport = FakeTransport(+ [+ [_sse({"content": heal}), _sse(finish = "stop"), _DONE],+ _answer_turn(),+ ]+ )+ _run(transport, messages = _healed_history("call_0", "call_0_1_0"))++ calls, results = _replayed_ids(transport)+ assert calls == results, (calls, results)+ assert len(calls) == len(set(calls)), calls+++def test_history_without_a_colliding_id_leaves_the_minted_id_alone(executed):+ """Seeding the ledger must not churn ids it has no reason to rename.++ A renamed id is longer, is not what the provider streamed, and invalidates+ the card key the client already painted.+ """+ heal = '<tool_call>{"name": "web_search", "arguments": {"query": "d"}}</tool_call>'+ transport = FakeTransport(+ [+ [_sse({"content": heal}), _sse(finish = "stop"), _DONE],+ _answer_turn(),+ ]+ )+ _run(transport, messages = _healed_history("call_9"))++ calls, results = _replayed_ids(transport)+ assert calls == results == ["call_9", "call_0"], (calls, results)++def test_finish_reason_length_mid_tool_call_does_not_execute(executed):"""Truncated arguments are not a call. Documented, current behaviour."""transport = FakeTransport(diff --git a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.pyindex 632c56d29e6..ddadf418aa2 100644--- a/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py+++ b/studio/backend/tests/test_llama_cpp_wait_for_vram_settle.py@@ -10,6 +10,7 @@ nvidia-smi involved.from __future__ import annotations+import importlib.util as _importlib_utilimport sysimport timeimport types as _types@@ -26,7 +27,26 @@ if _BACKEND_DIR not in sys.path:_loggers_stub = _types.ModuleType("loggers")_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)-sys.modules.setdefault("loggers", _loggers_stub)+# Same reasoning as httpx below: only when the real one is absent. With _BACKEND_DIR on+# sys.path the in-repo loggers package resolves, and stubbing over it trips the shadowing+# guard in test_backend_ci_parallel_isolation.py.+#+# Probed with find_spec, not `import loggers`: an import bound purely to test+# resolvability leaves an unused name that scripts/verify_import_hoist.py reads as a+# botched hoist, and loggers/handlers.py imports structlog at module scope, whose stub is+# not installed until below, so in the very environment this block exists for the import+# would fail on that transitive dep and the except branch would stub over the real+# package. find_spec answers "is it resolvable" without executing the module.+#+# Same except clause as _is_installed() in test_backend_ci_parallel_isolation.py:+# find_spec raises for a missing parent, and ValueError when a prior test left a bare+# ModuleType (__spec__ is None) in sys.modules, where the stub is already there anyway.+try:+ _real_loggers = _importlib_util.find_spec("loggers") is not None+except (ImportError, ValueError):+ _real_loggers = False+if not _real_loggers:+ sys.modules.setdefault("loggers", _loggers_stub)_structlog_stub = _types.ModuleType("structlog")_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")