文章目录
function calling(函数调用)是至关重要的一项能力。
示例
先设置环境变量MODELSCOPE_API_KEY,值为魔搭社区的token。
代码:
python
import requests
import json
import os
import re
# ====================== 核心配置 ======================
API_KEY = os.getenv("MODELSCOPE_API_KEY", "YOUR_MODELSCOPE_TOKEN_HERE")
URL = "https://api-inference.modelscope.cn/v1/chat/completions"
MODEL_NAME = "Qwen/Qwen3.5-35B-A3B"
# ====================== 函数定义 ======================
functions = [
{
"name": "get_weather",
"description": "查询指定城市的实时天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称,如北京、上海"},
"date": {"type": "string", "description": "日期,格式YYYY-MM-DD"}
},
"required": ["city"]
}
}
]
# ====================== 真实函数 ======================
def get_weather(city: str, date: str = "2026-03-23") -> str:
weather = {
"北京": "多云转晴 5~19℃,轻度污染",
"上海": "小雨 10~15℃",
"广州": "晴 18~28℃"
}
return f"{date} {city}天气:{weather.get(city, '暂无数据')}"
# ====================== 调用模型 ======================
def run(question):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": MODEL_NAME,
"messages": [{"role": "user", "content": question}],
"functions": functions,
"function_call": "auto",
"temperature": 0.0
}
resp = requests.post(URL, headers=headers, json=data, timeout=60)
resp_data = resp.json()
print("📌 模型返回:")
print(json.dumps(resp_data, ensure_ascii=False, indent=2))
# 读取 reasoning_content(Qwen3.5 把调用决策写在这里)
message = resp_data["choices"][0]["message"]
reasoning = message.get("reasoning_content", "")
content = message.get("content", "")
print("\n🧠 模型思考内容:", reasoning)
# ====================== 关键:从自然语言 reasoning 里提取函数调用 ======================
func_name = None
city = None
date = None
if "get_weather" in reasoning:
func_name = "get_weather"
# 正则提取 city
city_match = re.search(r'city[="\s]+([^"\s]+)', reasoning)
if city_match:
city = city_match.group(1).strip('"')
# 正则提取 date
date_match = re.search(r'\d{4}-\d{1,2}-\d{1,2}', reasoning)
if date_match:
date = date_match.group(0)
# 如果识别到要调用天气函数
if func_name == "get_weather" and city:
print(f"\n✅ 成功识别函数调用:get_weather(city={city}, date={date})")
result = get_weather(city=city, date=date or "2026-03-23")
print("🌤 天气结果:", result)
return
# 否则直接输出回答
print("\n💬 模型直接回答:", content)
# ====================== 测试 ======================
if __name__ == "__main__":
print("===== 测试1:天气查询 =====")
run("北京2026-03-23的天气怎么样")
print("\n===== 测试2:纯聊天 =====")
run("介绍一下Qwen3.5-35B-A3B")
示例-流程解读
1、用户提问 "北京的天气怎么样?"
2、代码调魔搭Qwen(传functions)
3、模型思考并写调用意图到reasoning
4、代码解析思考内容(可以用文本匹配来做,例如是否包含get_weather函数、包含必填参数city等)
5、执行本地函数
6、返回结果