Lesson 5 of 6
Connect Gemini to a Function
On this page
This is the lesson the whole course has been heading towards. Your assistant can answer shop questions, but it cannot say where order LL-2071 is, because it has no access to orders. You will give it one function, get_order_status, and teach your program to run the conversation in the right order: ask Gemini, receive a function request, check it, run the function and send the result back.
Keep one sentence in your head throughout: Gemini does not execute your code. It returns the name of a function and some arguments. Your application decides what happens next. Once you have written the loop yourself, line by line, that sentence stops being a slogan and becomes something you can point at in the program.
What you will learn
- Explain function calling in plain language.
- Declare a read-only function with a name, description and parameter schema.
- Run the manual loop: receive the function request, validate it, execute it and send the result back.
- Explain why the function runs in your own program, even if an SDK offers an automatic mode.
Before you start
- Lessons 3 and 4 finished: agent.py with the chat loop, MODEL and SYSTEM_INSTRUCTION.
- store_data.py containing ORDERS.
Function calling in plain language
Think of a hotel guest and the front desk. The guest says, "I would like to know whether my parcel has arrived." The guest cannot go into the stock room. The desk clerk can. So the guest tells the clerk what to look up, the clerk looks, and then reads the result back. The guest never touches the shelves.
Gemini is the guest. Your application is the clerk. You describe to Gemini a function it may ask for. If a customer's message needs it, Gemini replies not with an answer but with a request: the function's name and arguments. Your program reads that request and, if it is safe, looks up the order and sends the result back. Gemini then writes the answer for the customer.
- 1. Send question
Instruction, tools list and the customer's message go to Gemini.
- 2. Gemini replies with a function_call step
A name and arguments. No answer yet.
- 3. Validate
Is the name allowed? Is the order ID in the right format?
- 4. Execute
Your Python function looks in the sample orders.
- 5. Send the function_result
The result and the call's id go back, chained to the earlier interaction.
- 6. Gemini answers
A final text reply for the customer.
One order question takes two requests to Gemini. The highlighted work in the middle is all yours.
A note on automatic modes
Some SDKs and interfaces offer an automatic mode, in which you hand over an ordinary Python function and the library notices requests, calls your function and sends the result for you. Google's current function-calling documentation for the interface used here shows the manual loop in its Python examples, and this course follows that. It keeps automatic behaviour off by design, because you learn more by writing the loop once.
Even where an automatic mode exists, it does not move the function into Google's systems. The function still runs in your own Python program; the library merely does the plumbing. And automatic plumbing makes it easier to skip validation. Whichever you use, every request should pass through checks that you wrote.
Declare the function
Gemini cannot see your Python code. You describe the function in a declaration: a dictionary with the function's name, a description and a parameter schema written in JSON Schema style. The model reads the description to decide when the function is relevant, so write it as clearly as an instruction. The JSON Schema introduction (opens in a new tab) explains the format.
# What Gemini is told about the function. This is only a description:
# Gemini cannot see or run the Python code behind it.
GET_ORDER_STATUS_DECLARATION = {
"type": "function",
"name": "get_order_status",
"description": (
"Look up the status of one Lantern Lane Books order by its order ID. "
"Read-only: it never changes an order. Use it only when the customer "
"gives an order ID such as LL-2071."
),
"parameters": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The order ID: the letters LL, a hyphen, then four digits.",
}
},
"required": ["order_id"],
},
}Add near the top of agent.py, after SYSTEM_INSTRUCTION.
Notice how much the description helps. It says the function is read-only, when to use it and what the ID looks like. A vague description such as "gets orders" leads to the function being called at the wrong time or with the wrong argument.
Write the function and its safety checks
Now the real code, which only your program can see. It takes the proposed order ID, checks its format and looks it up. It returns a small dictionary: either the order or a clear error. Returning errors as data, instead of crashing, lets Gemini explain the problem politely.
import json
import re
from store_data import ORDERS
# Exactly "LL-", then four digits. fullmatch rejects any extra characters.
ORDER_ID_PATTERN = re.compile(r"LL-\d{4}")
def get_order_status(order_id) -> dict:
"""Read-only lookup in the sample data. It never modifies anything."""
# The value came from a model, so do not trust its type or shape.
if not isinstance(order_id, str):
return {"error": "invalid_order_id", "message": "Order ID must be text."}
cleaned = order_id.strip().upper()
if not ORDER_ID_PATTERN.fullmatch(cleaned):
return {
"error": "invalid_order_id",
"message": "Order IDs look like LL-2071.",
}
order = ORDERS.get(cleaned)
if order is None:
return {"error": "not_found", "message": "No order with that ID."}
return {"order_id": cleaned, **order}
# The only functions the model may ask for. Anything else is refused.
ALLOWED_FUNCTIONS = {"get_order_status": get_order_status}Add the import line at the top of the file, and the rest below the declaration.
Run the loop by hand
Here is the part that makes it an agent. The function answer() sends the question, then keeps checking the response for function requests. When there are none, Gemini has written its final answer. When there are some, your code validates and runs each one and sends the results back. A cap on the number of rounds stops a confused model from looping forever.
MAX_ROUNDS = 4 # safety limit on request/function rounds per question
def ask(client, input_data, previous_id=None):
"""One request to Gemini. Instructions and tools are sent every time,
because they only apply to the interaction they are set on."""
options = {}
if previous_id is not None:
options["previous_interaction_id"] = previous_id
return client.interactions.create(
model=MODEL,
input=input_data,
system_instruction=SYSTEM_INSTRUCTION,
tools=[GET_ORDER_STATUS_DECLARATION],
**options,
)
def run_function_call(call) -> dict:
"""Validate and execute one function request from Gemini."""
function = ALLOWED_FUNCTIONS.get(call.name)
if function is None:
return {"error": "unknown_function", "message": "That function is not available."}
# call.arguments holds what the model proposed, for example
# {"order_id": "LL-2071"}. It must be a dictionary with the right key.
arguments = call.arguments
if not isinstance(arguments, dict):
return {"error": "bad_arguments", "message": "Arguments were not an object."}
# Execute in OUR program. Gemini never does this step.
return function(arguments.get("order_id"))
def answer(client, question, previous_id=None):
"""Send a question, handle any function requests, return the last interaction."""
interaction = ask(client, question, previous_id)
for _ in range(MAX_ROUNDS):
calls = [step for step in interaction.steps if step.type == "function_call"]
if not calls:
return interaction # no function requested: this is the final reply
# Build one function_result per request. Each carries the call's id
# so Gemini can match results to requests.
results = []
for call in calls:
outcome = run_function_call(call)
results.append(
{
"type": "function_result",
"name": call.name,
"call_id": call.id,
"result": [{"type": "text", "text": json.dumps(outcome)}],
}
)
# Second request: send the results, chained to the first interaction.
interaction = ask(client, results, interaction.id)
raise RuntimeError("Too many function rounds; stopping for safety.")Add below ALLOWED_FUNCTIONS.
Finally, change the chat loop in main() so it calls answer() instead of calling the API directly.
interaction = answer(client, question, previous_id)
previous_id = interaction.id
print("Gemini:", interaction.output_text)The updated middle of the loop in main().
Step 1: Run the agent
Start the program and ask a shop question first to confirm the FAQ still works.
Bashterminal python agent.pyWhat you should see: A shop question is answered from the FAQ with no function involved.
Step 2: Ask about a real sample order
Type: Where is order LL-2071?
What you should see: Gemini replies with the status Shipped and the delivery note, in its own words.
Step 3: Ask about an order that does not exist
Type: What about order LL-9999?
What you should see: The function returns not_found and Gemini tells you it could not find that order.
Step 4: Ask something malformed
Type: Check order 12345 please.
What you should see: Either Gemini asks you for a correctly formatted ID, or your validation returns invalid_order_id and Gemini explains the format.
You: Where is order LL-2071?
Gemini: Order LL-2071 (The Cartographer's Garden) has shipped. It was dispatched on 2026-11-10 and should arrive within three to five working days.
You: What about order LL-9999?
Gemini: I could not find an order with that ID. Please check the number, or contact the shop team if you think it is right.To see the loop yourself, add a temporary line inside answer() that prints each function call's name and arguments, such as print("DEBUG call:", call.name, call.arguments). You will watch your own program, not Gemini, handle the request. Remove it afterwards, because logs can capture user data.
Reusable prompt
Function description checker
Get feedback on whether a function declaration is clear enough for a model to use correctly.
Here is a function declaration for an AI model. Tell me when you would call it, with which arguments, and what you would be unsure about. Then suggest improvements to the description only.
[paste GET_ORDER_STATUS_DECLARATION here]Show the reusable template
Replace each {{placeholder}} with your own details.
Here is a function declaration for an AI model. Tell me when you would call it, with which arguments, and what you would be unsure about. Then suggest improvements to the description only.
{{declaration}}Expected output and limitations
An explanation of when the model would call the function, the argument it would pass, and any ambiguities such as what to do with lower-case IDs or missing numbers.
I would call get_order_status when the customer gives an ID like LL-2071, passing order_id as that string. I am unsure what to do if they give only digits. Consider saying so in the description.Limitations to keep in mind
- The reviewing assistant is guessing how another model behaves. Test with real requests.
- A good declaration does not remove the need to validate arguments.
Common errors and how to fix them
The model never asks for the function.
Why it happens: tools was not passed on the request, or the description is vague, or the question had no order ID.
Fix: Confirm ask() passes tools every time, make the description say when to use the function, and test with an obvious order ID.
An error saying a function result does not match a call.
Why it happens: The call_id in the result is missing or not the id of the call.
Fix: Copy call.id exactly into call_id and send the results chained to the interaction that contained the calls.
The second request loses the function declarations.
Why it happens: Tools and instructions apply only to the interaction they are set on.
Fix: Send them on the second request too, as ask() does.
TypeError because arguments is not a dictionary.
Why it happens: The model proposed something unexpected, or the SDK shape changed.
Fix: Keep the isinstance check, print the call during development and compare with the current function-calling page.
RuntimeError: Too many function rounds.
Why it happens: The model kept requesting functions, perhaps because errors were unclear.
Fix: Make error messages explicit, check your results are being sent, and keep MAX_ROUNDS low. Do not raise it to hide the problem.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Add a second read-only field safely
Extend the sample orders with a carrier name for shipped orders, return it from get_order_status and confirm Gemini mentions it. Then deliberately ask for an order ID in lower case and trace what your code does with it.
You will need
- Your ORDERS dictionary and get_order_status function.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Add a key like carrier to one or two orders.
- Look at how cleaned is built from order_id.
Show a model answer
The new key rides along because the function returns the whole order dictionary. The lower-case ID is cleaned by strip and upper before the pattern is checked, so ll-2071 becomes LL-2071. The model's formatting is therefore never the only thing standing between a user and a correct lookup.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The function lives in your program and only your program can run it. The first option is tempting because the step comes from Gemini, but it is only a request that your code may accept or refuse.
Show the answer and explanation
Answer: A. The result is the information Gemini needs to answer, and the call id ties it to the request. The second option is wrong because Google never receives your code, only the result you choose to send.
Show the answer and explanation
Answer: A. Treat proposed arguments like form input from a stranger. The third option is tempting but irrelevant: validation is about correctness and safety, not speed.
Show the answer and explanation
Answer: B. Each round is a paid API request, and a loop without a limit can run far longer than intended. A bad key fails on the very first request, so it has nothing to do with the limit.
- Written by
- PromptFable Editorial
- Last updated 13 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Function calling with the Gemini API(opens in a new tab)
Google · Official documentation · Shows the function_call and function_result shapes used here.
- Interactions API overview(opens in a new tab)
Google · Official documentation
- Getting started with JSON Schema(opens in a new tab)
JSON Schema · Official documentation
- OWASP Top 10 for LLM Applications(opens in a new tab)
OWASP · Official documentation · Covers excessive agency and insecure output handling.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.