共计 2378 个字符,预计需要花费 6 分钟才能阅读完成。
大型语言模型(LLM)驱动的 AI Agent 可以帮我们订外卖、查天气、自动处理工单,它们通常由三部分组成:大脑(LLM)、工具(Tools)和记忆(Memory)。今天我们就用 Python 3.10+ 和 LangChain 框架,从零实现一个会查天气预报的智能助手。

新手常踩的三个坑
刚开始开发 AI Agent 时,最容易在这些地方翻车:
- 工具调用像抽奖:API 返回格式突变或网络抖动时,程序直接崩溃
- Prompt 像玄学:少个冒号就让 LLM 开始胡说八道
- 记忆七秒鱼:对话超过 5 轮就忘记用户之前说过什么
天气预报 Agent 完整实现
1. 准备工作
首先安装必要依赖(建议新建虚拟环境):
pip install langchain openai python-dotenv requests
在项目目录创建 .env 文件存放敏感信息:
OPENAI_API_KEY= 你的 OpenAI 密钥
OPENWEATHER_API_KEY= 你的天气 API 密钥
2. 核心代码实现
下面这个 weather_agent.py 包含了完整逻辑(关键部分有详细注释):
import os
from dotenv import load_dotenv
from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent
from langchain.chains import LLMChain
from langchain.memory import ConversationBufferMemory
from langchain_community.utilities import OpenWeatherMapAPIWrapper
from langchain_openai import ChatOpenAI
# 加载环境变量
load_dotenv()
# 初始化天气查询工具
weather = OpenWeatherMapAPIWrapper()
weather_tool = Tool(
name="Weather",
func=weather.run,
description="查询城市天气,输入格式:' 城市名, 国家代码 '如'Beijing,CN'"
)
# 构建 Prompt 模板
from langchain.prompts import StringPromptTemplate
class CustomPromptTemplate(StringPromptTemplate):
template = """
你是一个专业的天气预报助手,请根据工具返回的信息回答用户问题。历史对话:{history}
问题:{input}
可用工具:{tools}
请按这个格式响应:Thought: 思考需要使用的工具
Action: 工具名称
Action Input: 工具输入参数
"""
def format(self, **kwargs):
kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in kwargs["tools"]])
return self.template.format(**kwargs)
# 设置记忆功能
memory = ConversationBufferMemory(memory_key="history")
# 创建 Agent
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo")
prompt = CustomPromptTemplate(input_variables=["input", "history", "tools"]
)
agent = LLMSingleActionAgent(llm_chain=LLMChain(llm=llm, prompt=prompt),
output_parser=... # 这里应该有输出解析器代码
stop=["\nObservation:"],
allowed_tools=[weather_tool.name]
)
# 异常处理装饰器
def api_protector(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return f"API 调用失败: {str(e)}"
return wrapper
# 执行示例
agent_executor = AgentExecutor.from_agent_and_tools(
agent=agent,
tools=[weather_tool],
memory=memory,
verbose=True
)
print(agent_executor.run("上海明天会下雨吗?"))
3. 关键点解析
- 工具封装:将 OpenWeatherMap API 包装成 LangChain 的 Tool 对象,注意 description 要写清楚输入格式
- 记忆实现 :
ConversationBufferMemory会保存最近的对话历史 - 异常防护:用装饰器捕获 API 调用时的网络异常
避坑指南
- API 限流处理:
- 在 OpenWeatherMap 控制台设置每分钟最大调用次数
-
代码中添加
time.sleep(1)避免触发限流 -
输出稳定性:
- 在 Prompt 中严格规定响应格式(如必须包含 Thought/Action 字段)
-
添加输出解析器验证 LLM 返回内容
-
隐私保护:
- 对话历史存储前做匿名化处理
- 敏感信息(如 API 密钥)永远不要硬编码在代码中
扩展思考
- 如果想让 Agent 在回答天气时顺便推荐穿衣建议,应该如何扩展工具链?
- 当需要同时查询多个城市的天气时,怎样设计多 Agent 协作流程?
这个天气预报 Agent 虽然简单,但已经包含了 AI Agent 最核心的要素。你可以在此基础上继续扩展,比如加入日程管理、交通查询等功能,慢慢构建属于自己的智能助手军团。
正文完
