GPT3 探索指南(二)

发布于:2024-05-03 ⋅ 阅读:(30) ⋅ 点赞:(0)

原文:zh.annas-archive.org/md5/e19ec4b9c1d08c12abd2983dace7ff20

译者:飞龙

协议:CC BY-NC-SA 4.0

第三部分:使用 OpenAI API

本节提供了使用 OpenAI API 与 Node.js/JavaScript 和 Python 的实际示例。然后,它通过指导您构建一个完全功能的 GPT-3 驱动的 Web 应用来结束。

本节包括以下章节:

  • 第六章内容过滤

  • 第七章生成和转换文本

  • 第八章文本分类和分类

  • 第九章构建一个由 GPT-3 驱动的问答应用

  • 第十章使用 OpenAI 驱动的应用上线

第六章:内容过滤

第一章中,介绍 GPT-3 和 OpenAI API,我们简要提到了一个内容过滤模型,用于识别潜在的冒犯或有害语言。我们还讨论了 GPT-3 有时会生成一些可能被一些人认为不当或伤害的完成。在本章中,您将学习如何实现内容过滤,以防止您的应用程序用户看到冒犯性或可能有害的完成。

本章我们将涵盖以下主题:

  • 预防不当和冒犯性结果

  • 了解内容过滤

  • 测试内容过滤过程

  • 使用 JavaScript 进行内容过滤

  • 使用 Python 进行内容过滤

技术要求

本章要求您能够访问OpenAI API。您可以通过访问openapi.com来请求访问权限。

预防不当和冒犯性结果

有时,GPT-3 会生成一些被一些用户认为不当的文本。这可能是粗话、含有不当的种族、宗教或政治用语,或者性不当/露骨的内容,或者性质黑暗或暴力的文本。这并不是因为 GPT-3 试图恶意或伤害别人——它只是一个根据统计概率生成文本的语言模型——它没有恶意不当的概念。但 GPT-3 是使用互联网数据进行训练的,而互联网上不幸存在大量冒犯性内容。因此,模型有时会生成不适当的内容。值得庆幸的是,作为开发者,我们可以采取措施防止用户看到 GPT-3 可能生成的不适当响应。

避免不适当内容的最简单方法是利用您的提示文本来引导模型避免生成可能不适当的结果。一般来说,GPT-3 会模仿提示的结构和内容。因此,您可以通过告诉模型完成应该友好或礼貌,来引导模型远离可能的不适当结果,例如。但是无论如何,您都需要测试。例如,“友好”这样的词也可能导致性内容。因此,请使用提示来引导模型,并根据您看到的结果来精确控制措辞。

为了说明,这里有两个假设客服问题的示例提示和相关完成。在示例中,#$%@! 用于代替原始提示和完成中使用的脏话(诅咒词)。

  • 示例 1:

    提示:

    Customer: Where the #$%@! is my order! I placed the order more than three days ago. How long can it take to package and ship a #$%@! tee-shirt?
    Response: 
    

    完成:

    I don't know. This is my first #$%@! day on the job. If you want, I can call you a #$%@! taxi so you can come pick up your #$%@! Order.
    
  • 示例 2:

    提示:

    Customer: Where the #$%@! is my order! I placed the order more than three days ago. How long can it take to package and ship a #$%@! tee-shirt?
    Polite Response: 
    

    完成:

    It can take up to 5 business days for in stock t-shirts to be processed. You ordered three t-shirts and each shirt takes a different amount of production time to be produced. There were some complications with your order but as of today your t-shirts should be fully prepared for shipping. 
    

两个提示之间的唯一区别是,第二个示例末尾包含Polite Response:,而不仅仅是Response:。这足以指导模型生成更适当语言的回应。为了进一步指导模型,您还可以提供一个或多个对于攻击性或不礼貌客户问题的样本,以便提供有礼貌回应。

这里的关键是提示是最小化不适当回应的第一种,也是最容易的方法。

另一种防止不当完成的方法是限制完成的返回内容。例如,如果你正在对文本进行分类或总结,模型将在结果中包含的内容方面受到限制。

在不受约束的完成情况下,例如,如果你为聊天机器人生成回应,你将希望使用内容过滤,这将在接下来进行讨论。此外,零-shot 提示,没有示例,很可能会导致不可预测的完成。

了解内容过滤

内容过滤是指阻止或隐藏可能被视为冒犯、不当或甚至危险的内容。在我们的情况下,我们谈论的是 GPT-3 生成的内容,我们不希望我们的应用用户看到的内容。

为了过滤潜在的冒犯或不安全的文本,我们需要编写一小段代码来评估 GPT-3 生成的文本,并对其进行安全、敏感或不安全的分类。Cool 的地方在于我们可以使用 GPT-3 来进行分类。因此,这有点像自我管理,但在一定程度上依靠我们的代码进行辅助。

从高层次上看,这是我们如何使其工作的方式:

  1. GPT-3 对提示生成一个完成。

  2. 完成的文本被提交回 GPT-3 过滤引擎。

  3. 过滤引擎返回一个分类(安全、敏感、不安全)。

  4. 根据分类,原始完成文本被屏蔽或发送回用户。

  5. 可选地,如果完成文本是敏感的或不安全的,可以生成一个新的安全完成并发送,而用户并不知道某些内容被屏蔽了。

内容过滤是使用完成的端点进行的。然而,需要使用专门的内容过滤引擎以及一些特定设置和特殊格式的提示。

在撰写本文时,可用的内容过滤引擎为content-filter-alpha-c4。因此,我们将在该引擎的 URL 中使用用于完成的端点,如api.openai.com/v1/engines/content-filter-alpha-c4/completions

重申一遍,需要在 API 请求中包含一些特定参数的具体要求。具体来说,我们需要包括以下参数和相关数值:

  • 1

  • 0.0

  • 0

最后,内容过滤的提示必须以特定方式格式化。提示格式为"<|endoftext|>[prompt]\n--\nLabel:"[prompt]部分将被替换为我们希望内容过滤器评估的文本。

重要说明

在发布时,内容过滤处于 beta 阶段。很有可能引擎 ID 在您阅读此文时已更改。因此,请务必查看位于 beta.openai.com/docs/engines/content-filter 的 OpenAI 内容过滤器文档。

因此,这是我们将发布到完成端点的 JSON 的一个示例。在此示例中,我们正在评估的文本是 从前有座山

{
    "prompt": "<|endoftext|>Once upon a time\n--\nLabel:",
    "max_tokens": 1,
    "temperature": 0.0,
    "top_p": 0
}

可以相当肯定地假设 从前有座山 会被视为安全的。因此,如果那是我们要应用过滤器的文本,我们可以期望得到类似以下示例的响应,显示文本是 0 - 安全的:

{
    "id": "cmpl-2auhZQYDGJNpeyzYNwMEm5YsAAUEK",
    "object": "text_completion",
    "created": 1615150445,
    "model": "toxicity-double-18",
    "choices": [
        {
            "text": "0",
            "index": 0,
            "logprobs": null,
            "finish_reason": "length"
        }
    ]
}

注意,在 JSON 响应对象中,有一个名为choices的元素。该元素包含一个对象的 JSON 数组。每个对象都包含一个文本属性,该属性将表示一个完成的内容过滤分类。其值始终是以下之一:

  • 0 – 安全:文本中似乎没有任何可能引起冒犯或不安全的地方。

  • 1 – 敏感:敏感话题可能包括具有政治、宗教、种族或国籍相关内容的文本。

  • 2 – 不安全:文本包含一些人认为是刻薄的、伤人的、明确的、冒犯的、亵渎的、偏见的、仇恨的语言,或者大多数人认为不适合工作NSFW)的语言,或者可能以有害方式描绘某些群体/人的语言。

一个数组被发送回 choices 元素,因为可能一次发送多个提示。例如,如果您想要查看句子中的任何单词是否不安全,您可能会将句子拆分为一个单词的数组,并将每个单词作为提示发送。以下是将 Oh hi 作为两个提示发送 - 每个单词一个的请求的示例:

{
    "prompt": [
"<|endoftext|>Oh\n--\nLabel:",
"<|endoftext|>hi\n--\nLabel:"
],
    "max_tokens": 1,
    "temperature": 0.0,
    "top_p": 0
}

鉴于前面的示例,使用提示数组,您将看到类似以下的响应。现在请注意,choices 数组中有多个对象 - 每个单词/提示一个:

{
    "id": "cmpl-2bDTUPEzoCrtNBa2gbkpNVc1BcVh9",
    "object": "text_completion",
    "created": 1615222608,
    "model": "toxicity-double-18",
    "choices": [
        {
            "text": "0",
            "index": 0,
            "logprobs": null,
            "finish_reason": "length"
        },
        {
            "text": "0",
            "index": 1,
            "logprobs": null,
            "finish_reason": "length"
    ]
}

choices 数组具有从零开始的索引值,该值对应于传入的提示数组中项目的索引,这意味着第一个提示/单词(在我们的示例中是“Oh”)的 choices 对象具有索引值 0。在此示例中,我们只发送了两个单词(“Oh”和“hi”),并且两者都被分类为 0(安全)。但是,如果您将其中一个单词更改为您喜欢的(或最不喜欢的)脏话,您会看到分类将更改为 2(不安全),其索引对应于您更改的单词(假设您使用的脏话大多数英语为母语的人会觉得冒犯)。

另一件需要牢记的事情是,过滤引擎并不是 100%准确,而是更倾向于谨慎。因此,您可能会看到误报 - 一些实际上是安全的单词被标记为敏感或不安全的情况。这可能是您在 Playground 中已经看到的情况。甚至提及政治或宗教等话题通常会被标记。小心总比后悔要好,但您需要考虑这可能如何潜在影响到您的应用程序。

因此,简要总结一下,您可以使用 OpenAI API 完成端点来对潜在的敏感或不安全文本进行分类。您只需要执行以下操作:

  1. 使用内容过滤引擎。

  2. max_tokens设置为1temperature设置为0.0top_p设置为0

  3. 将您的提示格式化为"<|endoftext|>your text here\n--\nLabel:"

好了,让我们使用 Postman 熟悉一下内容过滤的工作原理。

测试内容过滤流程

在本章后面,我们将会在代码中创建一个简单的内容过滤。但在此之前,让我们使用 Postman 测试一下通用的内容过滤方法:

  1. 登录Postman.com

  2. 打开我们在第四章中创建的 Exploring GPT-3 工作空间,使用 OpenAI API

  3. 创建一个名为第六章的新 Postman 集合。

  4. 创建一个名为内容过滤 - 示例 1的新请求。

  5. 将请求类型设置为POST,并将请求 URL 设置为api.openai.com/v1/engines/content-filter-alpha-c4/completions,如下面的屏幕截图所示:外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

    图 6.1 - 在 Postman 中设置过滤端点

  6. 将请求主体设置为原始,并将主体类型设置为JSON,如以下屏幕截图所示:图 6.2 - Postman 中的过滤参数

    图 6.2 - Postman 中的过滤参数

  7. 将以下 JSON 对象添加到请求主体中:

    {
      "prompt" : "<|endoftext|>Are you religious?\n--\nLabel:",
      "max_tokens" : 1,
      "temperature" : 0.0,
      "top_p" : 0
    }
    
  8. 单击发送按钮并查看 JSON 响应。响应将类似于以下屏幕截图:

图 6.3 - Postman 过滤结果

图 6.3 - Postman 过滤结果

在响应中,您会注意到索引为0的选择项的文本值为1(敏感)。正如您所猜的那样,这很可能是因为文本Are you religious? 可能被视为敏感话题。

在继续之前,尝试将提示文字更改为您认为可能被视为敏感或不安全的内容,并查看其分类情况。熟悉内容过滤流程后,继续下一节,在 JavaScript 中尝试应用。

使用 JavaScript 过滤内容

在本节中,我们将使用 JavaScript 看一下一个简单的内容过滤代码示例。我们可以自己编写所有代码,但是 Postman 中有一个很酷的功能,可以为我们创建的请求生成代码片段。所以,让我们试试看:

  1. 要查看 Postman 生成的代码片段,请单击右侧菜单上的代码按钮。以下截图中的箭头指向要单击的**</>**图标:图 6.4 – 打开代码窗格的代码按钮

    图 6.4 – 打开代码窗格的代码按钮

  2. 单击代码按钮后,Postman 将打开一个代码片段窗格。从下拉列表中选择NodeJs – Axios,将代码片段类型更改为该选项。然后,单击以下截图中显示的复制按钮。这将复制代码片段到您的剪贴板:图 6.5 – 适用于 Node.js – Axios 的 Postman 代码片段

    图 6.5 – 适用于 Node.js – Axios 的 Postman 代码片段

  3. 将代码片段复制到剪贴板后,请执行以下步骤:

    a) 登录 replit.com,并打开您的chapter06

    c) 在名为filter.jschapter06文件夹中创建一个文件。

    d) 将来自 Postman 的代码片段粘贴到filter.js文件中。

  4. 最终生成的代码应该看起来像以下截图。但是,在运行文件之前,我们需要做一个小改变:图 6.6 – 从 Postman 代码片段复制到 replit.com 文件

    change we need to make is on the line that contains Authorization – *line number 8* in the screenshot shown in *Figure 6.6*. We need to change it to pick up our environment variable in repl.it. To do that, we will replace the text 'Bearer {{OPENAI_API_KEY}}' from the code snippet with `Bearer ${process.env.OPENAI_API_KEY}`. Note that backticks are used rather than single quotes. This is because we're using a JavaScript template string as the value. This lets us merge in the ${process.env.OPENAI_API_KEY}, which will be replaced with the value of the OPENAI_API_KEY environment variable. For details about template literals/strings, visit the following link:[`developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals).
    
  5. 因此,在更新授权行之后,最终代码应该如下所示:

    var axios = require('axios');
    var data = JSON.stringify({
      "prompt": "<|endoftext|>What religion are you?\n--\nLabel:",
      "max_tokens": 1,
      "temperature": 0,
      "top_p": 0
    });
    var config = {
      method: 'post',
      url: 'https://api.openai.com/v1/engines/content-filter-alpha-c4/completions',
      headers: { 
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`, 
        'Content-Type': 'application/json'
      },
      data : data
    };
    axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });
    
  6. 以下截图显示了replit.com中的先前代码:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 6.7 – 修改后的适用于 replit.com 的 Postman 代码片段

此时,代码与我们在第五章中所写的代码非常相似,在代码中使用 OpenAI API,当我们讨论调用完成端点时。我们只需要编辑.replit文件中的run命令,以运行我们的chapter06/filter.js文件中的代码。然后我们可以进行测试:

  1. 因此,将.replit文件更新为以下内容:

    Run "node chapter06/filter.js"
    
  2. 更新.replit文件后,单击绿色的运行按钮,您应该在控制台窗口中看到类似以下截图的结果:

图 6.8 – 运行 chapter06/filter.js 的结果

图 6.8 – 运行 chapter06/filter.js 的结果

这是一个简单的示例,将单个提示中的所有文本分类。让我们看另一个示例,该示例将字符串中的每个单词进行分类,并将每个单词分类为安全、敏感或不安全。

使用 Node.js/JavaScript 标记不安全的词汇

作为示例,我们将从创建一个名为chapter06/flag.js的新文件开始,并将chapter06/filter.js中的代码复制到其中作为起点。然后,我们将修改chapter06/flag.js中的代码,将每个单词列出并附带一个分类值(0 = 安全,1 = 敏感,2 = 不安全)。首先,执行以下步骤创建我们的起点:

  1. 登录到replit.com,打开您的exploring-gpt3-node repl。

  2. chapter06文件夹中创建一个名为flag.js的文件。

  3. chapter06/filter.js的整个内容复制并粘贴到chapter06/flag.js中。

  4. 编辑.replit文件以使用以下命令运行chapter06/flag.js

    Run = "node chapter06/flag.js"
    
  5. 我们将首先添加一个变量来保存我们要过滤的文本。我们将在第一行下面添加这段代码。因此,前两行将如下所示:

    var axios = require('axios');
    const textInput = "This is some text that will be filtered";
    
  6. 接下来,我们将添加一个变量来保存一个提示数组,并将初始值设置为空数组。这将用文本输入的每个单词的提示填充:

    const prompts = [];
    
  7. 现在,我们将把我们的textInput拆分成一个单词数组,并用每个单词的提示填充prompts数组。由于我们将提示发送到过滤引擎,我们还需要正确格式化每个提示项。因此,我们将在我们的prompts变量后添加以下代码。此代码将文本输入拆分为单个单词,循环遍历每个单词以创建提示项,然后将提示项添加到prompts数组中:

    const wordArray = textInput.split(' ');
    for (i = 0, len = wordArray.length, text = ""; i < len; i++) {
      text = `<|endoftext|>${wordArray[i]}\n--\nLabel:`;
      prompts.push(text);
    }
    
  8. 现在我们将更新由 Postman 创建的 data 变量。我们将使用我们的prompts数组作为提示值,而不是来自 Postman 的硬编码值。因此,我们将数据变量更改为以下内容:

    var data = JSON.stringify({"prompt": prompts,"max_tokens":1,"temperature":0,"top_p":0});
    
  9. 最后,我们将通过循环遍历单词数组并使用过滤器结果对每个单词进行分类来修改输出。为此,请将包含console.log(JSON.stringify(response.data));的行替换为以下代码:

        response.data.choices.forEach(item => {
          console.log(`${wordArray[item.index]} : ${item.text}`);
    

    在进行最后一次代码编辑之后,我们可以再次运行代码,这次我们将看到以下响应:

图 6.9 – 文本输入中每个单词的内容过滤器结果

图 6.9 – 文本输入中每个单词的内容过滤器结果

现在您会注意到单词(religion)的文本值为1(敏感)。如果您将textInput值更改为包含更具攻击性单词的文本,则可以再次运行代码以查看每个单词的分类方式。在实际实施中,您可能会替换或删除敏感或不安全的单词,现在可以轻松地通过 API 的结果使用类似的方法来完成。我们将在第七章中研究这样做,生成和转换文本,但现在,让我们来看看使用 Python 进行内容过滤。

使用 Python 过滤内容

现在让我们看看如何使用 Python 实现内容过滤。除非你跳过了“使用 JavaScript 过滤内容”,否则你可能能够猜到我们要如何开始使用 Python 实现内容过滤的示例——我们会使用由 Postman 生成的代码片段:

  1. 因此,首先需要在 Postman 中打开代码片段窗格。然后,点击右侧菜单中的代码按钮。箭头指向的即为代码按钮,如下面的截图所示:外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

    图 6.10 – 打开代码窗格的代码按钮

  2. 单击代码按钮后,代码片段窗格会打开。更改代码片段类型为 Python – Requests,方法是从下拉列表中选择它,然后单击下面截图中所示的复制按钮。这将将代码片段复制到你的剪贴板:图 6.11 – 用于 Python – requests 的 Postman 代码片段

    图 6.11 – 用于 Python – requests 的 Postman 代码片段

  3. 将代码片段复制到剪贴板后,执行以下步骤:

    a) 登录 replit.com,并打开你的 chapter06

    c) 创建一个在 chapter06 文件夹中命名为 filter.py 的文件。

    d) 将 Postman 代码片段粘贴到 filter.py 文件中。

  4. 最终代码应该如下截图所示。但是你会发现你的 API Key 是硬编码的 —— 它在截图中被模糊处理了。硬编码的 API Key 是我们要更改的第一项内容:图 6.12 – 从 Postman 代码段复制到 repl.it 文件

    图 6.12 – 从 Postman 代码段复制到 repl.it 文件

  5. 为了从我们的代码文件中删除硬编码的 API Key,在 filter.py 文件的第一行添加以下代码,这样我们就可以读取在使用 OpenAI API 进行代码编写中设置的 .env 文件中的 OPENAI_API_KEY 环境变量了:

    import os
    
  6. 导入 Python 的 os 库后,我们可以从环境变量获取授权头的 API Key 值。在先前的 图 6.12 中,你需要将 第 7 行 编辑为以下内容:

    'Authorization':'Bearer ' + os.environ.get("OPENAI_API_KEY")
    
  7. 更新授权行后,最终代码应如下所示:

    import os
    import requests
    import json
    url = "https://api.openai.com/v1/engines/content-filter-alpha-c4/completions"
    payload = json.dumps({
      "prompt": "<|endoftext|>What religion are you?\n--\nLabel:",
      "max_tokens": 1,
      "temperature": 0,
      "top_p": 0
    })
    headers = {
      'Authorization':'Bearer ' + os.environ.get("OPENAI_API_KEY"),
      'Content-Type': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)
    
  8. 下面的截图展示了前面章节中修改的 Postman Python 代码片段在 replit.com 中的效果:图 6.13 – 修改后的用于 repl.git.com 的 Postman Python 代码片段

    图 6.13 – 修改后的用于 repl.git.com 的 Postman Python 代码片段

  9. 此时,代码与我们在前一章“使用 OpenAI API 进行代码编写”中编写的代码非常相似,那时我们讨论了使用 Python 调用完成端点。我们只需编辑 .replit 文件中的 run 命令,以运行我们的 chapter06/filter.py 文件中的代码。然后我们可以进行测试。因此,请将 .replit 文件更新为以下内容:

    Run "python chapter06/filter.py"
    
  10. 更新.replit文件后,单击绿色的Run按钮,您应该会在控制台窗口中看到类似以下截图的结果:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 6.14-运行 chapter06/filter.py 的结果

这是一个简单的示例,它将一个单一提示中的所有文本进行分类。让我们现在看另一个例子,它将对字符串中的每个单词进行分类并替换不安全的单词。

使用 Python 标记不安全的单词

对于这个例子,我们将首先创建一个名为chapter06/flag.py的新文件,并将chapter06/filter.py中的代码复制到其中作为起点。从那里开始,我们将修改chapter06/flag.py中的代码,列出每个具有分类值的单词(0 = 安全,1 = 敏感,2 = 不安全)。开始之前,请执行以下步骤创建起点:

  1. 登录到 replit.com 并打开your exploring-gpt3-pythonrepl。

  2. chapter06文件夹中创建一个名为flag.py的文件。

  3. 复制并粘贴chapter06/filter.py的全部内容到chapter06/flag.py中。

  4. 编辑.replit文件,使用以下命令运行chapter06/flag.py

    Run = "python chapter06/flag.py"
    
  5. chapter06/flag.py文件中,我们将添加一个变量来保存我们要过滤的文本。我们将在第三行下面(最后一个以import开头的行之后)添加以下代码:

    textInput = "What religion are you?"
    
  6. 接下来,我们将添加一个变量来保存提示数组,并将初始值设置为空数组。这将从我们的文本输入中为每个单词填充一个提示:

    prompts = []
    
  7. 现在,我们将把textInput拆分为单词数组,并用每个单词的提示填充prompts数组。由于我们将提示发送到 filter engine,因此还需要正确格式化每个提示项。所以,在prompts变量之后添加以下代码。此代码将文本输入拆分为单个单词,循环遍历每个单词以创建提示项,并将提示项添加到prompts数组中:

    wordArray = textInput.split()
    for word in wordArray:
      prompts.append("<|endoftext|>" + word + "\n--\nLabel:")
    
  8. 现在,我们将把由 Postman 创建的payload变量更新为 Python 对象而不是字符串。这使它更容易读取和包含我们的prompts数组。因此,请将payload变量替换为以下代码:

    payload = json.dumps({
      "prompt" : prompts,
      "max_tokens" : 1,
      "temperature" : 0.0,
      "top_p" : 0
      })
    
  9. 最后,我们将用下面的代码替换最后一行代码print(response.text),通过循环遍历结果并为每个单词添加分类(0 = 安全,1 = 敏感,2 = 不安全):

    for word in response.json()['choices']:
      print(wordArray[word['index']] + ' : ' + word['text'])
    
  10. 在进行最终代码编辑后,我们可以点击Run按钮,这次我们将看到类似以下的响应:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 6.15-使用 Python 显示文本输入中每个单词内容过滤结果

您会注意到在控制台中,单词(religion)的文本值为1(敏感)。在实际应用中,您将使用类似的方法来编辑或替换不安全和敏感的单词。但请记住,没有任何内容过滤过程是完美的。语言不断发展,单词的上下文可能会改变含义,这可能会导致内容过滤器漏掉或错误地标记内容。因此,在设计您的过滤方法时考虑到这一点很重要。

摘要

在本章中,我们讨论了 GPT-3 有时可能生成不适当内容的情况。我们还讨论了我们可以采取的措施来预防和检测不适当内容。您学会了如何使用提示来防止生成不适当内容的可能性,以及如何使用内容过滤将内容分类为安全、敏感或不安全。

我们回顾了如何使用完成端点进行内容过滤,以及如何使用 JavaScript 和 Python 实现内容过滤。

下一章,我们将利用本章学到的知识,以及第五章在代码中调用 OpenAI API 中学到的知识,来构建一个由 GPT-3 驱动的聊天机器人。

第七章:生成和转换文本

虽然我们在前几章中已经看过一些文本生成和转换的例子,但在本章中,我们将看到更多。文本生成和转换有很多可能的用途,包括文章写作,纠正语法,生成列表,将文本从一种语言翻译成另一种语言,提取关键词和总结文本等等。虽然我们甚至不会接近涵盖所有可以使用 GPT-3 生成和转换文本的不同方式,但我们将看一下 15 个有趣的例子,让你的想象力发挥。

我们将要讨论的主题如下:

  • 使用示例

  • 生成内容和列表

  • 翻译和转换文本

  • 提取文本

  • 创建聊天机器人

技术要求

让我们来看看本章需要的要求:

  • 访问 OpenAI API

  • replit.com 上的一个账户

使用示例

在本章中,我们将看到很多例子 - 具体说来有 15 个。我们将为本章中的所有示例使用完成端点 - 因此,大多数示例的代码都类似。主要区别将是提示文本和端点参数的值。为了节省空间,我们将查看第一个示例的完整 JavaScript 和 Python 代码。之后,我们将只需复制第一个示例并编辑端点和参数。

为了开始我们的事情,我们将看一下生成原创内容和列表的例子。

生成内容和列表

让我们从几个例子开始创建原创内容和生成列表。在所有 GPT-3 可以做的事情中,内容和列表生成的可能性可能是最令人印象深刻的,也是最有趣的。GPT-3 可以撰写原创故事,创建产品描述,制作学习笔记,帮助你 brainstorm 创意,或者创建食谱 - 这只是个开始。

笨笑话生成器

我们将以一个例子开始,让气氛轻松一下 - 一个愚蠢的笑话生成器。剧透警告:并不是所有的笑话都可能那么好笑,但谁的都是呢?好吧,这是我们将使用的提示:

Dumb Joke: I'm not a vegetarian because I love animals. I'm a vegetarian because I hate plants.
###
Two-Sentence Joke: Parallel lines have so much in common. It's a shame they'll never meet.
###
Dumb Joke: Someone stole my mood ring. I don't know how I feel about that.
###
Dumb Joke:

我们将以一个使用 Node.js/JavaScript 的例子开始。记住,对于这个第一个例子,我们将逐步创建所有代码。对于接下来的例子,我们只需修改此第一个示例的副本。

Node.js/JavaScript 示例

要在 replit.comexploring-gpt3-node repl 中创建此示例,完成以下步骤:

  1. 登录 replit.com,打开你的 exploring-gpt3-node repl。

  2. 在项目根目录中创建一个名为 chapter07 的新文件夹。

  3. 创建一个名为 dumb-joke-generator.js 的新文件。

  4. 将以下代码添加到 dumb-joke-generator.js 文件中:

    //chapter07/dumb-joke-generator.js
    const axios = require('axios');
    const apiKey = process.env.OPENAI_API_KEY;
    const client = axios.create({
      headers: { 'Authorization': 'Bearer ' + apiKey }
    });
    const endpoint = "https://api.openai.com/v1/engines/davinci/completions";
    const params = {
      prompt: "Dumb Joke: I'm not a vegetarian because I love animals. I'm a vegetarian because I hate plants.\n###\nDumb Joke: Parallel lines have so much in common. It's a shame they'll never meet.\n###\nDumb Joke: Someone stole my mood ring. I don't know how I feel about that.\n###\nDumb Joke:",
      temperature: 0.5,
      max_tokens: 100,
      top_p: 1,
      frequency_penalty: 0.5,
      presence_penalty: 0.5,
      stop: ["###"]
    }
    client.post(endpoint, params)
      .then(result => {
        console.log(params.prompt + result.data.choices[0].text);
        // console.log(result.data);
      }).catch(err => {
        console.log(err);
      });
    
  5. 在根文件夹中更新 .replit 文件,加入以下代码:

    run = "node chapter07/dumb-joke-generator.js"
    
  6. 点击 chapter07/dumb-joke-generator.js,你应该会看到一个类似下面截图的结果。有多有趣?对吧?

图 7.1 - 来自 chapter07/dumb-joke-generator.js 的示例输出

图 7.1 - 来自 chapter07/dumb-joke-generator.js 的示例输出

现在让我们用 Python 看同一个示例。

Python 示例

要在 Python 中创建愚蠢笑话生成器,请完成以下步骤:

  1. 登录到 replit.com 并打开你的 exploring-gpt3-python repl。

  2. 在项目根目录中创建一个名为 chapter07 的新文件夹。

  3. 创建一个名为 dumb-joke-generator.py 的新文件。

  4. 将以下代码添加到 dumb-joke-generator.py 文件中:

    import requests
    import os
    import json
    apiKey = os.environ.get("OPENAI_API_KEY")
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + apiKey
    }
    endpoint = 'https://api.openai.com/v1/engines/davinci/completions'
    params = {
        "prompt": "Dumb Joke: I'm not a vegetarian because I love animals. I'm a vegetarian because I hate plants.\n###\nDumb Joke: Parallel lines have so much in common. It's a shame they'll never meet.\n###\nDumb Joke: Someone stole my mood ring. I don't know how I feel about that.\n###\nDumb Joke:",
        "temperature": 0.5,
        "max_tokens": 100,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0.5,
        "stop": ["###"]
    }
    result = requests.post(endpoint, headers=headers, data=json.dumps(params))
    print(params["prompt"] + result.json()["choices"][0]["text"])
    
  5. 将你根文件夹中的 .replit 文件更改为以下内容:

    run = "python chapter07/dumb-joke-generator.py"
    
  6. 点击 chapter07/dumb-joke-generator.py,你应该会看到类似以下截图中的控制台输出结果。你笑了吗?

图 7.2 - 来自 chapter07/dumb-joke-generator.py 的示例输出

图 7.2 - 来自 chapter07/dumb-joke-generator.py 的示例输出

让我们停止开玩笑,转而进行一个更为严肃的示例。

火星事实(在大多数情况下)

对于我们的下一个示例,我们将使用 GPT-3 来学习一些关于火星的知识。在大多数情况下,我们会得到一些事实,但请回想前几章中的内容,你不能一直相信它们是真实的。我们将使用以下提示生成关于火星的 10 条事实列表:

I'm studying the planets. List things I should know about Mars.
1\. Mars is the nearest planet to Earth.
2\. Mars has seasons, dry variety (not as damp as Earth's).
3\. Mars' day is about the same length as Earth's (24.6 hours).
4.

从这个示例开始,我们不会逐行走过所有的代码。我们将只复制我们的愚蠢笑话生成器的代码并对其进行修改。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建 Mars 事实示例,请按照以下步骤进行:

  1. 登录到 replit.com 并打开你的 exploring-gpt3-node repl。

  2. chapter07 文件夹中创建一个名为 mars-facts-list.js 的新文件。

  3. dumb-joke-generator.js 文件中的代码复制到 mars-facts-list.js 中。

  4. mars-facts-list.js 中的 params 变量替换为以下代码:

    const params = {
      prompt: "I'm studying the planets. List things I should know about Mars.\n\n1\. Mars is the nearest planet to Earth.\n2\. Mars has seasons, dry variety (not as damp as Earth's).\n3\. Mars' day is about the same length as Earth's (24.6 hours).\n4.",
      temperature: 0,
      max_tokens: 100,
      top_p: 1.0,
      frequency_penalty: 0.5,
      presence_penalty: 0.5,
      stop: "11."
    }
    
  5. 将你根文件夹中的 .replit 文件更改为以下内容:

    run = "node chapter07/mars-facts-list.js"
    
  6. 点击 chapter07/mars-facts-list.js,你应该会看到类似以下截图中的控制台输出结果。你知道关于火星的所有这些事情吗?

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 7.3 - 来自 chapter07/mars-facts-list.js 的示例输出

让我们来看看 Python 中的火星事实列表示例。

Python 示例

要在 Python 中创建 Mars 事实示例,请按照以下步骤进行:

  1. 登录到 replit.com 并打开你的 exploring-gpt3-python repl。

  2. chapter07 文件夹中创建一个名为 mars-facts-list.py 的新文件。

  3. dumb-joke-generator.py 文件中的代码复制到 mars-facts-list.py 中。

  4. mars-facts-list.py 中的 params 变量替换为以下代码:

    params = {
        "prompt": "I'm studying the planets. List things I should know about Mars.\n\n1\. Mars is the nearest planet to Earth.\n2\. Mars has seasons, dry variety (not as damp as Earth's).\n3\. Mars' day is about the same length as Earth's (24.6 hours).\n4.",
        "temperature": 0,
        "max_tokens": 100,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0.5,
        "stop": ["11."]
    }
    
  5. 将你根文件夹中的 .replit 文件更改为以下内容:

    run = "python chapter07/mars-facts-list.py"
    
  6. 点击 chapter07/mars-facts-list.py,你应该会看到类似以下截图中的控制台输出结果。一些有趣的事实,不是吗?

图 7.4 - 来自 chapter07/mars-facts-list.py 的示例输出

图 7.4 - 来自 chapter07/mars-facts-list.py 的示例输出

我们已经看过娱乐和教育示例,现在让我们用一个业务示例来完成一些工作 - 一个网络研讨会描述生成器。

网络研讨会描述生成器

在这个示例中,我们将使用 GPT-3 来帮助编写一个活动描述。我们将使用以下提示来为一个正念网络研讨会写一个描述:

Write a description for the following webinar:
Date: Monday, June 5, 2021
Time: 10 AM PT
Title: An introduction to mindfulness
Presenter: Gabi Calm
Event Description:

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建网络研讨会描述生成器,请按照以下步骤操作:

  1. 登录replit.com,并打开你的exploring-gpt3-node repl。

  2. chapter07文件夹中创建一个名为webinar-description-generator.js的新文件。

  3. 将代码从dumb-joke-generator.js文件复制到webinar-description-generator.js中。

  4. webinar-description-generator.js中的params变量替换为以下代码:

    const params = {
      prompt: "Write a description for the following webinar:\n\nDate: Monday, June 5, 2021\nTime: 10 AM PT\nTitle: An introduction to mindfulness\nPresenter: Gabi Calm\n\nEvent Description:",
      temperature: 0.7,
      max_tokens: 100,
      top_p: 1.0,
      frequency_penalty: 0.5,
      presence_penalty: 0.0,
      stop: ".\n"
    }
    
  5. 将你的根文件夹中的.replit文件更改为以下内容:

    run = "node chapter07/webinar-decription-generator.js"
    
  6. 点击chapter07/webinar-description-generator.js,你应该会看到与以下截图中控制台输出类似的结果:

图 7.5 - 来自 chapter07/webinar-description-generator.js 的示例输出

图 7.5 - 来自 chapter07/webinar-description-generator.js 的示例输出

现在让我们用 Python 创建网络研讨会描述生成器示例。

Python 示例

要创建 Python 中的网络研讨会描述生成器示例,请按照以下步骤操作:

  1. 登录replit.com,并打开你的exploring-gpt3-python repl。

  2. chapter07文件夹中创建一个名为webinar-description-generator.py的新文件。

  3. 将代码从dumb-joke-generator.py文件复制到webinar-description-generator.py中。

  4. webinar-description-generator.py中的params变量替换为以下代码:

    params = {
        "prompt": "Write a description for the following webinar:\n\nDate: Monday, June 5, 2021\nTime: 10 AM PT\nTitle: An introduction to mindfulness\nPresenter: Gabi Calm\n\nEvent Description:",
        "temperature": 0.7,
        "max_tokens": 100,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0,
        "stop": [".\n"]
    }
    
  5. 将你的根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/webinar-description-generator.py"
    
  6. 点击chapter07/webinar-description-generator.py,你应该会看到与以下截图中控制台输出类似的结果:

图 7.6 - 来自 chapter07/webinar-description-generator.py 的示例输出

图 7.6 - 来自 chapter07/webinar-description-generator.py 的示例输出

让我们继续,从 GPT-3 获取一些关于我们可能考虑阅读的书籍的建议。

书籍建议

你想读的书有哪些?让我们试试。我们将使用以下提示。这个提示将被完成为一个编号列表的书籍建议:

Suggest a list of books that everyone should try to read in their lifetime.
Books:
1.

现在让我们在代码中实现书籍建议提示。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建书籍建议列表示例,请按照以下步骤操作:

  1. 登录replit.com,并打开你的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/book-suggestions-list.js

  3. 将代码从dumb-joke-generator.py文件复制到chapter07/book-suggestions-list.js中。

  4. chapter07/book-suggestions-list.js中的params变量替换为以下代码:

    const params = {
      prompt: "Suggest a list of books that everyone should try to read in their lifetime.\n\nBooks:\n1.",
      temperature: 0.7,
      max_tokens: 100,
      top_p: 1,
      frequency_penalty: 0.5,
      presence_penalty: 0,
      stop: [".\n"]
    }
    
  5. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "node chapter07/book-suggestions-list.js"
    
  6. 点击chapter07/book-suggestions-list.js,您应该看到类似于以下截图中控制台输出的结果:

图 7.7 – 第七章/book-suggestions-list.js 的示例输出

图 7.7 – 第七章/book-suggestions-list.js 的示例输出

正如您在图 7.7中所看到的,完成是一系列书籍建议。现在让我们继续,看看使用 Python 的相同示例。

Python 示例

要在 Python 中创建书籍建议列表示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/book-suggestions-list.py

  3. 将代码从dumb-joke-generator.py文件复制到chapter07/book-suggestions-list.py中。

  4. chapter07/book-suggestions-list.js中的params变量替换为以下代码:

    params = {
        "prompt": "Suggest a list of books that everyone should try to read in their lifetime.\n\nBooks:\n1.",
        "temperature": 0.7,
        "max_tokens": 100,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0,
        "stop": [".\n"]
    }
    
  5. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/book-suggestions-list.py"
    
  6. 点击chapter07/book-suggestions-list.py,您应该看到类似于以下截图中控制台输出的结果:

图 7.8 – 第七章/book-suggestions-list.py 的示例输出

图 7.8 – 第七章/book-suggestions-list.py 的示例输出

现在让我们来看另一个例子。

儿童书籍生成器

现在让我们为孩子们做一些有创意的事情。要不我们来做一个定制的睡前故事书?以下是我们将使用的提示:

Write a short story for kids about a Dog named Bingo who travels to space.
---
Page 1: Once upon a time there was a dog named Bingo.
Page 2: He was trained by NASA to go in space.

在我们接下来的代码示例中,我们将只实现生成书籍的提示。然而,在实际版本中,您也会希望包含我们在第六章中讨论的内容过滤。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建儿童书籍生成器示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/childrens-book-generator.js

  3. 将代码从dumb-joke-generator.py文件复制到chapter07/childrens-book-generator.js中。

  4. chapter07/childrens-book-generator.js中的params变量替换为以下代码:

    const params = {
      prompt: "Write a short story for kids about a Dog named Bingo who travels to space.\n---\n\nPage 1: Once upon a time there was a dog named Bingo.\nPage 2: He was trained by NASA to go in space.\nPage 3:",
      temperature: 0.9,
      max_tokens: 500,
      top_p: 1,
      frequency_penalty: 0.7,
      presence_penalty: 0,
      stop: ["Page 11:"]
    }
    
  5. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "node chapter07/childrens-book-generator.js"
    
  6. 点击chapter07/childrens-book-generator.js,您应该看到类似于以下截图中控制台输出的结果:

图 7.9 – 第七章/childrens-book-generator.js 的示例输出

图 7.9 – 第七章/childrens-book-generator.js 的示例输出

让我们来看看 Python 版本。

Python 示例

要在 Python 中创建儿童书籍生成器示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/childrens-book-generator.py

  3. 将代码从dumb-joke-generator.py文件复制到chapter07/childrens-book-generator.py中。

  4. 用以下代码替换chapter07/childrens-book-generator.py中的params变量:

    params = {
        "prompt": "Write a short story for kids about a Dog named Bingo who travels to space.\n---\n\nPage 1: Once upon a time there was a dog named Bingo.\nPage 2: He was trained by NASA to go in space.\nPage 3:",
        "temperature": 0.9,
        "max_tokens": 500,
        "top_p": 1,
        "frequency_penalty": 0.7,
        "presence_penalty": 0,
        "stop": ["Page 11:"]
    }
    
  5. 将根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/childrens-book-generator.py"
    
  6. 点击chapter07/childrens-book-generator.py,你应该看到类似于以下屏幕截图中的控制台输出结果:

图 7.10 – 来自的示例输出

图 7.10 – 来自chapter07/childrens-book-generator.py的示例输出

现在让我们继续看一些将文本进行翻译和转换的示例。我们将看到一些你期望的示例,比如将口语翻译成为其他语言。我们还将看到一些带有变化的翻译。

文本的翻译和转换

当你考虑将文本进行翻译时,可能会想到如 Google 翻译这样的系统。但使用 GPT-3,你不仅可以进行口语翻译,还可以进行几乎任何内容的翻译。让我们来看看。

缩写译者

对于我们的第一个翻译示例,我们将把缩写词转换为它们的含义。以下是我们将使用的提示文本:

Provide the meaning for the following acronym.
---
acronym: LOL
meaning: Laugh out loud
acronym: BRB
meaning: Be right back
acronym: L8R
meaning:

提示中提供了一些缩写词及其含义的示例。尝试使用以下 Node.js/JavaScript 代码。

Node.js/JavaScript 示例

要创建 Node.js/JavaScript 的缩写译者示例,请按照以下步骤进行:

  1. 登录replit.com并打开你的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/acronym-translator.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/acronym-translator.js中。

  4. 用以下代码替换chapter07/acronym-translator.js中的params变量:

    const params = {
      prompt: "Provide the meaning for the following acronym.\n---\n\nacronym: LOL\nmeaning: Laugh out loud\nacronym: BRB\nmeaning: Be right back\nacronym: L8R",
      temperature: 0.5,
      max_tokens: 15,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["acronym:"]
    }
    
  5. 将根文件夹中的.replit文件更改为以下内容:

    run = "node chapter07/acronym-translator.js"
    
  6. 点击chapter07/acronym-translator.js,你应该看到类似于以下屏幕截图中的控制台输出结果:

图 7.11 – 来自的示例输出

图 7.11 – 来自chapter07/acronym-translator.js的示例输出

让我们看看 Python 示例。

Python 示例

要创建 Python 的缩写译者示例,请按照以下步骤进行:

  1. 登录replit.com并打开你的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/acronym-translator.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/acronym-translator.py中。

  4. 用以下代码替换chapter07/acronym-translator.py中的params变量:

    params = {
        "prompt": "Provide the meaning for the following acronym.\n---\n\nacronym: LOL\nmeaning: Laugh out loud\nacronym: BRB\nmeaning: Be right back\nacronym: L8R",
        "temperature": 0.5,
        "max_tokens": 15,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0,
        "stop": ["acronym:"]
    }
    
  5. 将根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/acronym-translator.py"
    
  6. 点击chapter07/acronym-translator.py,你应该看到类似于以下屏幕截图中的控制台输出结果:

图 7.12 – 来自的示例输出

图 7.12 – 来自chapter07/acronym-translator.py的示例输出

让我们看看另一个示例。

英语到西班牙语

现在让我们来看看口语翻译。在这个示例中,我们将创建一个简单的翻译器,将英语文本转换为西班牙语:

Translate from English to Spanish
---
English: Where is the bathroom?
Spanish:

GPT-3 在语言之间的翻译方面非常出色。当在流行语言之间进行翻译时,如英语和西班牙语,尤其如此。因此,即使像这样的简单提示通常也足以获得准确的完成。

Node.js/JavaScript 示例

要创建 Node.js/JavaScript 中的英语到西班牙语翻译器示例,请按照以下步骤进行:

  1. 登录 replit.com,并打开你的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/english-spanish-translator.js

  3. dumb-joke-generator.py 文件中的代码复制到 chapter07/english-spanish-translator.js 中。

  4. chapter07/english-spanish-translator.js 中的 params 变量替换为以下代码:

    const params = {
      prompt: "Translate from English to Spanish\n---\n\nEnglish: Where is the bathroom?\nSpanish:",
      temperature: 0.5,
      max_tokens: 15,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["---"]
    }
    
  5. 将你的根目录中的 .replit 文件更改为以下内容:

    run = "node chapter07/english-spanish-translator.js"
    
  6. 点击 chapter07/english-spanish-translator.js,你应该看到类似于以下截图中的控制台输出结果:

图 7.13 – 来自 chapter07/english-spanish-translator.js 的示例输出

图 7.13 – 来自 chapter07/english-spanish-translator.js 的示例输出

让我们使用 Python 来查看相同的示例,从英语翻译成西班牙语。

Python 示例

要创建 Python 中的英语到西班牙语翻译器示例,请按照以下步骤进行:

  1. 登录 replit.com,并打开你的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/english-spanish-translator.py

  3. dumb-joke-generator.py 文件中的代码复制到 chapter07/english-spanish-translator.py 中。

  4. chapter07/english-spanish-translator.py 中的 params 变量替换为以下代码:

    params = {
        "prompt": "Translate from English to Spanish\n---\n\nEnglish: Where is the bathroom?\nSpanish:",
        "temperature": 0.5,
        "max_tokens": 15,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0,
        "stop": ["---"]
    }
    
  5. 将你的根目录中的 .replit 文件更改为以下内容:

    run = "python chapter07/english-spanish-translator.py"
    
  6. 点击 chapter07/english-spanish-translator.py,你应该看到类似于以下截图中的控制台输出结果:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 7.14 – 来自 chapter07/english-spanish-translator.py 的示例输出

正如图 7.14所示,GPT-3 将英文文本翻译成了西班牙文。但更令人印象深刻的是,GPT-3 还能在计算机编程语言之间进行翻译。我们接下来将使用一个提示来查看将 JavaScript 代码翻译为 Python。

JavaScript 到 Python

翻译不仅仅需要在人类语言之间进行。由于 GPT-3 是使用互联网数据进行训练的,它还可以在编程语言之间进行翻译。以下提示提供了一个示例,显示了如何将 JavaScript 代码转换为 Python:

Translate from JavaScript to Python
JavaScript:
const request = require("requests");
request.get("https://example.com");
Python:

这是一个相当简单的代码转换示例,但它很好地展示了潜力。更复杂的代码转换可能需要更多样本的 few-shot 提示,但让我们尝试一下使用 Node.js/JavaScript。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建 JavaScript 到 Python 的翻译器示例,请按照以下步骤进行:

  1. 登录 replit.com,并打开你的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/javascript-python-translator.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/javascript-python-translator.js中。

  4. chapter07/javascript-python-translator.js中的params变量替换为以下代码:

    const params = {
      prompt: "Translate from JavaScript to Python\n---\n\nJavaScript:\nconst request = require(\"requests\");\nrequest.get(\"https://example.com\");\n\nPython:\n",
      temperature: 0.3,
      max_tokens: 15,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["---"]
    }
    
  5. 将根目录中的.replit文件更改为以下内容:

    run = "node chapter07/javascript-python-translator.js"
    
  6. 单击chapter07/javascript-python-translator.js,您应该会看到类似于以下屏幕截图中控制台输出的结果:

图 7.15 – 来自 chapter07/javascript-python-translator.js 的示例输出

图 7.15 – 来自 chapter07/javascript-python-translator.js 的示例输出

让我们看一下 Python 版本。

Python 示例

要在 Python 中创建 JavaScript 到 Python 的转换器示例,请按照以下步骤进行:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/javascript-python-translator.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/javascript-python-translator.py中。

  4. chapter07/javascript-python-translator.py中的params变量替换为以下代码:

    params = {
        "prompt": "Translate from JavaScript to Python\n---\n\nJavaScript:\nconst request = require(\"requests\");\nrequest.get(\"https://example.com\");\n\nPython:\n",
        "temperature": 0.3,
        "max_tokens": 15,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0,
        "stop": ["---"]
    }
    
  5. 将根目录中的.replit文件更改为以下内容:

    run = "python chapter07/javascript-python-translator.py"
    
  6. 单击chapter07/javascript-python-translator.py,您应该会看到类似于以下屏幕截图中控制台输出的结果:

图 7.16 – 来自 chapter07/javascript-python-translator.py 的示例输出

图 7.16 – 来自 chapter07/javascript-python-translator.py 的示例输出

在下一个示例中,我们将看一下总结文本。我们在Chapter 7生成和转换文本中使用 TLDR 总结文本,但这不是总结文本的唯一方法。您还可以根据提供的阅读水平/年级提供文本摘要。

第五年级总结

GPT-3 可以为给定的年级或阅读水平总结文本。虽然年级水平不是完全精确的,可能是主观的,但您会注意到随着年级水平的降低,文本变得更简单。以下提示提供了一个示例,您可以用这种方式来处理:

Summarize the following passage for me as if I was in fifth grade:
"""
Quantum mechanics is a fundamental theory in physics that provides a description of the physical properties of nature at the scale of atoms and subatomic particles. It is the foundation of all quantum physics including quantum chemistry, quantum field theory, quantum technology, and quantum information science.
Classical physics, the description of physics that existed before the theory of relativity and quantum mechanics, describes many aspects of nature at an ordinary (macroscopic) scale, while quantum mechanics explains the aspects of nature at small (atomic and subatomic) scales, for which classical mechanics is insufficient. Most theories in classical physics can be derived from quantum mechanics as an approximation valid at large (macroscopic) scale.
Quantum mechanics differs from classical physics in that energy, momentum, angular momentum, and other quantities of a bound system are restricted to discrete values (quantization), objects have characteristics of both particles and waves (wave-particle duality), and there are limits to how accurately the value of a physical quantity can be predicted prior to its measurement, given a complete set of initial conditions (the uncertainty principle).
"""
Here is the fifth-grade version of this passage:
"""

让我们在 Node.js/JavaScript 中尝试这个示例,并审查结果。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建第五年级总结示例,请按照以下步骤进行:

  1. 登录replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/fith-grade-summary.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/fith-grade-summary.js中。

  4. chapter07/fith-grade-summary.js中的params变量替换为以下代码:

    const params = {
      prompt: "Summarize the following passage for me as if I was in fifth grade:\n\"\"\"\nQuantum mechanics is a fundamental theory in physics that provides a description of the physical properties of nature at the scale of atoms and subatomic particles. It is the foundation of all quantum physics including quantum chemistry, quantum field theory, quantum technology, and quantum information science.\n\nClassical physics, the description of physics that existed before the theory of relativity and quantum mechanics, describes many aspects of nature at an ordinary (macroscopic) scale, while quantum mechanics explains the aspects of nature at small (atomic and subatomic) scales, for which classical mechanics is insufficient. Most theories in classical physics can be derived from quantum mechanics as an approximation valid at large (macroscopic) scale.\n\nQuantum mechanics differs from classical physics in that energy, momentum, angular momentum, and other quantities of a bound system are restricted to discrete values (quantization), objects have characteristics of both particles and waves (wave-particle duality), and there are limits to how accurately the value of a physical quantity can be predicted prior to its measurement, given a complete set of initial conditions (the uncertainty principle).\n\"\"\"\nHere is the fifth-grade version of this passage:\n\"\"\"",
      temperature: 0,
      max_tokens: 100,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["\"\"\""]
    }
    
  5. 将根目录中的.replit文件更改为以下内容:

    run = "node chapter07/fith-grade-summary.js"
    
  6. 单击chapter07/fith-grade-summary.js,您应该会看到类似于以下屏幕截图中控制台输出的结果:

图 7.17 – 来自 chapter07/fith-grade-summary.js 的示例输出

图 7.17 – 来自 chapter07/fith-grade-summary.js 的示例输出

让我们来看看 Python 代码。

Python 示例

要在 Python 中创建第五年级摘要示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/fith-grade-summary.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/fith-grade-summary.py中。

  4. chapter07/fith-grade-summary.py中的params变量替换为以下代码:

    params = {
        "prompt": "Summarize the following passage for me as if I was in fifth grade:\n\"\"\"\nQuantum mechanics is a fundamental theory in physics that provides a description of the physical properties of nature at the scale of atoms and subatomic particles. It is the foundation of all quantum physics including quantum chemistry, quantum field theory, quantum technology, and quantum information science.\n\nClassical physics, the description of physics that existed before the theory of relativity and quantum mechanics, describes many aspects of nature at an ordinary (macroscopic) scale, while quantum mechanics explains the aspects of nature at small (atomic and subatomic) scales, for which classical mechanics is insufficient. Most theories in classical physics can be derived from quantum mechanics as an approximation valid at large (macroscopic) scale.\n\nQuantum mechanics differs from classical physics in that energy, momentum, angular momentum, and other quantities of a bound system are restricted to discrete values (quantization), objects have characteristics of both particles and waves (wave-particle duality), and there are limits to how accurately the value of a physical quantity can be predicted prior to its measurement, given a complete set of initial conditions (the uncertainty principle).\n\"\"\"\nHere is the fifth-grade version of this passage:\n\"\"\"",
        "temperature": 0,
        "max_tokens": 100,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0,
        "stop": ["\"\"\""]
    }
    
  5. 将根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/fith-grade-summary.py"
    
  6. 单击chapter07/fith-grade-summary.py,您应该看到类似于以下截图中控制台输出的结果:

图 7.18 - 来自的示例输出

图 7.18 - 来自chapter07/fith-grade-summary.py的示例输出

让我们看另一个例子。 这次我们将看看 GPT-3 如何进行语法纠正。

语法纠正

英语语法纠正可以通过非常简单的提示来完成,例如以下内容:

Original: You be mistaken
Standard American English:

让我们使用 Node.js/JavaScript 来测试这个语法纠正提示。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建语法纠正转换器示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/grammar-correction-converter.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/grammar-correction-converter.js中。

  4. chapter07/grammar-correction-converter.js中的params变量替换为以下代码:

    const params = {
      prompt: "Original: You be mistaken\nStandard American English:",
      temperature: 0,
      max_tokens: 60,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["\n"]
    }
    
  5. 将根文件夹中的.replit文件更改为以下内容:

    run = "node chapter07/grammar-correction-converter.js"
    
  6. 单击chapter07/grammar-correction-converter.js,您应该看到类似于以下截图中控制台输出的结果:

图 7.19 - 来自的示例输出

图 7.19 - 来自chapter07/grammar-correction-converter.js的示例输出

让我们来看看 Python 代码。

Python 示例

要在 Python 中创建语法纠正转换器示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/grammar-correction-converter.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/grammar-correction-converter.py中。

  4. chapter07/grammar-correction-converter.py中的params变量替换为以下代码:

    params = {
        "prompt": "Original: You be mistaken\nStandard American English:",
        "temperature": 0,
        "max_tokens": 60,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0,
        "stop": ["\n"]
    }
    
  5. 将根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/grammar-correction-converter.py"
    
  6. 单击chapter07/gramar-correction-converter.py,您应该看到类似于以下截图中控制台输出的结果:

图 7.20 - 来自的示例输出

图 7.20 - 来自chapter07/grammar-correction-converter.py的示例输出

好了,我们在本章中涵盖了很多例子,但我们还没有完成。让我们继续前进,看看如何从文本中提取信息。

提取文本

您还可以使用 GPT-3 从较大的文本中提取文本值。这通常称为实体提取,其中实体是您要提取的项或模式。或者您可能想要提取关键字。为此,您可以使用以下提示。

提取关键字

以下提示提供了如何从文本中提取关键字的示例。在本例中,文本来自en.wikipedia.org/wiki/Quantum_mechanics,但当然,这可以用任何文本来完成:

Quantum mechanics is a fundamental theory in physics that provides a description of the physical properties of nature at the scale of atoms and subatomic particles. It is the foundation of all quantum physics including quantum chemistry, quantum field theory, quantum technology, and quantum information science.
Classical physics, the description of physics that existed before the theory of relativity and quantum mechanics, describes many aspects of nature at an ordinary (macroscopic) scale, while quantum mechanics explains the aspects of nature at small (atomic and subatomic) scales, for which classical mechanics is insufficient. Most theories in classical physics can be derived from quantum mechanics as an approximation valid at large (macroscopic) scale.
Quantum mechanics differs from classical physics in that energy, momentum, angular momentum, and other quantities of a bound system are restricted to discrete values (quantization), objects have characteristics of both particles and waves (wave-particle duality), and there are limits to how accurately the value of a physical quantity can be predicted prior to its measurement, given a complete set of initial conditions (the uncertainty principle).
Keywords:

现在尝试使用 Node.js/JavaScript 提取关键词。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建关键词提取器示例,请按照以下步骤操作:

  1. 登录 replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/keyword-extractor.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/keyword-extractor.js中。

  4. chapter07/keyword-extractor.js中的params变量替换为以下代码:

    const params = {
      prompt: "Quantum mechanics is a fundamental theory in physics that provides a description of the physical properties of nature at the scale of atoms and subatomic particles. It is the foundation of all quantum physics including quantum chemistry, quantum field theory, quantum technology, and quantum information science.\n\nClassical physics, the description of physics that existed before the theory of relativity and quantum mechanics, describes many aspects of nature at an ordinary (macroscopic) scale, while quantum mechanics explains the aspects of nature at small (atomic and subatomic) scales, for which classical mechanics is insufficient. Most theories in classical physics can be derived from quantum mechanics as an approximation valid at large (macroscopic) scale.\n\nQuantum mechanics differs from classical physics in that energy, momentum, angular momentum, and other quantities of a bound system are restricted to discrete values (quantization), objects have characteristics of both particles and waves (wave-particle duality), and there are limits to how accurately the value of a physical quantity can be predicted prior to its measurement, given a complete set of initial conditions (the uncertainty principle).\n\nKeywords:",
      temperature: 0.3,
      max_tokens: 60,
      top_p: 1,
      frequency_penalty: 0.8,
      presence_penalty: 0,
      stop: ["\n"]
    }
    
  5. 更改根文件夹中的.replit文件为以下内容:

    run = "node chapter07/keyword-extractor.js"
    
  6. 点击chapter07/keyword-extractor.js,您应该会看到类似于以下截图中的控制台输出的结果:

图 7.21 – 来自章节 07/keyword-extractor.js 的示例输出

图 7.21 – 来自章节 07/keyword-extractor.js 的示例输出

现在是 Python 示例。

Python 示例

要在 Python 中创建关键词提取器示例,请按照以下步骤操作:

  1. 登录 replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/keyword-extractor.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/keyword-extractor.py中。

  4. chapter07/keyword-extractor.py中的params变量替换为以下代码:

    params = {
        "prompt": "Quantum mechanics is a fundamental theory in physics that provides a description of the physical properties of nature at the scale of atoms and subatomic particles. It is the foundation of all quantum physics including quantum chemistry, quantum field theory, quantum technology, and quantum information science.\n\nClassical physics, the description of physics that existed before the theory of relativity and quantum mechanics, describes many aspects of nature at an ordinary (macroscopic) scale, while quantum mechanics explains the aspects of nature at small (atomic and subatomic) scales, for which classical mechanics is insufficient. Most theories in classical physics can be derived from quantum mechanics as an approximation valid at large (macroscopic) scale.\n\nQuantum mechanics differs from classical physics in that energy, momentum, angular momentum, and other quantities of a bound system are restricted to discrete values (quantization), objects have characteristics of both particles and waves (wave-particle duality), and there are limits to how accurately the value of a physical quantity can be predicted prior to its measurement, given a complete set of initial conditions (the uncertainty principle).\n\nKeywords:",
        "temperature": 0.3,
        "max_tokens": 60,
        "top_p": 1,
        "frequency_penalty": 0.8,
        "presence_penalty": 0,
        "stop": ["\n"]
    }
    
  5. 更改根文件夹中的.replit文件为以下内容:

    run = "python chapter07/keyword-extractor.py"
    
  6. 点击chapter07/keyword-extractor.py,您应该会看到类似于以下截图中的控制台输出的结果:

图 7.22 – 来自章节 07/keyword-extractor.py 的示例输出

图 7.22 – 来自章节 07/keyword-extractor.py 的示例输出

让我们看看另一个示例。

HTML 解析

在此示例中,我们将从 HTML 中提取文本。具体来说,以下提示提取标题标签的值(在<title></title>之间的文本)。正如您所看到的,提示非常简单。它只提供了一些简单的指示、要从中提取的 HTML 和标题的标签:

Extract the title, h1, and body text from the following HTML document:
<head><title>A simple page</title></head><body><h1>Hello World</h1><p>This is some text in a simple html page.</p></body></btml>
Title:

现在,让我们尝试使用 Node.js/JavaScript 进行 HTML 解析。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建来自 HTML 示例的文本,请按照以下步骤操作:

  1. 登录 replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/text-from-html.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/text-from-html.js中。

  4. chapter07/text-from-html.js中的params变量替换为以下代码:

    const params = {
      prompt: "Extract the title, h1, and body text from the following HTML document:\n\n<head><title>A simple page</title></head><body><h1>Hello World</h1><p>This is some text in a simple html page.</p></body></html>\n\nTitle:",
      temperature: 0,
      max_tokens: 64,
      top_p: 1,
      frequency_penalty: 0.5,
      presence_penalty: 0
    }
    
  5. 将根文件夹中的 .replit 文件更改为以下内容:

    run = "node chapter07/text-from-html.js"
    
  6. 单击 chapter07/text-from-html.js,您应该会看到类似以下截图中控制台输出的结果:

图 7.23 – 来自 chapter07/text-from-html.js 的示例输出

图 7.23 – 来自 chapter07/text-from-html.js 的示例输出

让我们来看看 Python 代码。

Python 示例

要在 Python 中创建来自 HTML 的文本示例,请按照以下步骤进行:

  1. 登录 replit.com,打开您的 exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/text-from-html.py

  3. dumb-joke-generator.py 文件中的代码复制到 chapter07/text-from-html.py 中。

  4. chapter07/text-from-html.py 中的 params 变量替换为以下代码:

    params = {
        "prompt": "Extract the title, h1, and body text from the following HTML document:\n\n<head><title>A simple page</title></head><body><h1>Hello World</h1><p>This is some text in a simple html page.</p></body></html>\n\nTitle:",
        "temperature": 0,
        "max_tokens": 64,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0
    }
    
  5. 将根文件夹中的 .replit 文件更改为以下内容:

    run = "python chapter07/text-from-html.py"
    
  6. 单击 chapter07/text-from-html.py,您应该会看到类似以下截图中控制台输出的结果:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 7.24 – 来自 chapter07/text-from-html.py 的示例输出

让我们看看另一个示例。

提取邮政地址

让我们看一个从电子邮件中提取邮政地址的示例。以下提示显示了您如何完成此操作。

重要说明

此示例使用的是davinci-instruct-beta引擎,在发布时处于测试阶段。

您可以看到提示提供了基本说明,电子邮件中的邮政地址以标准方式提供,因此 GPT-3 可能能够识别出该地址:

Extract the postal address from this email:
Dear Paul,
I'm in the market for a new home and I understand you're the listing agent for the property located at 2620 Riviera Dr, Laguna Beach, CA 92651.
Is the seller flexible at all on the asking price?
Best,
Linda
Property Address:

现在尝试使用 Node.js/JavaScript 进行此提示。

Node.js/JavaScript 示例

要创建 Node.js/JavaScript 中提取邮政地址的示例,请按照以下步骤进行:

  1. 登录 replit.com,打开您的 exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/extract-postal-address.js

  3. dumb-joke-generator.py 文件中的代码复制到 chapter07/extract-postal-address.js 中。

  4. chapter07/extract-postal-address.js 中的 params 变量替换为以下代码:

    const params = {
      prompt: "Extract the postal address from this email:\n\nDear Paul,\n\nI'm in the market for a new home and I understand you're the listing agent for the property located at 2620 Riviera Dr, Laguna Beach, CA 92651.\n\nIs the seller flexible at all on the asking price?\n\nBest,\n\nLinda\n\nProperty Address:\n",
      temperature: 0,
      max_tokens: 64,
      top_p: 1,
      frequency_penalty: 0.5,
      presence_penalty: 0,
      stop: [""]
    }
    
  5. 将根文件夹中的 .replit 文件更改为以下内容:

    run = "node chapter07/extract-postal-address.js"
    
  6. 单击 chapter07/extract-postal-address.js,您应该会看到类似以下截图中控制台输出的结果:

图 7.25 – 来自 chapter07/extract-postal-address.js 的示例输出

图 7.25 – 来自 chapter07/extract-postal-address.js 的示例输出

现在让我们尝试使用 Python 相同的示例。

Python 示例

要创建 Python 中提取邮政地址的示例,请按照以下步骤进行:

  1. 登录 replit.com,打开您的 exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/extract-postal-address.py

  3. dumb-joke-generator.py 文件中的代码复制到 chapter07/extract-postal-address.py 中。

  4. chapter07/extract-postal-address.py 中的 params 变量替换为以下代码:

    params = {
        "prompt": "Extract the postal address from this email:\n\nDear Paul,\n\nI'm in the market for a new home and I understand you're the listing agent for the property located at 2620 Riviera Dr, Laguna Beach, CA 92651.\n\nIs the seller flexible at all on the asking price?\n\nBest,\n\nLinda\n\nProperty Address:\n",
        "temperature": 0,
        "max_tokens": 64,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0,
        "stop": [""]
    }
    
  5. 在您的根文件夹中更改.replit文件为以下内容:

    run = "python chapter07/extract-postal-address.py"
    
  6. 单击chapter07/extract-postal-address.py,您应该看到类似于以下截图中控制台输出的结果:

图 7.26 – 来自 chapter07/extract-postal-address.py 的示例输出

图 7.26 – 来自 chapter07/extract-postal-address.py 的示例输出

让我们看一个类似的例子 – 提取电子邮件地址。

提取电子邮件地址

这个提示与邮政地址示例类似,但这次我们指示 GPT-3 提取电子邮件地址:

Extract the email address from the following message:
Dear Paul,
I'm in the market for a new home and I understand you're the listing agent for the property located at 2620 Riviera Dr, Laguna Beach, CA 92651.
Can you send details to my wife's email which is beth@example.com?
Best,
Kevin
Email Address:

现在,让我们尝试用 Node.js/JavaScript 运行这个提示。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建提取电子邮件地址的示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/extract-email-address.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/extract-email-address.js中。

  4. 用以下代码替换chapter07/extract-email-address.js中的params变量:

    const params = {
      prompt: "Extract the email address from the following message:\n\nDear Paul,\n\nI'm in the market for a new home and I understand you're the listing agent for the property located at 2620 Riviera Dr, Laguna Beach, CA 92651.\n\nCan you send details to my wife's email which is beth@example.com?\n\nBest,\n\nKevin\n\nEmail Address:\n",
      temperature: 0,
      max_tokens: 64,
      top_p: 1,
      frequency_penalty: 0.5,
      presence_penalty: 0,
      stop: [""]
    }
    
  5. 在您的根文件夹中更改.replit文件为以下内容:

    run = "node chapter07/extract-email-address.js"
    
  6. 单击chapter07/extract-email-address.js,您应该看到类似于以下截图中控制台输出的结果:

图 7.27 – 来自 chapter07/extract-email-address.js 的示例输出

图 7.27 – 来自 chapter07/extract-email-address.js 的示例输出

让我们看看 Python 代码。

Python 示例

要在 Python 中创建提取电子邮件地址的示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/extract-email-address.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/extract-email-address.py中。

  4. 用以下代码替换chapter07/extract-email-address.py中的params变量:

    params = {
        "prompt": "Extract the email address from the following message:\n\nDear Paul,\n\nI'm in the market for a new home and I understand you're the listing agent for the property located at 2620 Riviera Dr, Laguna Beach, CA 92651.\n\nCan you send details to my wife's email which is beth@example.com?\n\nBest,\n\nKevin\n\nEmail Address:\n",
        "temperature": 0,
        "max_tokens": 64,
        "top_p": 1,
        "frequency_penalty": 0.5,
        "presence_penalty": 0,
        "stop": [""]
    }
    
  5. 在您的根文件夹中更改.replit文件为以下内容:

    run = "python chapter07/extract-email-address.py"
    
  6. 单击chapter07/extract-email-address.py,您应该看到类似于以下截图中控制台输出的结果:

图 7.28 – 来自 chapter07/extract-email-address.py 的示例输出

图 7.28 – 来自 chapter07/extract-email-address.py 的示例输出

对于我们的最后一个示例,我们将以一个聊天机器人结束。

创建聊天机器人

对于最后一组示例,我们将看看如何创建聊天机器人。从技术上讲,这将被分类为生成文本,因此它可以被归类为生成内容和列表。但是使用 GPT-3 创建聊天机器人是如此有趣,它值得拥有自己的一节。我们将从一个简单的对话式聊天机器人开始。

一个简单的聊天机器人

对于我们的简单聊天机器人,我们将使用以下提示。我们将分别查看 Node.js/JavaScript 和 Python 的代码,但两者的提示是相同的。

提示的第一部分提供了有关机器人应如何响应以及一般对话风格的指导。通过更改指导和示例对话,您可以改变机器人响应的许多方面。例如,您可以通过将词语友好和礼貌更改为粗鲁和讽刺来改变对话语气。

这是我们简单机器人的提示文本:

The following is a conversation with an AI bot. The bot is very friendly and polite.
Human: Hello, how are you?
AI: I am doing great, thanks for asking. How can I help you today?
Human: I just wanting to talk with you.
AI:

现在,让我们看看如何在 Node.js/JavaScript 中实现一个简单的机器人。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建简单的聊天机器人示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-node repl。

  2. 创建一个新文件:chapter07/simple-chatbot.js

  3. dumb-joke-generator.py文件中的代码复制到chapter07/simple-chatbot.js中。

  4. chapter07/simple-chatbot.js中用以下代码替换params变量:

    const params = {
      prompt: "The following is a conversation with an AI bot. The bot is very friendly and polite.\n\nHuman: Hello, how are you?\nAI: I am doing great, thanks for asking. How can I help you today?\nHuman: I just wanting to talk with you.\nAI:",
      temperature: 0.9,
      max_tokens: 150,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0.6,
      stop: ["\n, Human:, AI:"]
    }
    
  5. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "node chapter07/simple-chatbot.js"
    
  6. 点击chapter07/simple-chatbot.js,你应该会看到类似以下截图中的控制台输出:

图 7.29 – 来自 chapter07/simple-chatbot.js 的示例输出

图 7.29 – 来自 chapter07/simple-chatbot.js 的示例输出

现在是 Python 版本。

Python 示例

要在 Python 中创建简单的聊天机器人示例,请按照以下步骤操作:

  1. 登录replit.com,并打开您的exploring-gpt3-python repl。

  2. 创建一个新文件:chapter07/simple-chatbot.py

  3. dumb-joke-generator.py文件中的代码复制到chapter07/simple-chatbot.py中。

  4. chapter07/simple-chatbot.py中用以下代码替换params变量:

    params = {
        "prompt": "The following is a conversation with an AI bot. The bot is very friendly and polite.\n\nHuman: Hello, how are you?\nAI: I am doing great, thanks for asking. How can I help you today?\nHuman: I just wanting to talk with you.\nAI:",
        "temperature": 0.9,
        "max_tokens": 150,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0.6,
        "stop": ["\n, Human:, AI:"]
    }
    
  5. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "python chapter07/simple-chatbot.py"
    
  6. 点击chapter07/simple-chatbot.py,你应该会看到类似以下截图中的控制台输出:

图 7.30 – 来自 chapter07/simple-chatbot.py 的示例输出

图 7.30 – 来自 chapter07/simple-chatbot.py 的示例输出

这是我们的最后一个例子。让我们用一个快速总结结束。

摘要

在本章中,我们介绍了生成和转换文本的内容。我们讨论了 15 个示例,涵盖了 Node.js/JavaScript 和 Python 两种语言。示例包括生成内容和列表、翻译和转换文本、提取文本以及创建简单的聊天机器人。

在下一章中,我们将介绍分类和归类文本的示例。

第八章:分类和归类文本

在上一章中,我们探讨了生成文本的不同方法。在本章中,我们将讨论文本分类和 OpenAI API 分类端点。我们将从快速概述文本分类和分类端点开始,然后进行实施情感分析、为文本分配 ESRB 评级、通过语言对文本进行分类以及从关键词对文本进行分类,这些都是常见的文本分类示例。

本章将涵盖以下主题:

  • 理解文本分类

  • 介绍分类端点

  • 实施情感分析

  • 为文本分配 ESRB 评级

  • 通过语言对文本进行分类

  • 从关键词对文本进行分类

技术要求

本章需要您访问 OpenAI API。您可以通过访问openapi.com来请求访问权限。

理解文本分类

文本分类任务接受文本并返回标签。将电子邮件分类为垃圾邮件或确定推文的情感都是文本分类任务的例子。使用 OpenAI API 进行文本分类有多种方法,我们已经看过其中一些。但我们还没有涵盖的一种方法是使用完成端点。然而,在我们深入研究完成端点之前,让我们快速回顾一下我们已经涵盖的一些不同的文本分类方法。

使用完成端点进行文本分类

你可以使用完成端点来执行分类任务,只需在提示中描述任务。例如,下面的提示可用于对社交媒体发布进行分类:

Social media post: "My favorite restaurant is opening again Monday. I can't wait!"
Sentiment (positive, neutral, negative):

以往的提示可能会根据发布返回积极,自然或消极,但很可能是积极的。

内容过滤是一个文本分类任务

内容过滤也是一种文本分类任务。回想一下第六章中的内容过滤,当我们使用内容过滤引擎时,返回的结果是0 = 安全1 = 敏感2 = 不安全,这就是文本分类。

虽然可以使用 OpenAI API 进行多种文本分类的方法,但有一个端点专门设计用于分类任务。该端点就是分类端点,接下来我们将讨论这个内容。

介绍分类端点

OpenAI API 还为文本分类任务提供了分类端点。分类端点简化了许多分类任务。它使用语义搜索和完成引擎的组合,根据您提供的样本对文本进行分类。您可以在 HTTP 请求中提供最多 200 个示例,或者可以提前上传包含示例数据的文件。

分类端点的 URL 是api.openai.com/v1/classifications。它期望使用包含输入参数的 JSON 主体的 HTTP POST。其中一个必需的参数是query参数。query参数的值是要分类的文本。query值首先用于进行语义搜索,以从提供的示例中找到相关示例。然后,这些示例连同查询一起用于创建一个定义的完成引擎的提示,该引擎将对文本进行分类。

以下代码块显示了分类端点的简单请求主体。请注意,此请求与示例一起提供,并且将用于执行分类的模型是curie模型:

{
  "query": "That makes me smile",
  "examples": [
    ["That is awesome", "Happy"],
    ["I feel so sad", "Sad"],
    ["I don't know how I feel", "Neutral"]
  ],
  "model": "curie"
}

正如前面提到的,你也可以上传示例数据,并使用file参数引用上传的示例数据。当你有大量示例时,这是很有用的 – 超过 200 个。让我们来看看如何上传文件。

上传文件

可以使用 OpenAI API 文件端点上传分类端点的示例数据。文件应该基于 JSON 行文本格式进行格式化,基本上就是每行一个有效的 JSON 对象,这些对象之间用换行符分隔。

重要提示

您可以在jsonlines.org了解更多关于 JSON 行格式的信息。

以下代码块提供了一个分类样本文件所需的格式示例。text属性和label属性是必需的,但metadata是可选的。元数据属性可以包含一个 JSON 对象,其中包含您想要的任何信息。然后这些数据可以选择性地随查询结果返回:

{"text": "that is awesome", "label": "Happy", "metadata": {"id":"1"}}
{"text": "i feel so sad", "label": "Sad", "metadata": {"id":"2"}}
{"text": "i don't know how i feel", "label": "Neutral", "metadata": {"id":"3"}}

要上传一个样本文件,您可以使用 OpenAI API 的文件端点。在本章的示例中,我们不会使用文件。但是,在第九章中,我们将更仔细地研究文件端点,构建一个 GPT-3 支持的问答应用

实施情感分析

常见的分类任务是情感分析。使用情感分析,您可以根据文本的一般语气进行分类 – 例如,快乐,悲伤,愤怒或中性。这在许多应用中都很有用;例如,如果您是餐馆老板,您希望能够迅速对不满意的顾客评论做出回应。让我们来看看如何使用 OpenAI API 分类端点来实现这一点。

在此示例中,我们将对餐厅评论进行分类。我们将使用分类端点进行此示例,并且我们将在请求中提供一些示例评论。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建评论分类器示例,请按照以下步骤进行:

  1. 登录到replit.com,并打开你的exploring-gpt3-node REPL。

  2. 创建一个新文件 – chapter08/reviews-classifier.js

  3. 将以下代码添加到reviews-classifier.js文件的开头:

    const axios = require('axios');
    const client = axios.create({
      headers: {
        'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY
      }
    });
    const endpoint = "https://api.openai.com/v1/classifications";
    
  4. 然后,添加将与请求一起使用的示例评论:

    const examples = [
      ["The service was super quick. I love that.","Good"],
      ["Would not go back.","Poor"],
      ["I tried the chicken and cranberry pizza...mmmm!","Good"],
      ["There were no signs indicating cash only!","Poor"],
      ["I was disgusted. There was a hair in my food.","Poor"],
      ["The waitress was a little slow but friendly.","Neutral"]
    ]
    
  5. 接下来,为分类端点添加请求参数:

    const params = {
      "query": "I'm never going to this place again",
      "examples": reviews,
      "model": "curie"
    }
    
  6. 最后,添加以下代码将结果记录到控制台:

    client.post(endpoint, params)
      .then(result => {
        console.log(params.query + '\nLABEL:' + result.data.label);
      }).catch(err => {
        console.log(err);
      });
    
  7. 将你的根文件夹中的 .replit 文件更改为以下内容:

    run = "node chapter08/reviews-classifier.js"
    
  8. 单击 chapter08/reviews-classifier.js 文件,你应该会看到类似于以下截图中控制台输出的结果:

图 8.1 – 来自 chapter08/reviews-classifier.js 的示例输出

图 8.1 – 来自 chapter08/reviews-classifier.js 的示例输出

接下来,让我们使用 Python 来看一下相同的示例。

Python 示例

要创建 Python 中的在线评论分类器示例,请按照以下步骤操作:

  1. 登录到 replit.com,并打开你的 exploring-gpt3-python REPL。

  2. 创建一个新文件 – chapter08/reviews-classifier.py

  3. 将以下代码添加到 reviews-classifier.py 文件的开头:

    import requests
    import os
    import json
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + os.environ.get("OPENAI_API_KEY")
    }
    endpoint = "https://api.openai.com/v1/classifications"
    
  4. 为评论示例创建一个数组:

    examples = [
      ["The service was super quick. I love that.","Good"],
      ["Would not go back.","Poor"],
      ["I tried the chicken and cranberry pizza...mmmm!","Good"],
      ["There were no signs indicating cash only!","Poor"],
      ["I was disgusted. There was a hair in my food.","Poor"],
      ["The waitress was a little slow but friendly.","Neutral"]
    ]
    
  5. 为端点设置请求参数:

    params = {
      "query": "I'm never going to this place again",
      "examples": examples,
      "model": "curie"
    }
    
  6. 进行 HTTP 请求并将结果打印到控制台:

    result = requests.post(endpoint, headers=headers, data=json.dumps(params))
    print(params["query"] + '\nLABEL:' + result.json()["label"])
    
  7. 将你的根文件夹中的 .replit 文件更改为以下内容:

    run = "python chapter08/reviews-classifier.py"
    
  8. 单击 chapter08/online-review-classifier.py 文件,你应该会看到类似于以下截图中控制台输出的结果:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

图 8.2 – 来自 chapter08/online-review-classifier.py 的示例输出

现在让我们看另一个示例。

为文本分配 ESRB 等级

在上一个示例中,我们提供了样本数据来帮助我们的分类任务。但 GPT-3 是预先训练的,具有大量数据集,这意味着它可以执行令人惊讶的数量的分类任务,而无需提供任何示例数据。让我们看另一个使用完成端点的示例。在这个示例中,我们将研究使用 娱乐软件评级委员会 (ESRB) 等级对文本进行分类。

在这个示例中,我们将使用完成端点为文本分配 ESRB 等级,而不需要任何示例数据。

Node.js/JavaScript 示例

要创建 Node.js/JavaScript 中的 ESRB 等级分类器示例,请按照以下步骤操作:

  1. 登录到 replit.com,并打开你的 exploring-gpt3-node REPL。

  2. 创建一个新文件 – chapter08/esrb-rating-classifier.js

  3. 将以下代码添加到 esrb-rating-classifier.js 文件的开头:

    const axios = require('axios');
    const apiKey = process.env.OPENAI_API_KEY;
    const client = axios.create({
      headers: { 'Authorization': 'Bearer ' + apiKey }
    });
    const endpoint = "https://api.openai.com/v1/engines/davinci/completions";
    
  4. 使用以下代码将端点参数添加到 esrb-rating-classifier.js 文件中:

    const params = {
      prompt: "Provide an ESRB rating for the following text:\n\n\"i'm going to hunt you down, and when I find you, I'll make you wish you were dead.\"\n\nESRB rating:",
      temperature: 0.7,
      max_tokens: 60,
      top_p: 1,
      frequency_penalty: 0,
      presence_penalty: 0,
      stop: ["\n"]
    }
    
  5. 将以下代码添加到将端点响应记录到控制台的文件中:

    client.post(endpoint, params)
      .then(result => {
        console.log(params.prompt + result.data.choices[0].text);
        // console.log(result.data);
      }).catch(err => {
        console.log(err);
      });
    
  6. 将你的根文件夹中的 .replit 文件更改为以下内容:

    run = "node chapter08/esrb-rating-classifier.js"
    
  7. 单击 chapter08/esrb-rating-classifier.js 文件,你应该会看到类似于以下截图中控制台输出的结果:

图 8.3 – 来自 chapter08/esrb-rating-classifier.js 的示例输出

图 8.3 – 来自 chapter08/esrb-rating-classifier.js 的示例输出

现在,让我们来看一下 Python 中的 ESRB 等级分类器。

Python 示例

要在 Python 中创建 ESRB 分级分类器示例,请按照以下步骤操作:

  1. 登录到 replit.com 并打开你的 exploring-gpt3-python REPL。

  2. 创建一个新文件 – chapter08/esrb-rating-classifier.py

  3. esrb-rating-classifier.py 文件的开头添加以下代码:

    import requests
    import os
    import json
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + os.environ.get("OPENAI_API_KEY")
    }
    endpoint = 'https://api.openai.com/v1/engines/davinci/completions'
    
  4. 使用以下代码将端点参数添加到 esrb-rating-classifier.js 文件中:

    params = {
      "prompt": "Provide an ESRB rating for the following text:\n\n\"i'm going to hunt you down, and when I find you, I'll make you wish you were dead.\"\n\nESRB rating:",
      "temperature": 0.7,
      "max_tokens": 60,
      "top_p": 1,
      "frequency_penalty": 0,
      "presence_penalty": 0,
      "stop": ["\n"]
    }
    
  5. 添加以下代码将端点响应记录到控制台:

    result = requests.post(endpoint, headers=headers, data=json.dumps(params))
    print(params["prompt"] + result.json()["choices"][0]["text"])
    
  6. 更改你根目录下的 .replit 文件为以下内容:

    run = "node chapter08/esrb-rating-classifier.js"
    
  7. 点击 chapter08/esrb-rating-classifier.js 文件,你应该看到类似于以下截图中控制台输出的结果:

![图 8.4 – 来自 chapter08/esrb-rating-classifier.py 的示例输出]

](https://gitee.com/OpenDocCN/freelearn-dl-pt2-zh/raw/master/docs/expl-gpt3/img/B16854_08_004.jpg)

图 8.4 – 来自 chapter08/esrb-rating-classifier.py 的示例输出

现在让我们看另一个例子。

文本分类为语言

现在,让我们考虑一个例子。假设我们需要根据消息所写的语言将支持消息路由到一个跨国支持中心。在这种情况下,我们可以使用 GPT-3 来按语言分类消息,例如英语、法语、印地语、西班牙语和俄语。让我们看看我们如何去做。

在此示例中,我们将使用分类端点和每种语言的示例来按语言分类支持消息。

Node.js/JavaScript 示例

要在 Node.js/JavaScript 中创建电子邮件分类器示例,请按照以下步骤操作:

  1. 登录到 replit.com 并打开你的 exploring-gpt3-node REPL。

  2. 创建一个新文件 – chapter08/language-classifier.js

  3. language-classifier.js 文件的开头添加以下代码:

    const axios = require('axios');
    const apiKey = process.env.OPENAI_API_KEY;
    const client = axios.create({
      headers: { 'Authorization': 'Bearer ' + apiKey }
    });
    const endpoint = "https://api.openai.com/v1/classifications";
    
  4. 为语言示例创建一个数组:

    const examples = [
      ["Hello, I'm interested in applying for the prompt designer position you are hiring for. Can you please tell me where I should send my resume?","English"],
      ["Здравствуйте, я хочу подать заявку на должность быстрого дизайнера, на которую вы нанимаете. Подскажите, пожалуйста, куда мне отправить резюме?","Russian"],
      ["Hola, estoy interesado en postularme para el puesto de diseñador rápido para el que está contratando. ¿Puede decirme dónde debo enviar mi currículum?", "Spanish"],
      ["Bonjour, je suis intéressé à postuler pour le poste de concepteur rapide pour lequel vous recrutez. Pouvez-vous me dire où je dois envoyer mon CV?","French"],
      ["नमस्कार, मैं उस त्वरित डिज़ाइनर पद के लिए आवेदन करने में रुचि रखता हूं, जिसके लिए आप नौकरी कर रहे हैं। क्या आप मुझे बता सकते हैं कि मुझे अपना रिज्यूम कहां भेजना चाहिए?","Hindi"]
    ]
    

    如果需要,你可以使用 translate.google.com 创建示例数据。

  5. 使用以下代码添加端点参数:

    const params = {
      "query": "¿Con quién debo comunicarme sobre ofertas de trabajo técnico?",
      "examples": examples,
      "model": "curie"
    }
    
  6. 添加以下代码将端点响应记录到控制台:

    client.post(endpoint, params)
      .then(result => {
        console.log(params.query + '\nLABEL:' + result.data.label);
      }).catch(err => {
        console.log(err);
      });
    
  7. 更改你根目录下的 .replit 文件为以下内容:

    run = "node chapter08/language-classifier.js"
    
  8. 点击 chapter08/email-classifier.js 文件,你应该看到类似于以下截图中控制台输出的结果:

![图 8.5 – 来自 chapter08/language-classifier.js 的示例输出]

](https://gitee.com/OpenDocCN/freelearn-dl-pt2-zh/raw/master/docs/expl-gpt3/img/B16854_08_005.jpg)

图 8.5 – 来自 chapter08/language-classifier.js 的示例输出

接下来让我们看看 Python 版本。

Python 示例

要在 Python 中创建语言分类器示例,请按照以下步骤操作:

  1. 登录到 replit.com 并打开你的 exploring-gpt3-python REPL。

  2. 创建一个新文件 – chapter08/language-classifier.py

  3. language-classifier.py 文件的开头添加以下代码:

    import requests
    import os
    import json
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + os.environ.get("OPENAI_API_KEY")
    }
    endpoint = "https://api.openai.com/v1/classifications"
    
  4. 为语言示例创建一个数组:

    examples = [
      ["Hello, I'm interested in applying for the prompt designer position you are hiring for. Can you please tell me where I should send my resume?","English"],
      ["Здравствуйте, я хочу подать заявку на должность быстрого дизайнера, на которую вы нанимаете. Подскажите, пожалуйста, куда мне отправить резюме?","Russian"],
      ["Hola, estoy interesado en postularme para el puesto de diseñador rápido para el que está contratando. ¿Puede decirme dónde debo enviar mi currículum?", "Spanish"],
      ["Bonjour, je suis intéressé à postuler pour le poste de concepteur rapide pour lequel vous recrutez. Pouvez-vous me dire où je dois envoyer mon CV?","French"],
      ["नमस्कार, मैं उस त्वरित डिज़ाइनर पद के लिए आवेदन करने में रुचि रखता हूं, जिसके लिए आप नौकरी कर रहे हैं। क्या आप मुझे बता सकते हैं कि मुझे अपना रिज्यूम कहां भेजना चाहिए?","Hindi"]
    ]
    

    如果需要,你可以使用 translate.google.com 创建示例数据。

  5. 使用以下代码添加端点参数:

    const params = {
      "query": "¿Con quién debo comunicarme sobre ofertas de trabajo técnico?",
      "examples": examples,
      "model": "curie"
    }
    
  6. 添加以下代码将端点响应记录到控制台:

    result = requests.post(endpoint, headers=headers, data=json.dumps(params))
    print(params["query"] + '\nLABEL:' + result.json()["label"])
    
  7. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "python chapter08/language-classifier.py"
    
  8. 单击chapter08/language-classifier.py文件,您应该看到与以下截图中的控制台输出类似的结果:

图 8.6 - 来自 chapter08/language-classifier.py 的示例输出

图 8.6 - 来自 chapter08/language-classifier.py 的示例输出

现在让我们看另一个例子。

基于关键字分类文本

另一个常见的文本分类任务是基于关键字对文档进行分类。为此,我们可以使用 GPT3 创建一个与文档内容相关的关键字列表。然而,GPT3 不仅仅是从文档中提取关键字。它根据文档内容确定相关的关键字。让我们尝试一个例子。

在这个例子中,我们将使用完成端点来基于相关关键字对文档进行分类。

Node.js/JavaScript 示例

要在Node.js/JavaScript中创建关键词分类器示例,请按照以下步骤进行:

  1. 登录到replit.com,然后打开您的exploring-gpt3-node REPL。

  2. 创建一个新文件 - chapter08/keywords-classifier.js

  3. keywords-classifier.js文件的开头添加以下代码:

    const axios = require('axios');
    const apiKey = process.env.OPENAI_API_KEY;
    const client = axios.create({
      headers: { 'Authorization': 'Bearer ' + apiKey }
    });
    const endpoint = "https://api.openai.com/v1/engines/davinci/completions";
    
  4. 使用以下代码将端点参数添加到keywords-classifier.js中:

    const params = {
      prompt: "Text: When NASA opened for business on October 1, 1958, it accelerated the work already started on human and robotic spaceflight. NASA's first high profile program was Project Mercury, an effort to learn if humans could survive in space. This was followed by Project Gemini, which used spacecraft built for two astronauts to perfect the capabilities needed for the national objective of a human trip to the Moon by the end of the 1960s. Project Apollo achieved that objective in July 1969 with the Apollo 11 mission and expanded on it with five more successful lunar landing missions through 1972\. After the Skylab and Apollo-Soyuz Test Projects of the mid-1970s, NASA's human spaceflight efforts again resumed in 1981, with the Space Shuttle program that continued for 30 years. The Shuttle was not only a breakthrough technology, but was essential to our next major step in space, the construction of the International Space Station.\n\nKeywords:",
      temperature: 0.3,
      max_tokens: 60,
      top_p: 1,
      frequency_penalty: 0.8,
      presence_penalty: 0,
      stop: ["\n"]
    }
    
  5. 添加以下代码以将端点响应记录到控制台:

    client.post(endpoint, params)
      .then(result => {
        console.log(params.prompt + result.data.choices[0].text);
        // console.log(result.data);
      }).catch(err => {
        console.log(err);
      });
    
  6. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "node chapter08/keywords-classifier.js"
    
  7. 单击chapter08/keywords-classifier.js文件,您应该看到与以下截图中的控制台输出类似的结果。请注意,在结果中识别出的一些关键字可能不存在于原始文本中:

图 8.7 - 来自 chapter08/keywords-classifier.js 的示例输出

图 8.7 - 来自 chapter08/keywords-classifier.js 的示例输出

好了,接下来,让我们看一下 Python 版本。

Python 示例

要在 Python 中创建关键词分类器示例,请按照以下步骤进行:

  1. 登录到replit.com,然后打开您的exploring-gpt3-python REPL。

  2. 创建一个新文件 - chapter08/keywords-classifier.py

  3. keywords-classifier.py文件的开头添加以下代码:

    import requests
    import os
    import json
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + os.environ.get("OPENAI_API_KEY")
    }
    endpoint = 'https://api.openai.com/v1/engines/davinci/completions'
    
  4. chapter08/keywords-classifier.py中添加一个params变量,其中包含以下代码:

    params = {
      "prompt": "Text: When NASA opened for business on October 1, 1958, it accelerated the work already started on human and robotic spaceflight. NASA's first high profile program was Project Mercury, an effort to learn if humans could survive in space. This was followed by Project Gemini, which used spacecraft built for two astronauts to perfect the capabilities needed for the national objective of a human trip to the Moon by the end of the 1960s. Project Apollo achieved that objective in July 1969 with the Apollo 11 mission and expanded on it with five more successful lunar landing missions through 1972\. After the Skylab and Apollo-Soyuz Test Projects of the mid-1970s, NASA's human spaceflight efforts again resumed in 1981, with the Space Shuttle program that continued for 30 years. The Shuttle was not only a breakthrough technology, but was essential to our next major step in space, the construction of the International Space Station.\n\nKeywords:",
      "temperature": 0.3,
      "max_tokens": 60,
      "top_p": 1,
      "frequency_penalty": 0.8,
      "presence_penalty": 0,
      "stop": ["\n"]
    }
    
  5. 添加以下代码以将端点响应记录到控制台:

    result = requests.post(endpoint, headers=headers, data=json.dumps(params))
    print(params["prompt"] + result.json()["choices"][0]["text"])
    
  6. 将您的根文件夹中的.replit文件更改为以下内容:

    run = "python chapter08/keywords-classifier.py"
    
  7. 单击chapter08/keywords-classifier.py文件,您应该看到与以下截图中的控制台输出类似的结果:

图 8.8 - 来自 chapter08/keywords-classifier.py 的示例输出

图 8.8 - 来自 chapter08/keywords-classifier.py 的示例输出

再次注意,返回的一些关键字并不出现在提供的文本中,但它们仍然相关。这是可能的,因为 GPT3 正在使用其语言模型来考虑最合适的关键字,即使它们不包含在文本中。

摘要

在本章中,我们介绍了理解文本分类和分类 API 端点。然后,我们通过实例来实现情感分析,为文本分配 ESRB 等级,语言分类和关键字文本分类。

在下一章中,我们将了解如何使用语义搜索 API 端点。


网站公告

今日签到

点亮在社区的每一天
去签到