Skip to content

The agent that grows with you

fix(openai): cover nested sparse response fields

Alex Fournier89c44c0dadd1
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index b87f3d41edd..b7c37c61afc 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3559,8 +3559,9 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
delta_tool_calls = getattr(delta, "tool_calls", None)
if delta_tool_calls:
for tc_delta in delta_tool_calls:
- raw_idx = tc_delta.index if tc_delta.index is not None else 0
- delta_id = tc_delta.id or ""
+ raw_index = getattr(tc_delta, "index", None)
+ raw_idx = raw_index if raw_index is not None else 0
+ delta_id = getattr(tc_delta, "id", None) or ""
# Ollama fix: detect a new tool call reusing the same
# raw index (different id) and redirect to a fresh slot.
@@ -3579,7 +3580,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
if idx not in tool_calls_acc:
# Poolside may send integer id instead of string
- _tc_id = tc_delta.id
+ _tc_id = getattr(tc_delta, "id", None)
if isinstance(_tc_id, int):
_tc_id = str(_tc_id)
tool_calls_acc[idx] = {
@@ -3589,14 +3590,17 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
"extra_content": None,
}
entry = tool_calls_acc[idx]
- if tc_delta.id is not None:
- _new_id = tc_delta.id
+ tc_id = getattr(tc_delta, "id", None)
+ if tc_id is not None:
+ _new_id = tc_id
if isinstance(_new_id, int):
_new_id = str(_new_id)
if _new_id:
entry["id"] = _new_id
- if tc_delta.function:
- if tc_delta.function.name:
+ tc_function = getattr(tc_delta, "function", None)
+ if tc_function:
+ function_name = getattr(tc_function, "name", None)
+ if function_name:
# Use assignment, not +=. Function names are
# atomic identifiers delivered complete in the
# first chunk (OpenAI spec). Some providers
@@ -3605,9 +3609,10 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
# produce "read_fileread_file". Assignment
# (matching the OpenAI Node SDK / LiteLLM /
# Vercel AI patterns) is immune to this.
- entry["function"]["name"] = tc_delta.function.name
- if tc_delta.function.arguments:
- entry["function"]["arguments"] += tc_delta.function.arguments
+ entry["function"]["name"] = function_name
+ function_arguments = getattr(tc_function, "arguments", None)
+ if function_arguments:
+ entry["function"]["arguments"] += function_arguments
extra = getattr(tc_delta, "extra_content", None)
if extra is None and hasattr(tc_delta, "model_extra"):
extra = (tc_delta.model_extra if isinstance(tc_delta.model_extra, dict) else {}).get("extra_content")
@@ -3633,8 +3638,9 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta=
# discarding the attempted action.
result["partial_tool_names"].append(name)
- if chunk.choices[0].finish_reason:
- finish_reason = chunk.choices[0].finish_reason
+ chunk_finish_reason = getattr(chunk.choices[0], "finish_reason", None)
+ if chunk_finish_reason:
+ finish_reason = chunk_finish_reason
# Usage in the final chunk
if hasattr(chunk, "usage") and chunk.usage:
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index 40698dd6091..c62bcdf607e 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -835,7 +835,7 @@ class ChatCompletionsTransport(ProviderTransport):
# Promote it to content + a ``content_filter`` finish reason so the
# loop's refusal handler surfaces it clearly and stops. ``refusal`` is
# ``None`` for normal responses, so this is a no-op in the common case.
- content = msg.content
+ content = getattr(msg, "content", None)
refusal = getattr(msg, "refusal", None)
if refusal is None and hasattr(msg, "model_extra"):
_msg_extra = getattr(msg, "model_extra", None) or {}
diff --git a/tests/agent/transports/test_chat_completions.py b/tests/agent/transports/test_chat_completions.py
index d87aca32763..d8b9dcce5d6 100644
--- a/tests/agent/transports/test_chat_completions.py
+++ b/tests/agent/transports/test_chat_completions.py
@@ -18,13 +18,11 @@ def transport():
class TestChatCompletionsBasic:
-
-
- def test_normalize_response_allows_missing_optional_tool_calls(self, transport):
+ def test_normalize_response_allows_missing_optional_message_fields(self, transport):
response = SimpleNamespace(
choices=[
SimpleNamespace(
- message=SimpleNamespace(content="done"),
+ message=SimpleNamespace(),
finish_reason="stop",
)
],
@@ -33,11 +31,9 @@ class TestChatCompletionsBasic:
normalized = transport.normalize_response(response)
- assert normalized.content == "done"
+ assert normalized.content is None
assert normalized.tool_calls is None
-
-
@pytest.mark.parametrize("provider", ["nous", "openrouter"])
def test_gpt56_ultra_uses_max_wire_effort(self, transport, provider):
from providers import get_provider_profile
diff --git a/tests/run_agent/test_streaming.py b/tests/run_agent/test_streaming.py
index bc36450d4cf..b971f9ec82a 100644
--- a/tests/run_agent/test_streaming.py
+++ b/tests/run_agent/test_streaming.py
@@ -138,6 +138,52 @@ class TestStreamingAccumulator:
assert response.choices[0].message.content == "done"
assert response.choices[0].message.tool_calls is None
+ @patch("run_agent.AIAgent._create_request_openai_client")
+ @patch("run_agent.AIAgent._close_request_openai_client")
+ def test_sparse_tool_delta_allows_missing_nested_fields(
+ self, mock_close, mock_create
+ ):
+ """A partial tool delta may contain arguments before its other fields."""
+ from run_agent import AIAgent
+
+ sparse_tool_delta = SimpleNamespace(
+ index=0,
+ function=SimpleNamespace(arguments='{"city":"Paris"}'),
+ )
+ chunks = [
+ SimpleNamespace(
+ choices=[
+ SimpleNamespace(
+ index=0,
+ delta=SimpleNamespace(tool_calls=[sparse_tool_delta]),
+ )
+ ],
+ model="test-model",
+ usage=None,
+ ),
+ _make_stream_chunk(finish_reason="tool_calls", model="test-model"),
+ ]
+ mock_client = MagicMock()
+ mock_client.chat.completions.create.return_value = iter(chunks)
+ mock_create.return_value = mock_client
+ agent = AIAgent(
+ api_key="test-key",
+ base_url="https://openrouter.ai/api/v1",
+ model="test/model",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ agent.api_mode = "chat_completions"
+ agent._interrupt_requested = False
+
+ response = agent._interruptible_streaming_api_call({})
+
+ tool_call = response.choices[0].message.tool_calls[0]
+ assert tool_call.function.name == ""
+ assert tool_call.function.arguments == '{"city":"Paris"}'
+ assert response.choices[0].finish_reason == "tool_calls"
+
@patch("run_agent.AIAgent._create_request_openai_client")
@patch("run_agent.AIAgent._close_request_openai_client")
def test_chat_stream_closes_original_provider_resource(