What Is Function Calling? Explained With a Python Example
Function calling lets an AI model ask your code to do things it can't, like checking today's exchange rate. Here's how it works, with a free Python example.
Mahnoor 7 min read 4-item prompt pack
Function calling lets an AI model use your code. The model can't check today's exchange rate or read your database, but it can ask your program to run a function that does, and then use the result in its answer. The model never runs anything itself: it only asks. Here's how it works, with a free Python example you can run in five minutes.
The problem function calling solves
An LLM only knows what it learned in training. Ask it something live, and it can't help. I asked Gemini "How many Pakistani rupees is 50 US dollars today?" with no tools, and it replied:
I cannot provide the current exchange rate because I do not have access to
real-time financial data.It's honest, but it's useless. Function calling fixes this by giving the model a way to ask for real data.
How function calling works
Think of it like a waiter. The model is the waiter, and your functions are the kitchen. The waiter can't cook, but they know what's on the menu, and they know how to ask the kitchen for it.
You describe your functions. You send the model a short description of each function: its name, what it does and what inputs it needs. That's the menu.
The model decides. If it needs one, it doesn't answer with text. It sends back a request: "please call this function with these inputs".
Your code runs the function. This is the part most people get wrong. The model never runs your code. Your program does.
You send the result back. The model reads the real data and writes the final answer.
Example: a currency converter in Python
You need Python, a free Gemini API key (here's how to get a free Gemini API key) and two packages:
pip install google-genai python-dotenv requestsThe exchange rates come from the free ExchangeRate-API (no key needed). Here's the full example:
import requests
from dotenv import load_dotenv
from google import genai
from google.genai import types
load_dotenv() # reads GEMINI_API_KEY from .env
client = genai.Client()
MODEL = "gemini-3.5-flash-lite"
# 1. A normal Python function
def get_exchange_rate(base, target):
data = requests.get(f"https://open.er-api.com/v6/latest/{base.upper()}").json()
return {"rate": data["rates"][target.upper()], "updated": data["time_last_update_utc"]}
# 2. The description the model reads (the "menu")
rate_tool = types.Tool(function_declarations=[{
"name": "get_exchange_rate",
"description": "Get today's exchange rate between two currencies.",
"parameters": {"type": "object", "properties": {
"base": {"type": "string", "description": "Currency to convert from, for example USD"},
"target": {"type": "string", "description": "Currency to convert to, for example PKR"},
}, "required": ["base", "target"]},
}])
config = types.GenerateContentConfig(tools=[rate_tool])
question = "How many Pakistani rupees is 50 US dollars today?"
messages = [types.Content(role="user", parts=[types.Part(text=question)])]
# 3. The model ASKS for the function
response = client.models.generate_content(model=MODEL, contents=messages, config=config)
call = response.function_calls[0]
print("Model asked for:", call.name, call.args)
# 4. Your code runs it and sends the result back
result = get_exchange_rate(**call.args)
messages.append(response.candidates[0].content)
messages.append(types.Content(role="user", parts=[
types.Part.from_function_response(name=call.name, response={"result": result}),
]))
# 5. The model writes the answer using the real data
final = client.models.generate_content(model=MODEL, contents=messages, config=config)
print("Answer:", final.text)When I ran it:
Model asked for: get_exchange_rate {'base': 'USD', 'target': 'PKR'}
Answer: 50 US dollars is approximately 13,824.44 Pakistani rupees today
(at a rate of 276.49 PKR per USD).Look at the first line. The model didn't answer, and it didn't run anything. It turned "50 US dollars to rupees" into a clean request: get_exchange_rate with base='USD' and target='PKR'. Your code did the real work.
The shortcut: automatic function calling
The Python SDK can also run the loop for you. Pass your function itself (with type hints and a docstring), and use a chat:
def get_exchange_rate(base: str, target: str) -> dict:
"""Get today's exchange rate between two currencies, for example USD to PKR."""
data = requests.get(f"https://open.er-api.com/v6/latest/{base.upper()}").json()
return {"rate": data["rates"][target.upper()], "updated": data["time_last_update_utc"]}
chat = client.chats.create(
model="gemini-3.5-flash-lite",
config=types.GenerateContentConfig(tools=[get_exchange_rate]),
)
print(chat.send_message("How many Pakistani rupees is 50 US dollars today?").text)It prints "50 US dollars is equal to 13,824.44 Pakistani rupees." The SDK reads your docstring as the description, runs the function and sends the result back for you.
It's handy, but learn the manual way first. When you write the loop yourself, you can check the inputs before running anything, log every call and ask the user before risky actions like sending an email or deleting a file.
Function calling vs tool calling vs MCP
Function calling and tool calling are the same idea with two names. "Tool calling" is the newer name, because tools can also be built in, like web search.
MCP (Model Context Protocol) is a standard way to package tools so that many AI apps can use them, instead of each app wiring up its own functions. Under the hood, the model still uses function calling. We compared them properly in MCP vs function calling vs custom integrations.
Google's docs now show the Interactions API
If you open Google's function calling docs, the examples use a newer method, client.interactions.create, instead of generate_content. It's the same idea: you describe your tools, and the model sends back a function call for your code to run. Both work on the free tier. I tested this with the same SDK:
interaction = client.interactions.create(
model="gemini-3.5-flash-lite",
input="How many Pakistani rupees is 50 US dollars today?",
tools=[{"type": "function", "name": "get_exchange_rate",
"description": "Get today's exchange rate between two currencies.",
"parameters": {"type": "object", "properties": {
"base": {"type": "string"}, "target": {"type": "string"}},
"required": ["base", "target"]}}],
)
for step in interaction.steps:
if step.type == "function_call":
print(step.name, step.arguments) # get_exchange_rate {'base': 'USD', 'target': 'PKR'}Tips for good function calling
Write clear descriptions. The description is the only thing the model knows about your function. Say what it does and when to use it.
Check the inputs before you run anything. The model can send wrong or strange arguments, so validate them like you would any user input.
Keep the list short. Google recommends about 10 to 20 tools at most. More tools means more mistakes in choosing the right one.
Ask before risky actions. Never let the model send, pay or delete without a check in your code.
What to build next
Put function calling in a loop, so the model can call one function, read the result and decide on the next one, and you have an AI agent. Start with Chatbot vs LLM vs AI agent to see where function calling fits. If you hit errors while testing, see how to fix Gemini 429 and 503 errors.
Exchange rates by ExchangeRate-API.
Prompt pack
Every prompt from this lesson
2 free prompts + a confirm-before-acting step and a prompt that turns the converter into a mini agent.
Here is a Python function:
[paste your function]
Write the Gemini function declaration for it: the name, a clear description that says what it does and when to use it, and the parameters with types and descriptions. Then show the two lines that add it to GenerateContentConfig. Don't change my function.
I'm using Gemini function calling with the google-genai Python SDK.
My function declaration:
[paste]
My prompt:
[paste]
The model answers with text instead of calling the function (or calls the wrong one). Explain the likely reasons in simple words, then rewrite my description so the model uses the function at the right time.
2 more items in the full pack
Free. Sign in once and every prompt pack on Morow Global unlocks.
Sign in free to unlockAlready a member? Sign in
FAQ
What is function calling in simple words?
It's a way for an AI model to ask your program to run a function, like checking a price or the weather, and then use the result in its answer.
Does the LLM run the function itself?
No. The model only sends back the function name and inputs. Your code runs the function and sends the result back.
What's the difference between function calling and tool calling?
They're the same idea. "Tool calling" is the newer name, because tools can also include built-in ones like web search.
What's the difference between function calling and MCP?
Function calling is how a model asks for a tool. MCP is a standard way to package and share tools so many AI apps can use them. MCP still uses function calling underneath.
Is Gemini function calling free?
Yes, on the Gemini API free tier, within its rate limits. The example in this article runs on a free key.