2026/6/9 11:06:49
网站建设
项目流程
做网站需要懂什么,有没有免费代理项目,qq空间钓鱼网站制作,网站内容建设整改工作文章目录Function Calling在大模型中的作用Function Calling在大模型中的作用
扩展模型能力 大模型本身无法直接操作外部系统#xff08;如数据库、计算工具#xff09;#xff0c;但通过调用预设函数#xff0c;可以完成#xff1a; 实时数据获取#xff08;天气、股价…文章目录Function Calling在大模型中的作用Function Calling在大模型中的作用扩展模型能力大模型本身无法直接操作外部系统如数据库、计算工具但通过调用预设函数可以完成实时数据获取天气、股价、新闻复杂计算数学运算、代码执行操作外部系统发送邮件、控制智能设备结构化输出模型可将用户自然语言请求转化为结构化参数传递给函数。例如用户说“明天北京天气如何” → 模型调用 get_weather(location“北京”, date“2025-05-06”)动态决策流程模型可根据上下文决定是否/何时调用函数甚至链式调用多个函数如先查天气再推荐穿搭。Function Call是大模型与真实世界交互的“桥梁”从语言理解 具体行动Function Calling与MCP的区别Function Calling的优势开发快捷无需配置 MCP Server直接通过模型 API 调用预定义函数。低延迟单次请求-响应无需协议层开销。MCP 可能成为主流但 Function Calling 作为底层能力仍将存在importrequestsfromhttpimportHTTPStatusimportdashscope# 设置 DashScope API Keydashscope.api_keysk-**********# 高德天气 API 的 天气工具定义JSON 格式weather_tool{type:function,function:{name:get_current_weather,description:Get the current weather in a given location,parameters:{type:object,properties:{location:{type:string,description:The city name, e.g. 北京,},adcode:{type:string,description:The city code, e.g. 110000 (北京),}},required:[location],},},}defget_weather_from_gaode(location:str,adcode:strNone):调用高德地图API查询天气gaode_api_key你的API KEY# 替换成你的高德API Keybase_urlhttps://restapi.amap.com/v3/weather/weatherInfoparams{key:gaode_api_key,city:adcodeifadcodeelselocation,extensions:base,# 可改为 all 获取预报}responserequests.get(base_url,paramsparams)ifresponse.status_code200:returnresponse.json()else:return{error:fFailed to fetch weather:{response.status_code}}defrun_weather_query():使用 Qwen3 查询天气messages[{role:system,content:你是一个智能助手可以查询天气信息。},{role:user,content:北京现在天气怎么样}]responsedashscope.Generation.call(modelqwen-turbo,# 可使用 Qwen3 最新版本messagesmessages,tools[weather_tool],# 传入工具定义tool_choiceauto,# 让模型决定是否调用工具)ifresponse.status_codeHTTPStatus.OK:# 检查是否需要调用工具iftool_callsinresponse.output.choices[0].message:tool_callresponse.output.choices[0].message.tool_calls[0]iftool_call[function][name]get_current_weather:# 解析参数并调用高德APIimportjson argsjson.loads(tool_call[function][arguments])locationargs.get(location,北京)adcodeargs.get(adcode,None)weather_dataget_weather_from_gaode(location,adcode)print(f查询结果{weather_data})else:print(response.output.choices[0].message.content)else:print(f请求失败:{response.code}-{response.message})if__name____main__:run_weather_query()