Claude API Function Calling Tutorial in Python
What "function calling" means for Claude
Function calling — Anthropic calls it tool use — lets Claude decide, mid-conversation, that it needs to run a function you define (look up weather, query a database, call an internal API) instead of just generating text. Claude doesn't execute anything itself. It returns a structured request telling your Python code which tool to call and with what arguments. Your code runs the function, sends the result back, and Claude uses it to finish its answer.
This tutorial walks through a complete, working Python example: defining a tool schema, sending it with a message, parsing Claude's tool-call response, executing the function, and returning the result in a second request. It works the same way whether you're calling Anthropic's API directly or a pass-through API key service like SubToAPI, since both speak the same Messages API shape.
The basic flow
- You send a request with a
toolsarray describing the functions Claude can call (name, description, JSON schema for parameters). - Claude responds with either normal text or a
tool_usecontent block containing the tool name and input arguments. - Your code runs the actual function with those arguments.
- You send the result back as a
tool_resultblock in a follow-up message. - Claude reads the result and produces the final answer.
This loop can repeat multiple times if Claude needs several tool calls to answer one question.
Setting up the request
Here's a minimal Python example using the anthropic SDK (or any client pointed at a Claude-compatible endpoint). Install the SDK first:
pip install anthropic
Define a tool and send the first message:
import anthropic
import json
client = anthropic.Anthropic(api_key="YOUR_API_KEY")
tools = [
{
"name": "get_weather",
"description": "Get the current weather for a given city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Lisbon"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
]
messages = [
{"role": "user", "content": "What's the weather like in Lisbon right now?"}
]
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=messages
)
print(response.content)
Handling the tool_use block
If Claude decides it needs the tool, response.content will contain a block with type == "tool_use". You need to detect this, run your real function, and reply with the result.
def get_weather(city, unit="celsius"):
# Replace with a real API call
return {"city": city, "temperature": 18, "unit": unit, "condition": "cloudy"}
tool_use_block = next(
(block for block in response.content if block.type == "tool_use"),
None
)
if tool_use_block:
tool_name = tool_use_block.name
tool_input = tool_use_block.input
tool_use_id = tool_use_block.id
if tool_name == "get_weather":
result = get_weather(**tool_input)
# Append Claude's tool_use message and your tool_result to the conversation
messages.append({"role": "assistant", "content": response.content})
messages.append({
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": json.dumps(result)
}
]
})
final_response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
tools=tools,
messages=messages
)
for block in final_response.content:
if block.type == "text":
print(block.text)
That's the full round trip: tool definition, tool call, tool execution, tool result, final answer.
Common mistakes to avoid
- Vague descriptions. Claude decides whether to call a tool based on your
descriptionfield. Be specific about what the function does and when it should be used. - Loose JSON schemas. Mark required fields as
requiredand useenumwhere possible — this cuts down on malformed arguments. - Forgetting multi-step loops. Some tasks need two or three tool calls in sequence (search, then fetch details, then summarize). Your code should loop on
tool_useblocks until Claude returns a final text response instead of assuming one call is enough. - Not handling parallel tool calls. Claude can return multiple
tool_useblocks in a single response. Iterate over all of them, not just the first match. - Skipping error handling for the tool itself. If your function fails, send back a
tool_resultwith an error message rather than crashing — Claude can often recover and ask a clarifying question.
Running this in production
Once function calling works locally, the next problem is usually operational: per-application API keys, rate limits, usage tracking per team or per feature, and streaming the final response back to users. SubToAPI sits in front of your Claude access and exposes the same Messages-API shape with sub_live_... application keys, so the tool-use code above works unchanged — you just point requests at https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY.
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-4-5",
"max_tokens": 1024,
"tools": [{"name": "get_weather", "description": "Get current weather", "input_schema": {"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}],
"messages": [{"role": "user", "content": "Weather in Porto?"}]
}'
This is useful once multiple apps or teammates need Claude access with separate keys, usage visibility, and billing per plan rather than one shared secret passed around in environment variables. See the tool use docs for the full request/response reference, or start with the quickstart if you're setting up access for the first time. Plans start at Solo for individual projects, with Team and Scale tiers for multi-seat setups — details on pricing.
Can Claude call multiple tools in one turn?
Yes. A single response can include several tool_use blocks at once. Loop over all blocks in response.content, execute each matching function, and return all corresponding tool_result blocks in the next message before asking for a final answer.
Does function calling work with streaming?
Yes, but tool_use blocks arrive as accumulated JSON deltas during a stream, so you need to buffer the input argument chunks until the block is complete before parsing it as JSON. See the streaming docs for the event sequence.
What's the difference between tool use and plain prompting for JSON output?
Tool use guarantees a structured schema validated against your input_schema, and Claude explicitly signals when it's calling a function versus answering directly. Prompting for JSON in free text is less reliable — there's no schema enforcement and no clear signal to your code about whether the output is a tool call or a regular response.