大模型Function Calling是什么?
我们已经习惯大模型能回答问题、写代码、生成文案,但其本身“手无缚鸡之力”,无法直接访问数据库或实时获取天气。那么,大模型是如何突破自身限制,实现这些复杂操作的呢?答案就是——Function Calling(函数调用)。
什么是 Function Calling?
Function Calling 是一种核心能力,允许大模型在理解用户自然语言指令后,主动调用外部工具或函数。尽管大模型自身无法直接操作外部系统(如数据库、计算工具),但通过调用预设函数,它可以实现诸多功能,包括:实时数据获取(如天气、股价、新闻)、复杂计算(如数学运算、代码执行),以及操作外部系统(如发送邮件、控制智能设备)。
具体而言,模型能够将用户的自然语言请求转化为结构化参数,并传递给相应的函数。例如,当用户提问“明天北京天气如何?”,模型便会调用 get_weather(location="北京", date="2025-05-06") 函数。
此外,模型还能根据对话上下文智能判断是否以及何时调用函数,甚至能够链式调用多个函数,例如先查询天气再推荐穿搭。
举个例子🌰
以下通过一个天气查询的示例,展示 Function Calling 的实际应用。本例将向千问大模型询问北京天气,并利用自定义函数查询天气信息并返回给用户。
首先,定义一个工具函数(JSON格式),旨在向大模型说明该函数的功能及其所需参数。
import requests``from http import HTTPStatus``import dashscope``import os``# 设置 DashScope API Key``dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")# 高德天气 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"],``},``},``}
接着,编写实际调用高德地图API获取天气的函数。
def get_current_weather(location: str, adcode: str = None):``"""调用高德地图API查询天气"""``gaode_api_key = os.getenv("GAOGE_API_KEY") # 替换成你的高德API Key``base_url = "https://restapi.amap.com/v3/weather/weatherInfo"``params = {``"key": gaode_api_key,``"city": adcode if adcode else location,``"extensions": "base", # 可改为 "all" 获取预报``}``response = requests.get(base_url, params=params)``if response.status_code == 200:``return response.json()``else:``return {"error": f"Failed to fetch weather: {response.status_code}"}
最后,通过DashScope调用大模型来回答问题。大模型将根据之前定义的函数信息,自动构建出函数所需的参数值和格式,并执行函数调用。
"""使用 Qwen3 + 查询天气"""``messages = [``{"role": "system", "content": "你是一个智能助手,可以查询天气信息。"},``{"role": "user", "content": "北京现在天气怎么样?"}``]``response = dashscope.Generation.call(``model="qwen-turbo-latest", # 可使用 Qwen3 最新版本``messages=messages,``tools=[weather_tool], # 传入工具定义``tool_choice="auto", # 让模型决定是否调用工具``)``if response.status_code == HTTPStatus.OK:``# 检查是否需要调用工具``if "tool_calls" in response.output.choices[0].message:``print('response=', response.output.choices[0])``tool_call = response.output.choices[0].message.tool_calls[0]``print('tool_call=', tool_call)``if tool_call["function"]["name"] == "get_current_weather":``# 解析参数并调用高德API``import json``args = json.loads(tool_call["function"]["arguments"])``location = args.get("location", "北京")``adcode = args.get("adcode", None)``weather_data = get_current_weather(location, adcode)``print(f"查询结果:{weather_data}")``else:``print(response.output.choices[0].message.content)``else:``print(f"请求失败: {response.code} - {response.message}")
由此可见,Function Calling 的使用方式非常简洁高效。开发者只需定义并实现函数的具体功能,并将其告知大模型,大模型便能自动识别用户意图并调用相应函数,从而获取所需关键信息,极大地扩展了其应用边界。
