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
26 changes: 18 additions & 8 deletions src/openrouter_agent/tool_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,15 @@

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

from ._utils import is_content_array, json_dumps, json_loads_maybe, maybe_await, schema_to_json_schema, validate_schema
from ._utils import (
dump,
is_content_array,
json_dumps,
json_loads_maybe,
maybe_await,
schema_to_json_schema,
validate_schema,
)
from .tool_context import ToolContextStore, build_tool_execute_context
from .tool_types import (
ParsedToolCall,
Expand Down Expand Up @@ -203,15 +211,17 @@ async def apply_on_response_received_hooks(
if not tools:
return input_items
items = input_items if isinstance(input_items, list) else [input_items]
# Items echoed back from a live turn are SDK pydantic models, not dicts.
as_mappings = [item if isinstance(item, Mapping) else dump(item) for item in items]
call_names: Dict[str, str] = {}
for item in items:
if isinstance(item, Mapping) and item.get("type") == "function_call":
call_names[str(item.get("callId") or item.get("call_id") or item.get("id"))] = str(item.get("name", ""))
for entry in as_mappings:
if isinstance(entry, Mapping) and entry.get("type") == "function_call":
call_names[str(entry.get("callId") or entry.get("call_id") or entry.get("id"))] = str(entry.get("name", ""))
rewritten: List[Any] = []
changed = False
for item in items:
for original, item in zip(items, as_mappings, strict=True):
if not (isinstance(item, Mapping) and item.get("type") == "function_call_output"):
rewritten.append(item)
rewritten.append(original)
continue
call_id = str(item.get("callId") or item.get("call_id") or "")
name = call_names.get(call_id)
Expand All @@ -224,7 +234,7 @@ async def apply_on_response_received_hooks(
None,
)
if tool is None:
rewritten.append(item)
rewritten.append(original)
continue
hook = get_tool_function(tool).get("on_response_received")
ctx = build_tool_execute_context(tool, turn_context, context_store, shared_context_schema)
Expand All @@ -233,7 +243,7 @@ async def apply_on_response_received_hooks(
if not hook:
try:
validate_schema(get_tool_function(tool).get("output_schema"), raw)
rewritten.append(item)
rewritten.append(original)
continue
except Exception as exc:
new_item["output"] = json_dumps({"error": str(exc), "originalOutput": raw})
Expand Down
140 changes: 140 additions & 0 deletions tests/unit/test_hitl_model_history.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""HITL resume must find the original call when history holds SDK models.

A live turn stores the generated SDK's pydantic `OutputFunctionCallItem` in
conversation state. Resuming from that in-memory state must still run the
tool's `on_response_received` hook (and output validation) on the caller's
`function_call_output`, exactly as it does after a serialize/deserialize
round trip turns the history into dicts.
"""

from __future__ import annotations

import json
from typing import Any, Dict, List

import httpx
from openrouter.components import OutputFunctionCallItem

from openrouter_agent import OpenRouter, call_model, tool
from openrouter_agent.tool_executor import apply_on_response_received_hooks
from tests._fixtures import MemoryStateAccessor

PRIVATE = "reviewer-only-note"


def _response(response_id: str, output: List[Dict[str, Any]]) -> Dict[str, Any]:
return {
"id": response_id,
"object": "response",
"created_at": 0,
"completed_at": 0,
"status": "completed",
"model": "test/model",
"error": None,
"incomplete_details": None,
"instructions": None,
"metadata": None,
"frequency_penalty": None,
"presence_penalty": None,
"temperature": None,
"top_p": None,
"tool_choice": "auto",
"tools": [],
"parallel_tool_calls": False,
"output": output,
}


def _review_tool(calls: List[Any]) -> Any:
def strip_private(raw: Any, _ctx: Any) -> Dict[str, Any]:
calls.append(raw)
return {"decision": raw["decision"]}

return tool(
name="review",
input_schema=dict,
output_schema=dict,
on_tool_called=lambda _args, _ctx: None,
on_response_received=strip_private,
)


def _output_item() -> Dict[str, Any]:
return {
"type": "function_call_output",
"callId": "call_1",
"output": json.dumps({"decision": "approved", "private": PRIVATE}),
}


async def test_hook_runs_for_pydantic_function_call_in_history() -> None:
calls: List[Any] = []
historical = OutputFunctionCallItem(
type="function_call", id="fc_1", call_id="call_1", name="review", arguments="{}", status="completed"
)
hooked = await apply_on_response_received_hooks([historical, _output_item()], [_review_tool(calls)])

assert hooked[0] is historical
assert len(calls) == 1
assert json.loads(hooked[1]["output"]) == {"decision": "approved"}


async def test_in_memory_hitl_resume_sends_hook_output_not_raw_output() -> None:
requests: List[Dict[str, Any]] = []
first = _response(
"resp_1",
[
{
"type": "function_call",
"id": "fc_1",
"call_id": "call_1",
"name": "review",
"arguments": "{}",
"status": "completed",
}
],
)
second = _response(
"resp_2",
[
{
"type": "message",
"id": "msg_2",
"role": "assistant",
"status": "completed",
"content": [{"type": "output_text", "text": "done", "annotations": []}],
}
],
)

def handle(request: httpx.Request) -> httpx.Response:
requests.append(json.loads(request.content))
event = {
"type": "response.completed",
"sequence_number": 1,
"response": first if len(requests) == 1 else second,
}
return httpx.Response(
200, headers={"content-type": "text/event-stream"}, content=f"data: {json.dumps(event)}\n\n".encode()
)

calls: List[Any] = []
review = _review_tool(calls)
accessor = MemoryStateAccessor()
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http_client:
client = OpenRouter(api_key="test", server_url="http://127.0.0.1:9", async_client=http_client)
await call_model(
client, {"model": "test/model", "input": "go", "tools": [review], "state": accessor}
).get_response()
assert accessor.stored is not None and accessor.stored.status == "awaiting_hitl"
assert any(isinstance(item, OutputFunctionCallItem) for item in accessor.stored.messages)

await call_model(
client, {"model": "test/model", "input": [_output_item()], "tools": [review], "state": accessor}
).get_response()

assert len(requests) == 2
sent = [item for item in requests[1]["input"] if item.get("type") == "function_call_output"]
assert len(calls) == 1
assert [json.loads(item["output"]) for item in sent] == [{"decision": "approved"}]
assert PRIVATE not in json.dumps(requests[1])
Loading