Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions src/openrouter_agent/model_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@
)
from .next_turn_params import apply_next_turn_params_to_request, execute_next_turn_params_functions
from .stop_conditions import is_stop_condition_met
from .stream_transformers import extract_text_from_response, extract_tool_calls_from_response
from .stream_transformers import (
assert_streamed_tool_calls_match_response,
extract_text_from_response,
extract_tool_calls_from_response,
)
from .tool_context import ToolContextStore, resolve_context
from .tool_executor import apply_on_response_received_hooks, execute_tool
from .tool_types import (
Expand Down Expand Up @@ -171,15 +175,18 @@ async def _coerce_response(self, value: Any) -> Any:
raise getattr(value, "error", RuntimeError("Responses API request failed"))
if is_async_iterable(value):
completed = None
received: List[Any] = []
async for event in value:
await self._append_event(event)
received.append(event)
typ = get_field(event, "type")
if typ in {"response.completed", "response.incomplete"}:
completed = get_field(event, "response")
if typ == "response.failed":
raise RuntimeError(str(get_field(event, "message", "Response failed")))
if completed is None:
raise RuntimeError("Stream ended without response.completed")
assert_streamed_tool_calls_match_response(received, completed)
return completed
for attr in ("value", "response", "result"):
if hasattr(value, attr):
Expand All @@ -195,6 +202,8 @@ async def _coerce_response(self, value: Any) -> Any:
await self._append_event(event)
if event.get("type") in {"response.completed", "response.incomplete"}:
completed = event.get("response")
if completed is not None:
assert_streamed_tool_calls_match_response(value, completed)
return completed or {"id": "response_from_events", "output": []}
return value

Expand Down Expand Up @@ -1215,7 +1224,7 @@ async def get_tool_calls_stream(self) -> AsyncIterator[ParsedToolCall]:
if get_field(item, "type") == "function_call":
item_id = str(get_field(item, "id", get_field(item, "callId", "")))
names[item_id] = str(get_field(item, "name", ""))
call_ids[item_id] = str(get_field(item, "callId", item_id))
call_ids[item_id] = str(get_field(item, "callId", get_field(item, "call_id", item_id)))
buffers.setdefault(item_id, [])
elif typ == "response.function_call_arguments.delta":
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
Expand Down
48 changes: 46 additions & 2 deletions src/openrouter_agent/stream_transformers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import json
from typing import Any, AsyncIterable, AsyncIterator, Dict, List, Mapping, Optional
from typing import Any, AsyncIterable, AsyncIterator, Dict, List, Mapping, Optional, Tuple

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


def assert_streamed_tool_calls_match_response(events: List[Any], response: Any) -> None:
"""Raise if a function call finalized in the stream differs from the completed response.

`get_tool_calls_stream()` shows calls built from stream events, while pending state and
execution use the completed response. Both views must describe the same call.
"""
names: Dict[str, str] = {}
call_ids: Dict[str, str] = {}
buffers: Dict[str, List[str]] = {}
streamed: List[Tuple[str, str, str, Any]] = []
for event in events:
typ = get_field(event, "type")
if typ == "response.output_item.added":
item = get_field(event, "item", {})
if get_field(item, "type") == "function_call":
item_id = str(get_field(item, "id", get_field(item, "callId", "")))
names[item_id] = str(get_field(item, "name", ""))
call_ids[item_id] = str(get_field(item, "callId", get_field(item, "call_id", item_id)))
buffers.setdefault(item_id, [])
elif typ == "response.function_call_arguments.delta":
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
buffers.setdefault(item_id, []).append(str(get_field(event, "delta", "")))
elif typ == "response.function_call_arguments.done":
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
raw = get_field(event, "arguments", "".join(buffers.get(item_id, [])))
name = names.get(item_id, str(get_field(event, "name", "")))
streamed.append((item_id, call_ids.get(item_id, item_id), name, json_loads_maybe(raw)))
if not streamed:
return

terminal = [item for item in _output_items(response) if get_field(item, "type") == "function_call"]
for item_id, call_id, name, args in streamed:
for item in terminal:
terminal_call_id = str(get_field(item, "callId", get_field(item, "call_id", get_field(item, "id", ""))))
if terminal_call_id != call_id and str(get_field(item, "id", "")) != item_id:
continue
terminal_args = json_loads_maybe(get_field(item, "arguments", {}))
if str(get_field(item, "name", "")) != name or terminal_args != args:
raise ValueError(
f'Streamed function_call "{call_id}" does not match the function_call in the completed '
"response; refusing to save or run tool calls from this response"
)


async def consume_stream_for_completion(stream: AsyncIterable[Any]) -> Any:
completed: Optional[Any] = None
async for event in stream:
Expand Down Expand Up @@ -97,7 +141,7 @@ async def build_tool_call_stream(events: AsyncIterable[Any]) -> AsyncIterator[Pa
if get_field(item, "type") == "function_call":
item_id = str(get_field(item, "id", get_field(item, "callId", "")))
names[item_id] = str(get_field(item, "name", ""))
call_ids[item_id] = str(get_field(item, "callId", item_id))
call_ids[item_id] = str(get_field(item, "callId", get_field(item, "call_id", item_id)))
buffers.setdefault(item_id, [])
elif typ == "response.function_call_arguments.delta":
item_id = str(get_field(event, "itemId", get_field(event, "item_id", get_field(event, "callId", ""))))
Expand Down
144 changes: 144 additions & 0 deletions tests/unit/test_streamed_tool_call_binding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
"""The tool call shown by get_tool_calls_stream() must be the one that is saved and run."""

from __future__ import annotations

import json
from typing import Any, AsyncIterator, Dict, List, Optional

import pytest
from pydantic import BaseModel

from openrouter_agent import call_model, tool
from tests._fixtures import MemoryStateAccessor, QueuedClient, function_call_item, make_response, text_response


class Amount(BaseModel):
amount: int


def _stream(events: List[Dict[str, Any]]) -> Any:
async def gen() -> AsyncIterator[Dict[str, Any]]:
for event in events:
yield event

return gen()


def _tool_call_events(
streamed_amount: int,
terminal_amount: int,
*,
item_id: str = "fc_1",
terminal_name: str = "pay",
call_id_key: str = "callId",
) -> List[Dict[str, Any]]:
terminal_item = function_call_item("call_1", terminal_name, json.dumps({"amount": terminal_amount}))
return [
{
"type": "response.output_item.added",
"item": {"type": "function_call", "id": item_id, call_id_key: "call_1", "name": "pay", "arguments": ""},
},
{"type": "response.function_call_arguments.delta", "itemId": item_id, "delta": '{"amount":'},
{"type": "response.function_call_arguments.delta", "itemId": item_id, "delta": f"{streamed_amount}}}"},
{"type": "response.function_call_arguments.done", "itemId": item_id},
{"type": "response.completed", "response": make_response("r1", [terminal_item])},
]


def _pay_tool(executed: List[int]) -> Any:
def execute(params: Amount, _context: Any) -> Dict[str, bool]:
executed.append(params.amount)
return {"ok": True}

return tool(name="pay", input_schema=Amount, output_schema=dict, execute=execute, require_approval=True)


async def _run(events: List[Dict[str, Any]]) -> Dict[str, Any]:
state = MemoryStateAccessor()
executed: List[int] = []
pay = _pay_tool(executed)
client = QueuedClient(
[_stream(events), _stream([{"type": "response.completed", "response": text_response("r2", "done")}])]
)
shown: List[Any] = []
error: Optional[BaseException] = None
try:
result = call_model(client, {"model": "m", "input": "pay", "tools": [pay], "state": state})
async for call in result.get_tool_calls_stream():
shown.append((call.id, call.name, call.arguments))
except ValueError as exc:
error = exc
pending = [(c.id, c.arguments) for c in (state.stored.pending_tool_calls or [])] if state.stored else []
if error is None:
await call_model(
client, {"model": "m", "input": "go", "tools": [pay], "state": state, "approve_tool_calls": ["call_1"]}
).get_response()
return {"shown": shown, "pending": pending, "executed": executed, "error": error, "requests": len(client.requests)}


async def test_matching_stream_and_terminal_call_runs_after_approval() -> None:
out = await _run(_tool_call_events(1, 1))

assert out["error"] is None
assert out["shown"] == [("call_1", "pay", {"amount": 1})]
assert out["pending"] == [("call_1", {"amount": 1})]
assert out["executed"] == [1]


async def test_terminal_arguments_that_differ_from_the_stream_are_refused() -> None:
out = await _run(_tool_call_events(1, 1000))

assert isinstance(out["error"], ValueError)
assert "call_1" in str(out["error"])
assert out["pending"] == []
assert out["executed"] == []
assert out["requests"] == 1


async def test_terminal_name_that_differs_from_the_stream_is_refused() -> None:
out = await _run(_tool_call_events(1, 1, terminal_name="refund"))

assert isinstance(out["error"], ValueError)
assert out["pending"] == []
assert out["executed"] == []


async def test_mismatch_is_refused_when_stream_and_terminal_item_ids_differ() -> None:
out = await _run(_tool_call_events(1, 1000, item_id="stream_item", call_id_key="call_id"))

assert isinstance(out["error"], ValueError)
assert out["pending"] == []
assert out["executed"] == []


async def test_stream_reports_snake_case_call_id_instead_of_item_id() -> None:
out = await _run(_tool_call_events(1, 1, call_id_key="call_id"))

assert out["error"] is None
assert out["shown"] == [("call_1", "pay", {"amount": 1})]
assert out["executed"] == [1]


@pytest.mark.parametrize("terminal_amount", [1, 1000])
async def test_resume_after_refused_response_runs_nothing(terminal_amount: int) -> None:
state = MemoryStateAccessor()
executed: List[int] = []
pay = _pay_tool(executed)
client = QueuedClient(
[
_stream(_tool_call_events(1, terminal_amount)),
_stream([{"type": "response.completed", "response": text_response("r2", "done")}]),
]
)
try:
await call_model(client, {"model": "m", "input": "pay", "tools": [pay], "state": state}).get_response()
except ValueError:
pass
try:
await call_model(
client, {"model": "m", "input": "go", "tools": [pay], "state": state, "approve_tool_calls": ["call_1"]}
).get_response()
except Exception:
pass

assert executed == ([1] if terminal_amount == 1 else [])
Loading