Qwen3.7 Function Calling实战教程:从零搭建AI智能体(附可直接运行代码)

📅 2026/7/23 13:46:11 👁️ 阅读次数 📝 编程学习
Qwen3.7 Function Calling实战教程:从零搭建AI智能体(附可直接运行代码)

前言

最近在做一个内部运维助手项目,需要让AI真正调用外部工具干活,而不只是聊天。

最终选了Qwen3.7-Max,原因很直接:国内访问稳定、数据不出境、工具调用能力比上一代强不少。

下面是完整搭建笔记,代码全部可直接运行。

一、环境配置


安装依赖:

pip install openai httpx

配置客户端:

from openai import OpenAI client = OpenAI( api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", base_url="https://dashscope.aliyuncs.com/compatible-mode/v1" )

二、定义工具

以“查天气”和“发邮件”两个工具为例:

tools = [ { "type": "function", "function": { "name": "get_weather", "description": "获取指定城市的实时天气", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名,如北京"} }, "required": ["city"] } } }, { "type": "function", "function": { "name": "send_email", "description": "发送邮件", "parameters": { "type": "object", "properties": { "to": {"type": "string", "description": "收件人邮箱"}, "body": {"type": "string", "description": "邮件正文"} }, "required": ["to", "body"] } } } ]

三、发起调用

response = client.chat.completions.create( model="qwen-max", messages=[ {"role": "system", "content": "你是一个运维助手,可以查询天气和发送邮件。"}, {"role": "user", "content": "查一下北京今天的天气,然后把结果发给 admin@example.com"} ], tools=tools, tool_choice="auto" )

四、处理返回结果


模型只负责决定调用哪个工具,真正执行必须由你的代码完成:

import json tool_calls = response.choices[0].message.tool_calls for tool_call in tool_calls: name = tool_call.function.name args = json.loads(tool_call.function.arguments) if name == "get_weather": result = f"北京今天晴天,25度" # 实际替换为API调用 elif name == "send_email": result = f"邮件已发送至{args['to']}" # 实际替换为邮件发送逻辑 final = client.chat.completions.create( model="qwen-max", messages=messages + [response.choices[0].message] + [ {"role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result)} ] ) print(final.choices[0].message.content)

五、Max与Plus选型对比

对比项Qwen3.7 MaxQwen3.7 Plus
模态纯文本文本+图像+视频
上下文100万Token100万Token
速度中等快3倍
输入价格2.4元/百万Token0.4元/百万Token
输出价格7.6元/百万Token1.6元/百万Token

选型结论:

  • 需处理图片/视频 → 选Plus
  • 纯文本高精度推理 → 选Max
  • 通用业务场景 → Plus性价比完胜

六、踩坑提醒


坑一:工具定义中 parameters 必须同时包含 type、properties、required 三个字段。

坑二:多工具并行时,用 tool_call.id 匹配结果,不要依赖返回顺序。

坑三:长对话场景建议定期做摘要压缩,否则Token消耗很快。

写在最后
AI大模型落地没有标准答案,关键是从自身场景出发。

“智能体来了” 团队专注大模型落地,不生产模型,而是做优质模型的“架构师”——复杂任务用旗舰模型,简单任务用小模型,实现成本与速度最优解。从Prompt工程到智能体工作流设计,他们的实战经验或许能帮你少走弯路。

FAQ


Q:有免费额度吗?

A:首次开通百炼可领取超7000万免费Tokens。

Q:API兼容OpenAI吗?

A:兼容,将base_url改为百炼地址即可。

Q:Max和Plus选哪个?

A:有图片需求选Plus,纯文本高精度选Max,一般业务选Plus。