上一篇主要讲了如何调用OPEN AI模型的API,提前将简单信息准备好后可以完成简单的机器人互动,这一章主要介绍如何通过API回调我们自己本地的方法
当触发某一个具体业务功能时,我们将用自己实现的方法精确处理逻辑时,通过此方法可以满足该场景
https://platform.openai.com/docs/guides/function-calling
在 API 调用中,您可以描述函数,并让模型智能地选择输出包含调用一个或多个函数的参数的 JSON 对象。聊天完成 API 不会调用该函数;相反,模型会生成 JSON,您可以使用它来调用代码中的函数。
最新模型(gpt-3.5-turbo-1106 和 gpt-4-turbo-preview)经过训练,可以检测何时应调用函数(取决于输入)并使用符合函数签名的 JSON 进行响应比以前的型号更接近。这种能力也带来了潜在的风险。我们强烈建议在代表用户采取影响世界的行动(发送电子邮件、在线发布内容、购买等)之前构建用户确认流程。
定义对话模型,声明工具方法类
def get_completion(messages, model="gpt-3.5-turbo"):
response = client.chat.completions.create(
model=model,
messages=messages,
temperature=0.7, # 模型输出的随机性,0 表示随机性最小
tools=[{ # 用 JSON 描述函数。可以定义多个。由大模型决定调用谁。也可能都不调用
"type": "function",
"function": {
"name": "sum",
"description": "加法器,计算一组数的和",
"parameters": {
"type": "object",
"properties": {
"numbers": {
"type": "array",
"items": {
"type": "number"
}
}
}
}
}
}],
)
return response.choices[0].message
对话模拟,大模型判断调用工具类
if __name__ == "__main__":
prompt = "1+2+3"
messages = [
{"role": "system", "content": "你是一个数学家"},
{"role": "user", "content": prompt}
]
response = get_completion(messages)
# 把大模型的回复加入到对话历史中
print_json(response)
messages.append(response)
print("=====GPT回复=====")
print_json(response)
# 如果返回的是函数调用结果,则打印出来
if (response.tool_calls is not None):
# 是否要调用 sum
tool_call = response.tool_calls[0]
if (tool_call.function.name == "sum"):
# 调用 sum
args = json.loads(tool_call.function.arguments)
result = sum(args["numbers"])
print("=====函数返回=====")
print(result)
# 把函数调用结果加入到对话历史中
messages.append(
{
"tool_call_id": tool_call.id, # 用于标识函数调用的 ID
"role": "tool",
"name": "sum",
"content": str(result) # 数值 result 必须转成字符串
}
)
# 再次调用大模型
print("=====最终回复=====")
print(get_completion(messages).content)
{
"content": null,
"role": "assistant",
"function_call": null,
"tool_calls": [
{
"id": "call_E4GpMEOSsaOMhi6Vwc0REjaX",
"function": {
"arguments": "{\n \"numbers\": [1, 2, 3]\n}",
"name": "sum"
},
"type": "function"
}
]
}
=====GPT回复=====
{
"content": null,
"role": "assistant",
"function_call": null,
"tool_calls": [
{
"id": "call_E4GpMEOSsaOMhi6Vwc0REjaX",
"function": {
"arguments": "{\n \"numbers\": [1, 2, 3]\n}",
"name": "sum"
},
"type": "function"
}
]
}
=====函数返回=====
6
=====最终回复=====
1 + 2 + 3 = 6