From 882fe4a7d2551a0494489c341e99800fcbf217fa Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:58:06 +0000 Subject: [PATCH] fix(agent): spend required tool_choice and forced choices on resume turns A forced tool_choice of "required" or allowed_tools with mode "required" was re-sent on every follow-up turn, and a specific forced choice was re-sent on the first turn after an approval or client-tool resume. In both cases the model was compelled to call a tool again after the forced call had already run. Relax these to auto on follow-up and resume turns, matching the TypeScript agent. --- src/openrouter_agent/model_result.py | 23 +++- .../unit/test_forced_tool_choice_one_shot.py | 119 +++++++++++++++++- 2 files changed, 136 insertions(+), 6 deletions(-) diff --git a/src/openrouter_agent/model_result.py b/src/openrouter_agent/model_result.py index 345291c..326e6e2 100644 --- a/src/openrouter_agent/model_result.py +++ b/src/openrouter_agent/model_result.py @@ -191,10 +191,27 @@ def _is_specific_forced_tool_choice(tool_choice: Any) -> bool: def _clear_forced_tool_choice(request: Mapping[str, Any]) -> Dict[str, Any]: + """Spend a forced `tool_choice` once it has produced a tool call. + + A specific tool is dropped (back to the provider default), `"required"` + becomes `"auto"`, and an `allowed_tools` allowlist with `mode: "required"` + keeps its tools with `mode: "auto"`. + """ cleaned = dict(request) for key in ("tool_choice", "toolChoice"): - if key in cleaned and _is_specific_forced_tool_choice(cleaned[key]): + if key not in cleaned: + continue + choice = cleaned[key] + if _is_specific_forced_tool_choice(choice): cleaned.pop(key, None) + elif choice == "required": + cleaned[key] = "auto" + elif get_field(choice, "type") == "allowed_tools" and get_field(choice, "mode") == "required": + relaxed = ( + choice.model_dump(by_alias=True, exclude_none=True) if hasattr(choice, "model_dump") else dict(choice) + ) + relaxed["mode"] = "auto" + cleaned[key] = relaxed return cleaned @@ -878,6 +895,8 @@ async def _run(self) -> Any: current_request = request is_resume_turn = self._resuming_from_client_tools + if is_resume_turn: + current_request = _clear_forced_tool_choice(current_request) if ( self._state is not None and self._state.pending_tool_calls @@ -1246,7 +1265,7 @@ async def _build_resume_request(self, request: Mapping[str, Any]) -> Dict[str, A unsent_tool_results=None, status="in_progress", ) - return {**dict(request), "input": updated_messages, "stream": True} + return {**_clear_forced_tool_choice(request), "input": updated_messages, "stream": True} async def _iter_events_live(self) -> AsyncIterator[Any]: self._ensure_task() diff --git a/tests/unit/test_forced_tool_choice_one_shot.py b/tests/unit/test_forced_tool_choice_one_shot.py index 0d8b740..05272f6 100644 --- a/tests/unit/test_forced_tool_choice_one_shot.py +++ b/tests/unit/test_forced_tool_choice_one_shot.py @@ -1,14 +1,14 @@ -"""Specific forced tool_choice is one-shot on follow-up turns unless re-set via next_turn_params.""" +"""Forced tool_choice is one-shot on follow-up and resume turns unless re-set via next_turn_params.""" from __future__ import annotations from typing import Any, Dict, List import pytest -from openrouter.components import OpenAIResponsesToolChoiceFunction +from openrouter.components import OpenAIResponsesToolChoiceFunction, ToolChoiceAllowed from openrouter_agent import call_model, tool -from tests._fixtures import QueuedClient, text_response, tool_call_response +from tests._fixtures import MemoryStateAccessor, QueuedClient, text_response, tool_call_response def _tool(name: str, executed: List[str], next_turn_params: Dict[str, Any] | None = None) -> Any: @@ -98,7 +98,6 @@ async def test_next_turn_params_can_explicitly_set_forced_tool_choice_for_next_t "preserved_choice", [ "auto", - "required", {"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "lookup"}]}, ], ) @@ -125,3 +124,115 @@ async def test_non_specific_tool_choice_is_preserved_on_followup_turn(preserved_ assert len(client.requests) == 2 assert client.requests[0]["tool_choice"] == preserved_choice assert client.requests[1]["tool_choice"] == preserved_choice + + +_LOOKUP_ONLY = [{"type": "function", "name": "lookup"}] + + +@pytest.mark.parametrize( + ("forced_choice", "relaxed_choice"), + [ + ("required", "auto"), + ( + {"type": "allowed_tools", "mode": "required", "tools": _LOOKUP_ONLY}, + {"type": "allowed_tools", "mode": "auto", "tools": _LOOKUP_ONLY}, + ), + ( + ToolChoiceAllowed(type="allowed_tools", mode="required", tools=_LOOKUP_ONLY), + {"type": "allowed_tools", "mode": "auto", "tools": _LOOKUP_ONLY}, + ), + ], +) +async def test_required_tool_choice_is_relaxed_to_auto_on_followup_turn( + forced_choice: Any, relaxed_choice: Any +) -> None: + executed: List[str] = [] + client = QueuedClient( + [ + tool_call_response("r1", "lookup", call_id="call_1", arguments="{}"), + text_response("r2", "found"), + ] + ) + + result = call_model( + client, + { + "model": "test/model", + "input": "look up", + "tools": [_tool("lookup", executed)], + "tool_choice": forced_choice, + }, + ) + + assert await result.get_text() == "found" + assert executed == ["lookup"] + assert client.requests[0]["tool_choice"] == forced_choice + assert client.requests[1]["tool_choice"] == relaxed_choice + + +async def test_forced_tool_choice_is_not_reapplied_after_approval_resume() -> None: + state = MemoryStateAccessor() + executed: List[str] = [] + forced = {"type": "function", "name": "charge_card"} + + def gated() -> Any: + def execute(params: Dict[str, Any], _ctx: Any) -> Dict[str, Any]: + executed.append("charge_card") + return {"ok": True} + + return tool(name="charge_card", input_schema=dict, execute=execute, require_approval=True) + + first = QueuedClient([tool_call_response("r1", "charge_card", call_id="call_1", arguments="{}")]) + await call_model( + first, + {"model": "test/model", "input": "charge", "tools": [gated()], "tool_choice": forced, "state": state}, + ).get_response() + assert executed == [] + assert state.stored is not None and state.stored.status == "awaiting_approval" + + resumed = QueuedClient([text_response("r2", "charged once")]) + result = call_model( + resumed, + { + "model": "test/model", + "input": [], + "tools": [gated()], + "tool_choice": forced, + "state": state, + "approve_tool_calls": ["call_1"], + }, + ) + + assert await result.get_text() == "charged once" + assert executed == ["charge_card"] + assert len(resumed.requests) == 1 + assert "tool_choice" not in resumed.requests[0] + + +async def test_forced_tool_choice_is_not_reapplied_after_client_tool_resume() -> None: + state = MemoryStateAccessor() + forced = {"type": "function", "name": "send_payment"} + manual = tool(name="send_payment", input_schema=dict, execute=False) + + first = QueuedClient([tool_call_response("r1", "send_payment", call_id="call_1", arguments="{}")]) + await call_model( + first, + {"model": "test/model", "input": "pay", "tools": [manual], "tool_choice": forced, "state": state}, + ).get_response() + assert state.stored is not None and state.stored.status == "awaiting_client_tools" + + resumed = QueuedClient([text_response("r2", "paid once")]) + result = call_model( + resumed, + { + "model": "test/model", + "input": [{"type": "function_call_output", "call_id": "call_1", "output": "{}"}], + "tools": [manual], + "tool_choice": forced, + "state": state, + }, + ) + + assert await result.get_text() == "paid once" + assert len(resumed.requests) == 1 + assert "tool_choice" not in resumed.requests[0]