Skip to content

Commit 33705d8

Browse files
Merge pull request #40 from OpenRouterTeam/devin/1795956501-hitl-hook-model-history
fix(agent): run on_response_received when resumed history holds SDK models
2 parents d52c22c + 5fe3715 commit 33705d8

2 files changed

Lines changed: 158 additions & 8 deletions

File tree

‎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])

0 commit comments

Comments
 (0)