06-day2-实验-agent分析选择工具-程序
刚刚成功体验了“工具调用”的核心思想 👏。
进一步 使用 通义千问(Qwen)原生支持的 Tools 能力 ——Qwen 系列模型的一大优势!
✅ Qwen-Max / Qwen-Plus 等模型原生支持 Function Calling(工具调用)
✅ 定义工具,让模型自动决定是否调用、传什么参数
✅ 不需要手动编辑规则
🚀 目标:用 Qwen 原生 Function Calling 实现自动工具调用
- 定义两个工具:
get_current_time,get_weather - 使用 DashScope SDK 或 LangChain + Qwen Function Calling
- 让 Qwen 自主解析用户意图并调用工具
✅ 推荐方案:使用 DashScope 官方 SDK(最稳定、最直接)
LangChain 对 Qwen 的 function calling 支持有时滞后,
而 DashScope 是阿里官方 API,对 Qwen 工具调用支持最好。
🔧 步骤 1:安装 DashScope SDK
# 1. 创建工作目录
mkdir day2; cd day2;
# 2. 创建虚拟环境
python3 -m venv day2-tools
# 3. 激活虚拟环境
source day2-tools/bin/activate
# 4. 升级 pip(避免旧版 bug)
pip install --upgrade pip -i https://mirrors.aliyun.com/pypi/simple/
# 5. 安装 dashscope 软件
pip install dashscope
🔧 步骤 2:创建 qwen_tool_calling.py
tee day2_qwen_tool_calling.py <<'EOF'
# qwen_tool_calling.py
import os
import json
from dotenv import load_dotenv
import dashscope
from dashscope import Generation
from datetime import datetime
# 加载 API Key
load_dotenv()
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
# ===== 定义工具函数 =====
def get_current_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def get_weather(city: str):
weather_data = {
"北京": "晴,15°C",
"上海": "多云,22°C",
"成都": "小雨,18°C"
}
return f"{city}今天{weather_data.get(city, '天气未知')}"
# ===== 工具描述 =====
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "获取当前日期和时间",
"parameters": {
"type": "object",
"properties": {},
"required": []
}
}
},
{
"type": "function",
"function": {
"name": "get_weather",
"description": "查询指定城市的天气",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "城市名称,如'北京'、'上海'"
}
},
"required": ["city"]
}
}
}
]
# ===== 用户问题 =====
user_input = "现在几点?成都天气如何?"
# ===== 第一次调用 =====
response = Generation.call(
model="qwen-max",
messages=[{"role": "user", "content": user_input}],
tools=tools,
tool_choice="auto" # ←←← 【允许模型自主决定,这是这一章要阐述的重点。】
)
message = response.output.choices[0].message
if "tool_calls" in message:
tool_calls = message["tool_calls"]
tool_results = []
for tool_call in tool_calls:
func_name = tool_call["function"]["name"]
# ✅ 关键修复:解析 arguments 为 dict
args_str = tool_call["function"].get("arguments", "{}")
args = json.loads(args_str) # ←←← 这里!
if func_name == "get_current_time":
result = get_current_time()
elif func_name == "get_weather":
city = args.get("city", "北京") # 现在 args 是 dict,可以 .get()
result = get_weather(city)
else:
result = "未知工具"
tool_results.append({
"tool_call_id": tool_call["id"],
"output": result
})
# ===== 第二次调用 =====
messages = [
{"role": "user", "content": user_input},
message,
*[{
"role": "tool",
"content": tr["output"],
"tool_call_id": tr["tool_call_id"]
} for tr in tool_results]
]
final_response = Generation.call(
model="qwen-max",
messages=messages,
tools=tools
)
answer = final_response.output.choices[0].message["content"]
else:
answer = message["content"]
print("最终回答:")
print(answer)
EOF
▶️ 运行
python day2_qwen_tool_calling.py
输出示例:
最终回答:
现在的时间是2026-01-24 11:30:23,而成都今天的天气情况是小雨,气温为18°C。
✅ 优势
| 特性 | 说明 |
|---|---|
| 官方支持 | 使用 DashScope SDK,100% 兼容 Qwen 工具调用协议 |
| 自动决策 | 模型自己判断是否需要调工具、传什么参数 |
| 结构清晰 | 两轮对话:1) 决策 2) 回答 |
| 可扩展 | 添加新工具只需加一个函数 + 一个 tool 描述 |
📌
- Qwen 的 function calling 要求
model="qwen-max"或qwen-plus tool_choice="auto"是关键,允许模型自主选择- 所有工具调用必须通过 两轮交互 完成(这是 LLM 工具调用的标准流程)
这个例子是 真正意义上的 Qwen 工具调用 Agent!🎉
下一步可以:
- 接入真实天气 API(如和风天气)
- 添加“查汇率”、“读文件”等工具
- 用
input()实现交互式提问
浙公网安备 33010602011771号