AI函数调用技术:并行与多函数调用
一、并行函数调用
(一)核心概念
自2023年11月后发布的GPT系列模型,在Function Calling架构下支持并行函数调用,可在单个响应中生成多个函数调用,适用于处理涉及多个实体触发函数调用或函数执行时间长的场景,以此提升效率。
(二)代码示例与逻辑图
from openai import OpenAI
import json
client = OpenAI()
def query_by_product_name(product_name):
products = [
('001', '足球', '高品质职业比赛用球', '圆形, 直径22 cm', '职业比赛、学校体育课', '耐克', 120.0, 50),
('002', '羽毛球拍', '轻量级, 适合初中级选手,提供优秀的击球感受', '碳纤维材质, 重量85 g', '业余比赛、家庭娱乐', '尤尼克斯', 300.0, 30),
('003', '篮球', '室内外可用,耐磨耐用, 适合各种天气条件', '皮质,标准7号球', '学校、社区运动场', '斯伯丁', 200.0, 40),
('004', '跑步鞋', '适合长距离跑步, 舒适透气,提供良好的足弓支撑', '多种尺码, 透气网布', '长跑、日常训练', '阿迪达斯', 500.0, 20),
('008', '乒乓球拍套装', '包括两只拍子和三个球,适合家庭娱乐和业余训练', '标准尺寸, 拍面防滑处理', '家庭、社区', '双鱼', 160.0, 35)
]
return [prod for prod in products if product_name in prod[1]]
tools = [
{
"type": "function",
"function": {
"name": "query_by_product_name",
"description": "Query the database to retrieve a list of products that match or contain the given product name.",
"parameters": {
"type": "object",
"properties": {
"product_name": {"type": "string"}
},
"required": ["product_name"]
}
}
}
]
messages = []
while True:
prompt = input('\n提出一个问题:')
if prompt.lower() == "退出":
break
messages.append({'role': 'user', 'content': prompt})
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools
)
response = completion.choices[0].message
tool_calls = response.tool_calls
if tool_calls:
messages.append(response)
#重点关注
for tool_call in tool_calls:
args = json.loads(tool_call.function.arguments)
res = query_by_product_name(args["product_name"])
messages.append({
"role": "tool",
"name": "query_by_product_name",
"content": str(res),
"tool_call_id": tool_call.id
})
final_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
).choices[0].message.content
messages.append({'role': 'assistant', 'content': final_response})
print(final_response)
else:
print(response.content)
messages.append({'role': 'assistant', 'content': response.content})
(三)代码逻辑图
二、多函数调用
(一)核心概念
多函数调用允许在一个系统中定义多个不同功能的函数,并让大模型根据用户需求自动选择和调用合适的函数。实现多函数调用主要通过定义新函数、添加其Json Schema表述并加入工具列表,以及在支持函数列表中增加对应键值对等步骤。
(二)代码示例与逻辑图
from openai import OpenAI
import json
client = OpenAI()
def query_by_product_name(product_name):
products = [
('001', '足球', '高品质职业比赛用球', '圆形, 直径22 cm', '职业比赛、学校体育课', '耐克', 120.0, 50),
('002', '羽毛球拍', '轻量级, 适合初中级选手,提供优秀的击球感受', '碳纤维材质, 重量85 g', '业余比赛、家庭娱乐', '尤尼克斯', 300.0, 30),
('003', '篮球', '室内外可用,耐磨耐用, 适合各种天气条件', '皮质,标准7号球', '学校、社区运动场', '斯伯丁', 200.0, 40),
('004', '跑步鞋', '适合长距离跑步, 舒适透气,提供良好的足弓支撑', '多种尺码, 透气网布', '长跑、日常训练', '阿迪达斯', 500.0, 20),
('008', '乒乓球拍套装', '包括两只拍子和三个球,适合家庭娱乐和业余训练', '标准尺寸, 拍面防滑处理', '家庭、社区', '双鱼', 160.0, 35)
]
return [prod for prod in products if product_name in prod[1]]
def read_store_promotions(product_name):
file_path = 'store_promotions.txt'
try:
with open(file_path, 'r', encoding='utf-8') as file:
promotions = file.readlines()
return "".join([line for line in promotions if product_name in line]) or "无相关优惠"
except Exception as e:
return f"查询失败: {str(e)}"
#修改一
tools = [
{
"type": "function",
"function": {
"name": "query_by_product_name",
"description": "Query the database to retrieve a list of products that match or contain the given product name.",
"parameters": {
"type": "object",
"properties": {
"product_name": {"type": "string"}
},
"required": ["product_name"]
}
}
},
{
"type": "function",
"function": {
"name": "read_store_promotions",
"description": "Read the store's promotion document to find specific promotions related to the given product name.",
"parameters": {
"type": "object",
"properties": {
"product_name": {"type": "string"}
},
"required": ["product_name"]
}
}
}
]
#修改二
available_functions = {
"query_by_product_name": query_by_product_name,
"read_store_promotions": read_store_promotions
}
messages = []
while True:
prompt = input('\n提出一个问题:')
if prompt.lower() == "退出":
break
messages.append({'role': 'user', 'content': prompt})
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
parallel_tool_calls=False
)
response = completion.choices[0].message
tool_calls = response.tool_calls
if tool_calls:
messages.append(response)
for tool_call in tool_calls:
#关键
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
res = available_functions[func_name](**args)
messages.append({
"role": "tool",
"name": func_name,
"content": str(res),
"tool_call_id": tool_call.id
})
final_response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
).choices[0].message.content
messages.append({'role': 'assistant', 'content': final_response})
print(final_response)
else:
print(response.content)
messages.append({'role': 'assistant', 'content': response.content})
(三)代码逻辑图
三、Function Calling的局限与AI Agent的需求
面对复杂任务需求(如一条文本涉及多个复杂需求,且工具调用存在顺序依赖或前后输出依赖)时,Function Calling无法满足,需要借助AI Agent框架来实现自主决策和复杂任务处理。OpenAI通过Assistant API实现智能代理功能,后续课程将详细介绍。React理念不仅适用于OpenAI的GPT模型,也是主流AI Agent框架的技术变种,掌握其原理和源码实现思想十分必要,下节课将基于React基础理论和进阶案例,帮助理解复杂文本生成和工作流场景下的应用。