旅行规划通常不是一个工具就能解决的。它本质上是多步骤任务。
1. 什么是多步骤任务
简单任务:
```text 用户:北京天气怎么样? Agent:调用 get_weather -> 返回结果 ```
复杂任务:
```text 用户:帮我规划一个北京到上海的出行计划 Agent:
- 查北京天气
- 查上海天气
- 获取当前时间
- 推荐景点
- 估算交通方式
- 综合生成建议 ```
2. 设计工具集
```python from datetime import datetime
@tool def get_weather(city: str) -> str: """查询城市天气,用于了解穿衣和出行建议""" return f"{city}:晴,温度 23°C"
@tool def get_current_time() -> str: """获取当前时间""" return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@tool def search_attractions(city: str) -> str: """搜索城市的热门景点""" attractions = { "北京": "故宫、长城、颐和园、天坛、南锣鼓巷", "上海": "外滩、东方明珠、豫园、南京路、迪士尼", "杭州": "西湖、灵隐寺、宋城、西溪湿地、千岛湖", "成都": "宽窄巷子、锦里、大熊猫基地、都江堰、青城山", } return attractions.get(city, f"{city} 暂无景点信息")
@tool def estimate_travel_time(from_city: str, to_city: str) -> str: """估算两个城市之间的交通时间""" times = { ("北京", "上海"): "高铁约 4.5 小时,飞机约 2 小时", ("上海", "杭州"): "高铁约 1 小时,自驾约 2 小时", ("北京", "杭州"): "高铁约 5 小时,飞机约 2 小时", ("成都", "北京"): "高铁约 8 小时,飞机约 2.5 小时", } key = (from_city, to_city) reverse_key = (to_city, from_city) return times.get(key) or times.get(reverse_key) or f"{from_city} 到 {to_city} 的交通信息暂无" ```
3. 让 Agent 自主拆解旅行规划
```python tools = [get_weather, get_current_time, search_attractions, estimate_travel_time] agent = create_agent(llm, tools, checkpointer=memory)
question = """ 我想在春节期间从北京去上海玩 3 天,请帮我:
- 查看两地天气
- 推荐上海的景点
- 估算交通时间
- 给出一个简单的出行建议 """
result = agent.invoke({"messages": [{"role": "user", "content": question}]}) print(result["messages"][-1].content) ```
4. Agent 的推理链路
```text 用户需求分析 ↓ 需要查天气 -> get_weather("北京"), get_weather("上海") ↓ 需要景点推荐 -> search_attractions("上海") ↓ 需要交通时间 -> estimate_travel_time("北京", "上海") ↓ 综合天气、景点、时间和交通信息 -> 输出旅行建议 ```
5. 这一课的重点
- 复杂任务的关键不是“写更大的 prompt”,而是“准备一组可协作的工具”
- Agent 的价值在于能自己组织工具调用顺序
- 旅行助手就是一个非常典型的多工具协同场景