Lección 2 · 5 min · Gratis

Agente Barista Bot con Llamadas a Funciones

Copyright 2026 Google LLC.
# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Este notebook muestra un ejemplo práctico de cómo usar llamadas automáticas a funciones con el SDK de Python de la API de Gemini para construir un agente. Definirás algunas funciones que componen el sistema de pedidos de una cafetería, las conectarás a la API de Gemini y escribirás un bucle de agente que interactúa con el usuario para pedir bebidas de café.

La guía se inspiró en el prompt Barista bot estilo ReAct disponible a través de AI Studio.

%pip install -qU "google-genai>=2.9.0"

Para ejecutar este notebook, tu clave de API debe estar almacenada en un Secreto de Colab llamado GEMINI_API_KEY. Si estás ejecutando en un entorno diferente, puedes almacenar tu clave en una variable de entorno. Consulta Autenticación image para obtener más información.

from google import genai
from google.colab import userdata

client = genai.Client(api_key=userdata.get("GEMINI_API_KEY"))

Define la API

Para emular el sistema de pedidos de una cafetería, define funciones para gestionar el pedido del cliente: añadir, editar, borrar, confirmar y completar.

Estas funciones rastrean el pedido del cliente usando las variables globales order (el pedido en curso) y placed_order (el pedido confirmado enviado a la cocina). Cada una de las funciones de edición de pedidos actualiza order, y una vez realizado, order se copia a placed_order y se borra.

En el SDK de Python puedes pasar funciones directamente al constructor del modelo, donde el SDK inspeccionará las firmas de tipo y las docstrings para definir el tools. Por esta razón, es importante que escribas correctamente cada uno de los parámetros, les des nombres sensatos a las funciones y docstrings detalladas.

from typing import Optional
from random import randint

order = []  # The in-progress order.
placed_order = []  # The confirmed, completed order.


def add_to_order(drink: str, modifiers: Optional[list[str]] = None) -> None:
    """Adds the specified drink to the customer's order, including any modifiers."""
    if modifiers is None:  # Ensures safe handling of None
        modifiers = []
    order.append((drink, modifiers))


def get_order() -> list[tuple[str, list[str]]]:
    """Returns the customer's order."""
    return order


def remove_item(n: int) -> str:
    """Removes the nth (one-based) item from the order.

    Returns:
        The item that was removed.
    """
    item, _ = order.pop(n - 1)
    return item


def clear_order() -> None:
    """Removes all items from the customer's order."""
    order.clear()


def confirm_order() -> str:
    """Asks the customer if the order is correct.

    Returns:
        The user's free-text response.
    """
    print("Your order:")
    if not order:
        print("  (no items)")

    for drink, modifiers in order:
        print(f"  {drink}")
        if modifiers:
            print(f'   - {", ".join(modifiers)}')

    return input("Is this correct? ")


def place_order() -> int:
    """Submit the order to the kitchen.

    Returns:
        The estimated number of minutes until the order is ready.
    """
    placed_order[:] = order.copy()
    clear_order()

    # TODO: Implement coffee fulfillment.
    return randint(1, 10)

Prueba la API

Con las funciones escritas, prueba que funcionan como esperas.

# Test it out!

clear_order()
add_to_order("Latte", ["Extra shot"])
add_to_order("Tea")
remove_item(2)
add_to_order("Tea", ["Earl Grey", "hot"])
confirm_order()
Your order:
  Latte
   - Extra shot
  Tea
   - Earl Grey, hot
Is this correct? yes
'yes'

Define el prompt

Aquí defines el prompt completo de Barista-bot. Este prompt contiene los elementos del menú de la cafetería y los modificadores, así como algunas instrucciones.

Las instrucciones incluyen orientación sobre cómo se deben llamar las funciones (por ejemplo, "Siempre confirm_order con el usuario antes de llamar a place_order"). Puedes modificar esto para añadir tu propio estilo de interacción al bot; por ejemplo, si quisieras que el bot repitiera cada solicitud antes de añadirla al pedido, podrías proporcionar esa instrucción aquí.

El final del prompt incluye algo de jerga que el bot podría encontrar, e instrucciones du jour; en este caso, señala que la cafetería se ha quedado sin leche de soja.

COFFEE_BOT_PROMPT = """\You are a coffee order taking system and you are restricted to talk only about drinks on the MENU. Do not talk about anything but ordering MENU drinks for the customer, ever.
Your goal is to do place_order after understanding the menu items and any modifiers the customer wants.
Add items to the customer's order with add_to_order, remove specific items with remove_item, and reset the order with clear_order.
To see the contents of the order so far, call get_order (by default this is shown to you, not the user)
Always confirm_order with the user (double-check) before calling place_order. Calling confirm_order will display the order items to the user and returns their response to seeing the list. Their response may contain modifications.
Always verify and respond with drink and modifier names from the MENU before adding them to the order.
If you are unsure a drink or modifier matches those on the MENU, ask a question to clarify or redirect.
You only have the modifiers listed on the menu below: Milk options, espresso shots, caffeine, sweeteners, special requests.
Once the customer has finished ordering items, confirm_order and then place_order.

Hours: Tues, Wed, Thurs, 10am to 2pm
Prices: All drinks are free.

MENU:
Coffee Drinks:
Espresso
Americano
Cold Brew

Coffee Drinks with Milk:
Latte
Cappuccino
Cortado
Macchiato
Mocha
Flat White

Tea Drinks:
English Breakfast Tea
Green Tea
Earl Grey

Tea Drinks with Milk:
Chai Latte
Matcha Latte
London Fog

Other Drinks:
Steamer
Hot Chocolate

Modifiers:
Milk options: Whole, 2%, Oat, Almond, 2% Lactose Free; Default option: whole
Espresso shots: Single, Double, Triple, Quadruple; default: Double
Caffeine: Decaf, Regular; default: Regular
Hot-Iced: Hot, Iced; Default: Hot
Sweeteners (option to add one or more): vanilla sweetener, hazelnut sweetener, caramel sauce, chocolate sauce, sugar free vanilla sweetener
Special requests: any reasonable modification that does not involve items not on the menu, for example: 'extra hot', 'one pump', 'half caff', 'extra foam', etc.

"dirty" means add a shot of espresso to a drink that doesn't usually have it, like "Dirty Chai Latte".
"Regular milk" is the same as 'whole milk'.
"Sweetened" means add some regular sugar, not a sweetener.

Soy milk has run out of stock today, so soy is not available.
"""

Configura el modelo

En este paso, recopilas las funciones en un "sistema" que se pasa como tools, instanciar el modelo e iniciar la sesión de chat.

También se define una función send_message reintentable para ayudar con conversaciones de baja cuota.

from google.genai import types
from google.api_core import retry

ordering_system = [
    add_to_order,
    get_order,
    remove_item,
    clear_order,
    confirm_order,
    place_order,
]
model_name = "gemini-3.7-flash" # @param ["gemini-3.1-pro-preview", "gemini-3.7-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input":true, isTemplate: true}
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(
        tools=ordering_system,
        system_instruction=COFFEE_BOT_PROMPT,
    ),
)

placed_order = []
order = []

Chatea con Barista Bot

Con el modelo definido y el chat creado, todo lo que queda es conectar la entrada del usuario al modelo y mostrar la salida, en un bucle. Este bucle continúa hasta que se realiza un pedido.

Cuando se ejecuta en Colab, cualquier texto de ancho fijo proviene de tu código Python (por ejemplo, llamadas print en el sistema de pedidos), el texto normal proviene de la API de Gemini, y los cuadros delineados permiten la entrada del usuario que se renderiza con un > inicial.

¡Pruébalo!

from IPython.display import display, Markdown

print("Welcome to Barista bot!\n\n")

while not placed_order:
    response = chat.send_message(input("> "))
    display(Markdown(response.text))


print("\n\n")
print("[barista bot session over]")
print()
print("Your order:")
print(f"  {placed_order}\n")
print("- Thanks for using Barista Bot!")
Welcome to Barista bot!


> i would like to have a cuppacino with almond milk
<IPython.core.display.Markdown object>
> do you have stone milk?
<IPython.core.display.Markdown object>
> do you have long black
<IPython.core.display.Markdown object>
>  no, that's all
Your order:
  Cappuccino
   - Almond Milk
Is this correct? yes
<IPython.core.display.Markdown object>
> yes
<IPython.core.display.Markdown object>
[barista bot session over]

Your order:
  [('Cappuccino', ['Almond Milk'])]

- Thanks for using Barista Bot!

Algunas cosas que puedes probar:

  • Pregunta sobre el menú (por ejemplo, "¿qué bebidas de café hay disponibles?")
  • Usa términos que no estén especificados en el prompt (por ejemplo, "un latte fuerte" o "un té EB")
  • Cambia de opinión a mitad de camino ("uhh, cancela el latte, lo siento")
  • Pide algo fuera del menú ("un babycino")

Ver también

Esta aplicación de ejemplo te mostró cómo integrar un sistema de software tradicional (las funciones de pedido de café) y un agente de IA impulsado por la API de Gemini. Esta es una forma sencilla y práctica de usar LLM que permite una entrada y salida de lenguaje humano abierta que se siente natural, pero que aún mantiene a un humano en el ciclo para garantizar un funcionamiento correcto.

Para obtener más información sobre cómo funciona Barista Bot, consulta:

Lección del curso «Gemini API Cookbook (examples)» de Google, publicado con licencia Apache 2.0. Traducción y adaptación al español de IA con Clase. IA con Clase no está afiliado a Google. Ver el original · Licencia
Esta lección es gratuita. El resto del curso se abre con la Membresía de IA con Clase, que incluye todos los cursos del catálogo. Ver precios