Skip to content

fix(openai,anthropic): relax tool_choice='required' to 'auto' after a tool turn #112

Done

Description

@huangjeff5

Problem

When calling ai.generate(..., tools=[...], tool_choice='required') without return_tool_requests=True, both OpenAI (tool_choice='required') and Anthropic (tool_choice={'type': 'any'}) forbid text/JSON replies whenever that setting stays on the wire.

Because genkit-openai and genkit-anthropic currently forward request.tool_choice unchanged on Turn 2+ after a tool responds, the model is forced to call tools on every follow-up turn until max_turns fails instead of returning a final answer.

genkit-google-genai fixed this for Gemini/Gemma in #107 (_effective_tool_choice in packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py), relaxing 'required' to 'auto' once a tool response follows the most recent model turn in request.messages.

Affected Code

  • genkit-openai:
    • packages/genkit-openai/src/genkit_openai/_models/_model.py (openai_config['tool_choice'] = request.tool_choice)
    • packages/genkit-openai/src/genkit_openai/_models/_responses.py (Responses API tool_choice mapping, if applicable)
    • packages/genkit-openai/tests/openai_tool_choice_test.py (test_required_tool_choice_persists_on_followup_turn currently pins 'required' on Turn 2)
  • genkit-anthropic:
    • packages/genkit-anthropic/src/genkit_anthropic/_models.py (_to_anthropic_tool_choice(request.tool_choice, ...) sends {'type': 'any'} on every turn; also ensure output_config / thinking compatibility on Turn 1 vs. Turn 2+)
  • Alternative (core): Consider lifting _effective_tool_choice(request) into core packages/genkit/src/genkit/_ai/_generate.py (to_model_request) so every model plugin inherits first-turn 'required' $\rightarrow$ follow-up 'auto' semantics uniformly, while preserving per-user-turn enforcement in multi-turn chats.

Expected Behavior

res = await ai.generate(
    model='openai/gpt-4o',  # or 'anthropic/claude-sonnet-4-5'
    prompt='Check sesame stock and summarize.',
    tools=[check_inventory],
    tool_choice='required',
)
# Turn 1 -> sends tool_choice='required' (or {'type': 'any'}) to force initial tool call
# Turn 2 -> relaxes to tool_choice='auto' (or {'type': 'auto'}) so the model can call another tool or return its final answer

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions