Claude Cookbook

Tool choice

Control how Claude selects tools using tool_choice parameter for forced or auto selection.

Alex Albert
Alex Albert
@alexalbertt
Published on May 15, 2024
Was this page helpful?

Tool choice

Tool use supports a parameter called tool_choice that allows you to specify how you want Claude to call tools. In this notebook, we'll take a look at how it works and when to use it. Before going any further, make sure you are comfortable with the basics of tool use with Claude.

When working with the tool_choice parameter, we have three possible options:

  • auto allows Claude to decide whether to call any provided tools or not
  • tool allows us to force Claude to always use a particular tool
  • any tells Claude that it must use one of the provided tools, but doesn't force a particular tool

Let's take a look at each option in detail. We'll start by importing the Anthropic SDK:

from anthropic import Anthropic
client = Anthropic()
MODEL_NAME = "claude-haiku-5-5"

Model note: this notebook uses claude-haiku-5-5 because forced tool_choice ({"type": "tool"} / {"type": "any"}) is accepted on Claude Haiku 5.5 but rejected with a 400 by Claude Opus 5.5, Claude Sonnet 5.5, and Claude Fable 5.1. On those models use tool_choice: {"type": "auto"} with an explicit instruction naming the tool, add "strict": true to the tool definition, or use structured outputs (output_config.format). Haiku 5.5 may return thinking blocks before the tool_use block, so read blocks by type rather than by position.

Auto

Setting tool_choice to auto allows the model to automatically decide whether to use tools or not. This is the default behavior when working with tools.

To demonstrate this, we're going to provide Claude with a fake web search tool. We will ask Claude questions, some of which would require calling the web search tool and other which Claude should be able to answer on its own.

Let's start by defining a tool called web_search. Please note, to keep this demo simple, we're not actually searching the web here:

def web_search(topic):
print(f"pretending to search the web for {topic}")
web_search_tool = {
"name": "web_search",
"description": "A tool to retrieve up to date information on a given topic by searching the web",
"input_schema": {
"type": "object",
"properties": {
"topic": {"type": "string", "description": "The topic to search the web for"},
},
"required": ["topic"],
},
}

Next, we write a function that accepts a user_query and passes it along to Claude, along with the web_search_tool.

We also set tool_choice to auto:

tool_choice={"type": "auto"}

Here's the complete function:

from datetime import date
def chat_with_web_search(user_query):
messages = [{"role": "user", "content": user_query}]
system_prompt = f"""
Answer as many questions as you can using your existing knowledge.
Only search the web for queries that you can not confidently answer.
Today's date is {date.today().strftime("%B %d %Y")}
If you think a user's question involves something in the future that hasn't happened yet, use the search tool.
"""
response = client.messages.create(
system=system_prompt,
model=MODEL_NAME,
messages=messages,
max_tokens=2048,
tool_choice={"type": "auto"},
tools=[web_search_tool],
)
last_content_block = response.content[-1]
if last_content_block.type == "text":
print("Claude did NOT call a tool")
print(f"Assistant: {last_content_block.text}")
elif last_content_block.type == "tool_use":
print("Claude wants to use a tool")
print(last_content_block)

Let's start with a question Claude should be able to answer without using the tool:

chat_with_web_search("What color is the sky?")
Claude did NOT call a tool
Assistant: The sky is usually blue during the day. This happens because of Rayleigh scattering: sunlight passes through the atmosphere, and shorter blue wavelengths scatter off air molecules more than longer red wavelengths do, so blue light reaches our eyes from all directions.

The sky can look different under other conditions. At sunrise and sunset it often looks orange, pink, or red, because light travels through more atmosphere and the blue is scattered out. On cloudy days it can look gray or white, and at night it is dark.

When we ask "What color is the sky?", Claude does not use the tool. Let's try asking something that Claude should use the web search tool to answer:

chat_with_web_search("Who won the most recent Miami Grand Prix?")
Claude wants to use a tool
ToolUseBlock(id='toolu_01SpdeYBZfEhEMHUgC45MLau', caller=DirectCaller(type='direct'), input={'topic': 'Miami Grand Prix 2026 race winner'}, name='web_search', type='tool_use')

When we ask about the most recent Miami Grand Prix, Claude cannot be sure its knowledge is current, so it uses the web search tool!

Let's try a few more examples:

# Claude should NOT need to use the tool for this:
chat_with_web_search("Who won the superbowl in 2022?")
Claude did NOT call a tool
Assistant: The **Los Angeles Rams** won Super Bowl LVI in February 2022, beating the Cincinnati Bengals 23–20 at SoFi Stadium in Inglewood, California.
# Claude SHOULD use the tool for this:
chat_with_web_search("Who won the most recent Super Bowl?")
Claude wants to use a tool
ToolUseBlock(id='toolu_01538T8powgXWLgxc53avSnj', caller=DirectCaller(type='direct'), input={'topic': 'Super Bowl LX winner February 2026'}, name='web_search', type='tool_use')

Your Prompt Matters!

When working with tool_choice of auto, it's important that you spend time to write a detailed prompt. Often, Claude can be over-eager to call tools. Writing a detailed prompt helps Claude determine when to call a tool and when not to. In the above example, we included specific instructions in the system prompt:

system_prompt=f"""
Answer as many questions as you can using your existing knowledge.
Only search the web for queries that you can not confidently answer.
Today's date is {date.today().strftime("%B %d %Y")}
If you think a user's question involves something in the future that hasn't happened yet, use the search tool.
"""

Forcing a specific tool

We can force Claude to use a particular tool using tool_choice. In the example below, we've defined two simple tools:

tools = [
{
"name": "print_sentiment_scores",
"description": "Prints the sentiment scores of a given tweet or piece of text.",
"input_schema": {
"type": "object",
"properties": {
"positive_score": {
"type": "number",
"description": "The positive sentiment score, ranging from 0.0 to 1.0.",
},
"negative_score": {
"type": "number",
"description": "The negative sentiment score, ranging from 0.0 to 1.0.",
},
"neutral_score": {
"type": "number",
"description": "The neutral sentiment score, ranging from 0.0 to 1.0.",
},
},
"required": ["positive_score", "negative_score", "neutral_score"],
},
},
{
"name": "calculator",
"description": "Adds two number",
"input_schema": {
"type": "object",
"properties": {
"num1": {"type": "number", "description": "first number to add"},
"num2": {"type": "number", "description": "second number to add"},
},
"required": ["num1", "num2"],
},
},
]

Our goal is to write a function called analyze_tweet_sentiment that takes a tweet and prints a basic sentiment analysis of that tweet. Eventually we will "force" Claude to use our sentiment analysis tool, but we'll start by showing what happens when we do not force the tool use.

In this first "bad" version of the analyze_tweet_sentiment function, we provide Claude with both tools. For the sake of comparison, we'll start by setting tool_choice to "auto":

tool_choice={"type": "auto"}

Please note that we are deliberately not providing Claude with a well-written prompt, to make it easier to see the impact of forcing the use of a particular tool.

def analyze_tweet_sentiment(query):
response = client.messages.create(
model=MODEL_NAME,
max_tokens=4096,
tools=tools,
tool_choice={"type": "auto"},
messages=[{"role": "user", "content": query}],
)
print(response)

Let's see what happens when we call the function with the tweet "Holy cow, I just made the most incredible meal!"

analyze_tweet_sentiment("Holy cow, I just made the most incredible meal!")
Message(id='msg_011Cg4UE1eK9vKN67pFtQGAE', container=None, content=[ThinkingBlock(signature='CAQS3wQKVAgSGAIiQMDKvq1uCMHUFMYMLRqz9mc8ezXulDzkMGkuTQHJIrvlB06LzRbMsiGV9wrypeySQOKKwY0o/2Ue/a3Y58uWy0coATgBQgh0aGlua2luZxIMce+sUvV2rOuYXjsCGgz/XltMeJn60CZXp5wiMIA8qT8ZyWA5Kus+50RkRuihJ1IK0DW/cuTU6uqTVQWd02B9p+ck0VGPe2A1ElNw0yq4Axt7+RN5Ah7vznLvh/csm6LWn73juCvwYET8rIl1EArIVDdU24vIb3Ot5CVsRh16xSMsrvuF1MPvQ52nLZy7y7B47ZgNxHE8SxwQ9xMbtwyb5Y3fWqetr+YfzJ1R1Siz2u6+21D4+QRQQYhyUyjBO7M2XwpQsM1Hxw8J5u3CUFQTyde3aj2pR+p6fmR8Xct/+/YjBlTvkr9vr3dnOqmUZ8O7AuRA8WhG3EB6Ja1pLPXqD/cvp8gc5AT4/hVohJymzSvCG4lS+bwXAz5q7d1EiVnW1xYeCwepie3FEEBr4h7z2ZBbG/6NBcA+ATyUiprE+sfaPM0/1dO//tSzgmqElfgXaFskT2j4veYlOdTqN1sYYkFLr2q9CWC+m66oxEKlILZuv75J70mGscNdzSNmpj9U6ZP9XF1fDBShCayoD4ldplrmBYVoIytxhtXK5uK0DWE+ZMhTznOPgaN/pTcXtxxH+JDxTKAia9R8Ybt3lHzmo1Xe+rpMb+c7y3VZ4LPZLLOeN/bBvGCT3UrHzPThmup2iC4Cv/TPfYdCDuMzsblC9pYmsCza1Lm6zgeeBkVIflyviJvP9ynaGAI=', thinking="The user says a sentence. They didn't ask for sentiment analysis explicitly. The tool prints sentiment scores of a given text, but the tool takes scores as input, not text. Odd tool: it takes positive/negative/neutral scores as parameters. I could compute the sentiment myself and call the tool. But is that appropriate? The user just made an exclamation. Perhaps they want a reply. I should respond warmly and ask what meal. Maybe don't call tools. Keep short.", type='thinking'), TextBlock(citations=None, text="That sounds like a great cooking win! What did you make? I'd love to hear about it, whether it was a new recipe or something you improvised.", type='text')], model='claude-haiku-5-5', role='assistant', stop_details=None, stop_reason='end_turn', stop_sequence=None, type='message', usage=Usage(cache_creation=CacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0), cache_creation_input_tokens=0, cache_read_input_tokens=0, inference_geo='global', input_tokens=641, output_tokens=204, output_tokens_details=OutputTokensDetails(thinking_tokens=159), server_tool_use=None, service_tier='standard', iterations=[{'input_tokens': 641, 'output_tokens': 204, 'cache_read_input_tokens': 0, 'cache_creation_input_tokens': 0, 'cache_creation': {'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'type': 'message'}]), diagnostics=None)

Claude does not call our sentiment analysis tool:

"That's awesome! It sounds like you're really excited about what you cooked up! ... What did you make?"

Next, let's imagine someone tweets this: "I love my cats! I had four and just adopted 2 more! Guess how many I have now?"

analyze_tweet_sentiment(
"I love my cats! I had four and just adopted 2 more! Guess how many I have now?"
)
Message(id='msg_011Cg4UE7w5FcmGvkmnTu5VZ', container=None, content=[ThinkingBlock(signature='CAQS3wQKVAgSGAIiQJ7UaMKDMvsTIn1kJ0Te9nRzODOnCAoYHJi+CGhKk5UDoE4DeWUxufJOoIxpqttyVQh7wM92v7yThy+IoTtd03MoATgBQgh0aGlua2luZxIMNFG7YQbnyz2X1D/TGgxXg2nr0W4L8ZstJwkiMF5b0+gbQPn/feXqPS2jpUzsr6t1S4yFIHieCLh57xTWkooGV20IQe+UNKWUZaUVHCq4A3Cui6nrsekoJzDtQwDbsS88joumwS8jQIkBE4IaLYXQ5egQn55YJg1vdo7jWHU2+YgpfwNoZ+D/dKDbYxtvxkKZLyyo8ZL8caV9COfVJlcIbyWiL7QImqjJ58elKjt9ylwb1W6ML6mgLVt3UX/RKwA/eXXDUgHlAzn7MGM869AdSRbI6vuA9+8PgXgwWJQCa9Uo7WwwtJ4NYILHYUdyYWA43fDb5raTKAEFZ638DnupUnsL9SpRU0k24iInBxEoOoshgQsWpwayrFjgBzvsUtv6BCU5VnJYF09P+QPq05xYj/ssE0J/XL9Yu8M3HXJtuzFirD5YTI8R9D5H/GrvzkM5dXhmXobacc4zC5YC6MZ3CveLLPMJ2D2WRf/SBo1t3+0N25Gp+yZ2Tc4Gu37jWykiNDLZaSPrOvgAVBmPT+h0IIfFxsNjK3xaq7xeOiUMbbWdUzW0FlxkdjTUW4ZUJep9JksYQglCuGLmyuidnyIdb+XwadKO/GWglT1hNX15S+3Mi3BmQGojGfUNmvawbfuwmdvsFXZpCZyiaZLcNsqxu1axCgCvpWmVgiEwEQKRLvvLaFdS3BeQGAI=', thinking="The user asks a simple math question: 4 + 2 = 6. I can use calculator tool. Should I? It's simple; could just answer. The tool exists; using it is fine. I'll call calculator with 4 and 2.", type='thinking'), ToolUseBlock(id='toolu_01DoLR6PzfydqVfjbS9iRgQ6', caller=DirectCaller(type='direct'), input={'num1': 4, 'num2': 2}, name='calculator', type='tool_use')], model='claude-haiku-5-5', role='assistant', stop_details=None, stop_reason='tool_use', stop_sequence=None, type='message', usage=Usage(cache_creation=CacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0), cache_creation_input_tokens=0, cache_read_input_tokens=0, inference_geo='global', input_tokens=652, output_tokens=144, output_tokens_details=OutputTokensDetails(thinking_tokens=73), server_tool_use=None, service_tier='standard', iterations=[{'input_tokens': 652, 'output_tokens': 144, 'cache_read_input_tokens': 0, 'cache_creation_input_tokens': 0, 'cache_creation': {'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'type': 'message'}]), diagnostics=None)

Claude wants to call the calculator tool:

ToolUseBlock(id='toolu_01...', input={'num1': 4, 'num2': 2}, name='calculator', type='tool_use')

Clearly, this current implementation is not doing what we want (mostly because we set it up to fail).

Next, let's force Claude to always use the print_sentiment_scores tool by updating tool_choice:

tool_choice={"type": "tool", "name": "print_sentiment_scores"}

In addition to setting type to tool, we must provide a particular tool name.

def analyze_tweet_sentiment(query):
response = client.messages.create(
model=MODEL_NAME,
max_tokens=4096,
tools=tools,
tool_choice={"type": "tool", "name": "print_sentiment_scores"},
messages=[{"role": "user", "content": query}],
)
print(response)

Now if we try prompting Claude with the same prompts from earlier, it's always going to call the print_sentiment_scores tool:

analyze_tweet_sentiment("Holy cow, I just made the most incredible meal!")
Message(id='msg_011Cg4UECUfkHso53Kieoabs', container=None, content=[ToolUseBlock(id='toolu_01WJoB9kA8sjR17wJ8vK4VCq', caller=DirectCaller(type='direct'), input={'positive_score': 0.95, 'negative_score': 0.02, 'neutral_score': 0.03}, name='print_sentiment_scores', type='tool_use')], model='claude-haiku-5-5', role='assistant', stop_details=None, stop_reason='tool_use', stop_sequence=None, type='message', usage=Usage(cache_creation=CacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0), cache_creation_input_tokens=0, cache_read_input_tokens=0, inference_geo='global', input_tokens=772, output_tokens=90, output_tokens_details=OutputTokensDetails(thinking_tokens=0), server_tool_use=None, service_tier='standard', iterations=[{'input_tokens': 772, 'output_tokens': 90, 'cache_read_input_tokens': 0, 'cache_creation_input_tokens': 0, 'cache_creation': {'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'type': 'message'}]), diagnostics=None)

Claude calls our print_sentiment_scores tool:

ToolUseBlock(id='toolu_01...', input={'positive_score': 0.95, 'negative_score': 0.02, 'neutral_score': 0.03}, name='print_sentiment_scores', type='tool_use')

Even if we try to trip up Claude with a "Math-y" tweet, it still always calls the print_sentiment_scores tool:

analyze_tweet_sentiment(
"I love my cats! I had four and just adopted 2 more! Guess how many I have now?"
)
Message(id='msg_011Cg4UEHS5DckQXLEsK4bp5', container=None, content=[ToolUseBlock(id='toolu_01B4Pdo9ceA6PAqtGNufwPyy', caller=DirectCaller(type='direct'), input={'positive_score': 0.95, 'negative_score': 0.01, 'neutral_score': 0.04}, name='print_sentiment_scores', type='tool_use'), ToolUseBlock(id='toolu_01Rciej4xSiLg62Ff4fumQTk', caller=DirectCaller(type='direct'), input={'num1': 4, 'num2': 2}, name='calculator', type='tool_use')], model='claude-haiku-5-5', role='assistant', stop_details=None, stop_reason='tool_use', stop_sequence=None, type='message', usage=Usage(cache_creation=CacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0), cache_creation_input_tokens=0, cache_read_input_tokens=0, inference_geo='global', input_tokens=783, output_tokens=157, output_tokens_details=OutputTokensDetails(thinking_tokens=0), server_tool_use=None, service_tier='standard', iterations=[{'input_tokens': 783, 'output_tokens': 157, 'cache_read_input_tokens': 0, 'cache_creation_input_tokens': 0, 'cache_creation': {'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'type': 'message'}]), diagnostics=None)

Forcing a tool guarantees that the named tool is called, but it does not stop Claude from calling other tools in the same turn: in the run above it also called calculator in parallel. If you need exactly one tool call, pass disable_parallel_tool_use=True inside tool_choice as well.

Even though we're forcing Claude to call our print_sentiment_scores tool, we should still employ some basic prompt engineering:

def analyze_tweet_sentiment(query):
prompt = f"""
Analyze the sentiment in the following tweet:
<tweet>{query}</tweet>
"""
response = client.messages.create(
model=MODEL_NAME,
max_tokens=4096,
tools=tools,
tool_choice={"type": "auto"},
messages=[{"role": "user", "content": prompt}],
)
print(response)

Any

The final option for tool_choice is any which allows us to tell Claude "you must call a tool, but you can pick which one". Imagine we want to create a SMS chatbot using Claude. The only way for this chatbot to actually "communicate" with a user is via SMS text message.

In the example below, we make a very simple text-messaging assistant that has access to two tools:

  • send_text_to_user sends a text message to a user
  • get_customer_info looks up customer data based on a username

The idea is to create a chatbot that always calls one of these tools and never responds with a non-tool response. In all situations, Claude should either respond back by trying to send a text message or calling get_customer_info to get more customer information.

Most importantly, we set tool_choice to "any":

tool_choice={"type": "any"}
def send_text_to_user(text):
# Sends a text to the user
# We'll just print out the text to keep things simple:
print(f"TEXT MESSAGE SENT: {text}")
def get_customer_info(username):
return {
"username": username,
"email": f"{username}@email.com",
"purchases": [
{"id": 1, "product": "computer mouse"},
{"id": 2, "product": "screen protector"},
{"id": 3, "product": "usb charging cable"},
],
}
tools = [
{
"name": "send_text_to_user",
"description": "Sends a text message to a user",
"input_schema": {
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "The piece of text to be sent to the user via text message",
},
},
"required": ["text"],
},
},
{
"name": "get_customer_info",
"description": "gets information on a customer based on the customer's username. Response includes email, username, and previous purchases. Only call this tool once a user has provided you with their username",
"input_schema": {
"type": "object",
"properties": {
"username": {
"type": "string",
"description": "The username of the user in question. ",
},
},
"required": ["username"],
},
},
]
system_prompt = """
All your communication with a user is done via text message.
Only call tools when you have enough information to accurately call them.
Do not call the get_customer_info tool until a user has provided you with their username. This is important.
If you do not know a user's username, simply ask a user for their username.
"""
def sms_chatbot(user_message):
messages = [{"role": "user", "content": user_message}]
response = client.messages.create(
system=system_prompt,
model=MODEL_NAME,
max_tokens=4096,
tools=tools,
tool_choice={"type": "any"},
messages=messages,
)
if response.stop_reason == "tool_use":
last_content_block = response.content[-1]
if last_content_block.type == "tool_use":
tool_name = last_content_block.name
tool_inputs = last_content_block.input
print(f"=======Claude Wants To Call The {tool_name} Tool=======")
if tool_name == "send_text_to_user":
send_text_to_user(tool_inputs["text"])
elif tool_name == "get_customer_info":
print(get_customer_info(tool_inputs["username"]))
else:
print("Oh dear, that tool doesn't exist!")
else:
print("No tool was called. This shouldn't happen!")

Let's start simple:

sms_chatbot("Hey there! How are you?")
=======Claude Wants To Call The send_text_to_user Tool=======
TEXT MESSAGE SENT: Hey there! I'm doing well, thanks for asking. How can I help you today? If you need help with your account or a previous purchase, please send me your username.

Claude responds back by calling the send_text_to_user tool.

Next, we'll ask Claude something a bit trickier:

sms_chatbot("I need help looking up an order")
=======Claude Wants To Call The send_text_to_user Tool=======
TEXT MESSAGE SENT: I'd be happy to help you look up your order. Could you please provide your username?

Claude wants to send a text message, asking a user to provide their username.

Now, let's see what happens when we provide Claude with our username:

sms_chatbot("I need help looking up an order. My username is jenny76")
=======Claude Wants To Call The get_customer_info Tool=======
{'username': 'jenny76', 'email': 'jenny76@email.com', 'purchases': [{'id': 1, 'product': 'computer mouse'}, {'id': 2, 'product': 'screen protector'}, {'id': 3, 'product': 'usb charging cable'}]}

Claude calls the get_customer_info tool, just as we hoped!

Even if we send Claude a gibberish message, it will still call one of our tools:

sms_chatbot("askdj aksjdh asjkdbhas kjdhas 1+1 ajsdh")
=======Claude Wants To Call The send_text_to_user Tool=======
TEXT MESSAGE SENT: Hi! I'm not sure I understood your message. It looks like it may have been sent by mistake. Could you tell me what you need help with? If you have an account question, please share your username so I can look up your information.
Was this page helpful?