海南藏族自治州网站建设_网站建设公司_测试上线_seo优化
2025/12/20 22:18:22 网站建设 项目流程

文章目录

  • 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_key="sk-**********"# 高德天气 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:str=None):"""调用高德地图API查询天气"""gaode_api_key="你的API KEY"# 替换成你的高德API Keybase_url="https://restapi.amap.com/v3/weather/weatherInfo"params={"key":gaode_api_key,"city":adcodeifadcodeelselocation,"extensions":"base",# 可改为 "all" 获取预报}response=requests.get(base_url,params=params)ifresponse.status_code==200:returnresponse.json()else:return{"error":f"Failed to fetch weather:{response.status_code}"}defrun_weather_query():"""使用 Qwen3 + 查询天气"""messages=[{"role":"system","content":"你是一个智能助手,可以查询天气信息。"},{"role":"user","content":"北京现在天气怎么样?"}]response=dashscope.Generation.call(model="qwen-turbo",# 可使用 Qwen3 最新版本messages=messages,tools=[weather_tool],# 传入工具定义tool_choice="auto",# 让模型决定是否调用工具)ifresponse.status_code==HTTPStatus.OK:# 检查是否需要调用工具if"tool_calls"inresponse.output.choices[0].message:tool_call=response.output.choices[0].message.tool_calls[0]iftool_call["function"]["name"]=="get_current_weather":# 解析参数并调用高德APIimportjson args=json.loads(tool_call["function"]["arguments"])location=args.get("location","北京")adcode=args.get("adcode",None)weather_data=get_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()

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

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

立即咨询