How to use Claude's tool_use (function calling) feature in Python. Define tools, let Claude decide when to call them, and handle results.
Tool use lets Claude call external functions — web search, calculators, databases, APIs — and incorporate the results into its response.
import anthropic
import json
client = anthropic.Anthropic()
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a city. Returns temperature in Celsius and conditions.",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g. 'London' or 'New York'"
}
},
"required": ["city"]
}
}
]
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=[{"role": "user", "content": "What's the weather in Paris?"}]
)
print(response.stop_reason) # "tool_use" if Claude wants to call a tool
def get_weather(city: str) -> dict:
# Replace with real API call
return {"temperature": 18, "conditions": "Partly cloudy", "city": city}
def run_agent(user_message: str) -> str:
messages = [{"role": "user", "content": user_message}]
while True:
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=tools,
messages=messages
)
if response.stop_reason == "end_turn":
return response.content[0].text
if response.stop_reason == "tool_use":
# Find all tool_use blocks
tool_results = []
for block in response.content:
if block.type == "tool_use":
if block.name == "get_weather":
result = get_weather(**block.input)
tool_results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(result)
})
# Append assistant turn and tool results
messages.append({"role": "assistant", "content": response.content})
messages.append({"role": "user", "content": tool_results})
print(run_agent("What's the weather in Paris and Tokyo?"))
tools = [
{
"name": "search_web",
"description": "Search the web for recent information.",
"input_schema": {
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"]
}
},
{
"name": "calculate",
"description": "Evaluate a mathematical expression.",
"input_schema": {
"type": "object",
"properties": {"expression": {"type": "string", "description": "e.g. '(15 * 4) / 2'"}},
"required": ["expression"]
}
}
]
For the Node.js equivalent, see the tool use Node.js example. To estimate token costs for tool-heavy workloads, use the Claude API Cost Calculator.