Saltar al contenido

Lección 20 · The Gemini API

Function Calling and Built-In Tools

Let Gemini call your functions and use built-in tools such as Google Search grounding and code execution, with a safe loop, validation and approvals.

A model alone only produces output. Tools let it ask for information or actions. With function calling, you describe your own functions. The model requests a call, your code runs it and you send back the result. There are also built-in tools that Google runs. If tools are new to you, read what are tools first. Facts are as of December 2026.

Declare a function

Python
# Read-only.
get_stock = {
    "type": "function",
    "name": "get_stock",
    "description": "Returns how many units of a product are in stock.",
    "parameters": {
        "type": "object",
        "properties": {
            "sku": {"type": "string", "description": "Product code, e.g. TEA-100"}
        },
        "required": ["sku"],
    },
}

A good description says what the function does and when to use it. See tool schemas with JSON Schema.

The calling loop

Python
# Read-only. Shows one round only.
import json

interaction = client.interactions.create(
    model="gemini-4-hydrogen",
    input="How many TEA-100 do we have?",
    tools=[get_stock],
)

call = next(s for s in interaction.steps if s.type == "function_call")
result = my_get_stock(**call.arguments)     # your own function, with checks

final = client.interactions.create(
    model="gemini-4-hydrogen",
    previous_interaction_id=interaction.id,
    input=[{
        "type": "function_result",
        "name": call.name,
        "call_id": call.id,
        "result": [{"type": "text", "text": json.dumps(result)}],
    }],
    tools=[get_stock],                       # send the tools again
)
print(final.output_text)

Key points from Google's documentation:

  • A function_call step has a name, arguments and an id.
  • Your function_result uses that id as its call_id.
  • Tool declarations are not carried over, so send tools again.

The sample above assumes exactly one call. The model might not call a function at all, or it might ask for several. Real code loops over all call steps and stops after a maximum number of rounds.

In generation_config, tool_choice can be auto (the default), any, none or validated, and you can also limit which functions are allowed.

A safe loop you can run

The stand-in below acts like a model that first sends a bad argument. The dispatcher checks the name and values, returns useful errors and limits the number of rounds.

Python Stand-in: a safe function-calling loop

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Treat arguments as untrusted

The model chooses the arguments, and user text or a document it read can influence that choice. So:

  • Run only functions on your allowed list.
  • Validate every argument, and check the user's permissions in your code.
  • Require human approval for actions that send, delete or buy.
  • Use database queries with parameters, never SQL built by joining strings.
  • Log calls and results without secrets.

There is more in executing tool calls safely.

Built-in tools

Grounding with Google Search. Add tools=[{"type": "google_search"}]. Output text can carry citation annotations with a URL, a title and the text range they support. The documentation also describes search suggestions and display requirements. If you show grounded results to users, read the terms. As of December 2026, the documentation says Gemini 3 and newer models are billed for each search query the model runs, with a shared monthly free allowance.

Code execution. Add tools=[{"type": "code_execution"}]. The model writes and runs Python in a sandbox. The documentation lists a 30-second maximum runtime, only the preinstalled libraries and charts through Matplotlib. The interaction's steps show the code and its result, so you can inspect what ran.

Google also documents other tools, such as URL context, file search, grounding with Google Maps and computer use. Support differs by model, so check the current page, also for remote MCP servers.

Python Show citations next to the text they support

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Do not assume how the real API counts positions (characters or bytes) when text contains non-English characters. Check the reference and test with such text.

Design tools for failure

Think about what happens when a call goes wrong. Return a short, structured error that says what failed and, if it helps, what valid input looks like. Do not return stack traces, secrets or data about other users, because everything in a tool result becomes model input.

For actions, make repeats safe. A network problem may leave you unsure whether an action happened, and a retry could create a second order. Many systems use a unique request ID that the server remembers, so that the same request is carried out only once.

Finally, keep the tool list short. Offer only the functions that the current task and user need. A read-only assistant should not even receive a delete function. Test requests that try to misuse each tool, and confirm that your code refuses them even when the model asks politely and confidently.

Common mistake: letting a "refund" function run automatically because the model asked for it. Add approval, limits and a record of who approved each refund.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Who runs your custom function?

    The model only requests a call.
  2. 2. How is a function result linked to its request?

    The matching ID tells the model which call the result answers.
  3. 3. Which language does the code execution tool run, according to Google's documentation?

    The documentation says that only Python code is executed.
  4. 4. What best protects a delete function?

    Prompts can be bypassed. Code checks and approvals are dependable controls.

Summary

  • Declare functions with JSON Schema. The model requests, and your code executes.
  • Return results with the matching call_id, and send the tools again.
  • Validate arguments, cap the rounds and require approval for risky actions.
  • Built-in tools include Google Search grounding and Python code execution.

Next: API Costs, Rate Limits and Errors

Tu progreso se guarda en este navegador. No necesitas una cuenta.