人工智能-function calling(函数调用)

人工智能-function calling(函数调用) 文章目录示例示例-流程解读function calling(函数调用)是至关重要的一项能力。示例先设置环境变量MODELSCOPE_API_KEY值为魔搭社区的token。代码importrequestsimportjsonimportosimportre# 核心配置 API_KEYos.getenv(MODELSCOPE_API_KEY,YOUR_MODELSCOPE_TOKEN_HERE)URLhttps://api-inference.modelscope.cn/v1/chat/completionsMODEL_NAMEQwen/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]}}]# 真实函数 defget_weather(city:str,date:str2026-03-23)-str:weather{北京:多云转晴 5~19℃轻度污染,上海:小雨 10~15℃,广州:晴 18~28℃}returnf{date}{city}天气{weather.get(city,暂无数据)}# 调用模型 defrun(question):headers{Authorization:fBearer{API_KEY},Content-Type:application/json}data{model:MODEL_NAME,messages:[{role:user,content:question}],functions:functions,function_call:auto,temperature:0.0}resprequests.post(URL,headersheaders,jsondata,timeout60)resp_dataresp.json()print( 模型返回)print(json.dumps(resp_data,ensure_asciiFalse,indent2))# 读取 reasoning_contentQwen3.5 把调用决策写在这里messageresp_data[choices][0][message]reasoningmessage.get(reasoning_content,)contentmessage.get(content,)print(\n 模型思考内容,reasoning)# 关键从自然语言 reasoning 里提取函数调用 func_nameNonecityNonedateNoneifget_weatherinreasoning:func_nameget_weather# 正则提取 citycity_matchre.search(rcity[\s]([^\s]),reasoning)ifcity_match:citycity_match.group(1).strip()# 正则提取 datedate_matchre.search(r\d{4}-\d{1,2}-\d{1,2},reasoning)ifdate_match:datedate_match.group(0)# 如果识别到要调用天气函数iffunc_nameget_weatherandcity:print(f\n✅ 成功识别函数调用get_weather(city{city}, date{date}))resultget_weather(citycity,datedateor2026-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传functions3、模型思考并写调用意图到reasoning4、代码解析思考内容(可以用文本匹配来做例如是否包含get_weather函数、包含必填参数city等)5、执行本地函数6、返回结果