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.
Gemini API: Агенты и автоматический вызов функций с Barista Bot
Изображение (внешний источник)
Этот блокнот демонстрирует практический пример использования автоматического вызова функций с помощью Python SDK Gemini API для создания агента. Вы определите несколько функций, составляющих систему заказа в кафе, подключите их к Gemini API и напишете цикл агента, который взаимодействует с пользователем для заказа напитков в кафе.
Руководство было вдохновлено запросом Barista bot в стиле ReAct, доступным через AI Studio.
%pip install -qU "google-genai>=2.9.0"
Чтобы запустить этот блокнот, ваш ключ API должен быть сохранен в Colab Secret с именем GEMINI_API_KEY. Если вы работаете в другой среде, вы можете сохранить свой ключ в переменной среды. Подробнее см. в разделе Аутентификация image.
from google import genai
from google.colab import userdata
client = genai.Client(api_key=userdata.get("GEMINI_API_KEY"))
Определение API
Чтобы имитировать систему заказа в кафе, определите функции для управления заказом клиента: добавление, редактирование, очистка, подтверждение и выполнение.
Эти функции отслеживают заказ клиента с помощью глобальных переменных order (текущий заказ) и placed_order (подтвержденный заказ, отправленный на кухню). Каждая из функций редактирования заказа обновляет order, и после размещения order копируется в placed_order и очищается.
В Python SDK вы можете передавать функции непосредственно конструктору модели, где SDK будет проверять сигнатуры типов и docstrings для определения tools. По этой причине важно правильно типизировать каждый из параметров, давать функциям осмысленные имена и подробные docstrings.
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)
Тестирование API
После написания функций проверьте, что они работают так, как ожидается.
# 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'
Определение запроса
Здесь вы определяете полный запрос Barista-bot. Этот запрос содержит пункты меню кафе, модификаторы и некоторые инструкции.
Инструкции включают рекомендации по вызову функций (например, "Всегда confirm_order с пользователем перед вызовом place_order"). Вы можете изменить это, чтобы добавить свой собственный стиль взаимодействия с ботом, например, если вы хотите, чтобы бот повторял каждый запрос перед добавлением в заказ, вы можете предоставить эту инструкцию здесь.
В конце запроса содержится некоторый жаргон, с которым может столкнуться бот, и инструкции du jour - в данном случае отмечается, что в кафе закончилось соевое молоко.
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.
"""
Настройка модели
На этом шаге вы объединяете функции в "систему", которая передается как tools, создаете экземпляр модели и начинаете сеанс чата.
Также определяется функция send_message с возможностью повторной попытки для помощи в разговорах с низкими квотами.
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.8-flash" # @param ["gemini-4-argon", "gemini-3.1-pro-preview", "gemini-3.8-flash", "gemini-3.7-flash", "gemini-3.6-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 = []
Общение с Barista Bot
После определения модели и создания чата остается только подключить ввод пользователя к модели и отобразить вывод в цикле. Этот цикл продолжается до тех пор, пока заказ не будет размещен.
При запуске в Colab любой текст фиксированной ширины исходит из вашего кода Python (например, вызовы print в системе заказа), обычный текст исходит из Gemini API, а выделенные рамки позволяют вводить пользовательский ввод, который отображается с ведущим >.
Попробуйте!
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!
Что можно попробовать: * Спросите о меню (например, "какие кофейные напитки доступны?") * Используйте термины, не указанные в запросе (например, "крепкий латте" или "чай EB") * Передумайте на полпути ("эээ, отмените латте, извините") * Закажите что-то не из меню ("бейбичино")
См. также
Это демонстрационное приложение показало вам, как интегрировать традиционную программную систему (функции заказа кофе) и AI-агента на базе Gemini API. Это простой, практичный способ использования LLM, который позволяет вводить и выводить открытый человеческий язык, который кажется естественным, но при этом сохраняет человека в цикле для обеспечения правильной работы.
Чтобы узнать больше о том, как работает Barista Bot, ознакомьтесь с: