|
| 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