实战一:构建你的第一个工具调用 Agent
Talk is cheap. 我们将用 Python + Google Gemini API 手写一个能够查询实时天气的 Agent。
这个例子虽然简单,但它包含了 Agent 的核心三要素:思考 (Reasoning)、工具 (Tool) 和 执行 (Execution)。
[PROMPT_LAB_BANNER]
1. 准备工作
我们将使用 google-generativeai 库。它的 Function Calling 接口非常直观。
pip install -q -U google-generativeai
2. 定义工具 (Define Tool)
Agent 不知道“现在”的天气。我们需要给它一个函数 get_current_weather。
import google.generativeai as genai
import os
# 模拟的天气 API(实际项目中这里会调用 OpenWeatherMap 等 API)
def get_current_weather(location: str):
"""获取指定地点的当前天气信息"""
print(f"🔧 工具被调用: get_current_weather('{location}')")
# 这里只是模拟返回
weather_data = {
"Beijing": "Sunny, 25°C",
"Melbourne": "Rainy, 12°C",
"New York": "Cloudy, 18°C"
}
return weather_data.get(location, "Unknown location")
# 将函数放入工具箱
tools = [get_current_weather]
3. 初始化模型
我们将工具直接传递给 Gemini 模型。
genai.configure(api_key="YOUR_API_KEY")
# 使用支持 Function Calling 的模型 (如 gemini-1.5-flash)
model = genai.GenerativeModel(
model_name='gemini-1.5-flash',
tools=tools # 注入工具
)
# 开启自动工具调用 (Auto Function Calling)
# Gemini 的 Python SDK 支持自动执行工具并回传结果,无需手动写循环
chat = model.startChat(enable_automatic_function_calling=True)
4. 运行 Agent
现在,我们可以像跟人聊天一样给它下指令。
response = chat.send_message("墨尔本和北京现在的天气怎么样?适合穿什么?")
print(f"🤖 Agent 回答:\n{response.text}")
幕后发生了什么?
- User: "墨尔本和北京..."
- Model: 思考 -> 决定调用
get_current_weather(location='Melbourne')和get_current_weather(location='Beijing')。 - Execution (SDK自动处理): 运行函数,获取 "Rainy, 12°C" 和 "Sunny, 25°C"。
- Model: 接收到工具结果 -> 综合生成最终建议。
- Output: "墨尔本现在下雨,12度,建议穿雨衣和保暖衣物;北京..."
5. 进阶:手动控制循环
虽然 SDK 的 enable_automatic_function_calling=True 很方便,但在复杂的 Agent 系统(如 LangChain/LangGraph)中,我们需要手动控制这个循环,以便处理错误、添加日志或人工介入。
手动循环伪代码:
messages = [...] # ...
while True:
# 1. 调用 LLM
response = model.generate_content(messages)
# 2. 检查是否有 Tool Call
if not response.function_calls:
break # 没工具调用,直接结束
# 3. 执行工具
for call in response.function_calls:
tool_result = execute_tool(call.name, call.args)
# 4. 将结果追加到对话历史
messages.append({
"role": "tool",
"name": call.name,
"content": tool_result
})
# 5. 循环继续,LLM 看到工具结果后会生成下一步
小结
构建一个 Agent 其实就是构建一个 While Loop:
- Ask: 问模型要做什么。
- Act: 执行模型要求的动作。
- Observe: 把结果喂回给模型。
- Repeat: 重复直到模型说“做完了”。