Skip to content

Commit 0adbd7f

Browse files
Merge branch 'main' into devin/1796053817-to-model-output-parsed-input
2 parents 2521b94 + 5c1ea4f commit 0adbd7f

4 files changed

Lines changed: 245 additions & 9 deletions

File tree

‎src/openrouter_agent/model_result.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -937,6 +937,7 @@ async def _run(self) -> Any:
937937

938938
outputs: List[Any] = unsent_results_to_api_format(hook_resolved_unsent) if hook_resolved_unsent else []
939939
paused: List[ParsedToolCall] = []
940+
# Calls whose tool body ran without error; only these may drive next_turn_params.
940941
executed_calls: List[ParsedToolCall] = []
941942
for call in executable_calls:
942943
tool = self._find_tool(call.name, tools)
@@ -992,7 +993,8 @@ async def _run(self) -> Any:
992993
)
993994
output = await self._tool_result_to_output(effective_call, tool, result)
994995
outputs.append(output)
995-
executed_calls.append(effective_call)
996+
if result.get("error") is None:
997+
executed_calls.append(effective_call)
996998
self._tool_outputs.append(output)
997999
await self._append_event({"type": "tool.call_output", "output": output, "timestamp": _now_ms()})
9981000
step.tool_results.append(result)

‎src/openrouter_agent/tool_executor.py‎

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,15 @@
22

33
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence
44

5-
from ._utils import is_content_array, json_dumps, json_loads_maybe, maybe_await, schema_to_json_schema, validate_schema
5+
from ._utils import (
6+
dump,
7+
is_content_array,
8+
json_dumps,
9+
json_loads_maybe,
10+
maybe_await,
11+
schema_to_json_schema,
12+
validate_schema,
13+
)
614
from .tool_context import ToolContextStore, build_tool_execute_context
715
from .tool_types import (
816
ParsedToolCall,
@@ -203,15 +211,17 @@ async def apply_on_response_received_hooks(
203211
if not tools:
204212
return input_items
205213
items = input_items if isinstance(input_items, list) else [input_items]
214+
# Items echoed back from a live turn are SDK pydantic models, not dicts.
215+
as_mappings = [item if isinstance(item, Mapping) else dump(item) for item in items]
206216
call_names: Dict[str, str] = {}
207-
for item in items:
208-
if isinstance(item, Mapping) and item.get("type") == "function_call":
209-
call_names[str(item.get("callId") or item.get("call_id") or item.get("id"))] = str(item.get("name", ""))
217+
for entry in as_mappings:
218+
if isinstance(entry, Mapping) and entry.get("type") == "function_call":
219+
call_names[str(entry.get("callId") or entry.get("call_id") or entry.get("id"))] = str(entry.get("name", ""))
210220
rewritten: List[Any] = []
211221
changed = False
212-
for item in items:
222+
for original, item in zip(items, as_mappings, strict=True):
213223
if not (isinstance(item, Mapping) and item.get("type") == "function_call_output"):
214-
rewritten.append(item)
224+
rewritten.append(original)
215225
continue
216226
call_id = str(item.get("callId") or item.get("call_id") or "")
217227
name = call_names.get(call_id)
@@ -224,7 +234,7 @@ async def apply_on_response_received_hooks(
224234
None,
225235
)
226236
if tool is None:
227-
rewritten.append(item)
237+
rewritten.append(original)
228238
continue
229239
hook = get_tool_function(tool).get("on_response_received")
230240
ctx = build_tool_execute_context(tool, turn_context, context_store, shared_context_schema)
@@ -233,7 +243,7 @@ async def apply_on_response_received_hooks(
233243
if not hook:
234244
try:
235245
validate_schema(get_tool_function(tool).get("output_schema"), raw)
236-
rewritten.append(item)
246+
rewritten.append(original)
237247
continue
238248
except Exception as exc:
239249
new_item["output"] = json_dumps({"error": str(exc), "originalOutput": raw})
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
"""HITL resume must find the original call when history holds SDK models.
2+
3+
A live turn stores the generated SDK's pydantic `OutputFunctionCallItem` in
4+
conversation state. Resuming from that in-memory state must still run the
5+
tool's `on_response_received` hook (and output validation) on the caller's
6+
`function_call_output`, exactly as it does after a serialize/deserialize
7+
round trip turns the history into dicts.
8+
"""
9+
10+
from __future__ import annotations
11+
12+
import json
13+
from typing import Any, Dict, List
14+
15+
import httpx
16+
from openrouter.components import OutputFunctionCallItem
17+
18+
from openrouter_agent import OpenRouter, call_model, tool
19+
from openrouter_agent.tool_executor import apply_on_response_received_hooks
20+
from tests._fixtures import MemoryStateAccessor
21+
22+
PRIVATE = "reviewer-only-note"
23+
24+
25+
def _response(response_id: str, output: List[Dict[str, Any]]) -> Dict[str, Any]:
26+
return {
27+
"id": response_id,
28+
"object": "response",
29+
"created_at": 0,
30+
"completed_at": 0,
31+
"status": "completed",
32+
"model": "test/model",
33+
"error": None,
34+
"incomplete_details": None,
35+
"instructions": None,
36+
"metadata": None,
37+
"frequency_penalty": None,
38+
"presence_penalty": None,
39+
"temperature": None,
40+
"top_p": None,
41+
"tool_choice": "auto",
42+
"tools": [],
43+
"parallel_tool_calls": False,
44+
"output": output,
45+
}
46+
47+
48+
def _review_tool(calls: List[Any]) -> Any:
49+
def strip_private(raw: Any, _ctx: Any) -> Dict[str, Any]:
50+
calls.append(raw)
51+
return {"decision": raw["decision"]}
52+
53+
return tool(
54+
name="review",
55+
input_schema=dict,
56+
output_schema=dict,
57+
on_tool_called=lambda _args, _ctx: None,
58+
on_response_received=strip_private,
59+
)
60+
61+
62+
def _output_item() -> Dict[str, Any]:
63+
return {
64+
"type": "function_call_output",
65+
"callId": "call_1",
66+
"output": json.dumps({"decision": "approved", "private": PRIVATE}),
67+
}
68+
69+
70+
async def test_hook_runs_for_pydantic_function_call_in_history() -> None:
71+
calls: List[Any] = []
72+
historical = OutputFunctionCallItem(
73+
type="function_call", id="fc_1", call_id="call_1", name="review", arguments="{}", status="completed"
74+
)
75+
hooked = await apply_on_response_received_hooks([historical, _output_item()], [_review_tool(calls)])
76+
77+
assert hooked[0] is historical
78+
assert len(calls) == 1
79+
assert json.loads(hooked[1]["output"]) == {"decision": "approved"}
80+
81+
82+
async def test_in_memory_hitl_resume_sends_hook_output_not_raw_output() -> None:
83+
requests: List[Dict[str, Any]] = []
84+
first = _response(
85+
"resp_1",
86+
[
87+
{
88+
"type": "function_call",
89+
"id": "fc_1",
90+
"call_id": "call_1",
91+
"name": "review",
92+
"arguments": "{}",
93+
"status": "completed",
94+
}
95+
],
96+
)
97+
second = _response(
98+
"resp_2",
99+
[
100+
{
101+
"type": "message",
102+
"id": "msg_2",
103+
"role": "assistant",
104+
"status": "completed",
105+
"content": [{"type": "output_text", "text": "done", "annotations": []}],
106+
}
107+
],
108+
)
109+
110+
def handle(request: httpx.Request) -> httpx.Response:
111+
requests.append(json.loads(request.content))
112+
event = {
113+
"type": "response.completed",
114+
"sequence_number": 1,
115+
"response": first if len(requests) == 1 else second,
116+
}
117+
return httpx.Response(
118+
200, headers={"content-type": "text/event-stream"}, content=f"data: {json.dumps(event)}\n\n".encode()
119+
)
120+
121+
calls: List[Any] = []
122+
review = _review_tool(calls)
123+
accessor = MemoryStateAccessor()
124+
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http_client:
125+
client = OpenRouter(api_key="test", server_url="http://127.0.0.1:9", async_client=http_client)
126+
await call_model(
127+
client, {"model": "test/model", "input": "go", "tools": [review], "state": accessor}
128+
).get_response()
129+
assert accessor.stored is not None and accessor.stored.status == "awaiting_hitl"
130+
assert any(isinstance(item, OutputFunctionCallItem) for item in accessor.stored.messages)
131+
132+
await call_model(
133+
client, {"model": "test/model", "input": [_output_item()], "tools": [review], "state": accessor}
134+
).get_response()
135+
136+
assert len(requests) == 2
137+
sent = [item for item in requests[1]["input"] if item.get("type") == "function_call_output"]
138+
assert len(calls) == 1
139+
assert [json.loads(item["output"]) for item in sent] == [{"decision": "approved"}]
140+
assert PRIVATE not in json.dumps(requests[1])
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
"""next_turn_params must run only for calls whose tool body ran and succeeded."""
2+
3+
from __future__ import annotations
4+
5+
from typing import Any, Dict, List
6+
7+
from pydantic import BaseModel
8+
9+
from openrouter_agent import HookEntry, HookName, HooksManager, call_model, tool
10+
from tests._fixtures import QueuedClient, text_response, tool_call_response
11+
12+
13+
class SelectInput(BaseModel):
14+
target: str
15+
16+
17+
def _selector(seen: List[Any], **overrides: Any) -> Any:
18+
def next_instructions(args: Any, _ctx: Any) -> str:
19+
seen.append(args)
20+
return "widened"
21+
22+
options: Dict[str, Any] = {
23+
"name": "select",
24+
"input_schema": SelectInput,
25+
"execute": lambda params, ctx: {"ok": True},
26+
"next_turn_params": {"instructions": next_instructions},
27+
}
28+
options.update(overrides)
29+
return tool(**options)
30+
31+
32+
async def _run(selector: Any, arguments: str, hooks: Any = None) -> QueuedClient:
33+
client = QueuedClient(
34+
[
35+
tool_call_response("r1", "select", call_id="call_1", arguments=arguments),
36+
text_response("r2", "done"),
37+
]
38+
)
39+
request: Dict[str, Any] = {"model": "test/model", "input": "go", "instructions": "narrow", "tools": [selector]}
40+
if hooks is not None:
41+
request["hooks"] = hooks
42+
await call_model(client, request).get_response()
43+
return client
44+
45+
46+
async def test_successful_call_applies_next_turn_params() -> None:
47+
seen: List[Any] = []
48+
client = await _run(_selector(seen), '{"target": "x"}')
49+
assert seen == [{"target": "x"}]
50+
assert client.requests[1]["instructions"] == "widened"
51+
52+
53+
async def test_hook_blocked_call_does_not_apply_next_turn_params() -> None:
54+
seen: List[Any] = []
55+
hooks = HooksManager()
56+
hooks.on(HookName.PreToolUse.value, HookEntry(handler=lambda payload, ctx: {"block": "no"}))
57+
client = await _run(_selector(seen), '{"target": "x"}', hooks)
58+
assert seen == []
59+
assert client.requests[1]["instructions"] == "narrow"
60+
61+
62+
async def test_input_schema_rejected_call_does_not_apply_next_turn_params() -> None:
63+
seen: List[Any] = []
64+
client = await _run(_selector(seen), '{"wrong": 1}')
65+
assert seen == []
66+
assert client.requests[1]["instructions"] == "narrow"
67+
68+
69+
async def test_failed_call_does_not_apply_next_turn_params() -> None:
70+
seen: List[Any] = []
71+
72+
def boom(params: Any, _ctx: Any) -> Any:
73+
raise RuntimeError("tool failed")
74+
75+
client = await _run(_selector(seen, execute=boom), '{"target": "x"}')
76+
assert seen == []
77+
assert client.requests[1]["instructions"] == "narrow"
78+
79+
80+
async def test_invalid_json_call_does_not_apply_next_turn_params() -> None:
81+
seen: List[Any] = []
82+
client = await _run(_selector(seen), "{not json")
83+
assert seen == []
84+
assert client.requests[1]["instructions"] == "narrow"

0 commit comments

Comments
 (0)