Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: harden Responses stream parsing (#825)

Bingxi Zhao (Frank)c96440d6aca6
diff --git a/deeptutor/services/llm/provider_core/openai_responses/parsing.py b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
index ecd2bcc81..35b8cfeba 100644
--- a/deeptutor/services/llm/provider_core/openai_responses/parsing.py
+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
import json
from typing import Any, AsyncGenerator
@@ -24,6 +25,101 @@ def map_finish_reason(status: str | None) -> str:
return FINISH_REASON_MAP.get(status or "completed", "stop")
+@dataclass(slots=True)
+class _ToolCallBuffer:
+ """Arguments accumulated for one streamed Responses API function call."""
+
+ call_id: str
+ item_id: str
+ name: str
+ arguments: str
+
+
+class _ToolCallBuffers:
+ """Resolve stream events by either call ID or output-item ID.
+
+ OpenAI-compatible providers are not consistent about which identity they
+ put on argument delta events. Keeping the aliases here lets both the raw
+ SSE and SDK consumers share the same correlation rules.
+ """
+
+ def __init__(self) -> None:
+ self._by_identity: dict[str, _ToolCallBuffer] = {}
+
+ def add(
+ self,
+ *,
+ call_id: str,
+ item_id: str,
+ name: str,
+ arguments: str,
+ ) -> None:
+ buffer = _ToolCallBuffer(call_id, item_id, name, arguments)
+ self._by_identity[call_id] = buffer
+ self._by_identity[item_id] = buffer
+
+ def get(
+ self,
+ *,
+ call_id: str | None = None,
+ item_id: str | None = None,
+ ) -> _ToolCallBuffer | None:
+ for identity in (call_id, item_id):
+ if identity and identity in self._by_identity:
+ return self._by_identity[identity]
+ return None
+
+ def append(
+ self,
+ value: str,
+ *,
+ call_id: str | None = None,
+ item_id: str | None = None,
+ ) -> None:
+ if buffer := self.get(call_id=call_id, item_id=item_id):
+ buffer.arguments += value
+
+ def replace(
+ self,
+ value: str,
+ *,
+ call_id: str | None = None,
+ item_id: str | None = None,
+ ) -> None:
+ if buffer := self.get(call_id=call_id, item_id=item_id):
+ buffer.arguments = value
+
+
+def _parse_tool_arguments(arguments: Any, tool_name: str) -> dict[str, Any]:
+ """Parse function arguments consistently across all response modes."""
+ try:
+ parsed = json.loads(arguments) if isinstance(arguments, str) else arguments
+ except Exception:
+ logger.warning(
+ "Failed to parse tool call arguments for '{}': {}",
+ tool_name,
+ str(arguments)[:200],
+ )
+ parsed = json_repair.loads(arguments) if isinstance(arguments, str) else arguments
+ if not isinstance(parsed, dict):
+ return {"raw": arguments}
+ return parsed if isinstance(parsed, dict) else {}
+
+
+def _build_tool_call(
+ *,
+ call_id: str,
+ item_id: str,
+ name: str,
+ arguments: Any,
+) -> ToolCallRequest:
+ return ToolCallRequest(
+ id=f"{call_id}|{item_id}",
+ name=name,
+ arguments=_parse_tool_arguments(arguments, name),
+ )
+
+
async def iter_sse(response: httpx.Response) -> AsyncGenerator[dict[str, Any], None]:
"""Yield parsed JSON events from a Responses API SSE stream."""
buffer: list[str] = []
@@ -64,7 +160,7 @@ async def consume_sse(
"""Consume a Responses API SSE stream."""
content = ""
tool_calls: list[ToolCallRequest] = []
- tool_call_buffers: dict[str, dict[str, Any]] = {}
+ tool_call_buffers = _ToolCallBuffers()
finish_reason = "stop"
async for event in iter_sse(response):
@@ -75,48 +171,43 @@ async def consume_sse(
call_id = item.get("call_id")
if not call_id:
continue
- tool_call_buffers[call_id] = {
- "id": item.get("id") or "fc_0",
- "name": item.get("name"),
- "arguments": item.get("arguments") or "",
- }
+ tool_call_buffers.add(
+ call_id=call_id,
+ item_id=item.get("id") or "fc_0",
+ name=item.get("name") or "",
+ arguments=item.get("arguments") or "",
+ )
elif event_type == "response.output_text.delta":
delta_text = event.get("delta") or ""
content += delta_text
if on_content_delta and delta_text:
await on_content_delta(delta_text)
elif event_type == "response.function_call_arguments.delta":
- call_id = event.get("call_id")
- if call_id and call_id in tool_call_buffers:
- tool_call_buffers[call_id]["arguments"] += event.get("delta") or ""
+ tool_call_buffers.append(
+ event.get("delta") or "",
+ call_id=event.get("call_id"),
+ item_id=event.get("item_id"),
+ )
elif event_type == "response.function_call_arguments.done":
- call_id = event.get("call_id")
- if call_id and call_id in tool_call_buffers:
- tool_call_buffers[call_id]["arguments"] = event.get("arguments") or ""
+ tool_call_buffers.replace(
+ event.get("arguments") or "",
+ call_id=event.get("call_id"),
+ item_id=event.get("item_id"),
+ )
elif event_type == "response.output_item.done":
item = event.get("item") or {}
if item.get("type") == "function_call":
call_id = item.get("call_id")
if not call_id:
continue
- buf = tool_call_buffers.get(call_id) or {}
- args_raw = buf.get("arguments") or item.get("arguments") or "{}"
- try:
- args = json.loads(args_raw)
- except Exception:
- logger.warning(
- "Failed to parse tool call arguments for '{}': {}",
- buf.get("name") or item.get("name"),
- args_raw[:200],
- )
- args = json_repair.loads(args_raw)
- if not isinstance(args, dict):
- args = {"raw": args_raw}
+ item_id = item.get("id") or "fc_0"
+ buf = tool_call_buffers.get(call_id=call_id, item_id=item_id)
tool_calls.append(
- ToolCallRequest(
- id=f"{call_id}|{buf.get('id') or item.get('id') or 'fc_0'}",
- name=buf.get("name") or item.get("name") or "",
- arguments=args if isinstance(args, dict) else {},
+ _build_tool_call(
+ call_id=call_id,
+ item_id=buf.item_id if buf else item_id,
+ name=(buf.name if buf else "") or item.get("name") or "",
+ arguments=(buf.arguments if buf else "") or item.get("arguments") or "{}",
)
)
elif event_type == "response.completed":
@@ -164,22 +255,12 @@ def parse_response_output(response: Any) -> LLMResponse:
call_id = item.get("call_id") or ""
item_id = item.get("id") or "fc_0"
args_raw = item.get("arguments") or "{}"
- try:
- args = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
- except Exception:
- logger.warning(
- "Failed to parse tool call arguments for '{}': {}",
- item.get("name"),
- str(args_raw)[:200],
- )
- args = json_repair.loads(args_raw) if isinstance(args_raw, str) else args_raw
- if not isinstance(args, dict):
- args = {"raw": args_raw}
tool_calls.append(
- ToolCallRequest(
- id=f"{call_id}|{item_id}",
+ _build_tool_call(
+ call_id=call_id,
+ item_id=item_id,
name=item.get("name") or "",
- arguments=args if isinstance(args, dict) else {},
+ arguments=args_raw,
)
)
@@ -213,7 +294,7 @@ async def consume_sdk_stream(
"""Consume an SDK async stream from client.responses.create(stream=True)."""
content = ""
tool_calls: list[ToolCallRequest] = []
- tool_call_buffers: dict[str, dict[str, Any]] = {}
+ tool_call_buffers = _ToolCallBuffers()
finish_reason = "stop"
usage: dict[str, int] = {}
reasoning_content: str | None = None
@@ -226,43 +307,45 @@ async def consume_sdk_stream(
call_id = getattr(item, "call_id", None)
if not call_id:
continue
- tool_call_buffers[call_id] = {
- "id": getattr(item, "id", None) or "fc_0",
- "name": getattr(item, "name", None),
- "arguments": getattr(item, "arguments", None) or "",
- }
+ tool_call_buffers.add(
+ call_id=call_id,
+ item_id=getattr(item, "id", None) or "fc_0",
+ name=getattr(item, "name", None) or "",
+ arguments=getattr(item, "arguments", None) or "",
+ )
elif event_type == "response.output_text.delta":
delta_text = getattr(event, "delta", "") or ""
content += delta_text
if on_content_delta and delta_text:
await on_content_delta(delta_text)
elif event_type == "response.function_call_arguments.delta":
- call_id = getattr(event, "call_id", None)
- if call_id and call_id in tool_call_buffers:
- tool_call_buffers[call_id]["arguments"] += getattr(event, "delta", "") or ""
+ tool_call_buffers.append(
+ getattr(event, "delta", "") or "",
+ call_id=getattr(event, "call_id", None),
+ item_id=getattr(event, "item_id", None),
+ )
elif event_type == "response.function_call_arguments.done":
- call_id = getattr(event, "call_id", None)
- if call_id and call_id in tool_call_buffers:
- tool_call_buffers[call_id]["arguments"] = getattr(event, "arguments", "") or ""
+ tool_call_buffers.replace(
+ getattr(event, "arguments", "") or "",
+ call_id=getattr(event, "call_id", None),
+ item_id=getattr(event, "item_id", None),
+ )
elif event_type == "response.output_item.done":
item = getattr(event, "item", None)
if item and getattr(item, "type", None) == "function_call":
call_id = getattr(item, "call_id", None)
if not call_id:
continue
- buf = tool_call_buffers.get(call_id) or {}
- args_raw = buf.get("arguments") or getattr(item, "arguments", None) or "{}"
- try:
- args = json.loads(args_raw) if isinstance(args_raw, str) else args_raw
- except Exception:
- args = json_repair.loads(args_raw) if isinstance(args_raw, str) else args_raw
- if not isinstance(args, dict):
- args = {"raw": args_raw}
+ item_id = getattr(item, "id", None) or "fc_0"
+ buf = tool_call_buffers.get(call_id=call_id, item_id=item_id)
tool_calls.append(
- ToolCallRequest(
- id=f"{call_id}|{buf.get('id') or getattr(item, 'id', None) or 'fc_0'}",
- name=buf.get("name") or getattr(item, "name", None) or "",
- arguments=args if isinstance(args, dict) else {},
+ _build_tool_call(
+ call_id=call_id,
+ item_id=buf.item_id if buf else item_id,
+ name=(buf.name if buf else "") or getattr(item, "name", None) or "",
+ arguments=(buf.arguments if buf else "")
+ or getattr(item, "arguments", None)
+ or "{}",
)
)
elif event_type == "response.reasoning_summary_text.delta":
diff --git a/deeptutor/utils/json_parser.py b/deeptutor/utils/json_parser.py
index 60459585f..06f43a183 100644
--- a/deeptutor/utils/json_parser.py
+++ b/deeptutor/utils/json_parser.py
@@ -71,10 +71,8 @@ def parse_json_response(
"""
Safely parse JSON from LLM responses with automatic repair.
- Implements a three-tier parsing strategy:
- 1. Extract JSON from markdown code blocks if present
- 2. Direct JSON parsing
- 3. Automated repair using json-repair library with fallback
+ Implements a parsing strategy that preserves valid JSON first, then tries
+ markdown extraction, embedded values, and automated repair.
Args:
response: Raw string response from LLM
@@ -102,7 +100,14 @@ def parse_json_response(
log.warning("LLM returned empty response")
return fallback
- # Extract from markdown code blocks if present
+ # Parse the complete response before looking for markdown fences. A valid
+ # JSON string value can itself contain fenced source code (#825).
+ try:
+ return json.loads(response)
+ except (json.JSONDecodeError, TypeError) as parse_error:
+ log.debug(f"Complete response JSON parse failed: {parse_error}")
+
+ # Extract from markdown code blocks if present.
extracted_response = response
if "```" in response:
json_match = re.search(r"```(?:json)?\s*\n?(.*?)```", response, re.DOTALL)
@@ -110,9 +115,7 @@ def parse_json_response(
extracted_response = json_match.group(1).strip()
log.debug("Extracted JSON from markdown code block")
- # Strategy 1: Direct parsing. Done before any <think> stripping so a valid
- # JSON payload whose string values legitimately contain "<think>" is
- # preserved exactly.
+ # Parse an extracted fence before any <think> stripping.
try:
return json.loads(extracted_response)
except (json.JSONDecodeError, TypeError) as parse_error:
diff --git a/tests/services/llm/test_openai_responses_parsing.py b/tests/services/llm/test_openai_responses_parsing.py
new file mode 100644
index 000000000..44bb1fcba
--- /dev/null
+++ b/tests/services/llm/test_openai_responses_parsing.py
@@ -0,0 +1,101 @@
+"""Regression tests for OpenAI Responses API stream parsing."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from deeptutor.services.llm.provider_core.openai_responses.parsing import (
+ consume_sdk_stream,
+ consume_sse,
+)
+
+
+class _SSEFixture:
+ def __init__(self, events: list[dict]) -> None:
+ self._events = events
+
+ async def aiter_lines(self):
+ for event in self._events:
+ yield f"data: {json.dumps(event)}"
+ yield ""
+
+
+async def _sdk_events(events):
+ for event in events:
+ yield event
+
+
+async def test_sse_arguments_can_be_correlated_by_item_id() -> None:
+ response = _SSEFixture(
+ [
+ {
+ "type": "response.output_item.added",
+ "item": {
+ "type": "function_call",
+ "id": "fc_1",
+ "call_id": "call_1",
+ "name": "lookup",
+ },
+ },
+ {
+ "type": "response.function_call_arguments.delta",
+ "item_id": "fc_1",
+ "delta": '{"topic":',
+ },
+ {
+ "type": "response.function_call_arguments.done",
+ "item_id": "fc_1",
+ "arguments": '{"topic":"algebra"}',
+ },
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "function_call",
+ "id": "fc_1",
+ "call_id": "call_1",
+ "name": "lookup",
+ },
+ },
+ ]
+ )
+
+ _, tool_calls, _ = await consume_sse(response) # type: ignore[arg-type]
+
+ assert len(tool_calls) == 1
+ assert tool_calls[0].id == "call_1|fc_1"
+ assert tool_calls[0].arguments == {"topic": "algebra"}
+
+
+async def test_sdk_arguments_can_be_correlated_by_item_id() -> None:
+ function_call = SimpleNamespace(
+ type="function_call",
+ id="fc_1",
+ call_id="call_1",
+ name="lookup",
+ arguments="",
+ )
+ events = [
+ SimpleNamespace(type="response.output_item.added", item=function_call),
+ SimpleNamespace(
+ type="response.function_call_arguments.delta",
+ item_id="fc_1",
+ delta='{"topic":',
+ ),
+ SimpleNamespace(
+ type="response.function_call_arguments.done",
+ item_id="fc_1",
+ arguments='{"topic":"geometry"}',
+ ),
+ SimpleNamespace(type="response.output_item.done", item=function_call),
+ ]
+
+ _, tool_calls, _, _, _ = await consume_sdk_stream(_sdk_events(events))
+
+ assert len(tool_calls) == 1
+ assert tool_calls[0].id == "call_1|fc_1"
+ assert tool_calls[0].arguments == {"topic": "geometry"}
diff --git a/tests/utils/test_json_parser.py b/tests/utils/test_json_parser.py
index 9de2c745a..392a81add 100644
--- a/tests/utils/test_json_parser.py
+++ b/tests/utils/test_json_parser.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import json
import logging
from unittest.mock import patch
@@ -63,6 +64,14 @@ class TestParseJsonResponseMarkdown:
result = parse_json_response(response)
assert result == {"a": 1}
+ def test_fenced_code_inside_json_string_is_not_extracted(self) -> None:
+ payload = {
+ "content": "Use this example:\n```python\nprint('hello')\n```",
+ "language": "en",
+ }
+
+ assert parse_json_response(json.dumps(payload)) == payload
+
# ---------------------------------------------------------------------------
# parse_json_response — json-repair