函数调用 (Function Calling)
概述
大模型中的函数调用又称 Function Calling
。函数调用指的是用户通过描述函数和目标任务,让大模型尝试去调用某个函数。
需要注意的是,大模型本身没有能力自行执行函数,大模型根据用户输入和函数定义,向您提供:是否需要调用、调用什么函数、函数参数。得到这些信息后,客户端再自行执行函数,再把执行结果给到大模型,进行下一轮的任务。
一些框架比如 LangGraph
、LlamaIndex
可以简化这一过程。模力方舟提供了开箱即用的大模型函数调用能力,下文将讲述如何使用。
提示
Function Calling
与 tool call
是类似概念,tool call
是升级版,已替代 Function Calling
。
工具列表需要传入 tools
。
案例一:让AI知道今天的天气,直接解析函数调用结果
本案例的方法为最直接的方法,用于理解 Function Calling
流程和原理。结合Langchain的更简便的方法实现参考 案例二
步骤一:组合tools参数
首先组合tools参数,下面向大模型描述了一个名为 get_current_weather
的函数,函数传入参数为 city
, x
, y
,函数能力是通过城市名和经纬度获取地点的天气情况:
python
tools = [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "通过城市名和日期获取地点的天气情况,包括温度、天气状况等信息",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "用户想要查询天气的城市名称",
},
"date": {
"type": "string",
"description": "想要查询的日期,如'今天'、'明天'或具体日期'2023-10-01'",
}
},
"required": ["city", "date"],
},
}
}
]
tools
是一个列表,可定义多个,参数说明:
type
:定义参数对象的类型,通常是 object,表示参数结构为一个包含多个属性的 JSON 对象。properties
:这是核心部分,列出每个参数的具体定义 JSON Schema 格式。name
:每个属性的名称,对应函数的参数名。type
:参数的数据类型,比如 string、float、integer 等。description
:描述每个参数的用途,帮助模型理解如何填充参数值。required
:指定哪些参数是必填的,如果参数在 required 列表中,那么模型在生成调用时必须填充这些参数。
步骤二:调用大模型
将上文拼凑好的 tools
参数传入客户端中,解析响应的请求,并根据请求调用定义好的 get_current_weather
函数。
python
import json
completion_tool = client.chat.completions.create(
model=model_name,
stream=False,
tools=tools,
temperature=0.1,
top_p=0.95,
tool_choice="auto",
messages=[
{"role": "system", "content": "你是聪明的助手,在需要查询天气时会调用工具。"},
{"role": "user", "content": "北京今天的天气怎么样?"}
]
)
print(completion_tool, end="\n\n")
def get_current_weather(city: str, date: str) -> str:
print(f"执行 get_current_weather, 获得的参数是: city: {city}, date: {date}")
# 模拟天气查询接口返回结果
return f"""北 京市{date}天气信息:
天气状况:晴朗
温度:25-32℃
风力:东北风3-4级
湿度:45%
紫外线强度:中等,建议外出涂抹防晒霜"""
function_res = completion_tool.choices[0].message.tool_calls[0].function
arguments_res = function_res.arguments
print("即将调用的函数是: ", function_res.name)
json_arguments = json.loads(
completion_tool.choices[0].message.tool_calls[0].function.arguments)
print(f"tool call 参数: 城市: {json_arguments['city']}, 日期: {json_arguments['date']}")
# 执行函数
eval(f'{function_res.name}(**{arguments_res})')
至此函数已成功调用!您可以将函数响应的结果处理为:
{
'role': 'tool',
'name': 'get_current_weather',
'content': '北京市今天天气信息:天气状况:晴朗...',
'tool_call_id': 'xxxx'
}