Article
anthropic-tool-useclaude-3function-callingagentic-aipythonapi-integrationstructured-output
Get Started with Anthropic Tool Use for Claude
Enable Claude to interact with external APIs and functions. Define your tools, let Claude decide which to call, and process the results. This allows you to build more powerful, data-aware applications by connecting Claude to your own services.
beginner15 min4 steps
The play
- Set Up Your EnvironmentInstall the official Python library and configure your API key. The client will automatically read the key from the `ANTHROPIC_API_KEY` environment variable.
- Define Your ToolsCreate a list of tools Claude can use. Each tool needs a name, description, and an `input_schema` following the JSON Schema format. This structure tells Claude what the tool does and what arguments it expects.
- Make the Initial API CallSend your prompt and the tool definitions to Claude. If the model determines a tool is needed, the response will stop and include a `tool_use` content block instead of a final answer. This block contains the tool name and arguments.
- Execute the Tool and Get the Final AnswerParse the `tool_use` block from the response. Execute your corresponding local function with the provided arguments. Then, using Anthropic Tool Use, send the tool's output back to Claude in a new message to get a final, natural language response.
Starter code
import os
import json
import anthropic
# Assumes ANTHROPIC_API_KEY is set as an environment variable
client = anthropic.Anthropic()
def get_weather(location):
"""Mock function to get weather. In a real app, this would call a weather API."""
if "san francisco" in location.lower():
return json.dumps({"location": "San Francisco", "temperature": "72", "forecast": "Sunny"})
elif "tokyo" in location.lower():
return json.dumps({"location": "Tokyo", "temperature": "65", "forecast": "Cloudy"})
else:
return json.dumps({"location": location, "temperature": "unknown"})
# Define the available tools
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a specific location.",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g., San Francisco, CA"
}
},
"required": ["location"]
}
}
]
user_prompt = "What's the weather like in San Francisco?"
print(f"\nš¤ User: {user_prompt}")
# 1. First API call: Send the prompt and tools to Claude
message = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
messages=[{"role": "user", "content": user_prompt}],
tools=tools,
tool_choice={"type": "auto"}
)
print("\nš¤ Assistant: Initial response")
print(message)
# 2. Check if the model wants to use a tool
tool_calls = [block for block in message.content if block.type == "tool_use"]
if not tool_calls:
print("\nš¤ Assistant: No tool use requested. Final answer:")
print(message.content[0].text)
else:
print("\nš ļø Tool call(s) requested:")
tool_results = []
for tool_call in tool_calls:
tool_name = tool_call.name
tool_input = tool_call.input
tool_use_id = tool_call.id
print(f" - Tool: {tool_name}, Input: {tool_input}")
# 3. Execute the tool
if tool_name == "get_weather":
tool_output = get_weather(location=tool_input.get("location"))
tool_results.append({
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": tool_output
})
print("\nš Sending tool results back to the model...")
# 4. Second API call: Send tool results back to the model
response_message = client.messages.create(
model="claude-3-sonnet-20240229",
max_tokens=4096,
messages=[
{"role": "user", "content": user_prompt},
{"role": "assistant", "content": message.content},
{"role": "user", "content": tool_results}
],
tools=tools
)
print("\nš¤ Assistant: Final response after tool use:")
print(response_message.content[0].text)