Agents_Function_Calling_Barista_Bot.ipynb 中文教程:构建智能咖啡师机器人
技术背景
传统软件系统通常依赖固定的用户界面和预定义的命令,而大语言模型(LLM)能够理解自然语言,但缺乏与外部系统交互的能力。函数调用(Function Calling)允许 LLM 在对话中调用开发者定义的函数,从而将自然语言理解与具体业务逻辑结合。本教程以咖啡馆点餐为例,展示如何构建一个 AI 代理,它既能理解用户的自然语言订单,又能通过函数调用管理订单状态。这种模式适用于客服、预订、数据查询等场景,但需要注意函数调用的可靠性、上下文管理以及安全边界。
核心原理
核心原理是自动函数调用:模型在生成回复时,会根据用户输入和系统提示词决定是否调用某个函数,并生成符合函数签名的参数。Python SDK 通过检查函数的类型签名和文档字符串自动生成工具定义,无需手动编写 JSON Schema。数据流为:用户输入 -> 模型推理 -> 若需调用函数则返回函数调用请求 -> SDK 执行函数并返回结果 -> 模型继续生成回复,直到满足结束条件。关键设计决策包括:使用全局变量存储订单状态,函数返回字符串或整数以提供反馈,系统提示词明确指令和菜单约束。
架构分析
系统由三部分组成:函数定义(模拟咖啡馆点餐系统)、模型配置(将函数作为工具传入)和代理循环(处理用户交互)。函数定义使用全局变量 order 和 placed_order 管理状态,每个函数负责特定操作。模型配置通过 types.GenerateContentConfig 设置 tools 和 system_instruction,其中 tools 是函数列表,SDK 自动生成工具定义。代理循环使用 chat.send_message 发送用户输入,并显示模型回复,直到 placed_order 非空。设计思想是解耦:函数层负责业务逻辑,模型层负责自然语言理解,循环层负责交互控制。可修改点包括:增加更多函数(如支付)、调整系统提示词以改变交互风格、使用不同的模型。
完整实战教程
##### 版权所有 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:代理与自动函数调用——咖啡师机器人
<a target="_blank" href="https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/Agents_Function_Calling_Barista_Bot.ipynb">
</a>
本笔记本展示了如何使用 Gemini API 的 Python SDK 进行自动函数调用的实际示例,以构建一个代理。您将定义一些构成咖啡馆点餐系统的函数,将它们连接到 Gemini API,并编写一个代理循环,与用户交互以订购咖啡馆饮品。
本指南的灵感来源于 AI Studio 中提供的 ReAct 风格的 Barista bot 提示。
%pip install -qU "google-genai>=2.9.0"
要运行此笔记本,您的 API 密钥必须存储在名为 GEMINI_API_KEY 的 Colab 密钥中。如果您在其他环境中运行,可以将密钥存储在环境变量中。请参阅 [身份验证
](../quickstarts/Authentication.ipynb) 了解更多信息。
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 会检查类型签名和文档字符串来定义 tools。因此,正确地为每个参数添加类型、给函数起合适的名称并编写详细的文档字符串非常重要。
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()
定义提示词
在这里,你定义了完整的 Barista-bot 提示词。该提示词包含咖啡馆的菜单项和修饰符,以及一些指令。
这些指令包括关于如何调用函数的指导(例如,“在调用 place_order 之前,始终使用 confirm_order 与用户确认”)。你可以修改此部分,为机器人添加你自己的交互风格,例如,如果你希望机器人在将每个请求添加到订单之前重复一遍,你可以在此处提供该指令。
提示词的结尾包含机器人可能遇到的一些行话,以及当日指令——在这种情况下,它指出咖啡馆的豆奶已经用完了。
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.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 = []
与 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!")
可以尝试以下操作:
* 询问菜单(例如“有哪些咖啡饮品?”)
* 使用提示中未指定的术语(例如“一杯浓拿铁”或“一杯英式早餐茶”)
* 中途改变主意(例如“呃,取消拿铁,抱歉”)
* 点菜单外的饮品(例如“一杯宝宝奇诺”)
另请参阅
此示例应用向您展示了如何将传统软件系统(咖啡订购功能)与由 Gemini API 驱动的 AI 代理集成。这是一种简单实用的 LLM 使用方式,允许开放式的自然语言输入和输出,感觉自然,但仍保持人工参与以确保正确操作。
要了解 Barista Bot 的更多工作原理,请查看:
* Barista Bot 提示词
* 系统指令
* 自动函数调用
常见问题
常见错误包括:1) 函数参数类型不匹配,导致模型生成错误参数,应确保类型注解清晰;2) 全局变量未初始化,导致状态混乱,应在会话开始前重置;3) 系统提示词未明确约束,导致模型调用不存在的函数,应严格定义菜单和指令;4) 配额限制导致请求失败,可使用重试机制(如 retry 装饰器)。排查方法:打印函数调用日志,检查模型返回的 function_call 内容;使用 get_order 函数验证状态;在开发环境中逐步调试。生产环境优化:使用数据库替代全局变量,增加身份验证和权限控制,实现日志监控和错误追踪,优化提示词以减少无效调用。
企业应用扩展
本教程可扩展为更复杂的代理系统:1) 集成支付和库存系统,实现完整交易流程;2) 使用向量数据库存储菜单和用户偏好,实现个性化推荐;3) 结合多模态输入(如语音)提升交互体验;4) 部署为 Web 服务,使用 FastAPI 或 Cloud Functions 提供 API;5) 增加多轮对话管理,处理更复杂的用户意图。此外,可参考 Google 的 ReAct 模式,将函数调用与推理步骤结合,提升代理的决策能力。
总结
本教程通过构建一个咖啡师机器人,深入讲解如何使用 Gemini API 的自动函数调用功能实现 AI 代理。你将学习定义咖啡馆点餐系统的函数、将其作为工具传递给模型、编写系统提示词,并实现一个代理循环与用户交互。教程涵盖环境准备、代码实现、测试、常见错误排查及生产环境优化,帮助开发者掌握将传统软件系统与 LLM 集成的工程实践。
- --
内容来源与验证
- 内容等级:PREMIUM_A
- 质量等级:A
- 难度:中级
- 验证等级:V1
- 原文作者:
- 原文日期:
- 来源许可:Apache-2.0
- 来源版本:
a0780d5e62a549409e9ecb24814b70b363431afd - 查看原文
站内还有更多完整实战教程
加入会员,解锁全部教程、完整代码与持续更新内容。
加入会员