Function calling explained: how LLM tool calls work, with Python

The short version
- Function calling (tool calling) is how an LLM asks your app to run a function. The model returns a function name and arguments; your code runs it.
- In the OpenAI format you send
tools, receivetool_calls, and return each result as arole: "tool"message. That is at least two requests. - When the model asks for several calls at once, send back every result before the next request.
- Use structured output when you only need JSON in a fixed shape. Use tool calls when the model has to reach something outside itself.
- Tool definitions cost input tokens, and the cost varies by model. On the same request we measured a gap of about eight times between three models.
A model does not know today's stock level or where an order is. You hand it your app's functions as tools, and it asks for one when it needs it. The code below was run against FastMetal. For the basics of calling a model over HTTP, see what an LLM API is.
What function calling is
With function calling, the model replies with a request ("call this function with these arguments") where it would otherwise write text. The work splits three ways:
- The model decides which function to call and with what arguments.
- Your app runs the function and sends the result back.
- The model writes the final answer from that result.
This is the way in for anything the model cannot reach alone: a database lookup, a stock check, an internal API. Retrieval can be built the same way, with search passed in as a function.
Function calling, tool calling, tool use
They are the same mechanism. OpenAI launched it as function calling in 2023 and later renamed the parameter from functions to tools, so it is also called tool calling. Anthropic calls it tool use. The functions and function_call fields in older tutorials are the legacy format.
The round trip
In the OpenAI Chat Completions format, a tool call takes four steps:
- The app sends the user's message and
tools, the list of functions the model may use. - The model returns
tool_calls: function names and arguments. - The app runs each function and appends the result as a
role: "tool"message. - The app sends the whole conversation again, and the model returns its answer.
OpenAI's Responses API uses a different shape; this post sticks to Chat Completions.
The request: tools and tool_choice
Each function is defined with JSON Schema. The model reads the description to decide whether to call it, so write it to say plainly what the function is for. tool_choice controls how calls happen:
| Value | Behavior |
|---|---|
"auto" | Call a function only when needed (default) |
"none" | Answer in text, call nothing |
"required" | Call at least one function |
{"type": "function", "function": {"name": "..."}} | Call this function |
The response: finish_reason and tool_calls
When the model decides to use a function, it sets finish_reason to "tool_calls" and returns the list of calls:
"tool_calls": [{
"id": "call_...",
"type": "function",
"function": {
"name": "get_order_status",
"arguments": "{\"order_id\": \"A-1001\"}"
}
}]
argumentsis a JSON string. Parse it withjson.loads()before you use it.idties each result to its call. In our runs the ids started withcall_,tooluse_orchatcmpl-tool-, depending on the model. Pass back whatever you received.- A
finish_reasonof"stop"means the model answered without a tool.
Returning results: role tool and tool_call_id
Append the assistant message that holds tool_calls to the history, then one role: "tool" message per call, with tool_call_id set to that call's id. Then send the conversation again.
A working example in Python
FastMetal speaks the OpenAI API, so the official OpenAI SDK works with only base_url changed. This example passes one function that looks up an order's shipping status.
import json
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["FASTMETAL_API_KEY"],
base_url="https://api.fastmetal.ai/v1",
)
MODEL = "gemini-flash-lite-free"
def get_order_status(order_id: str) -> dict:
# In a real app this queries your order database or API
return {"order_id": order_id, "status": "shipped"}
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its order number",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order number, e.g. A-1001"},
},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "What's the status of orders A-1001 and A-1002?"}]
# Request 1: the model picks the function and arguments
first = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg) # put the assistant message with tool_calls back in the history
for call in msg.tool_calls: # parallel calls arrive as several entries
args = json.loads(call.function.arguments) # JSON string to dict
if call.function.name == "get_order_status":
result = get_order_status(args["order_id"])
else:
result = {"error": "unknown function"}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
# Request 2: the model answers from the results
final = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)
On October 6, 2026 we ran this code on gemini-flash-lite-free, deepseek-v4-flash and anthropic-claude-haiku-4-5. All three returned two calls on the first request and an answer on the second. To turn it into a loop, follow the tool calling tutorial. To get a key, start with the API getting-started guide.
Parallel tool calls
When one response carries several calls, as in the example above, those are parallel tool calls. Independent lookups go out together with no extra round trips.
- Assume
tool_callscan hold more than one entry, and loop over it. - Return a result, with its
tool_call_id, for every call. - Collect all the results before the next request.
Some models return an error if even one result is missing. When order matters, set parallel_tool_calls to false to limit each turn to zero or one call (whether a model honors it varies).
Structured output or tool calls
Both deal in JSON, for different jobs.
| Structured output | Tool calls | |
|---|---|---|
| You send | A JSON Schema in response_format | Function definitions in tools |
| You get | The answer itself, in the schema's shape | A function name and arguments |
| Round trips | One | Two or more |
| Good for | Extraction, classification, summaries in a fixed shape | Search, database lookups, calling external APIs |
If you only need fields back as JSON, structured output is simpler: one request. To fetch outside data or make something happen, use tool calls. The structured output tutorial shows the first.
Support and token cost differ by model
FastMetal passes OpenAI-format tool calls and structured output through, so you can try the same code on different labs' models by changing model. Support and accuracy still differ by model. Open a model's page from the model catalog and check that tools is in its supported parameters.
Tool definitions are added to the prompt on every request and billed as input tokens. We compared input tokens on the first request of the code above:
| Model | Input tokens (prompt_tokens) |
|---|---|
| gemini-flash-lite-free | 91 |
| deepseek-v4-flash | 319 |
| anthropic-claude-haiku-4-5 | 706 |
Measured through FastMetal on October 6, 2026, when the prompt and the function description were in Japanese; English text gives slightly different counts. Same request, about eight times apart, because each model builds tool definitions into its prompt in its own way. Text models are billed per million tokens (see pricing), so in a tool-heavy app the model choice moves your bill, and the definitions eat into the context window too.
Set model to "auto" and FastMetal routes the request to the cheapest model that meets its needs, tools included. You pay the chosen model's price.
Next: agents and MCP
Repeat tool calls until the model stops asking for one, and you have the basic shape of an agent. Coding agents such as Claude Code work this way. One task can resend the conversation tens or hundreds of times, so most of the cost is input tokens.
MCP (Model Context Protocol) is a shared standard for publishing and connecting tools. Tools from an MCP server still reach the model as tools, by way of the client. See what MCP is.
FastMetal's own MCP server (https://mcp.fastmetal.ai/mcp) adds tools such as asking another model or generating an image to Claude Code and other clients with one command. Setup is in the MCP guide.
Common mistakes
Using arguments as a string
Treat arguments as a dict without json.loads() and the code fails on the spot.
Forgetting the assistant message
The assistant message with tool_calls goes into the history before the results. Some models attach their own fields to it, so append it as received; do not rebuild it.
No cap on the loop
A model can repeat the same call, and the charges add up. Cap the number of round trips. On FastMetal you can also give each API key its own balance cap.
Trusting the arguments
Models sometimes return a function name that does not exist or leave out a required field. Validate arguments the way you validate user input, and put a human check in front of anything that moves money or deletes data. Passing only the functions a step needs also cuts wrong picks.
FAQ
Does the model run the function?
No. The model only returns which function to call and with what arguments. Your code runs it, sends the result back, and the model writes the final answer.
How is RAG different from function calling?
RAG retrieves relevant documents and adds them to the prompt before the model answers. Function calling is the model asking your app to run a function. Pass search in as a function and you can build RAG on top of function calling.
How is function calling different from MCP?
Function calling is the API mechanism through which a model and an app exchange function calls. MCP is a protocol that standardizes how tools are published and connected. Tools connected through MCP still reach the model as tools.
Which model should I start with?
The code in this post runs on gemini-flash-lite-free, a $0 model, so you can test the round trip before you choose a paid one. Paid models draw on prepaid credit, with a $5 minimum top-up.