Add tool choice support for Gemini, OpenAI, and Anthropic
Currently there's no way to tell a model it must call a tool. Every gateway hardcodes tool choice to auto (or omits it), so the model is always free to skip the tools and answer with prose instead. For an agent whose whole job is to perform an action (register a payment, create a ticket, call a function), this shows up as the model confidently saying it did the thing without ever calling the tool.
This PR adds a ToolChoice class that is both a value object and a #[ToolChoice] attribute, so an agent can require tool use:
use Laravel\Ai\ToolChoice;
#[ToolChoice(ToolChoice::required)] // must call one of the tools
class RegisterPaymentAgent implements Agent, HasTools
{
// ...
}
You can also force a specific tool, or decide at runtime from the agent's own state:
#[ToolChoice(ToolChoice::tool, 'save_payment')] // must call save_payment
// or dynamically, based on whatever the agent already knows:
public function toolChoice(): ?ToolChoice
{
return $this->readyToSave
? ToolChoice::tool('save_payment')
: null; // let the model decide
}
It resolves the same way as the other agent options like #[MaxSteps] and #[Temperature]: a toolChoice() method wins, falling back to the attribute. The four modes (auto, none, required, a named tool) map to each provider's native field:
- Gemini —
tool_config.function_calling_configwithAUTO/NONE/ANY, plusallowed_function_namesfor a named tool (docs) - OpenAI (Responses) —
tool_choiceset toauto/none/required, or{type: function, name}(docs) - Anthropic —
tool_choiceset toauto/none/any, or{type: tool, name}(docs) - xAI (Responses) —
tool_choiceset toauto/none/required, or{type: function, name} - Chat Completions providers (Mistral, Groq, DeepSeek, OpenRouter, and the configurable OpenAI-compatible provider) —
tool_choiceset toauto/none/required, or{type: function, function: {name}}
An agent that doesn't declare a tool choice behaves exactly as before, so nothing changes for existing code.
One provider-specific note: Anthropic can't force tool use while extended thinking is enabled (the API only allows auto or none in that mode). Instead of silently downgrading a forced choice to auto, which would quietly reintroduce the "said it did it without calling the tool" problem, it throws an InvalidArgumentException so you find out right away.