diff --git a/src/openrouter_agent/conversation_state.py b/src/openrouter_agent/conversation_state.py index 2cce4d8..212f36b 100644 --- a/src/openrouter_agent/conversation_state.py +++ b/src/openrouter_agent/conversation_state.py @@ -205,6 +205,12 @@ def _parse_tool_arguments(tool: Tool, arguments: Any) -> Tuple[bool, Any]: return True, parsed +def parsed_tool_input(tool: Tool, arguments: Any) -> Any: + """Arguments as `execute` sees them (schema defaults and coercions applied), + or the raw arguments when they do not validate.""" + return _parse_tool_arguments(tool, arguments)[1] + + async def tool_requires_approval( tool_call: ParsedToolCall, tools: Sequence[Tool], diff --git a/src/openrouter_agent/model_result.py b/src/openrouter_agent/model_result.py index 611a796..57edf00 100644 --- a/src/openrouter_agent/model_result.py +++ b/src/openrouter_agent/model_result.py @@ -15,6 +15,7 @@ create_rejected_result, create_unsent_result, generate_conversation_id, + parsed_tool_input, partition_tool_calls, unsent_results_to_api_format, update_state, @@ -661,9 +662,8 @@ async def _execute_calls_to_unsent_results( results.append(create_rejected_result(call.id, call.name, str(outcome["result"]["error"]))) else: effective_call = outcome["call"] - results.append( - create_unsent_result(effective_call.id, effective_call.name, outcome["result"].get("result")) - ) + _, model_output = await self._model_output_value(effective_call, tool, outcome["result"].get("result")) + results.append(create_unsent_result(effective_call.id, effective_call.name, model_output)) return results 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: } ) + async def _model_output_value(self, call: ParsedToolCall, tool: Tool, value: Any) -> Tuple[bool, Any]: + """Apply `to_model_output` to a successful result. Returns + `(is_content, value)`: a content array to send as-is, or a value to + JSON-encode.""" + converter = get_tool_function(tool).get("to_model_output") + if not converter: + return False, value + converted = await maybe_await(converter({"output": value, "input": parsed_tool_input(tool, call.arguments)})) + if isinstance(converted, Mapping) and converted.get("type") == "content": + return True, converted.get("value", []) + if isinstance(converted, Mapping) and converted.get("type") == "json": + return False, converted.get("value") + return False, value + async def _tool_result_to_output( self, call: ParsedToolCall, tool: Tool, result: Mapping[str, Any] ) -> Dict[str, Any]: if result.get("error") is not None: output: Any = json_dumps({"error": str(result["error"])}) else: - converter = get_tool_function(tool).get("to_model_output") - if converter: - converted = await maybe_await(converter({"output": result.get("result"), "input": call.arguments})) - if isinstance(converted, Mapping) and converted.get("type") == "content": - output = converted.get("value", []) - elif isinstance(converted, Mapping) and converted.get("type") == "json": - output = json_dumps(converted.get("value")) - else: - output = json_dumps(result.get("result")) - else: - output = json_dumps(result.get("result")) + is_content, value = await self._model_output_value(call, tool, result.get("result")) + output = value if is_content else json_dumps(value) return {"type": "function_call_output", "id": f"output_{call.id}", "callId": call.id, "output": output} def _rejected_output(self, call_id: str, reason: str) -> Dict[str, Any]: diff --git a/src/openrouter_agent/next_turn_params.py b/src/openrouter_agent/next_turn_params.py index 2c670e5..2dad6ed 100644 --- a/src/openrouter_agent/next_turn_params.py +++ b/src/openrouter_agent/next_turn_params.py @@ -3,6 +3,7 @@ from typing import Any, Dict, Mapping, Sequence from ._utils import maybe_await +from .conversation_state import parsed_tool_input from .tool_types import ParsedToolCall, Tool, get_tool_function, is_client_tool 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( if not matching: continue fns = get_tool_function(matching).get("next_turn_params") or {} + if not fns: + continue + arguments = parsed_tool_input(matching, call.arguments) for key, fn in fns.items(): - computed[key] = await maybe_await(fn(call.arguments, context)) + computed[key] = await maybe_await(fn(arguments, context)) context[key] = computed[key] return computed diff --git a/tests/unit/test_to_model_output_parity.py b/tests/unit/test_to_model_output_parity.py new file mode 100644 index 0000000..34d8e35 --- /dev/null +++ b/tests/unit/test_to_model_output_parity.py @@ -0,0 +1,120 @@ +"""`to_model_output` and `next_turn_params` see the schema-parsed input +`execute` gets, and results stored before an approval pause go through +`to_model_output` before they reach the model. Mirrors upstream +`tests/unit/to-model-output-parity.test.ts`. +""" + +from __future__ import annotations + +import json +from typing import Any, Dict, List + +from pydantic import BaseModel + +from openrouter_agent import call_model, tool +from tests._fixtures import ( + MemoryStateAccessor, + QueuedClient, + function_call_item, + make_response, + text_response, + tool_call_response, +) + +PRIVATE = "private-value-must-not-reach-model" +RAW_ARGS = json.dumps({"count": "3"}) +PARSED_ARGS = {"count": 3, "mode": "safe"} + + +class LookupArgs(BaseModel): + count: int + mode: str = "safe" + + +def _as_dict(value: Any) -> Any: + return value.model_dump() if isinstance(value, BaseModel) else value + + +def _outputs(request: Dict[str, Any]) -> Dict[str, Any]: + return { + i.get("callId", i.get("call_id")): i["output"] + for i in request["input"] + if i.get("type") == "function_call_output" + } + + +def _lookup_tool(seen: List[Dict[str, Any]], **extra: Any) -> Any: + def execute(params: Any, ctx: Any) -> Dict[str, Any]: + seen.append({"execute": _as_dict(params)}) + return {"public_status": "ok", "private_token": PRIVATE} + + def to_model_output(args: Dict[str, Any]) -> Dict[str, Any]: + seen.append({"to_model_output": _as_dict(args["input"])}) + return {"type": "json", "value": {"public_status": args["output"]["public_status"]}} + + return tool( + name="lookup", + input_schema=LookupArgs, + output_schema=dict, + execute=execute, + to_model_output=to_model_output, + **extra, + ) + + +async def test_to_model_output_receives_schema_parsed_input() -> None: + seen: List[Dict[str, Any]] = [] + client = QueuedClient([tool_call_response("r1", "lookup", arguments=RAW_ARGS), text_response("r2", "done")]) + + await call_model(client, {"model": "m", "input": "hi", "tools": [_lookup_tool(seen)]}).get_text() + + assert seen == [{"execute": PARSED_ARGS}, {"to_model_output": PARSED_ARGS}] + + +async def test_next_turn_params_receive_schema_parsed_input() -> None: + seen: List[Dict[str, Any]] = [] + + def temperature(args: Any, ctx: Any) -> float: + seen.append({"next_turn_params": _as_dict(args)}) + return 0.2 + + lookup = _lookup_tool(seen, next_turn_params={"temperature": temperature}) + client = QueuedClient([tool_call_response("r1", "lookup", arguments=RAW_ARGS), text_response("r2", "done")]) + + await call_model(client, {"model": "m", "input": "hi", "tools": [lookup]}).get_text() + + assert {"next_turn_params": PARSED_ARGS} in seen + assert client.requests[1]["temperature"] == 0.2 + + +async def test_unsent_result_from_approval_pause_applies_to_model_output_on_resume() -> None: + seen: List[Dict[str, Any]] = [] + state = MemoryStateAccessor() + deploy = tool( + name="deploy", + input_schema=dict, + output_schema=dict, + execute=lambda params, ctx: {"ok": True}, + require_approval=True, + ) + tools = [_lookup_tool(seen), deploy] + first = make_response( + "r1", + [function_call_item("call_lookup", "lookup", RAW_ARGS), function_call_item("call_deploy", "deploy")], + ) + + await call_model( + QueuedClient([first]), {"model": "m", "input": "lookup then deploy", "tools": tools, "state": state} + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_approval" + + client = QueuedClient([text_response("r2", "done")]) + await call_model( + client, + {"model": "m", "input": [], "tools": tools, "state": state, "approve_tool_calls": ["call_deploy"]}, + ).get_text() + + outputs = _outputs(client.requests[0]) + assert PRIVATE not in outputs["call_lookup"] + assert json.loads(outputs["call_lookup"]) == {"public_status": "ok"} + assert {"to_model_output": PARSED_ARGS} in seen