Module 3 · Lesson 2 · 15 min read
Function calling step by step
Function Calling
Introduction
Function calling is the mechanism that lets the model express its wish to use a tool in a structured format that the program understands. In this lesson we trace the full cycle from defining the tool to the final answer, build a simple calling loop in Python, and see the same shape in a real library.
Learning objectives
- Explain the stages of the function calling cycle in order
- Distinguish between the model's text message and the structured tool call request
- Build a simple execution loop that returns the tool's result to the model
- Recognize the shape of function tools in the OpenAI Agents SDK
The basic idea
In the early days of building agents, developers asked the model to write something like "ACTION: search(...)" and then parsed the text with fragile regular expressions. Function calling solved this problem: we send the model a list of tools described in a structured format, and when needed the model returns a call request with the tool's name and its arguments in JSON instead of free text. The program reads this request directly without guessing.
The important thing to remember: the model executes nothing. It generates structured data that says "I want to run tool X with these values", and the final decision to execute lies with the application.
The full cycle in six steps
- Definition: the application sends the model the user's message together with the list of available tools (name, description, input schema).
- Decision: the model decides whether it needs a tool. If it does not, it answers directly in text.
- Request: if it does, it returns a structured call request, which may carry a unique call ID.
- Validation and execution: the application checks the tool's name and the validity of the arguments, then runs the function.
- Return: the application adds the tool's result to the conversation, linked to the same call ID.
- Composition: the model reads the result and decides: call another tool or write the final answer.
Steps 2 to 6 repeat until a final answer appears or the agent reaches a maximum number of cycles.
The shape of the request and the result
The details differ between providers, but the idea is the same. This is a general illustrative shape of a call request and its result:
{
"tool_call": {
"id": "call_01",
"name": "get_exchange_rate",
"arguments": {"base": "USD", "target": "EGP"}
},
"tool_result": {
"call_id": "call_01",
"content": {"rate": 48.5, "source": "demo_data"}
}
}The values here are sample data for explanation only. Notice that call_id in the result matches id in the request; this link is essential when the model requests more than one tool in a single cycle.
A practical example: a simplified calling loop
Let us simulate the full cycle in plain Python. We replace the model with a simple rule function fake_model so the example runs without any API key, just as the academy simulator does:
import json
def get_exchange_rate(base: str, target: str) -> dict:
demo = {("USD", "EGP"): 48.5, ("USD", "SAR"): 3.75}
return {"rate": demo.get((base, target)), "source": "demo_data"}
TOOLS = {"get_exchange_rate": get_exchange_rate}
def fake_model(messages):
# A rule-based fake model: requests the tool first, then answers
last = messages[-1]
if last["role"] == "user":
return {"tool_call": {"id": "call_01", "name": "get_exchange_rate",
"arguments": {"base": "USD", "target": "SAR"}}}
rate = last["content"]["rate"]
return {"text": f"The dollar rate in riyals in the sample data: {rate}"}
messages = [{"role": "user", "content": "What is the dollar rate in riyals?"}]
for turn in range(5): # maximum number of cycles
reply = fake_model(messages)
if "text" in reply:
print(reply["text"])
break
call = reply["tool_call"]
fn = TOOLS.get(call["name"])
if fn is None:
result = {"error": "unknown tool"}
else:
result = fn(**call["arguments"])
messages.append({"role": "tool", "call_id": call["id"], "content": result})
print("Call:", json.dumps(call, ensure_ascii=False))When you replace fake_model with a call to a real model, the structure of the loop stays the same: send, inspect the reply, execute, return, repeat.
The same shape in a real library
In the OpenAI Agents SDK (according to the official documentation, reviewed 18 November 2026, version 0.25.0) the library turns a Python function into a tool through the @function_tool decorator and infers the schema from the type hints, then the Runner manages the loop itself. This example requires installing openai-agents and the OPENAI_API_KEY environment variable:
# Requires: pip install openai-agents and an OPENAI_API_KEY key
from agents import Agent, Runner, function_tool
@function_tool
def get_exchange_rate(base: str, target: str) -> str:
return "3.75 (sample data)"
agent = Agent(name="Assistant",
instructions="Answer currency questions using the tool.",
tools=[get_exchange_rate])
result = Runner.run_sync(agent, "What is the dollar rate in riyals?")
print(result.final_output)If the loop exceeds the max_turns limit, the library raises the MaxTurnsExceeded exception, which is the official equivalent of the maximum in our hand-written example.
Summary
Function calling lets the model express its need for a tool through a structured JSON request instead of free text. The cycle goes through definition, decision, request, validation, execution, return and composition, and repeats until the final answer or the maximum. Linking the result to the call ID is essential when there are several calls. Libraries such as the OpenAI Agents SDK manage this loop for you, but the logic is the same.
Terms
| Term | English | Definition |
|---|---|---|
| Function calling | Function Calling | The model's ability to return a structured request to run a defined function |
| Call request | Tool Call | An object carrying the tool's name, its arguments and a unique ID |
| Arguments | Arguments | The values the model passes to the tool |
| Call ID | Call ID | A code that links a tool's result to the request that produced it |
| Maximum number of cycles | Max Turns | A cap on the number of loop cycles that prevents endless looping |
Review questions
- Put the stages of the function calling cycle in order and explain the application's role in each.
- Why is the call ID important when two tools are requested in a single cycle?
- What is the danger of using eval to run a tool name proposed by the model?
- How does max_turns in the OpenAI Agents SDK correspond to the maximum in the hand-written loop?
References
- OpenAI Agents SDK documentation openai.github.io Reviewed on 2026-11-18
- OpenAI Agents SDK: Running agents openai.github.io Reviewed on 2026-11-18
- Toolformer: Language Models Can Teach Themselves to Use Tools arxiv.org Reviewed on 2026-11-18
