Tool Calling & tool_choice
Forzar al modelo a usar herramientas
El parámetro `tool_choice` controla si el modelo PUEDE, DEBE, o DEBE usar una herramienta específica. Sin tool_choice, el modelo elige: puede responder con texto libre o usar una tool. Con tool_choice={'type': 'tool', 'name': 'extract'}, el modelo DEBE usar esa herramienta — no hay alternativa.
Para structured output, siempre usa `tool_choice` en modo strict. Esto garantiza que la respuesta sea un bloque tool_use con argumentos válidos contra el input_schema, no texto libre que tengas que parsear como JSON.
Los modos de tool_choice: (1) Sin parámetro: modelo elige. (2) {'type': 'tool', 'name': 'X'}: DEBE usar herramienta X. (3) {'type': 'auto'}: modelo elige automáticamente si usar tool o no (default). (4) Modo disabled: no usar herramientas.
import anthropic
client = anthropic.Anthropic()
schema = {...} # JSON Schema
# WITHOUT tool_choice: model can respond with text
response = client.messages.create(
model='claude-opus-4-5',
tools=[{'name': 'extract', 'input_schema': schema}],
messages=[{'role': 'user', 'content': text}]
# no tool_choice → model may respond with .text instead of tool_use
)
# WITH tool_choice: MUST use the tool
response = client.messages.create(
model='claude-opus-4-5',
tools=[{'name': 'extract', 'input_schema': schema}],
tool_choice={'type': 'tool', 'name': 'extract'}, # FORCES tool_use
messages=[{'role': 'user', 'content': text}]
)
# response.stop_reason == 'tool_use' guaranteedDebugging lab
Detecta y corrige el error en el código.
- 01
response = client.messages.create( tools=[extract_tool], messages=[...] ) # no tool_choice data = response.content[0].input # assumes tool_use
- 02
# Multi-tool scenario, no tool_choice response = client.messages.create( tools=[search_tool, calculator_tool, summarize_tool], messages=[...] )
- 03
# Forgot to import tool_choice in parameters response = client.messages.create( model='claude', messages=[...], tools=[...] ) # tool_choice not mentioned