diff --git a/packages/genkit-anthropic/src/genkit_anthropic/_models.py b/packages/genkit-anthropic/src/genkit_anthropic/_models.py index 8dec656c..973e0c1e 100644 --- a/packages/genkit-anthropic/src/genkit_anthropic/_models.py +++ b/packages/genkit-anthropic/src/genkit_anthropic/_models.py @@ -239,6 +239,26 @@ def _to_anthropic_output_config(config: AnthropicConfig) -> dict[str, Any] | Non _TOOL_CHOICE_TYPES = {'auto': 'auto', 'required': 'any', 'none': 'none'} +def _effective_tool_choice(request: ModelRequest) -> str | None: + """The request's tool_choice, with 'required' relaxed to 'auto' once tools have answered. + + 'required' forces the first tool call of a user turn. Keeping it after the + tool results forbids a text answer, so the run loops until max_turns. If any + message after the most recent model turn carries a tool response, later + turns may answer. + """ + choice = request.tool_choice + if choice != 'required': + return choice + saw_tool_response = False + for msg in reversed(request.messages): + if msg.role == Role.MODEL: + return 'auto' if saw_tool_response else choice + if msg.role == Role.TOOL or any(p.tool_response is not None for p in msg.content): + saw_tool_response = True + return choice + + def _to_anthropic_tool_choice(tool_choice: str | None, disable_parallel_tool_use: bool) -> dict[str, Any] | None: """Translate Genkit's tool_choice into Anthropic's object; None sends nothing. @@ -587,7 +607,7 @@ def _build_params( } for t in request.tools ] - tool_choice = _to_anthropic_tool_choice(request.tool_choice, disable_parallel_tool_use) + tool_choice = _to_anthropic_tool_choice(_effective_tool_choice(request), disable_parallel_tool_use) if tool_choice is not None: params['tool_choice'] = tool_choice diff --git a/packages/genkit-anthropic/tests/anthropic_generate_test.py b/packages/genkit-anthropic/tests/anthropic_generate_test.py index 63e34cec..9fcf9f6b 100644 --- a/packages/genkit-anthropic/tests/anthropic_generate_test.py +++ b/packages/genkit-anthropic/tests/anthropic_generate_test.py @@ -30,6 +30,7 @@ from genkit import FinishReason, Genkit, GenkitError, Message, Part, Role from genkit.middleware import Middleware +from genkit.model import ToolRequest, ToolResponse from genkit.plugin_api import ActionKind MODEL = 'anthropic/claude-sonnet-4-6' @@ -474,6 +475,41 @@ async def lookup_menu(dish: str) -> str: assert api.body().get('tool_choice') == sent +@pytest.mark.asyncio +async def test_generate_claude_required_tool_choice_relaxes_to_auto_after_tool_result() -> None: + """'required' forces the first call; once a tool has answered, the follow-up sends {'type': 'auto'}.""" + api = FakeClaudeApi() + ai = _genkit(api) + + @ai.tool(name='lookup_menu') + async def lookup_menu(dish: str) -> str: + return 'ramen' + + history = [ + Message(role=Role.USER, content=[Part(text='Is ramen in stock?')]), + Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(ref='t1', name='lookup_menu', input='ramen'))], + ), + Message( + role=Role.TOOL, + content=[Part(tool_response=ToolResponse(ref='t1', name='lookup_menu', output='ramen'))], + ), + ] + await ai.generate(model=MODEL, messages=history, tools=['lookup_menu'], tool_choice='required') + assert api.body().get('tool_choice') == {'type': 'auto'} + + # A new user turn after the tool round is forced again. + await ai.generate( + model=MODEL, + messages=[*history, Message(role=Role.MODEL, content=[Part(text='Yes.')])], + prompt='And pho?', + tools=['lookup_menu'], + tool_choice='required', + ) + assert api.body().get('tool_choice') == {'type': 'any'} + + @pytest.mark.asyncio async def test_generate_claude_tool_choice_dropped_without_tools() -> None: """The API rejects tool_choice on a request with no tools, so option, flag, and extra tool_choice are dropped.""" diff --git a/packages/genkit-openai/src/genkit_openai/_models/_model.py b/packages/genkit-openai/src/genkit_openai/_models/_model.py index ec00050c..cb785c69 100644 --- a/packages/genkit-openai/src/genkit_openai/_models/_model.py +++ b/packages/genkit-openai/src/genkit_openai/_models/_model.py @@ -347,6 +347,26 @@ def _unwrap_tool_inputs(message: Message, wrapped: frozenset[str]) -> Message: return _map_tool_requests(message, wrapped, wrap=False) +def _effective_tool_choice(request: ModelRequest) -> str | None: + """The request's tool_choice, with 'required' relaxed to 'auto' once tools have answered. + + 'required' forces the first tool call of a user turn. Keeping it after the + tool results forbids a text answer, so the run loops until max_turns. If any + message after the most recent model turn carries a tool response, later + turns may answer. + """ + choice = request.tool_choice + if choice != 'required': + return choice + saw_tool_response = False + for msg in reversed(request.messages): + if msg.role == Role.MODEL: + return 'auto' if saw_tool_response else choice + if msg.role == Role.TOOL or any(p.tool_response is not None for p in msg.content): + saw_tool_response = True + return choice + + class OpenAIModel: """Handles OpenAI API interactions for the Genkit plugin.""" @@ -570,8 +590,9 @@ async def _get_openai_request_config(self, request: ModelRequest) -> dict: # Genkit's auto/required/none are OpenAI's values. OpenAI rejects # tool_choice without tools, so it rides only with them. Core's # max_turns bounds a 'required' run that never answers. - if request.tool_choice: - openai_config['tool_choice'] = request.tool_choice + tool_choice = _effective_tool_choice(request) + if tool_choice: + openai_config['tool_choice'] = tool_choice if request.output_format: response_format = self._get_response_format(request) if response_format: diff --git a/packages/genkit-openai/tests/openai_tool_choice_test.py b/packages/genkit-openai/tests/openai_tool_choice_test.py index da9c4e32..9a44438b 100644 --- a/packages/genkit-openai/tests/openai_tool_choice_test.py +++ b/packages/genkit-openai/tests/openai_tool_choice_test.py @@ -128,8 +128,8 @@ async def test_tool_choice_kept_after_a_tool_turn(tool_choice: Any) -> None: # @pytest.mark.asyncio -async def test_required_tool_choice_persists_on_followup_turn() -> None: - """Under 'required', the follow-up request after a tool result still sends tool_choice='required'.""" +async def test_required_tool_choice_relaxes_to_auto_on_followup_turn() -> None: + """'required' forces the first tool call; after a tool result the follow-up request sends 'auto'.""" server = _ScriptedServer([ _tool_call('call_1', 'lookup_menu', 'pho'), _tool_call('call_2', 'check_allergens', 'pho'), @@ -147,7 +147,7 @@ async def test_required_tool_choice_persists_on_followup_turn() -> None: assert len(server.bodies) == 2 assert server.bodies[0]['tool_choice'] == 'required' assert any(m['role'] == 'tool' for m in server.bodies[1]['messages']) - assert server.bodies[1]['tool_choice'] == 'required' + assert server.bodies[1]['tool_choice'] == 'auto' @pytest.mark.asyncio