OpenAI 函数调用教程

推荐:使用 NSDT场景编辑器 快速搭建3D应用场景

 

什么是OpenAI函数调用?

OpenAI API 非常擅长以系统的方式生成响应。只需几行代码即可管理提示、优化模型输出以及执行、生成和语言应用程序。

即使有这么多好东西,OpenAI API对开发人员和工程师来说也是一场噩梦。为什么?他们习惯于使用结构化数据类型,并且很难处理字符串等非结构化数据。

为了获得一致的结果,开发人员必须使用正则表达式 (RegEx) 或提示工程从文本字符串中提取信息。

这就是OpenAI的函数调用功能的用武之地。它允许 GPT-3.5 和 GPT-4 模型将用户定义的函数作为输入并生成结构输出。这样,您无需编写正则表达式或执行提示工程。

在本教程中,我们将探讨 OpenAI 函数调用如何帮助解决由不规则模型输出引起的常见开发人员问题。

如果您刚刚开始使用 ChatGPT 和 OpenAI API,请考虑查看 OpenAI API 和 ChatGPT 入门网络研讨会。此资源可以指导您完成语言和编码生成,并帮助您使用 Python API 执行基本任务。

使用OpenAI而无需调用函数

在本节中,我们将使用 GPT-3.5-Turbo 模型生成响应,而无需调用函数,以查看我们是否获得一致的输出。

在安装 OpenAI Python API 之前,您必须获取 API 密钥并在本地系统上进行设置。通过 Python 中的 OpenAI API 教程关注 GPT-3.5 和 GPT-4,了解如何获取 API 密钥并进行设置。本教程还包括在数据营工作区中设置环境变量的示例。

如需进一步帮助,请查看 OpenAI 函数调用工作区中的带有输出的笔记本。

我们将随机编写学生描述。您可以想出自己的文本,也可以使用 ChatGPT 为您生成一个。

student_1_description = "David Nguyen is a sophomore majoring in computer science at Stanford University. He is Asian American and has a 3.8 GPA. David is known for his programming skills and is an active member of the university's Robotics Club. He hopes to pursue a career in artificial intelligence after graduating."

在下一部分中,我们将编写一个提示,以从文本中提取学生信息,并将输出作为 JSON 对象返回。我们将在学生描述中提取姓名、专业、学校、年级和俱乐部。

# A simple prompt to extract information from "student_description" in a JSON format.prompt1 = f''' Please extract the following information from the given text and return it as a JSON object: name major school grades club This is the body of text to extract the information from: {student_1_description}'''

将提示添加到 OpenAI API 聊天完成模块以生成响应。

import openai # Generating response back from gpt-3.5-turboopenai_response = openai.ChatCompletion.create(    model = 'gpt-3.5-turbo',    messages = [{'role': 'user', 'content': prompt1}])openai_response['choices'][0]['message']['content']

反响相当不错。让我们将其转换为 JSON 以更好地理解它。

'{\n  "name": "David Nguyen",\n  "major": "computer science",\n  "school": "Stanford University",\n  "grades": "3.8 GPA",\n  "club": "Robotics Club"\n}'

我们将使用该库将文本转换为 JSON 对象。json

import json # Loading the response as a JSON objectjson_response = json.loads(openai_response['choices'][0]['message']['content'])json_response

最终的结果几乎是完美的。那么,为什么我们需要函数调用?

{'name': 'David Nguyen', 'major': 'computer science', 'school': 'Stanford University', 'grades': '3.8 GPA', 'club': 'Robotics Club'}

让我们尝试相同的提示,但使用不同的学生描述。

student_2_description="Ravi Patel is a sophomore majoring in computer science at the University of Michigan. He is South Asian Indian American and has a 3.7 GPA. Ravi is an active member of the university's Chess Club and the South Asian Student Association. He hopes to pursue a career in software engineering after graduating."

我们只会在提示中更改学生描述文本。

prompt2 = f''' Please extract the following information from the given text and return it as a JSON object: name major school grades club This is the body of text to extract the information from: {student_2_description}'''

并使用第二个提示符运行聊天完成功能。

openai_response = openai.ChatCompletion.create(    model = 'gpt-3.5-turbo',    messages = [{'role': 'user', 'content': prompt2 }]) # Loading the response as a JSON objectjson_response = json.loads(openai_response['choices'][0]['message']['content'])json_response

如您所见,它并不一致。

  • 第一个学生的成绩是“3.8 GPA”,而在第二个学生提示中,我们只得到数字“3.7”。当您构建稳定的系统时,这是一件大事。
  • 它没有返回一个俱乐部,而是返回了拉维加入的俱乐部名单。它也与第一个学生不同。

{'name': 'Ravi Patel', 'major': 'computer science', 'school': 'University of Michigan', 'grades': '3.7', 'club': ['Chess Club', 'South Asian Student Association']}

开放人工智能函数调用示例

为了解决此问题,我们现在将使用最近引入的称为函数调用的功能。必须创建自定义函数以将必要的信息添加到字典列表中,以便 OpenAI API 可以理解其功能。

  • name:写下您最近创建的 Python 函数名称。
  • 说明:函数的功能。
  • 参数:在“属性”中,我们将写入参数的名称、类型和描述。它将帮助OpenAI API识别我们正在寻找的世界。

注意:请确保您遵循正确的模式。通过阅读官方文档了解有关函数调用的更多信息。

student_custom_functions = [
{
'name': 'extract_student_info',
'description': 'Get the student information from the body of the input text',
'parameters': {
'type': 'object',
'properties': {
'name': {
'type': 'string',
'description': 'Name of the person'
},
'major': {
'type': 'string',
'description': 'Major subject.'
},
'school': {
'type': 'string',
'description': 'The university name.'
},
'grades': {
'type': 'integer',
'description': 'GPA of the student.'
},
'club': {
'type': 'string',
'description': 'School club for extracurricular activities. '
}

        }
    }
}

]

接下来,我们将使用添加到“functions”参数中的自定义函数为两个学生描述生成响应。之后,我们将文本响应转换为 JSON 对象并打印出来。

student_description = [student_1_description,student_2_description]
for sample in student_description:
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': sample}],
functions = student_custom_functions,
function_call = 'auto'
)

# Loading the response as a JSON object
json_response = json.loads(response['choices'][0]['message']['function_call']['arguments'])
print(json_response)

如我们所见,我们得到了统一的输出。我们甚至得到了数字而不是字符串的成绩。一致的输出对于创建无错误的 AI 应用程序至关重要。

{'name': 'David Nguyen', 'major': 'computer science', 'school': 'Stanford University', 'grades': 3.8, 'club': 'Robotics Club'}

{'name': 'Ravi Patel', 'major': 'computer science', 'school': 'University of Michigan', 'grades': 3.7, 'club': 'Chess Club'}

多个自定义函数

您可以在聊天完成功能中添加多个自定义函数。在本节中,我们将看到OpenAI API的神奇功能,以及它如何自动选择正确的函数并返回正确的参数。

在字典的 Python 列表中,我们将添加另一个名为“extract_school_info”的函数,它将帮助我们从文本中提取大学信息。

为此,您必须添加另一个带有名称、描述和参数的函数字典。

custom_functions = [
{
'name': 'extract_student_info',
'description': 'Get the student information from the body of the input text',
'parameters': {
'type': 'object',
'properties': {
'name': {
'type': 'string',
'description': 'Name of the person'
},
'major': {
'type': 'string',
'description': 'Major subject.'
},
'school': {
'type': 'string',
'description': 'The university name.'
},
'grades': {
'type': 'integer',
'description': 'GPA of the student.'
},
'club': {
'type': 'string',
'description': 'School club for extracurricular activities. '
}

        }
    }
},
{
    'name': 'extract_school_info',
    'description': 'Get the school information from the body of the input text',
    'parameters': {
        'type': 'object',
        'properties': {
            'name': {
                'type': 'string',
                'description': 'Name of the school.'
            },
            'ranking': {
                'type': 'integer',
                'description': 'QS world ranking of the school.'
            },
            'country': {
                'type': 'string',
                'description': 'Country of the school.'
            },
            'no_of_students': {
                'type': 'integer',
                'description': 'Number of students enrolled in the school.'
            }
        }
    }
}

]

我们将使用 ChatGPT 生成“斯坦福大学”描述来测试我们的函数。

school_1_description = "Stanford University is a private research university located in Stanford, California, United States. It was founded in 1885 by Leland Stanford and his wife, Jane Stanford, in memory of their only child, Leland Stanford Jr. The university is ranked #5 in the world by QS World University Rankings. It has over 17,000 students, including about 7,600 undergraduates and 9,500 graduates23. "

创建学生和学校描述列表,并通过 OpenAI 聊天完成功能传递它以生成响应。确保您已提供更新的自定义函数。

description = [student_1_description, school_1_description]
for i in description:
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': i}],
functions = custom_functions,
function_call = 'auto'
)

# Loading the response as a JSON object
json_response = json.loads(response['choices'][0]['message']['function_call']['arguments'])
print(json_response)

GPT-3.5-Turbo 型号已自动为不同的描述类型选择了正确的功能。我们为学生和学校提供完美的JSON输出。

{'name': 'David Nguyen', 'major': 'computer science', 'school': 'Stanford University', 'grades': 3.8, 'club': 'Robotics Club'}

{'name': 'Stanford University', 'ranking': 5, 'country': 'United States', 'no_of_students': 17000}

我们甚至可以查看使用“extract_school_info”函数生成休息的名称。

图像3.png

使用函数调用的应用程序

在本节中,我们将构建一个稳定的文本摘要器,该摘要器将以某种方式汇总学校和学生信息。

首先,我们将创建两个 Python 函数,它们从函数调用中获取参数并返回一个汇总的字符串。extract_student_infoextract_school_info,

def extract_student_info(name, major, school, grades, club):

"""Get the student information"""

return f"{name} is majoring in {major} at {school}. He has {grades} GPA and he is an active member of the university's {club}."

def extract_school_info(name, ranking, country, no_of_students):

"""Get the school information"""

return f"{name} is located in the {country}. The university is ranked #{ranking} in the world with {no_of_students} students."
  1. 创建 Python 列表,该列表由学生一描述、随机提示和学校一描述组成。添加随机提示以验证自动函数调用机制。
  2. 我们将使用“描述”列表中的每个文本生成响应。
  3. 如果使用函数调用,我们将获取函数的名称,并基于它,使用响应将相关参数应用于函数。否则,返回正常响应。
  4. 打印所有三个样本的输出。

descriptions = [
student_1_description,
"Who was a Abraham Lincoln?",
school_1_description
]
for i, sample in enumerate(descriptions):
response = openai.ChatCompletion.create(
model = 'gpt-3.5-turbo',
messages = [{'role': 'user', 'content': sample}],
functions = custom_functions,
function_call = 'auto'
)

response_message = response["choices"][0]["message"]

if response_message.get('function_call'):
    
    # Which function call was invoked
    function_called = response_message['function_call']['name']
    
    # Extracting the arguments
    function_args  = json.loads(response_message['function_call']['arguments'])
    
    # Function names
    available_functions = {
        "extract_school_info": extract_school_info,
        "extract_student_info": extract_student_info
    }
    
    fuction_to_call = available_functions[function_called]
    response_message = fuction_to_call(*list(function_args .values()))
    
else:
    response_message = response_message['content']

print(f"\nSample#{i+1}\n")
print(response_message)
  • 示例 #1:GPT 模型选择了“extract_student_info”,我们得到了有关该学生的简短摘要。
  • 示例#2:GPT 模型没有选择任何函数并将提示视为常规问题,结果,我们得到了亚伯拉罕·林肯的传记。
  • 示例#3:GPT 模型选择了“extract_school_info”,我们得到了有关斯坦福大学的简短摘要。

示例#1

David Nguyen在斯坦福大学主修计算机科学。他的GPA为3.8,是该大学机器人俱乐部的活跃成员。

示例#2

亚伯拉罕·林肯是美国第16任总统。他从 1861 年 1865 月开始担任总统,直到 <> 年 <> 月被暗杀。林肯领导美国度过了最大的内部危机——美国内战,他的解放宣言宣布邦联领土上的奴隶是自由的。他以他的领导才能、他对维护联邦的承诺以及他废除奴隶制的努力而闻名。林肯的总统任期被广泛认为是美国历史上最具变革性的总统任期之一。

示例#3

斯坦福大学位于美国。该大学在世界排名#5,拥有17000名学生。

结论

OpenAI 的函数调用为构建 AI 应用程序的开发人员开辟了令人兴奋的新可能性。通过允许 GPT-3.5 和 GPT-4 等模型通过自定义函数生成结构化 JSON 数据,它解决了围绕不一致和不可预测的文本输出的主要痛点。

函数调用可用于访问外部 Web API、执行自定义 SQL 查询以及开发稳定的 AI 应用程序。它可以从文本中提取相关信息,并为 API 和 SQL 命令提供一致的响应。

在本教程中,我们了解了 OpenAI 的新功能,函数调用。我们还学习了如何使用它来生成一致的输出、创建多个函数以及构建可靠的文本摘要器。

如果您想了解有关 OpenAI API 的更多信息,请考虑参加使用 OpenAI API 课程并使用 Python 中的 OpenAI API 备忘单来创建您的第一个 AI 驱动的项目。

原文链接:OpenAI 函数调用教程 (mvrlink.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: async-http-client 是一个用于发送 HTTP 请求的异步非阻塞的 Java 客户端库。而 OpenAI 则是一个提供人工智能服务的平台。如果我们需要使用 async-http-client 调用 OpenAI 接口,可以按照以下步骤进行操作: 1. 首先,我们需要引入 async-http-client 库。可以通过 Maven 或 Gradle 将其添加到项目的依赖中。 2. 接下来,我们需要获取 OpenAI 平台提供的 API 密钥,这个密钥将用于进行身份验证。 3. 在代码中,我们需要构建一个 HttpClient 实例,这个实例将负责发送 HTTP 请求。可以使用 async-http-client 提供的自定义配置选项,设置连接超时时间、最大连接数等。 4. 然后,我们需要构建一个 Request 对象,指定请求的 URL、请求方法、请求头等信息。在这个 Request 对象中,我们可以添加请求的参数,例如可以将需要处理的数据通过请求的 body 发送给 OpenAI 接口。 5. 使用 HttpClient 的 `executeRequest` 方法发送请求。这个方法是异步的,它会立即返回一个 `Future<Response>` 对象。 6. 我们可以通过调用 `getResponse` 方法来获取异步请求的结果。这个方法会一直阻塞,直到请求的结果返回。 7. 最后,我们可以对请求结果进行处理,例如提取返回的数据或者进行错误处理。 使用 async-http-client 调用 OpenAI 接口需要注意以下几点:确保 API 密钥正确且有效、设置合适的请求参数、合理处理请求的返回结果。另外,可能还需要参考 OpenAI 提供的 API 文档,了解具体的接口使用方法和参数要求。 通过将 async-http-client 和 OpenAI 结合使用,我们可以更方便地在 Java 中使用 OpenAI 提供的人工智能服务,实现各种智能化的功能。 ### 回答2: async-http-client是一个基于Java的异步HTTP客户端,它提供了一个简单而强大的方式来进行HTTP请求和处理响应。那么如何使用async-http-client来调用openai接口呢? 首先,你需要在项目中导入async-http-client的依赖,可以通过Maven或Gradle等构建工具来进行安装和配置。 接下来,你需要创建一个HTTP客户端实例。你可以通过AsyncHttpClient类的构造函数来实现,如下所示: ```java AsyncHttpClient client = new DefaultAsyncHttpClient(); ``` 然后,你需要构建一个HTTP请求。对于openai接口,你可以使用HttpGet或HttpPost等类来发送GET或POST请求。假设你要发送一个GET请求,你可以这样构建: ```java Request request = new RequestBuilder().setUrl("https://api.openai.com/your-endpoint") .setMethod("GET") .build(); ``` 然后,你可以通过client的execute方法来发送请求并获取响应,如下所示: ```java ListenableFuture<Response> future = client.executeRequest(request); ``` 你可以通过添加回调函数来处理响应,比如成功时的回调函数onCompleted、失败时的回调函数onThrowable等。例如,你可以这样处理响应: ```java future.addListener(() -> { try { Response response = future.get(); // 处理响应数据 } catch (InterruptedException | ExecutionException e) { // 处理异常 } }, executor); ``` 最后,你可以在onCompleted回调函数中处理openai接口的响应数据。你可以通过使用response类的方法来获取HTTP响应的状态码、头部信息和响应体等。例如,你可以这样获取响应体: ```java String responseBody = response.getResponseBody(); ``` 这样,你就可以使用async-http-client来调用openai接口了。记得在使用完毕后关闭客户端资源,以释放相关的资源: ```java client.close(); ``` 这只是async-http-client的基本用法,你还可以根据具体的需求和openai接口的要求进行进一步的定制和扩展。 ### 回答3: async-http-client 是一个用于异步发送 HTTP 请求的 Java 库。可以通过该库来调用 openai 接口,可以实现异步发送请求并获取响应的功能。 首先,需要使用 async-http-client 的 API 创建一个 HTTP 客户端。然后,通过该客户端发送 HTTP 请求到 openai 接口的 URL。可以在请求中设置必要的请求头信息,如 token、content-type 等。可以使用 POST 方法发送数据,将需要传递给 openai 接口的参数作为请求体发送。 在发送请求后,async-http-client 会异步地等待 openai 接口的响应。可以通过设置回调函数来处理异步响应,在回调函数中可以对接口的响应进行处理,如获取响应的状态码、响应体等信息。 当接收到 openai 接口的响应后,可以根据需要进行相应的处理,如解析响应体的数据,进行数据处理或展示。若需要发送更多的请求,可以重复以上步骤。 需要注意的是,调用 openai 接口时可能会出现网络连接异常、超时等问题,可以通过 async-http-client 提供的错误处理机制来处理这些问题,如设置超时时间、重试次数等。 总之,使用 async-http-client 可以很方便地调用 openai 接口,并且实现异步发送请求和获取响应的功能,使得请求过程更加高效和可靠。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值