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
51 changes: 47 additions & 4 deletions src/openrouter_agent/model_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,33 @@ def _find_latest_user_string_index(items: Sequence[Any]) -> int:
return -1


def _is_specific_forced_tool_choice(tool_choice: Any) -> bool:
"""Return True when `tool_choice` pins a specific tool (e.g. a named function).

String modes (`"auto"`, `"none"`, `"required"`) and `allowed_tools` allowlists
constrain tool usage without forcing the same tool on every follow-up turn.
"""
if tool_choice is None or isinstance(tool_choice, str):
return False
choice_type = get_field(tool_choice, "type")
if choice_type == "allowed_tools":
return False
if isinstance(choice_type, str) and choice_type:
return True
name = get_field(tool_choice, "name")
if isinstance(name, str) and name:
return True
return get_field(tool_choice, "function") is not None


def _clear_forced_tool_choice(request: Mapping[str, Any]) -> Dict[str, Any]:
cleaned = dict(request)
for key in ("tool_choice", "toolChoice"):
if key in cleaned and _is_specific_forced_tool_choice(cleaned[key]):
cleaned.pop(key, None)
return cleaned


class ModelResult:
def __init__(self, options: Mapping[str, Any]) -> None:
assert_unique_client_tool_names(options.get("tools"))
Expand Down Expand Up @@ -802,7 +829,9 @@ async def _run(self) -> Any:
)
if self.options.get("on_turn_end"):
await maybe_await(self.options["on_turn_end"]({"number_of_turns": turn_number}, response))
calls = extract_tool_calls_from_response(response)
calls = (
extract_tool_calls_from_response(response) if get_field(response, "status") == "completed" else []
)
self._tool_calls.extend(calls)
final_response = response
await self._save_response_to_state(response)
Expand Down Expand Up @@ -1018,9 +1047,17 @@ async def _run(self) -> Any:
self._all_tool_rounds += 1
force_resume_count = 0
next_params = await execute_next_turn_params_functions(executed_calls, tools, current_request)
preserve_tool_choice = False
if next_params:
if "tool_choice" in next_params or "toolChoice" in next_params:
current_request = {
k: v for k, v in current_request.items() if k not in {"tool_choice", "toolChoice"}
}
preserve_tool_choice = True
current_request = apply_next_turn_params_to_request(current_request, next_params)
current_request = self._build_followup_request(current_request, response, outputs)
current_request = self._build_followup_request(
current_request, response, outputs, preserve_tool_choice=preserve_tool_choice
)
else:
raise RuntimeError("call_model exceeded the 20-turn safety limit")

Expand Down Expand Up @@ -1138,13 +1175,19 @@ async def _iter_events_live(self) -> AsyncIterator[Any]:
await self.get_response()

def _build_followup_request(
self, request: Mapping[str, Any], response: Any, outputs: Sequence[Any]
self,
request: Mapping[str, Any],
response: Any,
outputs: Sequence[Any],
*,
preserve_tool_choice: bool = False,
) -> Dict[str, Any]:
output_items = get_field(response, "output", []) or []
if not isinstance(output_items, list):
output_items = [output_items]
base_request = dict(request) if preserve_tool_choice else _clear_forced_tool_choice(request)
return {
**dict(request),
**base_request,
"input": [*normalize_input_to_array(request.get("input")), *output_items, *outputs],
"stream": True,
}
Expand Down
127 changes: 127 additions & 0 deletions tests/unit/test_forced_tool_choice_one_shot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"""Specific forced tool_choice is one-shot on follow-up 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_agent import call_model, tool
from tests._fixtures import QueuedClient, text_response, tool_call_response


def _tool(name: str, executed: List[str], next_turn_params: Dict[str, Any] | None = None) -> Any:
def execute(params: Dict[str, Any], _ctx: Any) -> Dict[str, Any]:
executed.append(name)
return {"ran": name}

options: Dict[str, Any] = {"name": name, "input_schema": dict, "execute": execute}
if next_turn_params is not None:
options["next_turn_params"] = next_turn_params
return tool(**options)


@pytest.mark.parametrize(
("key", "forced_choice"),
[
("tool_choice", {"type": "function", "name": "charge_card"}),
("toolChoice", {"type": "function", "name": "charge_card"}),
("tool_choice", {"type": "function", "function": {"name": "charge_card"}}),
("tool_choice", OpenAIResponsesToolChoiceFunction(type="function", name="charge_card")),
("tool_choice", {"type": "web_search_preview"}),
],
)
async def test_specific_forced_tool_choice_is_cleared_on_followup_turn(key: str, forced_choice: Any) -> None:
executed: List[str] = []
client = QueuedClient(
[
tool_call_response("r1", "charge_card", call_id="call_1", arguments="{}"),
text_response("r2", "charged once"),
]
)

result = call_model(
client,
{
"model": "test/model",
"input": "charge",
"tools": [_tool("charge_card", executed)],
key: forced_choice,
},
)

assert await result.get_text() == "charged once"
assert executed == ["charge_card"]
assert len(client.requests) == 2
assert client.requests[0]["tool_choice"] == forced_choice
assert "tool_choice" not in client.requests[1]


async def test_next_turn_params_can_explicitly_set_forced_tool_choice_for_next_turn() -> None:
executed: List[str] = []
step_two_choice = {"type": "function", "name": "step_two"}
step_one = _tool(
"step_one",
executed,
next_turn_params={"tool_choice": lambda _args, _ctx: step_two_choice},
)
step_two = _tool("step_two", executed)

client = QueuedClient(
[
tool_call_response("r1", "step_one", call_id="call_1", arguments="{}"),
tool_call_response("r2", "step_two", call_id="call_2", arguments="{}"),
text_response("r3", "all done"),
]
)

result = call_model(
client,
{
"model": "test/model",
"input": "run two steps",
"tools": [step_one, step_two],
"toolChoice": {"type": "function", "name": "step_one"},
},
)

assert await result.get_text() == "all done"
assert executed == ["step_one", "step_two"]
assert len(client.requests) == 3
assert client.requests[0]["tool_choice"] == {"type": "function", "name": "step_one"}
assert client.requests[1]["tool_choice"] == step_two_choice
assert "tool_choice" not in client.requests[2]


@pytest.mark.parametrize(
"preserved_choice",
[
"auto",
"required",
{"type": "allowed_tools", "mode": "auto", "tools": [{"type": "function", "name": "lookup"}]},
],
)
async def test_non_specific_tool_choice_is_preserved_on_followup_turn(preserved_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": preserved_choice,
},
)

assert await result.get_text() == "found"
assert len(client.requests) == 2
assert client.requests[0]["tool_choice"] == preserved_choice
assert client.requests[1]["tool_choice"] == preserved_choice
181 changes: 181 additions & 0 deletions tests/unit/test_non_completed_response_tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
"""Tool calls from non-completed responses must not be executed."""

from __future__ import annotations

from typing import Any, AsyncIterator, Dict, List

import pytest

from openrouter_agent import HookEntry, HookName, HooksManager, call_model, step_count_is, tool
from tests._fixtures import (
MemoryStateAccessor,
QueuedClient,
function_call_item,
make_response,
message_item,
text_response,
tool_call_response,
)


def _side_effect_tool(executed: List[Any], **overrides: Any) -> Any:
def execute(params: Dict[str, Any], _ctx: Any) -> Dict[str, bool]:
executed.append(params)
return {"ok": True}

options: Dict[str, Any] = {"name": "delete_record", "input_schema": dict, "execute": execute}
options.update(overrides)
return tool(**options)


@pytest.mark.parametrize(
("status", "extra"),
[
("incomplete", {"incompleteDetails": {"reason": "max_output_tokens"}}),
("incomplete", {"incompleteDetails": {"reason": "content_filter"}}),
("failed", {"error": {"code": "server_error", "message": "boom"}}),
("cancelled", {}),
("in_progress", {}),
("queued", {}),
(None, {}),
],
)
async def test_refuses_tool_execution_for_non_completed_response_status(status: Any, extra: Dict[str, Any]) -> None:
executed: List[Any] = []
pre_hook_seen: List[Any] = []

def record_pre_hook(payload: Dict[str, Any], _ctx: Any) -> Dict[str, Any]:
pre_hook_seen.append(payload)
return {}

hooks = HooksManager()
hooks.on(HookName.PreToolUse.value, HookEntry(handler=record_pre_hook))

client = QueuedClient(
[
tool_call_response(
"r1",
"delete_record",
call_id="call_1",
arguments='{"id": 7}',
status=status,
**extra,
),
text_response("r2", "should never be reached"),
]
)

result = call_model(
client,
{
"model": "test/model",
"input": "delete 7",
"tools": [_side_effect_tool(executed)],
"hooks": hooks,
},
)
response = await result.get_response()

assert response["id"] == "r1"
assert response["status"] == status
assert executed == []
assert pre_hook_seen == []
assert await result.get_tool_calls() == []
assert len(client.requests) == 1


async def test_refuses_tool_execution_from_streamed_response_incomplete_event() -> None:
executed: List[Any] = []
incomplete_resp = make_response(
"r_inc",
[
message_item("partial"),
function_call_item("call_1", "delete_record", '{"id": 7}'),
],
status="incomplete",
incompleteDetails={"reason": "max_output_tokens"},
)

async def stream_events() -> AsyncIterator[Dict[str, Any]]:
yield {"type": "response.output_text.delta", "delta": "partial"}
yield {"type": "response.incomplete", "response": incomplete_resp}

client = QueuedClient([stream_events(), text_response("r2", "unreachable")])
result = call_model(
client,
{"model": "test/model", "input": "delete 7", "tools": [_side_effect_tool(executed)]},
)
response = await result.get_response()

assert response["id"] == "r_inc"
assert response["status"] == "incomplete"
assert await result.get_text() == "partial"
assert executed == []
assert await result.get_tool_calls() == []
assert len(client.requests) == 1


async def test_incomplete_response_does_not_pause_for_approval_or_run_allow_final_response() -> None:
executed: List[Any] = []
state = MemoryStateAccessor()
client = QueuedClient(
[
tool_call_response(
"r1",
"delete_record",
call_id="call_1",
arguments='{"id": 7}',
status="incomplete",
incompleteDetails={"reason": "content_filter"},
),
text_response("r2", "unreachable"),
]
)

result = call_model(
client,
{
"model": "test/model",
"input": "delete 7",
"tools": [_side_effect_tool(executed, require_approval=True)],
"state": state,
"stop_when": step_count_is(1),
"allow_final_response": True,
},
)
response = await result.get_response()

assert response["id"] == "r1"
assert executed == []
assert await result.requires_approval() is False
assert await result.get_pending_tool_calls() == []
assert len(client.requests) == 1


async def test_completed_turn_runs_but_subsequent_incomplete_turn_does_not_execute_tools() -> None:
executed: List[Any] = []
client = QueuedClient(
[
tool_call_response("r1", "delete_record", call_id="call_1", arguments='{"id": 1}'),
tool_call_response(
"r2",
"delete_record",
call_id="call_2",
arguments='{"id": 2}',
status="incomplete",
incompleteDetails={"reason": "max_output_tokens"},
),
text_response("r3", "unreachable"),
]
)

result = call_model(
client,
{"model": "test/model", "input": "delete", "tools": [_side_effect_tool(executed)]},
)
response = await result.get_response()

assert response["id"] == "r2"
assert executed == [{"id": 1}]
assert [c.id for c in await result.get_tool_calls()] == ["call_1"]
assert len(client.requests) == 2
Loading