部分模型支持函数调用对模型能力进行扩展和增强,你可以在模型广场中通过 函数调用
标签筛选查看支持函数调用的模型。
函数调用链路较普通的对话流程更加复杂,需要在提交问题时附带函数名称描述信息,以及调用函数需要的参数,如果用户问题意图和函数名称描述匹配,并且参数齐全(不够的话会引导用户提交),那么AI响应会返回匹配的函数名和标识该函数的ID,客户端根据函数名和参数调用本地函数后,将执行结果和函数ID一起再次提交给AI模型,AI模型会根据上下文基于函数调用结果回答用户最初的问题,这就是函数调用的基本流程。
下面我们以获取当地天气为例,给出函数调用的示例代码:
curl --location --request POST 'https://geekai.co/api/v1/chat/completions' \
--header 'Authorization: Bearer {YOUR_GEEKAI_API_KEY}' \
--header 'Content-Type: application/json' \
--data-raw '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "你是一个乐于助人的客户服务助理,请使用提供的工具来协助用户。"
},
{
"role": "user",
"content": "你好,杭州今天的天气怎么样?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_current_weather",
"description": "获取给定地区的天气信息",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市或者地区,如浙江杭州"
},
"unit": {
"type": "string",
"enum": ["℃","℉"]
}
},
"required": [
"location"
]
}
}
}
],
"tool_choice": "auto"
}'
正如前面提到的,函数调用需要在提交问题时附带 tools
字段指定函数名称、描述以及参数信息,以及 tool_choice
字段用于设置是否让AI模型根据用户意图自动选择要调用的函数。
执行上述代码后,会返回如下响应消息字段:
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": "call_wrpN3RNE7AYlFRxEwaD5DSWA",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{\"location\":\"杭州, 中国\"}"
}
}
]
},
"finish_reason": "tool_calls"
}
],
可以看到,AI响应中包含了 tool_calls
字段,其中包含了函数调用的ID和参数信息,客户端根据这些信息调用本地函数 get_current_weather
后,将执行结果和函数ID一起再次提交给AI模型:
curl --location --request POST 'https://geekai.co/api/v1/chat/completions' \
--header 'Authorization: Bearer {YOUR_GEEKAI_API_KEY}' \
--header 'Content-Type: application/json' \
--data-raw '{
"model": "gpt-4o-mini",
"messages": [
{
"role": "system",
"content": "你是一个乐于助人的客户服务助理,请使用提供的工具来协助用户。"
},
{
"role": "user",
"content": "你好,杭州今天的天气怎么样?"
},
{
"role":"assistant",
"tool_calls": [
{
"id": "call_wrpN3RNE7AYlFRxEwaD5DSWA",
"type": "function",
"function": {
"name": "get_current_weather",
"arguments": "{\"location\":\"杭州, 中国\"}"
}
}
]
},
{
"role": "tool",
"content": "{\"location\":\"杭州, 中国\", \"weather\":\"晴转多云\"}",
"tool_call_id": "call_wrpN3RNE7AYlFRxEwaD5DSWA"
}
]
}'
AI模型会根据上下文基于函数调用结果回答用户最初的问题: