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
22 changes: 21 additions & 1 deletion packages/genkit-anthropic/src/genkit_anthropic/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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

Expand Down
36 changes: 36 additions & 0 deletions packages/genkit-anthropic/tests/anthropic_generate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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."""
Expand Down
25 changes: 23 additions & 2 deletions packages/genkit-openai/src/genkit_openai/_models/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand Down Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions packages/genkit-openai/tests/openai_tool_choice_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand All @@ -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
Expand Down
Loading