Skip to content

Commit 5933bae

Browse files
Merge pull request #39 from OpenRouterTeam/devin/1795351812-bind-streamed-tool-calls
fix(agent): refuse responses whose streamed tool call differs from the completed one
2 parents ed7a13d + f60b8e1 commit 5933bae

3 files changed

Lines changed: 201 additions & 4 deletions

File tree

‎src/openrouter_agent/model_result.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,11 @@
2121
)
2222
from .next_turn_params import apply_next_turn_params_to_request, execute_next_turn_params_functions
2323
from .stop_conditions import is_stop_condition_met
24-
from .stream_transformers import extract_text_from_response, extract_tool_calls_from_response
24+
from .stream_transformers import (
25+
assert_streamed_tool_calls_match_response,
26+
extract_text_from_response,
27+
extract_tool_calls_from_response,
28+
)
2529
from .tool_context import ToolContextStore, resolve_context
2630
from .tool_executor import apply_on_response_received_hooks, execute_tool
2731
from .tool_types import (
@@ -171,15 +175,18 @@ async def _coerce_response(self, value: Any) -> Any:
171175
raise getattr(value, "error", RuntimeError("Responses API request failed"))
172176
if is_async_iterable(value):
173177
completed = None
178+
received: List[Any] = []
174179
async for event in value:
175180
await self._append_event(event)
181+
received.append(event)
176182
typ = get_field(event, "type")
177183
if typ in {"response.completed", "response.incomplete"}:
178184
completed = get_field(event, "response")
179185
if typ == "response.failed":
180186
raise RuntimeError(str(get_field(event, "message", "Response failed")))
181187
if completed is None:
182188
raise RuntimeError("Stream ended without response.completed")
189+
assert_streamed_tool_calls_match_response(received, completed)
183190
return completed
184191
for attr in ("value", "response", "result"):
185192
if hasattr(value, attr):
@@ -195,6 +202,8 @@ async def _coerce_response(self, value: Any) -> Any:
195202
await self._append_event(event)
196203
if event.get("type") in {"response.completed", "response.incomplete"}:
197204
completed = event.get("response")
205+
if completed is not None:
206+
assert_streamed_tool_calls_match_response(value, completed)
198207
return completed or {"id": "response_from_events", "output": []}
199208
return value
200209

@@ -1215,7 +1224,7 @@ async def get_tool_calls_stream(self) -> AsyncIterator[ParsedToolCall]:
12151224
if get_field(item, "type") == "function_call":
12161225
item_id = str(get_field(item, "id", get_field(item, "callId", "")))
12171226
names[item_id] = str(get_field(item, "name", ""))
1218-
call_ids[item_id] = str(get_field(item, "callId", item_id))
1227+
call_ids[item_id] = str(get_field(item, "callId", get_field(item, "call_id", item_id)))
12191228
buffers.setdefault(item_id, [])
12201229
elif typ == "response.function_call_arguments.delta":
12211230
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))

‎src/openrouter_agent/stream_transformers.py‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import json
4-
from typing import Any, AsyncIterable, AsyncIterator, Dict, List, Mapping, Optional
4+
from typing import Any, AsyncIterable, AsyncIterator, Dict, List, Mapping, Optional, Tuple
55

66
from ._utils import get_field, json_loads_maybe
77
from .tool_types import ParsedToolCall
@@ -55,6 +55,50 @@ def extract_tool_calls_from_response(response: Any) -> List[ParsedToolCall]:
5555
return calls
5656

5757

58+
def assert_streamed_tool_calls_match_response(events: List[Any], response: Any) -> None:
59+
"""Raise if a function call finalized in the stream differs from the completed response.
60+
61+
`get_tool_calls_stream()` shows calls built from stream events, while pending state and
62+
execution use the completed response. Both views must describe the same call.
63+
"""
64+
names: Dict[str, str] = {}
65+
call_ids: Dict[str, str] = {}
66+
buffers: Dict[str, List[str]] = {}
67+
streamed: List[Tuple[str, str, str, Any]] = []
68+
for event in events:
69+
typ = get_field(event, "type")
70+
if typ == "response.output_item.added":
71+
item = get_field(event, "item", {})
72+
if get_field(item, "type") == "function_call":
73+
item_id = str(get_field(item, "id", get_field(item, "callId", "")))
74+
names[item_id] = str(get_field(item, "name", ""))
75+
call_ids[item_id] = str(get_field(item, "callId", get_field(item, "call_id", item_id)))
76+
buffers.setdefault(item_id, [])
77+
elif typ == "response.function_call_arguments.delta":
78+
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
79+
buffers.setdefault(item_id, []).append(str(get_field(event, "delta", "")))
80+
elif typ == "response.function_call_arguments.done":
81+
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
82+
raw = get_field(event, "arguments", "".join(buffers.get(item_id, [])))
83+
name = names.get(item_id, str(get_field(event, "name", "")))
84+
streamed.append((item_id, call_ids.get(item_id, item_id), name, json_loads_maybe(raw)))
85+
if not streamed:
86+
return
87+
88+
terminal = [item for item in _output_items(response) if get_field(item, "type") == "function_call"]
89+
for item_id, call_id, name, args in streamed:
90+
for item in terminal:
91+
terminal_call_id = str(get_field(item, "callId", get_field(item, "call_id", get_field(item, "id", ""))))
92+
if terminal_call_id != call_id and str(get_field(item, "id", "")) != item_id:
93+
continue
94+
terminal_args = json_loads_maybe(get_field(item, "arguments", {}))
95+
if str(get_field(item, "name", "")) != name or terminal_args != args:
96+
raise ValueError(
97+
f'Streamed function_call "{call_id}" does not match the function_call in the completed '
98+
"response; refusing to save or run tool calls from this response"
99+
)
100+
101+
58102
async def consume_stream_for_completion(stream: AsyncIterable[Any]) -> Any:
59103
completed: Optional[Any] = None
60104
async for event in stream:
@@ -97,7 +141,7 @@ async def build_tool_call_stream(events: AsyncIterable[Any]) -> AsyncIterator[Pa
97141
if get_field(item, "type") == "function_call":
98142
item_id = str(get_field(item, "id", get_field(item, "callId", "")))
99143
names[item_id] = str(get_field(item, "name", ""))
100-
call_ids[item_id] = str(get_field(item, "callId", item_id))
144+
call_ids[item_id] = str(get_field(item, "callId", get_field(item, "call_id", item_id)))
101145
buffers.setdefault(item_id, [])
102146
elif typ == "response.function_call_arguments.delta":
103147
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
"""The tool call shown by get_tool_calls_stream() must be the one that is saved and run."""
2+
3+
from __future__ import annotations
4+
5+
import json
6+
from typing import Any, AsyncIterator, Dict, List, Optional
7+
8+
import pytest
9+
from pydantic import BaseModel
10+
11+
from openrouter_agent import call_model, tool
12+
from tests._fixtures import MemoryStateAccessor, QueuedClient, function_call_item, make_response, text_response
13+
14+
15+
class Amount(BaseModel):
16+
amount: int
17+
18+
19+
def _stream(events: List[Dict[str, Any]]) -> Any:
20+
async def gen() -> AsyncIterator[Dict[str, Any]]:
21+
for event in events:
22+
yield event
23+
24+
return gen()
25+
26+
27+
def _tool_call_events(
28+
streamed_amount: int,
29+
terminal_amount: int,
30+
*,
31+
item_id: str = "fc_1",
32+
terminal_name: str = "pay",
33+
call_id_key: str = "callId",
34+
) -> List[Dict[str, Any]]:
35+
terminal_item = function_call_item("call_1", terminal_name, json.dumps({"amount": terminal_amount}))
36+
return [
37+
{
38+
"type": "response.output_item.added",
39+
"item": {"type": "function_call", "id": item_id, call_id_key: "call_1", "name": "pay", "arguments": ""},
40+
},
41+
{"type": "response.function_call_arguments.delta", "itemId": item_id, "delta": '{"amount":'},
42+
{"type": "response.function_call_arguments.delta", "itemId": item_id, "delta": f"{streamed_amount}}}"},
43+
{"type": "response.function_call_arguments.done", "itemId": item_id},
44+
{"type": "response.completed", "response": make_response("r1", [terminal_item])},
45+
]
46+
47+
48+
def _pay_tool(executed: List[int]) -> Any:
49+
def execute(params: Amount, _context: Any) -> Dict[str, bool]:
50+
executed.append(params.amount)
51+
return {"ok": True}
52+
53+
return tool(name="pay", input_schema=Amount, output_schema=dict, execute=execute, require_approval=True)
54+
55+
56+
async def _run(events: List[Dict[str, Any]]) -> Dict[str, Any]:
57+
state = MemoryStateAccessor()
58+
executed: List[int] = []
59+
pay = _pay_tool(executed)
60+
client = QueuedClient(
61+
[_stream(events), _stream([{"type": "response.completed", "response": text_response("r2", "done")}])]
62+
)
63+
shown: List[Any] = []
64+
error: Optional[BaseException] = None
65+
try:
66+
result = call_model(client, {"model": "m", "input": "pay", "tools": [pay], "state": state})
67+
async for call in result.get_tool_calls_stream():
68+
shown.append((call.id, call.name, call.arguments))
69+
except ValueError as exc:
70+
error = exc
71+
pending = [(c.id, c.arguments) for c in (state.stored.pending_tool_calls or [])] if state.stored else []
72+
if error is None:
73+
await call_model(
74+
client, {"model": "m", "input": "go", "tools": [pay], "state": state, "approve_tool_calls": ["call_1"]}
75+
).get_response()
76+
return {"shown": shown, "pending": pending, "executed": executed, "error": error, "requests": len(client.requests)}
77+
78+
79+
async def test_matching_stream_and_terminal_call_runs_after_approval() -> None:
80+
out = await _run(_tool_call_events(1, 1))
81+
82+
assert out["error"] is None
83+
assert out["shown"] == [("call_1", "pay", {"amount": 1})]
84+
assert out["pending"] == [("call_1", {"amount": 1})]
85+
assert out["executed"] == [1]
86+
87+
88+
async def test_terminal_arguments_that_differ_from_the_stream_are_refused() -> None:
89+
out = await _run(_tool_call_events(1, 1000))
90+
91+
assert isinstance(out["error"], ValueError)
92+
assert "call_1" in str(out["error"])
93+
assert out["pending"] == []
94+
assert out["executed"] == []
95+
assert out["requests"] == 1
96+
97+
98+
async def test_terminal_name_that_differs_from_the_stream_is_refused() -> None:
99+
out = await _run(_tool_call_events(1, 1, terminal_name="refund"))
100+
101+
assert isinstance(out["error"], ValueError)
102+
assert out["pending"] == []
103+
assert out["executed"] == []
104+
105+
106+
async def test_mismatch_is_refused_when_stream_and_terminal_item_ids_differ() -> None:
107+
out = await _run(_tool_call_events(1, 1000, item_id="stream_item", call_id_key="call_id"))
108+
109+
assert isinstance(out["error"], ValueError)
110+
assert out["pending"] == []
111+
assert out["executed"] == []
112+
113+
114+
async def test_stream_reports_snake_case_call_id_instead_of_item_id() -> None:
115+
out = await _run(_tool_call_events(1, 1, call_id_key="call_id"))
116+
117+
assert out["error"] is None
118+
assert out["shown"] == [("call_1", "pay", {"amount": 1})]
119+
assert out["executed"] == [1]
120+
121+
122+
@pytest.mark.parametrize("terminal_amount", [1, 1000])
123+
async def test_resume_after_refused_response_runs_nothing(terminal_amount: int) -> None:
124+
state = MemoryStateAccessor()
125+
executed: List[int] = []
126+
pay = _pay_tool(executed)
127+
client = QueuedClient(
128+
[
129+
_stream(_tool_call_events(1, terminal_amount)),
130+
_stream([{"type": "response.completed", "response": text_response("r2", "done")}]),
131+
]
132+
)
133+
try:
134+
await call_model(client, {"model": "m", "input": "pay", "tools": [pay], "state": state}).get_response()
135+
except ValueError:
136+
pass
137+
try:
138+
await call_model(
139+
client, {"model": "m", "input": "go", "tools": [pay], "state": state, "approve_tool_calls": ["call_1"]}
140+
).get_response()
141+
except Exception:
142+
pass
143+
144+
assert executed == ([1] if terminal_amount == 1 else [])

0 commit comments

Comments
 (0)