Hello! Welcome back to our module on the Foundations of AI Agents.
In our last lesson, we built a conceptual blueprint for an AI agent, identifying its core components: reasoning, planning, action, and memory. We established that for an agent to be useful, it must be able to interact with the outside world. The "Action" component, or tool use, is what makes this possible.
Today, we're moving from theory to practice. We will implement the primary mechanism that allows an LLM to use tools: function calling. This is the bridge between the LLM's "brain" and its "hands." By the end of this lesson, you will be able to implement function calling to give an LLM access to external tools, enabling it to perform actions beyond simple text generation.
What is Function Calling?
At its core, function calling allows an LLM to request that your application run a function on its behalf. Instead of generating a final text answer, the model generates a structured JSON object containing the name of a function it wants to call and the arguments to use.
Crucially, the LLM does not execute the function itself. Your application code receives this request, runs the corresponding function (e.g., calls a database, queries an external API), and then sends the result back to the LLM. The LLM then uses this new information to formulate its final response.

Think of it this way: the LLM is a project manager that can't leave its office. It can analyze a request and delegate tasks, but it needs an employee (your code) to go out into the world, gather information, and report back. Function calling is the formal process for this delegation.
The Function Calling Workflow: A Conversational Handshake
Function calling isn't a single API call but a multi-step conversation between your application and the LLM. The official OpenAI documentation provides a clear overview of this flow.
The OpenAI documentation on Function Calling clearly outlines the process. We'll follow its structure to understand the end-to-end workflow.
Please read the sections titled How it works and The tool calling flow. Focus on understanding the five high-level steps. Don't worry about the code examples just yet; we'll cover those next.
As you've just read, the process can be broken down into five key steps:
- Define Tools & Make Request: Your application sends a request to the LLM. This request includes not only the user's prompt but also a list of available "tools" (your functions), described in a specific format.
- Receive a Tool Call from the LLM: The LLM analyzes the prompt. If it determines that it needs to use one of the tools you provided, it responds with a special message containing a
tool_callsobject. This object specifies the function name and the arguments it has inferred from the prompt. - Execute the Tool: Your application code parses this
tool_callsobject. You then use the function name and arguments to execute your actual Python function. - Send the Result Back: You make a second API call to the LLM. This time, you include the history of the conversation so far, plus the output from your function call. This gives the model the context it needs.
- Receive Final Response: Now equipped with the information from the tool, the LLM generates a final, natural-language response that answers the user's original query.
This conversational loop is fundamental to how agents operate.
A Practical Implementation
Let's build a simple example to solidify this workflow. We'll give the model a tool to get the current weather for a specific location.
Step 1: Defining the Tool Schema
First, we need to describe our get_current_weather function to the model using a JSON schema. This schema tells the model the function's name, its purpose, and the parameters it accepts. The description fields are critical—this is how the model understands when and how to use your tool.
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g., San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]
This tells the model: "You have a tool named get_current_weather. Use it when you need to find the weather. It requires a location (a string) and optionally accepts a unit which must be either 'celsius' or 'fahrenheit'."
Step 2: The Full Code Workflow
Now, let's write the Python code to orchestrate the entire five-step process. We'll use the openai library.
First, let's define our actual Python function. In a real application, this would call a weather API. For now, it will just return a mock response.
import openai
import json
# For this example, we'll use a mock function.
def get_current_weather(location, unit="fahrenheit"):
"""Get the current weather in a given location"""
if "tokyo" in location.lower():
return json.dumps({"location": "Tokyo", "temperature": "10", "unit": "celsius"})
elif "san francisco" in location.lower():
return json.dumps({"location": "San Francisco", "temperature": "72", "unit": "fahrenheit"})
elif "paris" in location.lower():
return json.dumps({"location": "Paris", "temperature": "22", "unit": "celsius"})
else:
return json.dumps({"location": location, "temperature": "unknown"})
Next, let's implement the conversational loop.
# Initialize the OpenAI client
# Ensure your OPENAI_API_KEY environment variable is set
client = openai.OpenAI()
# Step 1: Define tools and send the first request
messages = [{"role": "user", "content": "What's the weather like in San Francisco?"}]
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "Get the current weather in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city and state, e.g., San Francisco, CA",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
},
}
]
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=messages,
tools=tools,
tool_choice="auto", # auto is default, but we'll be explicit
)
response_message = response.choices[0].message
tool_calls = response_message.tool_calls
# Step 2: Check if the model wants to call a tool
if tool_calls:
# Step 3: Execute the function
# In a real app, you would loop through all tool_calls
tool_call = tool_calls[0]
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
print(f"LLM wants to call {function_name} with arguments: {function_args}")
# Call the corresponding function
function_response = get_current_weather(
location=function_args.get("location"),
unit=function_args.get("unit"),
)
# Step 4: Send the info back to the model
# Append the assistant's response and the function's output to the message history
messages.append(response_message) # Assistant's response (the tool call)
messages.append(
{
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
}
)
# Make the second API call
second_response = client.chat.completions.create(
model="gpt-4-turbo",
messages=messages,
)
# Step 5: Get the final response
final_response = second_response.choices[0].message.content
print(f"Final response: {final_response}")
When you run this code, you'll see the LLM first decide to call the function, and then, after getting the result, provide a natural language answer like "The weather in San Francisco is 72°F."
A Software Engineer's Perspective on Function Calling
The Martin Fowler article "Function calling using LLMs" provides an excellent perspective on this topic that should resonate with your background as a software engineer. It frames function calling not just as an API feature, but as a core pattern for building robust, agentic applications with clear separation of concerns.
The article 'Function calling using LLMs' by Kiran Prakash on MartinFowler.com demonstrates how to build a 'Shopping Agent' using this pattern. It's a great practical example that aligns with a software engineering mindset.
Please read from the beginning of the article up to the end of the System prompt section. Pay close attention to: How the ShoppingAgent class is structured. The decide_next_action method, which contains the core function calling logic. The clear separation between the action schemas (e.g., SEARCH_SCHEMA) and the action classes that execute the logic (e.g., class Search).
The ShoppingAgent example from the article beautifully illustrates a key software design principle: the LLM is responsible for intent recognition and planning, while your application code is responsible for execution. The JSON schema acts as the contract or API definition between the two.
Test your understanding!
You want to create a simple "calculator" tool for an agent. The tool should be able to find the square root of a number.
- Define the JSON schema for a function named
calculate_square_rootthat takes one required parameter,number, which should be a number. - Write a simple Python function
calculate_square_root(number)that implements this logic.
Show answer
1. JSON Schema Definition:
tool_definition = {
"type": "function",
"function": {
"name": "calculate_square_root",
"description": "Calculates the square root of a given number.",
"parameters": {
"type": "object",
"properties": {
"number": {
"type": "number",
"description": "The number to find the square root of."
}
},
"required": ["number"]
}
}
}
2. Python Function Implementation:
import math
def calculate_square_root(number):
"""Calculates the square root of a number."""
if number < 0:
return "Error: Cannot calculate the square root of a negative number."
return str(math.sqrt(number)) # Return as a string, as tool outputs are strings
You would then map the function name calculate_square_root from the LLM's tool call to this Python function in your application logic.
Conclusion
In this lesson, we put theory into practice and gave our LLM its first real-world capability. You learned how to implement function calling, the fundamental mechanism that allows an agent to perform actions.
Key Takeaways:
- Function calling is a multi-step, conversational process where an LLM requests the execution of a function defined in your application.
- The LLM does not execute code; it generates a JSON object specifying the function and arguments. Your code handles the execution.
- A JSON schema acts as the "API contract," describing the available tools to the LLM. Clear descriptions are crucial for the model to know when to use a tool.
- The full workflow involves:
- Defining tools and making an initial request.
- Receiving a
tool_callsresponse from the model. - Executing the tool in your code.
- Sending the tool's output back to the model.
- Receiving the final, context-aware natural language response.
What's Next?
We've successfully given our agent a single tool. But what about managing a whole toolbox? In the next lesson, we will create custom tools and functions for an agent to extend its capabilities. We'll explore how to build a more complex agent that can choose from a set of different tools to solve more sophisticated problems, which is a direct step towards building the powerful agents you are aiming for.