什么是FunctionCalling
Function Calling(函数调用)是大型语言模型(如 OpenAI 的 GPT 系列)提供的一种能力,允许模型在生成文本的过程中调用外部函数或工具,以完成更复杂的任务。通过 Function Calling,模型可以将自然语言请求转换为结构化的函数调用,从而与外部系统、API 或工具进行交互。
想象你有一个智能助手(比如 GPT),它可以回答你的问题,但它本身无法直接执行某些操作,比如查询天气、发送邮件或查询数据库。这时,Function Calling 就像给这个助手提供了一组工具(函数),让它可以根据你的需求调用这些工具来完成具体任务。例如:
-
你问助手:“今天北京的天气怎么样?”
-
助手不会直接回答天气,而是调用一个外部的“天气查询函数”,获取天气数据后,再生成回答。
Function Calling工作流程
Function Calling指的是大模型在生成回复的过程中可以调用外部函数来处理它无法解决的问题,的实现原理如下
-
要使用 Function Calling我们需要先定义函数:比如预先定义一组函数(例如查询天气、发送邮件、查询数据库等),并描述这些函数的功能和输入参数。
-
当用户提出请求时,模型会判断是否需要调用函数。如果需要,模型会生成一个结构化的函数调用请求
-
执行函数:开发者编写的代码接收到函数调用请求后,执行对应的函数,模型根据函数返回的结果,生成自然语言回答给用户
实现天气查询助手
以下是一个简单的 Function Calling 示例,假设我们需要实现一个天气查询助手,首先找到一个天气查询的平台,我这里使用:https://www.weatherapi.com/my/,注册账号后得到一个APIkey,如下
然后我们需要准备一个调用天气API的函数,python 代码片段如下:(后面会有完整代码)
# 使用 WeatherAPI 的天气查询函数
def get_weather(city: str):# 使用 WeatherAPI 的 API 来获取天气信息api_key = "你的天气的APIkEY" # 替换为你自己的 WeatherAPI APIKEYbase_url = "http://api.weatherapi.com/v1/current.json"params = {'key': api_key,'q': 'Beijing','aqi': 'no' # 不需要空气质量数据}# 调用天气 APIresponse = requests.get(base_url, params=params)if response.status_code == 200:data = response.json()#拿到天气和温度weather = data['current']['condition']['text']temperature = data['current']['temp_c']return f"城市 {city} 天气是 {weather} 温度为 {temperature}°C."else:return f"无法检索 {city} 的天气信息 ."
然后我们定义 tools ,大模型通过tools来调用天气函数:(后面会有完整代码)
# 定义 OpenAI 的 function calling tools
tools = [{'type': 'function','function': {'name': 'get_weather','description': 'Get the current weather for a given city.','parameters': {'type': 'object','properties': {'city': {'type': 'string','description': 'The name of the city to query weather for.',},},'required': ['city'],},}}
]
接着我们调用大模型,并指定 tools 属性,如下
def function_call_playground(prompt):messages = [{'role': 'user', 'content': prompt}]# 发送请求到 OpenAI APIresponse = client.chat.completions.create(model="deepseek-ai/DeepSeek-V2.5",messages=messages,temperature=0.01,top_p=0.95,stream=False,# 默认值,由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数,详见官方文档tool_choice="auto",tools=tools #指定 function calling tools)
完整代码如下:
import requests
from openai import OpenAI
#这里使用的是硅基流动的API接口
client = OpenAI(api_key="硅基流动的apikey", # 从https://cloud.siliconflow.cn/account/ak获取base_url="https://api.siliconflow.cn/v1"
)# 使用 WeatherAPI 的天气查询函数
def get_weather(city: str):# 使用 WeatherAPI 的 API 来获取天气信息api_key = "天气的APIkey" # 替换为你自己的 WeatherAPI APIKEYbase_url = "http://api.weatherapi.com/v1/current.json"params = {'key': api_key,'q': 'Beijing','aqi': 'no' # 不需要空气质量数据}# 调用天气 APIresponse = requests.get(base_url, params=params)if response.status_code == 200:data = response.json()#拿到天气和温度weather = data['current']['condition']['text']temperature = data['current']['temp_c']return f"城市 {city} 天气是 {weather} 温度为 {temperature}°C."else:return f"无法检索 {city} 的天气信息 ."# 定义 OpenAI 的 function calling tools
tools = [{'type': 'function','function': {'name': 'get_weather','description': 'Get the current weather for a given city.','parameters': {'type': 'object','properties': {'city': {'type': 'string','description': 'The name of the city to query weather for.',},},'required': ['city'],},}}
]# 发送请求并处理 function calling
def function_call_playground(prompt):messages = [{'role': 'user', 'content': prompt}]# 发送请求到 OpenAI APIresponse = client.chat.completions.create(model="deepseek-ai/DeepSeek-V2.5",messages=messages,temperature=0.01,top_p=0.95,stream=False,# 默认值,由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数,详见官方文档tool_choice="auto",tools=tools)# 处理 API 返回的工具调用请求func1_name = response.choices[0].message.tool_calls[0].function.namefunc1_args = response.choices[0].message.tool_calls[0].function.argumentsfunc1_out = eval(f'{func1_name}(**{func1_args})')# 将结果添加到对话中并返回messages.append({'role': 'tool','content': f'{func1_out}','tool_call_id': response.choices[0].message.tool_calls[0].id})return messages# 示例使用
prompt = "how is the weather today in chegndu?"print(function_call_playground(prompt))
执行效果如下:
实现附近地图搜索
通过FunctionCalling调用百度地图进行附近搜索,和上面的思路一样,下面贴一下代码
import requests
from openai import OpenAIclient = OpenAI(api_key="你的key", # 从https://cloud.siliconflow.cn/account/ak获取base_url="https://api.siliconflow.cn/v1"
)# 使用 百度地图查询
def doQuery(keyword: str):api_key = "你的百度地图的key" # 替换为你自己的APIKEYbase_url = "https://api.map.baidu.com/place/v2/search"params = {'ak': api_key,'query': keyword,'radius': 2000,'output': "json",'location': '30.538031,104.061420' # 以成都为中心点}# 调用APIresponse = requests.get(base_url, params=params)if response.status_code == 200:data = response.json()return dataelse:return f"无法检索 {keyword} 信息."# 定义 OpenAI 的 function calling tools
tools = [{'type': 'function','function': {'name': 'doQuery','description': 'Search for nearby restaurants based on the given keyword','parameters': {'type': 'object','properties': {'keyword': {'type': 'string','description': 'The name of the keyword to query for near.',},},'required': ['keyword'],},}}
]# 发送请求并处理 function calling
def function_call_playground(prompt):messages = [{'role': 'user', 'content': prompt}]# 发送请求到 OpenAI APIresponse = client.chat.completions.create(model="deepseek-ai/DeepSeek-V2.5",messages=messages,temperature=0.01,top_p=0.95,stream=False,# 默认值,由 GPT 自主决定返回 function call 还是返回文字回复。也可以强制要求必须调用指定的函数,详见官方文档tool_choice="auto",tools=tools)# 处理 API 返回的工具调用请求func1_name = response.choices[0].message.tool_calls[0].function.namefunc1_args = response.choices[0].message.tool_calls[0].function.argumentsfunc1_out = eval(f'{func1_name}(**{func1_args})')# 将结果添加到对话中并返回messages.append({'role': 'tool','content': f'{func1_out}','tool_call_id': response.choices[0].message.tool_calls[0].id})return messages# 示例使用
prompt = "附近有哪些:饭店"print(function_call_playground(prompt))
文章就写到这,喜欢请给个好评!!!