How to use function calling with Claude API
Quick answer
Use the
Anthropic Python SDK to call Claude models with the functions parameter specifying your function schema. The API returns structured JSON in message.function_call.arguments for easy parsing and integration.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the anthropic Python SDK and set your API key as an environment variable.
pip install anthropic>=0.20 Step by step
This example demonstrates how to call a Claude model with a function schema to get structured JSON output representing a user profile.
import os
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
function_schema = {
"name": "create_user_profile",
"description": "Create a user profile with name, age, and email.",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "Full name of the user"},
"age": {"type": "integer", "description": "Age of the user"},
"email": {"type": "string", "description": "Email address"}
},
"required": ["name", "age", "email"]
}
}
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
system="You are a helpful assistant that outputs structured JSON.",
messages=[{"role": "user", "content": "Generate a user profile for Alice, age 30, email alice@example.com."}],
functions=[function_schema],
function_call={"name": "create_user_profile"},
max_tokens=300
)
# Extract the structured JSON arguments from the function call
structured_output = response.content[0].function_call.arguments
print(structured_output) output
{
"name": "Alice",
"age": 30,
"email": "alice@example.com"
} Common variations
- Use different Claude models like
claude-sonnet-4-5for improved coding or reasoning. - Call multiple functions by passing a list of function schemas in
functions. - Use
function_call="auto"to let Claude decide which function to call based on the prompt. - Implement async calls with
asyncioandclient.messages.acreate()for concurrency.
Troubleshooting
- If you get a
400 Bad Request, verify your function schema is valid JSON Schema. - If
function_call.argumentsis empty, ensurefunction_callparameter matches a function name infunctions. - Check your API key environment variable
ANTHROPIC_API_KEYis set correctly.
Key Takeaways
- Use the
functionsparameter to define JSON Schema for structured outputs with Claude. - Set
function_callto specify which function Claude should invoke for structured data. - Parse
response.content[0].function_call.argumentsto get the structured JSON result. - Use
claude-3-5-sonnet-20241022orclaude-sonnet-4-5for best coding and structured output support. - Validate your function schema and environment variables to avoid common errors.