Skip to content

Commit 2521b94

Browse files
fix(agent): give to_model_output and next_turn_params parsed input, and map unsent results
1 parent d52c22c commit 2521b94

4 files changed

Lines changed: 150 additions & 15 deletions

File tree

‎src/openrouter_agent/conversation_state.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,12 @@ def _parse_tool_arguments(tool: Tool, arguments: Any) -> Tuple[bool, Any]:
205205
return True, parsed
206206

207207

208+
def parsed_tool_input(tool: Tool, arguments: Any) -> Any:
209+
"""Arguments as `execute` sees them (schema defaults and coercions applied),
210+
or the raw arguments when they do not validate."""
211+
return _parse_tool_arguments(tool, arguments)[1]
212+
213+
208214
async def tool_requires_approval(
209215
tool_call: ParsedToolCall,
210216
tools: Sequence[Tool],

‎src/openrouter_agent/model_result.py‎

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
create_rejected_result,
1616
create_unsent_result,
1717
generate_conversation_id,
18+
parsed_tool_input,
1819
partition_tool_calls,
1920
unsent_results_to_api_format,
2021
update_state,
@@ -661,9 +662,8 @@ async def _execute_calls_to_unsent_results(
661662
results.append(create_rejected_result(call.id, call.name, str(outcome["result"]["error"])))
662663
else:
663664
effective_call = outcome["call"]
664-
results.append(
665-
create_unsent_result(effective_call.id, effective_call.name, outcome["result"].get("result"))
666-
)
665+
_, model_output = await self._model_output_value(effective_call, tool, outcome["result"].get("result"))
666+
results.append(create_unsent_result(effective_call.id, effective_call.name, model_output))
667667
return results
668668

669669
async def _record_preliminary(self, call_id: str, value: Any) -> None:
@@ -677,23 +677,28 @@ async def _record_preliminary(self, call_id: str, value: Any) -> None:
677677
}
678678
)
679679

680+
async def _model_output_value(self, call: ParsedToolCall, tool: Tool, value: Any) -> Tuple[bool, Any]:
681+
"""Apply `to_model_output` to a successful result. Returns
682+
`(is_content, value)`: a content array to send as-is, or a value to
683+
JSON-encode."""
684+
converter = get_tool_function(tool).get("to_model_output")
685+
if not converter:
686+
return False, value
687+
converted = await maybe_await(converter({"output": value, "input": parsed_tool_input(tool, call.arguments)}))
688+
if isinstance(converted, Mapping) and converted.get("type") == "content":
689+
return True, converted.get("value", [])
690+
if isinstance(converted, Mapping) and converted.get("type") == "json":
691+
return False, converted.get("value")
692+
return False, value
693+
680694
async def _tool_result_to_output(
681695
self, call: ParsedToolCall, tool: Tool, result: Mapping[str, Any]
682696
) -> Dict[str, Any]:
683697
if result.get("error") is not None:
684698
output: Any = json_dumps({"error": str(result["error"])})
685699
else:
686-
converter = get_tool_function(tool).get("to_model_output")
687-
if converter:
688-
converted = await maybe_await(converter({"output": result.get("result"), "input": call.arguments}))
689-
if isinstance(converted, Mapping) and converted.get("type") == "content":
690-
output = converted.get("value", [])
691-
elif isinstance(converted, Mapping) and converted.get("type") == "json":
692-
output = json_dumps(converted.get("value"))
693-
else:
694-
output = json_dumps(result.get("result"))
695-
else:
696-
output = json_dumps(result.get("result"))
700+
is_content, value = await self._model_output_value(call, tool, result.get("result"))
701+
output = value if is_content else json_dumps(value)
697702
return {"type": "function_call_output", "id": f"output_{call.id}", "callId": call.id, "output": output}
698703

699704
def _rejected_output(self, call_id: str, reason: str) -> Dict[str, Any]:

‎src/openrouter_agent/next_turn_params.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from typing import Any, Dict, Mapping, Sequence
44

55
from ._utils import maybe_await
6+
from .conversation_state import parsed_tool_input
67
from .tool_types import ParsedToolCall, Tool, get_tool_function, is_client_tool
78

89
NEXT_TURN_KEYS = ("input", "model", "models", "temperature", "max_output_tokens", "top_p", "top_k", "instructions")
@@ -24,8 +25,11 @@ async def execute_next_turn_params_functions(
2425
if not matching:
2526
continue
2627
fns = get_tool_function(matching).get("next_turn_params") or {}
28+
if not fns:
29+
continue
30+
arguments = parsed_tool_input(matching, call.arguments)
2731
for key, fn in fns.items():
28-
computed[key] = await maybe_await(fn(call.arguments, context))
32+
computed[key] = await maybe_await(fn(arguments, context))
2933
context[key] = computed[key]
3034
return computed
3135

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
"""`to_model_output` and `next_turn_params` see the schema-parsed input
2+
`execute` gets, and results stored before an approval pause go through
3+
`to_model_output` before they reach the model. Mirrors upstream
4+
`tests/unit/to-model-output-parity.test.ts`.
5+
"""
6+
7+
from __future__ import annotations
8+
9+
import json
10+
from typing import Any, Dict, List
11+
12+
from pydantic import BaseModel
13+
14+
from openrouter_agent import call_model, tool
15+
from tests._fixtures import (
16+
MemoryStateAccessor,
17+
QueuedClient,
18+
function_call_item,
19+
make_response,
20+
text_response,
21+
tool_call_response,
22+
)
23+
24+
PRIVATE = "private-value-must-not-reach-model"
25+
RAW_ARGS = json.dumps({"count": "3"})
26+
PARSED_ARGS = {"count": 3, "mode": "safe"}
27+
28+
29+
class LookupArgs(BaseModel):
30+
count: int
31+
mode: str = "safe"
32+
33+
34+
def _as_dict(value: Any) -> Any:
35+
return value.model_dump() if isinstance(value, BaseModel) else value
36+
37+
38+
def _outputs(request: Dict[str, Any]) -> Dict[str, Any]:
39+
return {
40+
i.get("callId", i.get("call_id")): i["output"]
41+
for i in request["input"]
42+
if i.get("type") == "function_call_output"
43+
}
44+
45+
46+
def _lookup_tool(seen: List[Dict[str, Any]], **extra: Any) -> Any:
47+
def execute(params: Any, ctx: Any) -> Dict[str, Any]:
48+
seen.append({"execute": _as_dict(params)})
49+
return {"public_status": "ok", "private_token": PRIVATE}
50+
51+
def to_model_output(args: Dict[str, Any]) -> Dict[str, Any]:
52+
seen.append({"to_model_output": _as_dict(args["input"])})
53+
return {"type": "json", "value": {"public_status": args["output"]["public_status"]}}
54+
55+
return tool(
56+
name="lookup",
57+
input_schema=LookupArgs,
58+
output_schema=dict,
59+
execute=execute,
60+
to_model_output=to_model_output,
61+
**extra,
62+
)
63+
64+
65+
async def test_to_model_output_receives_schema_parsed_input() -> None:
66+
seen: List[Dict[str, Any]] = []
67+
client = QueuedClient([tool_call_response("r1", "lookup", arguments=RAW_ARGS), text_response("r2", "done")])
68+
69+
await call_model(client, {"model": "m", "input": "hi", "tools": [_lookup_tool(seen)]}).get_text()
70+
71+
assert seen == [{"execute": PARSED_ARGS}, {"to_model_output": PARSED_ARGS}]
72+
73+
74+
async def test_next_turn_params_receive_schema_parsed_input() -> None:
75+
seen: List[Dict[str, Any]] = []
76+
77+
def temperature(args: Any, ctx: Any) -> float:
78+
seen.append({"next_turn_params": _as_dict(args)})
79+
return 0.2
80+
81+
lookup = _lookup_tool(seen, next_turn_params={"temperature": temperature})
82+
client = QueuedClient([tool_call_response("r1", "lookup", arguments=RAW_ARGS), text_response("r2", "done")])
83+
84+
await call_model(client, {"model": "m", "input": "hi", "tools": [lookup]}).get_text()
85+
86+
assert {"next_turn_params": PARSED_ARGS} in seen
87+
assert client.requests[1]["temperature"] == 0.2
88+
89+
90+
async def test_unsent_result_from_approval_pause_applies_to_model_output_on_resume() -> None:
91+
seen: List[Dict[str, Any]] = []
92+
state = MemoryStateAccessor()
93+
deploy = tool(
94+
name="deploy",
95+
input_schema=dict,
96+
output_schema=dict,
97+
execute=lambda params, ctx: {"ok": True},
98+
require_approval=True,
99+
)
100+
tools = [_lookup_tool(seen), deploy]
101+
first = make_response(
102+
"r1",
103+
[function_call_item("call_lookup", "lookup", RAW_ARGS), function_call_item("call_deploy", "deploy")],
104+
)
105+
106+
await call_model(
107+
QueuedClient([first]), {"model": "m", "input": "lookup then deploy", "tools": tools, "state": state}
108+
).get_response()
109+
assert state.stored is not None and state.stored.status == "awaiting_approval"
110+
111+
client = QueuedClient([text_response("r2", "done")])
112+
await call_model(
113+
client,
114+
{"model": "m", "input": [], "tools": tools, "state": state, "approve_tool_calls": ["call_deploy"]},
115+
).get_text()
116+
117+
outputs = _outputs(client.requests[0])
118+
assert PRIVATE not in outputs["call_lookup"]
119+
assert json.loads(outputs["call_lookup"]) == {"public_status": "ok"}
120+
assert {"to_model_output": PARSED_ARGS} in seen

0 commit comments

Comments
 (0)