The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(responses): preserve Codex namespace tool calls
Daniel Cadenasbd1478e4add9
diff --git a/litellm/responses/litellm_completion_transformation/streaming_iterator.py b/litellm/responses/litellm_completion_transformation/streaming_iterator.pyindex ddd05075763..09964d56c81 100644--- a/litellm/responses/litellm_completion_transformation/streaming_iterator.py+++ b/litellm/responses/litellm_completion_transformation/streaming_iterator.py@@ -124,6 +124,15 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):except (TypeError, ValueError):return None+ def _responses_namespace_tool_call_fields(self, fn_name: str) -> tuple[str, str | None]:+ tools = self.responses_api_request.get("tools")+ namespace_map = LiteLLMCompletionResponsesConfig._namespace_tool_name_map(tools)+ mapped = namespace_map.get(fn_name)+ if mapped:+ namespace, tool_name = mapped+ return tool_name, namespace+ return fn_name, None+def _is_reasoning_end(self, chunk):delta: Final = chunk.choices[0].delta@@ -182,13 +191,17 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):else:fn_name = str(getattr(fn, "name", "") or "")fn_args_delta = str(getattr(fn, "arguments", "") or "")+ tool_name, tool_namespace = self._responses_namespace_tool_call_fields(fn_name)output_index = self._get_or_assign_tool_output_index(call_id)if call_id not in self._tool_args_by_call_id:self._tool_args_by_call_id[call_id] = ""self._sequence_number += 1- item_kwargs = build_tool_call_item_kwargs(call_id, fn_name, "", "in_progress", self._custom_tool_names)+ names = self._custom_tool_names+ item_kwargs = build_tool_call_item_kwargs(call_id, tool_name, "", "in_progress", names)+ if tool_namespace:+ item_kwargs["namespace"] = tool_namespaceevent = OutputItemAddedEvent(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,output_index=output_index,@@ -249,6 +262,7 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):else:fn_name = str(getattr(fn, "name", "") or "")fn_args = str(getattr(fn, "arguments", "") or "")+ tool_name, tool_namespace = self._responses_namespace_tool_call_fields(fn_name)# Track if this is a new tool call that wasn't streamedis_new_tool_call = call_id not in self._tool_args_by_call_id@@ -257,7 +271,10 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):if is_new_tool_call:self._tool_args_by_call_id[call_id] = ""self._sequence_number += 1- item_kwargs = build_tool_call_item_kwargs(call_id, fn_name, "", "in_progress", self._custom_tool_names)+ names = self._custom_tool_names+ item_kwargs = build_tool_call_item_kwargs(call_id, tool_name, "", "in_progress", names)+ if tool_namespace:+ item_kwargs["namespace"] = tool_namespaceevent = OutputItemAddedEvent(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,output_index=output_index,@@ -299,9 +316,10 @@ class LiteLLMCompletionStreamingIterator(ResponsesAPIStreamingIterator):self._pending_tool_events.append(done_event)self._sequence_number += 1- item_kwargs = build_tool_call_item_kwargs(- call_id, fn_name, final_args, "completed", self._custom_tool_names- )+ names = self._custom_tool_names+ item_kwargs = build_tool_call_item_kwargs(call_id, tool_name, final_args, "completed", names)+ if tool_namespace:+ item_kwargs["namespace"] = tool_namespaceitem_done_event = OutputItemDoneEvent(type=ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,output_index=output_index,diff --git a/litellm/responses/litellm_completion_transformation/transformation.py b/litellm/responses/litellm_completion_transformation/transformation.pyindex f54023836e5..4134a65c95a 100644--- a/litellm/responses/litellm_completion_transformation/transformation.py+++ b/litellm/responses/litellm_completion_transformation/transformation.py@@ -78,6 +78,10 @@ from .custom_tools import (unwrap_custom_tool_arguments,)+NsMap = dict[str, tuple[str, str]]+NsTool = dict[str, Any]+RespTools = list[FunctionToolParam | OpenAIMcpServerTool] | None+########### Initialize Classes used for Responses API ###########TOOL_CALLS_CACHE: Final = InMemoryCache()@@ -1204,6 +1208,10 @@ class LiteLLMCompletionResponsesConfig:if "cache_control" in item:image_block["cache_control"] = item["cache_control"]content_list.append(image_block)+ elif item.get("type") == "encrypted_content":+ encrypted_content = item.get("encrypted_content")+ if encrypted_content is not None:+ content_list.append({"type": "text", "text": str(encrypted_content)})else:# Skip text blocks with None text to avoid downstream errorstext_value = item.get("text")@@ -1264,6 +1272,45 @@ class LiteLLMCompletionResponsesConfig:"""return ChatCompletionSystemMessage(role="system", content=instructions or "")+ @staticmethod+ def _build_ns_chat_tool(ns: str, ns_desc: str, ns_tool: NsTool, nested: bool) -> ChatCompletionToolParam | None:+ if nested and ns_tool.get("type") != "function":+ return None++ raw_parameters = ns_tool.get("parameters")+ parameters = dict(raw_parameters) if isinstance(raw_parameters, dict) else {}+ normalized_parameters = parameters if parameters and "type" in parameters else {**parameters, "type": "object"}+ tool_name = str(ns_tool.get("name") or "")+ raw_description = str(ns_tool.get("description") or "")+ description = raw_description+ if nested and ns_desc:+ description = f"{ns_desc}\n\n{raw_description}" if raw_description else ns_desc+ chat_tool_name = f"{ns}__{tool_name}" if nested else tool_name+ function: dict[str, Any] = {"name": chat_tool_name}+ function["description"] = description+ function["parameters"] = normalized_parameters+ function["strict"] = bool(ns_tool.get("strict", False))+ return {"type": "function", "function": function}++ @staticmethod+ def _namespace_chat_tools(tool: dict[str, Any]) -> list[ChatCompletionToolParam]:+ namespace = str(tool.get("name") or "")+ namespace_description = str(tool.get("description") or "")+ namespace_tools = tool.get("tools")+ if isinstance(namespace_tools, list):+ chat_completion_tools: list[ChatCompletionToolParam] = []+ ns = namespace+ ns_desc = namespace_description+ for ns_tool in namespace_tools:+ if not isinstance(ns_tool, dict):+ continue+ chat_tool = LiteLLMCompletionResponsesConfig._build_ns_chat_tool(ns, ns_desc, ns_tool, True)+ if chat_tool is not None:+ chat_completion_tools.append(chat_tool)+ return chat_completion_tools+ flat_tool = LiteLLMCompletionResponsesConfig._build_ns_chat_tool(namespace, namespace_description, tool, False)+ return [flat_tool] if flat_tool is not None else []+@staticmethoddef transform_responses_api_tools_to_chat_completion_tools(tools: list[FunctionToolParam | OpenAIMcpServerTool] | None,@@ -1317,13 +1364,15 @@ class LiteLLMCompletionResponsesConfig:if tool.get("input_examples"):chat_completion_tool["input_examples"] = tool.get("input_examples")chat_completion_tools.append(cast(ChatCompletionToolParam, chat_completion_tool))+ elif tool.get("type") == "namespace":+ chat_completion_tools.extend(LiteLLMCompletionResponsesConfig._namespace_chat_tools(tool))elif tool.get("type") == "custom":converted = convert_custom_tool_to_function_tool(tool)if converted is not None:chat_completion_tools.append(converted)else:_tool_type = tool.get("type")- if _tool_type in ("computer_use", "image_generation", "namespace", "shell"):+ if _tool_type in ("computer_use", "image_generation", "shell"):# Drop unsupported Responses-API-only tool types that have no# Chat Completions equivalent. Passing them through verbatim# causes providers to reject the request with "'function' is a@@ -1379,6 +1428,42 @@ class LiteLLMCompletionResponsesConfig:result.append(dict(tool))return result+ @staticmethod+ def _namespace_tool_name_map(tools: RespTools) -> NsMap:+ namespace_tool_names: NsMap = {}+ ambiguous_unqualified_names: set[str] = set()+ for tool in tools or []:+ if not isinstance(tool, dict) or tool.get("type") != "namespace":+ continue+ namespace = str(tool.get("name") or "")+ for namespace_tool in tool.get("tools") or []:+ if not isinstance(namespace_tool, dict) or namespace_tool.get("type") != "function":+ continue+ tool_name = str(namespace_tool.get("name") or "")+ namespace_tool_names[f"{namespace}__{tool_name}"] = (namespace, tool_name)+ if tool_name in ambiguous_unqualified_names:+ continue+ existing = namespace_tool_names.get(tool_name)+ if existing is not None and existing != (namespace, tool_name):+ ambiguous_unqualified_names.add(tool_name)+ namespace_tool_names.pop(tool_name, None)+ continue+ namespace_tool_names[tool_name] = (namespace, tool_name)+ return namespace_tool_names++ @staticmethod+ def _restore_namespace_tool_name(tool_name: str, names: NsMap) -> tuple[str, str | None]:+ mapped = names.get(tool_name)+ if mapped is None:+ return tool_name, None+ namespace, restored_tool_name = mapped+ return restored_tool_name, namespace++ @staticmethod+ def _set_tool_call_namespace(output_tool_call: ResponseFunctionToolCall, namespace: str | None) -> None:+ if namespace:+ setattr(output_tool_call, "namespace", namespace)+@staticmethoddef transform_chat_completion_tools_to_responses_tools(chat_completion_response: ModelResponse,@@ -1404,8 +1489,11 @@ class LiteLLMCompletionResponsesConfig:# Extract custom tool names from the original requestcustom_tool_names: set[str] = set()+ namespace_tool_names: NsMap = {}if responses_api_request and "tools" in responses_api_request:- custom_tool_names = extract_custom_tool_names(responses_api_request["tools"])+ req_tools = responses_api_request["tools"]+ custom_tool_names = extract_custom_tool_names(req_tools)+ namespace_tool_names = LiteLLMCompletionResponsesConfig._namespace_tool_name_map(req_tools)responses_tools: Final[list[ResponseFunctionToolCall | CustomToolCallOutputItem]] = []for tool in all_chat_completion_tools:@@ -1430,6 +1518,9 @@ class LiteLLMCompletionResponsesConfig:responses_tools.append(custom_item)else:# Build regular function_call output item+ restore_name = LiteLLMCompletionResponsesConfig._restore_namespace_tool_name+ tool_name, namespace = restore_name(tool_name, namespace_tool_names)+provider_specific_fields: dict | None = Noneif hasattr(tool, "provider_specific_fields") and getattr(tool, "provider_specific_fields", None):provider_specific_fields = getattr(tool, "provider_specific_fields")@@ -1454,6 +1545,7 @@ class LiteLLMCompletionResponsesConfig:type="function_call",status=function_definition.get("status") or "completed",)+ LiteLLMCompletionResponsesConfig._set_tool_call_namespace(output_tool_call, namespace)# Pass through provider_specific_fields as-is if presentif provider_specific_fields:diff --git a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.pyindex 51f757c9eaf..38c50693759 100644--- a/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py+++ b/tests/test_litellm/responses/litellm_completion_transformation/test_litellm_completion_responses.py@@ -11,10 +11,6 @@ from litellm.responses.litellm_completion_transformation.transformation import (TOOL_CALLS_CACHE,LiteLLMCompletionResponsesConfig,)-from litellm.types.llms.openai import (- ChatCompletionResponseMessage,- ChatCompletionToolMessage,-)from litellm.types.utils import (ChatCompletionMessageToolCall,Choices,@@ -608,6 +604,71 @@ class TestLiteLLMCompletionResponsesConfig:assert hasattr(responses_api_response, "_hidden_params")assert responses_api_response._hidden_params == {}+ def test_transform_chat_completion_response_restores_namespace_tool_call(self):+ tool_call_id = "call_namespace_restore"+ chat_completion_response = ModelResponse(+ id="test-response-id",+ created=1234567890,+ model="gemini-3.1-pro-preview-customtools",+ object="chat.completion",+ choices=[+ Choices(+ finish_reason="tool_calls",+ index=0,+ message=Message(+ content=None,+ role="assistant",+ tool_calls=[+ ChatCompletionMessageToolCall(+ id=tool_call_id,+ type="function",+ function=Function(+ name="collaboration__spawn_agent",+ arguments='{"message":"hello"}',+ ),+ )+ ],+ ),+ )+ ],+ )++ try:+ responses_api_response = LiteLLMCompletionResponsesConfig.transform_chat_completion_response_to_responses_api_response(+ request_input="Spawn an agent",+ responses_api_request={+ "tools": [+ {+ "type": "namespace",+ "name": "collaboration",+ "tools": [+ {+ "type": "function",+ "name": "spawn_agent",+ "parameters": {+ "type": "object",+ "properties": {},+ },+ }+ ],+ }+ ]+ },+ chat_completion_response=chat_completion_response,+ )+ finally:+ TOOL_CALLS_CACHE.delete_cache(key=tool_call_id)++ tool_calls = [+ item+ for item in responses_api_response.output+ if item.type == "function_call"+ ]+ assert len(tool_calls) == 1+ assert tool_calls[0].name == "spawn_agent"+ assert tool_calls[0].namespace == "collaboration"+ assert tool_calls[0].arguments == '{"message":"hello"}'+class TestFunctionCallTransformation:"""Test cases for function_call input transformation"""@@ -1037,6 +1098,29 @@ class TestContentTypeTransformation:assert result[0]["text"] == "valid text"assert result[1]["text"] == "another valid"+ def test_encrypted_content_blocks_preserved_as_text(self):+ """+ OpenAI Responses agent messages can include encrypted_content blocks.+ Chat-completions providers need the payload as text instead of silently+ dropping it.+ """+ content = [+ {"type": "input_text", "text": "Payload:\n"},+ {+ "type": "encrypted_content",+ "encrypted_content": "Reply exactly INPUT_AGENT_OK",+ },+ ]++ result = LiteLLMCompletionResponsesConfig._transform_responses_api_content_to_chat_completion_content(+ content+ )++ assert result == [+ {"type": "text", "text": "Payload:\n"},+ {"type": "text", "text": "Reply exactly INPUT_AGENT_OK"},+ ]+class TestToolTransformation:"""Test cases for tool transformation from Responses API to Chat Completion format"""@@ -1642,6 +1726,181 @@ class TestToolTransformation:assert "web_search_options" not in result+ def test_transform_nested_namespace_tools_to_function_tools(self):+ """Codex Responses namespace tools contain nested functions that chat+ providers need as flattened function names."""+ namespace_tool = {+ "type": "namespace",+ "name": "collaboration",+ "description": "Multi-agent tools",+ "tools": [+ {+ "type": "function",+ "name": "spawn_agent",+ "description": "Spawn an agent",+ "parameters": {+ "type": "object",+ "properties": {+ "task_name": {"type": "string"},+ "message": {"type": "string"},+ },+ "required": ["task_name", "message"],+ },+ }+ ],+ }++ result_tools, web_search_options = (+ LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(+ tools=[namespace_tool]+ )+ )++ assert web_search_options is None+ assert len(result_tools) == 1+ result_tool = result_tools[0]+ assert result_tool["type"] == "function"+ assert result_tool["function"]["name"] == "collaboration__spawn_agent"+ assert result_tool["function"]["parameters"] == namespace_tool["tools"][0]["parameters"]+ assert result_tool["function"]["description"] == "Multi-agent tools\n\nSpawn an agent"++ def test_transform_flat_namespace_tools_to_function_tools(self):+ namespace_tool = {+ "type": "namespace",+ "name": "mcp__node_repl",+ "description": "Run JavaScript in the node REPL",+ "parameters": {+ "type": "object",+ "properties": {+ "code": {+ "type": "string",+ "description": "JavaScript source to evaluate",+ }+ },+ "required": ["code"],+ },+ }++ result_tools, web_search_options = (+ LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(+ tools=[namespace_tool]+ )+ )++ assert web_search_options is None+ assert len(result_tools) == 1+ result_tool = result_tools[0]+ assert result_tool["type"] == "function"+ assert result_tool["function"]["name"] == "mcp__node_repl"+ assert result_tool["function"]["description"] == "Run JavaScript in the node REPL"+ assert result_tool["function"]["parameters"] == namespace_tool["parameters"]++ def test_namespace_tool_name_map_accepts_unique_unqualified_tool_names(self):+ """Some chat providers return the nested tool name without its namespace."""+ namespace_tool = {+ "type": "namespace",+ "name": "collaboration",+ "tools": [+ {+ "type": "function",+ "name": "wait_agent",+ "parameters": {"type": "object", "properties": {}},+ }+ ],+ }++ result = LiteLLMCompletionResponsesConfig._namespace_tool_name_map(+ [namespace_tool]+ )++ assert result["collaboration__wait_agent"] == ("collaboration", "wait_agent")+ assert result["wait_agent"] == ("collaboration", "wait_agent")++ def test_namespace_tool_name_map_drops_ambiguous_unqualified_names(self):+ tools = [+ {"type": "function", "name": "ordinary"},+ {+ "type": "namespace",+ "name": "alpha",+ "tools": [+ {+ "type": "function",+ "name": "run",+ "parameters": {"type": "object", "properties": {}},+ }+ ],+ },+ {+ "type": "namespace",+ "name": "beta",+ "tools": [+ {"type": "namespace", "name": "ignored"},+ {+ "type": "function",+ "name": "run",+ "parameters": {"type": "object", "properties": {}},+ },+ ],+ },+ {+ "type": "namespace",+ "name": "gamma",+ "tools": [+ {+ "type": "function",+ "name": "run",+ "parameters": {"type": "object", "properties": {}},+ }+ ],+ },+ ]++ result = LiteLLMCompletionResponsesConfig._namespace_tool_name_map(+ tools+ )++ assert result["alpha__run"] == ("alpha", "run")+ assert result["beta__run"] == ("beta", "run")+ assert result["gamma__run"] == ("gamma", "run")+ assert "run" not in result++ def test_restore_namespace_tool_name_leaves_unknown_tool_unchanged(self):+ tool_name, namespace = LiteLLMCompletionResponsesConfig._restore_namespace_tool_name(+ "mcp__node_repl",+ {},+ )++ assert tool_name == "mcp__node_repl"+ assert namespace is None++ def test_transform_nested_namespace_ignores_non_function_subtools(self):+ namespace_tool = {+ "type": "namespace",+ "name": "collaboration",+ "tools": [+ "ignored",+ {"type": "namespace", "name": "ignored"},+ {+ "type": "function",+ "name": "spawn_agent",+ "parameters": {"properties": {"task_name": {"type": "string"}}},+ },+ ],+ }++ result_tools, _ = (+ LiteLLMCompletionResponsesConfig.transform_responses_api_tools_to_chat_completion_tools(+ tools=[namespace_tool]+ )+ )++ assert len(result_tools) == 1+ assert result_tools[0]["function"]["name"] == "collaboration__spawn_agent"+ assert result_tools[0]["function"]["parameters"] == {+ "properties": {"task_name": {"type": "string"}},+ "type": "object",+ }+def test_bedrock_anthropic_responses_tools_yield_only_function_toolspec(self):"""End-to-end (no network) of the LIT-3858 acceptance criterion: the mixed tools array@@ -2185,7 +2444,7 @@ class TestStreamingIDConsistency:# Transform chunks to response API eventsevent1 = iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk1)event2 = iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk2)- event3 = iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk3)+ iterator._transform_chat_completion_chunk_to_response_api_chunk(chunk3)# Assert: All events should use the same item_id (from the first chunk)assert event1 is not None, "First event should not be None"@@ -2612,8 +2871,6 @@ class TestEnsureOutputItemContentPartAdded:def _make_iterator(self):"""Create a minimal LiteLLMCompletionStreamingIterator for testing."""- from unittest.mock import MagicMock-from litellm.responses.litellm_completion_transformation.streaming_iterator import (LiteLLMCompletionStreamingIterator,)@@ -2628,6 +2885,15 @@ class TestEnsureOutputItemContentPartAdded:iterator._cached_reasoning_item_id = Noneiterator._reasoning_active = Falseiterator._pending_response_events = []+ iterator._pending_tool_events = []+ iterator._tool_output_index_by_call_id = {}+ iterator._tool_args_by_call_id = {}+ iterator._tool_call_id_by_index = {}+ iterator._ambiguous_tool_call_indexes = set()+ iterator._next_tool_output_index = 1+ iterator._final_tool_events_queued = False+ iterator._custom_tool_names = set()+ iterator.responses_api_request = {}return iteratordef _make_text_chunk(self):@@ -2674,6 +2940,187 @@ class TestEnsureOutputItemContentPartAdded:assert events[1].part.type == "output_text"assert iterator.sent_content_part_added_event is True+ def test_streaming_namespace_tool_calls_restore_responses_namespace(self):+ """Flattened chat-completion namespace tool calls must stream back as+ Responses function calls with name + namespace split."""+ iterator = self._make_iterator()+ iterator.responses_api_request = {+ "tools": [+ {+ "type": "namespace",+ "name": "collaboration",+ "tools": [+ {+ "type": "function",+ "name": "spawn_agent",+ "parameters": {"type": "object", "properties": {}},+ }+ ],+ }+ ]+ }++ iterator._queue_tool_call_delta_events(+ [+ {+ "index": 0,+ "id": "call_1",+ "function": {+ "name": "collaboration__spawn_agent",+ "arguments": '{"task_name":"input_test"}',+ },+ }+ ]+ )++ added = iterator._pending_tool_events[0]+ assert added.item.name == "spawn_agent"+ assert added.item.namespace == "collaboration"++ def test_streaming_unqualified_namespace_tool_calls_restore_namespace(self):+ """A unique nested tool name without the namespace still maps back."""+ iterator = self._make_iterator()+ iterator.responses_api_request = {+ "tools": [+ {+ "type": "namespace",+ "name": "collaboration",+ "tools": [+ {+ "type": "function",+ "name": "wait_agent",+ "parameters": {"type": "object", "properties": {}},+ }+ ],+ }+ ]+ }++ iterator._queue_tool_call_delta_events(+ [+ {+ "index": 0,+ "id": "call_1",+ "function": {+ "name": "wait_agent",+ "arguments": "{}",+ },+ }+ ]+ )++ added = iterator._pending_tool_events[0]+ assert added.item.name == "wait_agent"+ assert added.item.namespace == "collaboration"++ def test_streaming_flat_namespace_tool_call_keeps_flat_name(self):+ iterator = self._make_iterator()+ iterator.responses_api_request = {+ "tools": [+ {+ "type": "namespace",+ "name": "mcp__node_repl",+ "description": "Run JavaScript",+ "parameters": {+ "type": "object",+ "properties": {"code": {"type": "string"}},+ },+ }+ ]+ }++ iterator._queue_tool_call_delta_events(+ [+ {+ "index": 0,+ "id": "call_1",+ "function": {+ "name": "mcp__node_repl",+ "arguments": '{"code":"1+1"}',+ },+ }+ ]+ )++ chat_completion_response = ModelResponse(+ id="chatcmpl-test",+ created=1234567890,+ model="gemini-3.1-pro-preview-customtools",+ object="chat.completion",+ choices=[+ Choices(+ finish_reason="tool_calls",+ index=0,+ message=Message(+ content=None,+ role="assistant",+ tool_calls=[+ ChatCompletionMessageToolCall(+ id="call_1",+ type="function",+ function=Function(+ name="mcp__node_repl",+ arguments='{"code":"1+1"}',+ ),+ )+ ],+ ),+ )+ ],+ )++ iterator._queue_final_tool_call_done_events(chat_completion_response)++ added = iterator._pending_tool_events[0]+ done = iterator._pending_tool_events[-1]+ assert added.item.name == "mcp__node_repl"+ assert getattr(added.item, "namespace", None) is None+ assert done.item.name == "mcp__node_repl"+ assert getattr(done.item, "namespace", None) is None++ def test_streaming_final_only_namespace_tool_call_restores_namespace(self):+ from unittest.mock import MagicMock++ iterator = self._make_iterator()+ iterator.responses_api_request = {+ "tools": [+ {+ "type": "namespace",+ "name": "collaboration",+ "tools": [+ {+ "type": "function",+ "name": "spawn_agent",+ "parameters": {"type": "object", "properties": {}},+ }+ ],+ }+ ]+ }+ message = MagicMock()+ message.tool_calls = [+ {+ "id": "call_1",+ "function": {+ "name": "collaboration__spawn_agent",+ "arguments": '{"message":"hello world"}',+ },+ }+ ]+ complete_response = MagicMock()+ complete_response.choices = [MagicMock(message=message)]++ iterator._queue_final_tool_call_done_events(complete_response)++ added = iterator._pending_tool_events[0]+ delta_events = iterator._pending_tool_events[1:-2]+ done = iterator._pending_tool_events[-1]+ assert added.item.name == "spawn_agent"+ assert added.item.namespace == "collaboration"+ assert "".join(event.delta for event in delta_events) == '{"message":"hello world"}'+ assert done.item.name == "spawn_agent"+ assert done.item.namespace == "collaboration"+def test_emit_response_completed_uses_stream_finish_reason(self):"""When the assembled model response carries finish_reason="content_filter"