青岛网站排名公司服务器租用一天
2026/4/18 5:29:40 网站建设 项目流程
青岛网站排名公司,服务器租用一天,wordpress如何修改版权,全球域名注册平台1、理解 Function Call 让大模型能调用外部工具、函数#xff0c;而非仅靠自身知识库回答问题。2、流程步骤#xff1a;用户提问→模型判断调用函数→执行自定义函数→模型基于函数结果生成回答第一调用模型 让模型分析用户问题#xff0c;判断是否需要调用函数#xff0c;…1、理解 Function Call让大模型能调用外部工具、函数而非仅靠自身知识库回答问题。2、流程步骤用户提问→模型判断调用函数→执行自定义函数→模型基于函数结果生成回答第一调用模型让模型分析用户问题判断是否需要调用函数并返回调用函数指令第二次调用模型把自定义函数执行的结果传给模型模型基于真实数据生成自然语言回答比如 “大连当前温度 10 摄氏度晴天微风”3、代码# 导入JSON模块用于序列化/反序列化函数参数和返回结果 import json # 导入操作系统模块读取环境变量中的API密钥 import os # 导入通义千问SDK核心模块 import dashscope # 从环境变量读取API密钥并配置 dashscope.api_key os.environ.get(DASHSCOPE_API_KEY) # 定义天气查询函数模拟返回指定城市的天气核心业务函数 def get_current_weather(location, unit摄氏度): # 初始化温度默认-1表示未匹配城市 temperature -1 # 按城市匹配模拟温度 if 大连 in location: temperature 10 if 上海 in location: temperature 36 if 深圳 in location: temperature 37 # 构造天气信息字典并转为JSON字符串返回符合Function Call格式要求 return json.dumps({ location: location, temperature: temperature, unit: unit, forecast: [晴天, 微风] }) # 封装模型调用函数 def call_qwen(messages): try: # 调用通义千问qwen-max模型指定函数列表和返回格式 return dashscope.Generation.call( modelqwen-max, messagesmessages, functionsfunctions, result_formatmessage # 结构化消息格式便于解析函数调用 ) except Exception as e: # 捕获异常并打印返回None标识调用失败 print(fAPI调用异常: {str(e)}) return None # 核心对话逻辑实现提问→判断调用函数→执行函数→生成最终回答 def weather_qa(): # 1. 初始化用户问题和消息上下文大模型对话必须的格式rolecontent messages [{role: user, content: 大连的天气怎样}] # 2. 第一次调用模型判断是否需要调用函数 response call_qwen(messages) # 校验响应有效性失败则直接返回 if not response or not response.output: return 模型响应失败 # 提取模型返回的核心消息 assistant_msg response.output.choices[0].message # 将模型消息加入上下文保证对话连贯性 messages.append(assistant_msg) # 3. 判断模型是否要求调用函数 if hasattr(assistant_msg, function_call) and assistant_msg.function_call: # 解析函数调用参数JSON字符串转字典 args json.loads(assistant_msg.function_call[arguments]) # 执行天气查询函数获取结果 weather_result get_current_weather( locationargs.get(location), unitargs.get(unit, 摄氏度) # 设默认值避免参数缺失 ) # 构造函数调用结果消息必须按rolefunction格式 function_msg { role: function, name: assistant_msg.function_call[name], content: weather_result } # 将函数结果加入上下文 messages.append(function_msg) # 4. 第二次调用模型基于函数结果生成最终回答 final_response call_qwen(messages) if final_response and final_response.output: return final_response.output.choices[0].message.content # 若无需调用函数直接返回模型初始回答 return assistant_msg.content # 定义函数调用描述核心告诉模型可调用的函数及参数规则 functions [{ name: get_current_weather, # 必须和自定义函数名一致 description: 获取指定城市的当前天气, # 改为中文描述更适配中文提问 parameters: { type: object, properties: { location: { type: string, description: 城市名称例如大连、上海 # 中文示例更直观 }, unit: {type: string, enum: [摄氏度, 华氏度]} # 改为中文枚举值 }, required: [location] # 必填参数location } }] # 主程序入口 if __name__ __main__: # 执行问答逻辑并打印最终结果 print(最终回答, weather_qa())

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询