AI agents › Agent basics
What is function calling? How LLMs ask your app to run tools
Function calling, or tool calling, lets an LLM ask your app to run a tool with chosen arguments. How one round works, shown with a small model you can run.
If you’ve opened the API docs of OpenAI or Anthropic, you’ve probably come across a section called function calling, or tool use. The term also shows up whenever people explain AI agents or MCP. Yet the name can make it sound as if the model reaches out and runs your code by itself, and that picture is a little off.
Function calling is a way for a large language model (LLM) to ask your application to run a function for it. An LLM is a model trained on huge amounts of text to read and write language, and ChatGPT and Claude are built on such models. Your app first tells the model which tools it may use, each with a name, a description, and parameters written in JSON Schema. When the model decides a tool would help, it doesn’t run anything. It writes a structured request that says, in effect, please call this tool with these arguments. Your app runs the function and sends the result back, and the model uses that result to finish its answer.
You hear the term often these days because a lot of what AI apps do now rests on it. On its own, a model knows only what it learned in training and can’t touch anything outside the conversation. So checking today’s weather, looking up an order, or editing a file usually goes through function calling. And AI agents, which you hear about so often lately, are built by repeating this one step many times.
One idea with several names
OpenAI introduced the feature on June 13, 2023, under the name function calling (announcement). It began with gpt-4-0613 and gpt-3.5-turbo-0613, which were fine-tuned to notice when a function the developer had described should be called and to output its arguments as JSON. OpenAI’s current guide says function calling is also known as tool calling (OpenAI guide).
Anthropic calls the same idea tool use, and its docs note that it’s also called function calling (Claude docs). The names differ from company to company, but the idea is the same: the model chooses, and the app runs. Researchers had been exploring the idea a little earlier. In February 2023, Timo Schick and his co-authors posted the Toolformer paper. In it, a model teaches itself when to call tools such as a calculator or a search engine, and with what arguments, from only a few demonstrations per API.
One round, message by message
A round of function calling is a short conversation between your app and the model, and every step becomes a message in that conversation.
| Step | Message | Sent by |
|---|---|---|
| 1 | The user’s request, sent along with the tool list | The app |
| 2 | A tool call naming the tool and its arguments | The model |
| 3 | The tool’s result | The app |
| 4 | The final answer built from that result | The model |
The call in step 2 comes back as a tool_use block in Claude’s API and as an entry in tool_calls in OpenAI’s. Your app runs the function, adds the result as a new message, and calls the model again with the whole conversation, so the model can see what it asked for and what came back while it writes the answer. The parameters are written in JSON Schema, a widely used vocabulary for describing what shape a piece of JSON should have, meaning which fields exist, what type each one is, and which ones are required (JSON Schema).
Watching it with a small model
To see what goes back and forth, I gave Qwen2.5-0.5B-Instruct, a small open model with about half a billion parameters, a Python function that returns the weather for two cities from made-up data. I ran it on my own computer with Hugging Face transformers, so no API service was involved.
import json
from transformers.utils import get_json_schema
WEATHER = {"Seoul": (18, "clear"), "Busan": (21, "cloudy")} # made-up data
def get_weather(city: str):
"""Get the current weather for a city.
Args:
city: The city name, for example Seoul.
"""
temp, sky = WEATHER[city]
return {"city": city, "temp_c": temp, "sky": sky}
print(json.dumps(get_json_schema(get_weather), indent=2))
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city name, for example Seoul."
}
},
"required": [
"city"
]
}
}
}
transformers builds this schema from the function’s name, its type hint, and its docstring (transformers docs). The code inside the function never reaches the model. When I printed the prompt, the chat template had placed this schema in the system prompt as plain text, along with an instruction to wrap any call in tool_call tags. A chat template is the rule that turns a list of messages into the text a model reads. OpenAI’s guide says something similar about its own models: function definitions are injected into the system message in a syntax the model was trained on, which is why they count as input tokens. Now let’s ask about two cities. With do_sample=False, the model picks each token without any randomness, so the output is the same on every run.
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
def generate(messages):
inputs = tok.apply_chat_template(
messages, tools=[get_weather], add_generation_prompt=True,
return_tensors="pt", return_dict=True,
)
out = model.generate(**inputs, max_new_tokens=150, do_sample=False) # greedy
new_tokens = out[0][inputs["input_ids"].shape[1]:]
return tok.decode(new_tokens, skip_special_tokens=True)
messages = [{"role": "user", "content": "What's the weather in Seoul and in Busan?"}]
reply = generate(messages)
print(reply)
<tool_call>
{"name": "get_weather", "arguments": {"city": "Seoul"}}
</tool_call>
<tool_call>
{"name": "get_weather", "arguments": {"city": "Busan"}}
</tool_call>
The model didn’t answer the question. It wrote two calls in the format it was given, one per city. Calling several tools in one turn like this is called parallel calling, and OpenAI’s guide notes that you can turn it off by setting parallel_tool_calls to false. OpenAI’s and Claude’s APIs give each call an ID so that results can be matched to their calls. This template has no IDs, so I send the results back in the same order as the calls. Next comes the app’s part: read the calls, check them, run them, and ask again.
import re
def finish_round(reply, messages):
calls = [json.loads(c) for c in re.findall(r"<tool_call>\n(.*?)\n</tool_call>", reply)]
messages.append({"role": "assistant", "tool_calls": [
{"type": "function", "function": c} for c in calls]})
for call in calls:
city = call["arguments"].get("city")
if call["name"] == "get_weather" and city in WEATHER: # check before running
result = get_weather(city)
else:
result = {"error": f"no weather data for {city}"}
messages.append({"role": "tool", "content": json.dumps(result)})
messages.append({"role": "assistant", "content": generate(messages)})
for m in messages:
print(f"{m['role']:9} |", m.get("content") or json.dumps(calls))
finish_round(reply, messages)
user | What's the weather in Seoul and in Busan?
assistant | [{"name": "get_weather", "arguments": {"city": "Seoul"}}, {"name": "get_weather", "arguments": {"city": "Busan"}}]
tool | {"city": "Seoul", "temp_c": 18, "sky": "clear"}
tool | {"city": "Busan", "temp_c": 21, "sky": "cloudy"}
assistant | The current temperature in Seoul is 18°C and it's clear sky. In Busan, the temperature is 21°C and it's cloudy.
These five lines are the whole round from the table above. The two tool lines are the results my code produced, and the last line is the answer the model built from them. Finally, I asked something that has nothing to do with the weather.
messages = [{"role": "user", "content": "What's the capital of France?"}]
finish_round(generate(messages), messages)
user | What's the capital of France?
assistant | [{"name": "get_weather", "arguments": {"city": "Paris"}}]
tool | {"error": "no weather data for Paris"}
assistant | There is no weather data available for Paris at this time. Could you please specify another location for me to provide information about?
The model called get_weather for Paris anyway. Since my code checks the city before running anything, the call ended as an error message instead of a crash, but the question itself went unanswered. Whether to call a tool is the model’s decision, and a model this small often decides poorly. When I gave the same tool and question to Qwen3-0.6B, a newer model of similar size from the same family, it answered “The capital of France is Paris.” without calling anything.
Making calls follow the schema
Nothing in my example forced the model to keep to the format. It did so only because it was trained to and the prompt asked it to, and Qwen’s function calling guide warns that the model isn’t guaranteed to follow the protocol every time. Structured outputs close that gap. On August 6, 2024, OpenAI introduced Structured Outputs, and setting strict: true in a function definition makes the model’s output match the supplied schema. It works through constrained decoding, which lets the model pick only tokens that keep the output valid under the schema at each step. Claude’s strict tool use works in a similar way to guarantee that tool inputs match the schema. Of course, matching the schema doesn’t make a value right, and “Paris” is a perfectly valid string.
How it relates to agents and MCP
If you repeat this round, letting the model look at each result and choose the next call, you have an AI agent. Anthropic’s Building effective agents (December 19, 2024) describes agents as typically just LLMs using tools based on feedback from their environment, in a loop.
My get_weather lives inside my script, so using it from several AI apps would mean hooking it into each one separately. MCP (Model Context Protocol) is an open-source standard for connecting AI applications to outside systems, and a tool built once as an MCP server can be used by any app that supports it. Function calling still happens between the app and the model, while MCP sits between the app and its tools.
When it fits and what to watch for
Function calling fits when an answer needs something the model doesn’t have, such as fresh or private data, or when the model has to act, like saving a file or sending a message. It also helps when a result must be computed exactly. On the other hand, if the model already knows the answer, or your code always needs the same function anyway, calling the function yourself is cheaper and more predictable. The OpenAI guide also suggests keeping the number of available functions small for higher accuracy.
If you do use it, keep three things in mind. First, treat the arguments a model writes as untrusted input, and check types, ranges, and allowed values before running anything, as my code did with Paris. Second, put a person in the loop for tools with real-world effects. OpenAI’s 2023 announcement already advised a user confirmation step before actions like sending an email, posting online, or making a purchase. Third, write tool descriptions clearly. The OpenAI guide suggests an “intern test”: could an intern use the function correctly with nothing but what you gave the model?
If you’re trying it for the first time
If you’d like to try it, I’d suggest running the example above as it is, then changing the question or adding a second tool and watching what the model chooses. After that, follow the same round trip in the OpenAI guide or the Claude docs. Those APIs parse the calls for you, but the four steps are the same. I ran these examples on October 28, 2026, on macOS with Python 3.13.12, transformers 5.20.2, and PyTorch 2.14.1, on the CPU.
AI tools helped with the research for this post.