expl-gpt3-merge-1

58 阅读1小时+

GPT3 探索指南(二)

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

译者:飞龙

协议:CC BY-NC-SA 4.0

第七章:生成和转换文本

虽然我们在前几章中已经看过一些文本生成和转换的例子,但在本章中,我们将看到更多。文本生成和转换有很多可能的用途,包括文章写作,纠正语法,生成列表,将文本从一种语言翻译成另一种语言,提取关键词和总结文本等等。虽然我们甚至不会接近涵盖所有可以使用 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 的示例输出

图 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 – 来自chapter07/childrens-book-generator.py的示例输出

图 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 – 来自chapter07/acronym-translator.js的示例输出

图 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 – 来自chapter07/acronym-translator.py的示例输出

图 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 – 来自 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 - 来自chapter07/fith-grade-summary.py的示例输出

图 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 - 来自chapter07/grammar-correction-converter.js的示例输出

图 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 - 来自chapter07/grammar-correction-converter.py的示例输出

图 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 的示例输出

图 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 的示例输出

图 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 的示例输出]

](github.com/OpenDocCN/f…)

图 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 的示例输出]

](github.com/OpenDocCN/f…)

图 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 端点。

第九章:构建一个由 GPT-3 提供动力的问答 app

到目前为止,我们已经查看了(并编写了)很多代码。但我们实际上还没有创建一个完全可用的 app。那就是我们将要做的事情。在本章中,我们将构建一个简单但功能强大的 Web app,让用户提出问题,由 GPT-3 从我们提供的知识库中回答。该 app 可用于回答任何类型的问题,但我们将用它来回答人们可能对我们有的问题 - 一个 问我任何事 的 app。所以,想象一个招聘专员或潜在雇主可以用来询问你的技能、成就和经验的网站。不想找新工作?没问题。同样,这个 app 可以用于任何类型的问答应用 - 所以可能是一个由 GPT-3 动力驱动的产品 FAQ,或一个由 GPT-3 动力驱动的教学助手 - 这完全取决于你。我们将从 app 将如何工作的快速概述开始,然后逐步介绍构建过程。

我们将涵盖的主题如下:

  • 介绍 GPT Answers

  • 介绍 Answers 端点

  • 设置和测试 Express

  • 为 GPT Answers 创建 API 端点

  • 创建 GPT Answers 用户界面

  • 整合 Answers 端点

  • 生成相关且准确的答案

  • 使用带有 Answers 端点的文件

技术要求

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

介绍 GPT Answers

在本节中,我们将构建一个由 GPT-3 提供动力的 Web app,让用户提出任何问题并从我们提供的数据知识库中获取答案。我们将称该 app 为 GPT Answers。是的,这个名称有点平淡,但我们可以随时使用 GPT-3 来帮助我们思考一个更好的名称。

以下是完成时 app 外观的截图。是的,用户界面可能像名称一样平淡,但其背后的功能一定令人印象深刻!

图 9.1 – GPT Answers 用户界面

图 9.1 – GPT Answers 用户界面

现在让我们深入了解 UI 的后台以及 app 将如何构建。

GPT Answers 技术概述

GPT Answers 将使用 Node.js、JavaScript 和 HTML 构建。我们还将使用一个名为 Express 的 Web 框架来简化开发。

重要提示

该 app 也可以使用 Python 构建,但对于本章,与之前的章节不同,我们只会介绍使用 Node.js/JavaScript 创建 app 的步骤。

问题将通过一个简单的网页表单提交,该表单将使用 JavaScript 向 app 也暴露的 API 端点发送请求。该 app 的 API 主要作为与 OpenAI API 交互的代理,但也将提供异常处理和响应格式化。

托管该 app

到目前为止,我们只使用replit.com来编写和测试代码。但是,replit.com还支持托管应用程序,并且使用起来非常容易。对于 Web 应用程序,您甚至可以使用自己的域名。因此,replit.com将成为我们的托管环境以及开发环境。

重要说明

由 GPT-3 支持的应用程序需要经过 OpenAI 批准才能向公众展示。我们在本章不会详细讨论此事,但我们将在第十章中涵盖应用程序批准流程,与 OpenAI 技术的应用上线

应用程序将使用的主要 OpenAI 端点是答案端点。但是由于我们尚未涵盖答案端点,请在开始编码之前快速介绍一下。

介绍答案端点

OpenAI Answers 端点专为问答任务而设计。它通过启用用于答案的真实来源而比 Completions 端点提供更多控制。对于我们的 GPT Answers 应用程序,这个真实来源将是用于回答问题的知识库。知识库(即文档)可以通过端点请求提供,也可以通过引用包含数据的预先上传的文件来提供。

答案端点的 URL 为 api.openai.com/v1/answers,该端点接受 HTTP POST 请求和一些输入参数。以下是可用输入参数的简要描述,但有关更完整的详细信息,请参阅位于 beta.openai.com/docs/api-reference/answers 的 OpenAI 文档的答案端点。

以下是必填参数:

  • model(必填,字符串) - 将用于完成的模型的 ID。

  • question(必填,字符串) - 要回答的问题。

  • examples(必填,数组) - 问题列表,带有答案,以帮助引导模型朝着答案的语气和格式前进。

  • examples_context(必填,字符串) - 包含用于为您提供的示例生成答案的上下文信息的文本片段。

  • documents(数组) - 应从中提取输入问题的答案的文档列表。如果documents参数是空列表,则将根据问题 - 答案示例来回答问题。另外,仅在不使用file参数时才需要documents参数。

  • file(字符串) - 包含要从中提取答案的文档的上传文件的 ID。如果未使用documents参数,则仅需要file参数。

可选参数如下:

  • search_model(字符串) - 用于搜索的引擎。默认为ada

  • max_rerank(整数)- 要处理的文档的最大数量。较高的值可以提高准确性,但会增加延迟和成本。默认为200

  • temperature(数字)- 默认为0,适用于定义明确答案,但较高的值可用于较不确定的答案。

  • logprobs(整数)- 默认为null。返回的可能标记数量。

  • max_tokens(整数)- 将用于生成答案的最大标记数量。默认为16

  • stop(字符串或数组)- 可选的最多四个模式序列,将导致 API 停止生成完成。默认为null

  • n(整数)- 为每个问题生成的答案数量。默认为1

  • logit_bias(映射)- 可以用于控制指定标记出现在完成中的可能性。

  • return_metadata(布尔值)- 如果使用了file参数并且文件引用包含元数据,则导致响应包含来自文件的元数据。

  • return_prompt(布尔值)- 导致将提示文本与响应一起返回。默认为false

  • expand(数组)- 导致响应包含关于完成或文件的详细信息。expand的值当前可以包括completionfile。默认为一个空数组。

    重要提示

    对于我们的 GPTAMA 应用程序,我们将不会使用所有可用的参数。

现在我们已经对 Answers 端点进行了快速介绍,让我们开始编写我们的 GPTAMA 应用程序!

设置和测试 Express

Express 是用于 Node.js 的轻量级但灵活的 Web 应用程序框架,我们将在应用程序中使用它。通过 Replit.com,它非常容易上手。所以,我们要做的第一件事是在 Replit.com 上设置 Express 并进行测试。我们将从头开始,因此我们将为 GPTAMA 创建一个新的 repl。

要创建一个新的 Node.js REPL 并设置 Express,请完成以下步骤:

  1. replit.com登录。

  2. 创建一个名为gptanswers-node的新 Node.js REPL。

  3. 在输出窗格中,单击Shell选项卡,然后输入此命令:

    npx express-generator --no-view --force .
    
  4. 通过按下Enter键运行上一个命令,您应该会看到一个类似以下截图的结果:图 9.2 - express-generator 的输出

    图 9.2 - express-generator 的输出

    重要提示

    npx命令包含在 NPM 中,NPM 与 Node.js 一起安装。它用于运行express-generator,该生成器将创建一个基本的 Express 应用程序作为起点。命令以句点结尾,以指示express-generator将文件添加到当前目录。--no-view开关告诉生成器我们只是使用纯 HTML 作为我们的 UI,--force开关告诉生成器覆盖当前目录中的任何现有文件。

  5. express-generator完成后,在 shell 中运行以下命令:

    npm update
    
  6. 现在创建一个名为.replit的文件,并将以下Run命令添加到其中:

    Run = "node ./bin/www"
    
  7. 最后,点击Run按钮启动 Express 服务器。如果一切顺利,您应该在 Replit.com 编辑器中看到一个打开的浏览器窗口,其中显示 Express 的欢迎消息。它应如下图所示:

图 9.3 – 在 Replit.com 中运行的 Express 服务器

图 9.3 – 在 Replit.com 中运行的 Express 服务器

需要注意的两件事是浏览器窗格中的 URL 以及Run按钮变成了Stop按钮。这是因为 Express 正在运行一个 HTTP 服务器,该服务器将持续运行,直到停止。因此,在 Express 服务器运行时,应用程序可在网上访问,并通过浏览器窗格中的 URL 访问。此外,当您进行更改时,您需要点击Stop按钮然后点击Run按钮来停止和重新启动 Express。

如果您遇到任何问题,并且看不到 Express 页面,您可以再次按照本节的步骤操作而不会损坏任何内容。当您看到 Express 的欢迎页面时,您就可以继续进行。接下来,我们将为我们的 GPT Answers 应用程序创建 API 端点。

为 GPT Answers 创建 API 端点

当我们的应用程序完成时,我们将拥有一个完全功能的 API 端点,可以返回由 OpenAI API 生成的答案。但现在,我们将只创建一个返回占位符响应的端点。然后,我们将使用 Postman 测试端点,稍后再回来完成编码。

创建 API 端点

要创建 API 端点,请执行以下操作:

  1. 打开由express-generator创建的app.js文件。该文件应如下图所示:图 9.4 – 由 express-generator 创建的默认 app.js 文件

    图 9.4 – 由 express-generator 创建的默认 app.js 文件

  2. 编辑第 7 行,将var usersRouter = require('./routes/users')更改为以下内容:

    var answerRouter = require('./routes/answer');
    
  3. 编辑第 18 行,将app.use('/users', usersRouter);更改为以下内容:

    app.use('/answer', answerRouter);
    

    编辑第 7行和18行后,app.js文件应如下图所示:

    图 9.5 – 编辑后的 app.js 文件

    图 9.5 – 编辑后的 app.js 文件

  4. 删除routes/users.js文件。

  5. 创建一个新文件routes/answer.js

  6. 添加以下代码到answers.js文件中:

    const axios = require('axios');
    const express = require('express');
    const router = express.Router();
    
    router.post('/', (req, res) => {
      res.send({answer:'placeholder for the answer'});
    });
    
    module.exports = router;
    
  7. 点击Stop按钮,然后Start。您应该再次看到Welcome to E****xpress的消息。

我们创建的 API 端点接受 HTTP/answer。但由于它接受 HTTP POST,我们需要通过进行 POST 请求来测试它。为了做到这一点,我们将使用 Postman。

使用 Postman 测试我们的 API

此时,我们应该能够向我们的/answer端点进行 HTTP POST 请求并获得响应。要完成测试,请将从Replit.com浏览器(显示 Express 欢迎消息的浏览器)复制到剪贴板的应用程序 URL:

  1. 打开一个新的浏览器选项卡并登录到postman.com

  2. 创建一个名为gptanswers-node的新集合。

  3. /answer 中创建一个名为 test-answer-api 的新请求。端点 URL 的格式如下,其中{username} 是你的 Replit.com 用户名(假设你将 repl 命名为 gptanswers-node):

    https://gptanswers-node.{username}.repl.co
    
  4. 在端点 URL 输入框下方,选择 Body 选项卡,选择 Raw 单选按钮,并从内容类型下拉列表中选择 JSON

  5. 最后,添加以下 JSON 请求体:

    {
        "question" : "How old are you?"
    }
    

    在设置 Postman 请求后,它应该像以下的屏幕截图:

    图 9.6 – 在 Postman 中测试 GPT-CV 应用程序 API 端点的请求。

    图 9.6 – 在 Postman 中测试 GPT-CV 应用程序 API 端点的请求。

  6. 点击蓝色 Send 按钮提交请求并查看响应,应如下所示:

    {
        "answer""placeholder for the answer"
    }
    

现在,我们已经得到 API 端点的回应,接下来我们将创建一个 Web 表单来调用 API。

创建 GPT Answers 用户界面。

现在,让我们创建一个简单的 Web 表单界面,让用户提交问题以从我们的 API 获取答案。我们将从添加 UIkit 开始 – 这是一个流行的轻量级前端框架,你可以在 getuikit.com/ 了解更多信息。我们还将使用 Axios 使用一些 JavaScript 来对应用程序 API 进行 HTTP 调用。

UIkit 将使我们的应用程序拥有简单但干净和现代的外观。你可以从 getuikit.com 免费下载 UIkit,或者你可以使用一个托管版本,该版本可从 jsdeliver.com 获得,那就是我们将要使用的。

要添加 UIkit,请执行以下操作:

  1. 打开 public/index.html 文件。

  2. cdn.jsdelivr.net/npm/uikit@3.6.22/dist/css/uikit.min.css替换样式表的 URL。

  3. 使用以下代码替换 <body> 标签和 </body> 标签之间的所有内容:

      <div class="uk-section uk-section-large uk-height-viewport">
      <div class="uk-container uk-text-center uk-padding-large">
            <h1 class="uk-heading-medium"><strong>GPT</strong> Answers </h1>
            <p class="uk-text-lead">An Example Knowledge Base App Powered by GPT-3</p>
        </div>
        <div class="uk-container uk-text-center">
            <form class="uk-grid-collapse" uk-grid>
              <div class="uk-width-1-1 ">
                <input id="question" class="uk-input uk-width-1-3" type="text">
                <button type="submit" class="uk-button uk-button-default uk-width-1-5">Get Answer</button>
              </div>
            </form>
        </div>
        <div class="uk-container uk-text-center uk-padding">
          <div class="uk-inline">
            <div id="answer" class="uk-flex uk-flex-center uk-flex-middle uk-padding uk-width-expand"></div>
          </div>
        </div>
      </div>
    
  4. </body>标签上方添加以下代码。这将添加页面使用的 JavaScript 文件的引用。其中三个脚本将来自 CDN,一个 /javascripts/script.js,我们将在下一步中创建它:

    <script src="img/axios.min.js"></script>
    <script src="img/uikit.min.js"></script>
    <script src="img/uikit-icons.min.js"></script>
    <script src="img/script.js"></script>
    

    此时,public/index.html 文件的代码应如图所示:

    图 9.7 – 完成的 index.html 代码

    图 9.7 – 完成的 index.html 代码

    如果你点击 Stop 按钮然后点击 Run 按钮停止并重新启动 Express 服务器,你会看到主屏幕更新为如下屏幕截图的样子:

    图 9.8 – 问题输入表单

    图 9.8 – 问题输入表单

    现在我们需要添加一些 JavaScript 来调用应用程序 API。

  5. 创建 javascripts/script.js 文件并添加以下代码。

  6. 首先,我们将添加两个变量来保存 HTML 表单和答案 div

    const form = document.querySelector('form');
    const answer = document.querySelector('#answer');
    
  7. 接下来,我们将添加当提交表单时触发的代码:

    const formEvent = form.addEventListener('submit', event => {
      event.preventDefault();
      const question = document.querySelector('#question');
      if (question.value) {
        askQuestion(question.value);
      } else {
        answer.innerHTML = "You need to enter a question to get an answer.";
        answer.classList.add("error");
      }
    });
    
  8. 下面的代码将将文本附加到答案div中:

    const appendAnswer = (result) => {
      answer.innerHTML = `<p>${result.answer}</p>`;
    };
    
  9. 最后,我们将添加一个函数,使用 Axios 调用应用程序的 API 端点:

    const askQuestion = (question) => {
      const params = {
        method: 'post',
        url: '/answer',
        headers: {
          'content-type': 'application/json'
        },
        data: { question }
      };
      axios(params)
        .then(response => {
          const answer = response.data;
          appendAnswer(answer);
        })
        .catch(error => console.error(error));
    };
    
  10. 现在我们可以通过点击Stop按钮,然后点击Start按钮来进行测试。然后,在浏览器窗格中,在文本框中输入一个问题,然后点击GET ANSWER按钮。你应该会看到 API 回复的占位符答案,如下图所示:

图 9.9 – 使用占位符 API 代码测试 Web UI

图 9.9 – 使用占位符 API 代码测试 Web UI

在这一点上,我们已经搭建好了应用程序的基本框架。接下来,我们需要做的是写一些代码,将问题传递给 OpenAI API 答案端点。

集成答案端点

现在我们将返回到routes/answer.js文件中添加一些代码,以便调用 OpenAI Answers 端点来回答用户的问题,而不是返回占位符文本:

  1. 打开routes/answer.js文件并执行以下操作。

  2. 删除 第 5 行 之后的所有代码。

  3. 第 5 行 开始,添加以下代码,然后换行:

    const apiKey = process.env.OPENAI_API_KEY;
    const client = axios.create({
      headers: { 'Authorization': 'Bearer ' + apiKey }
    });
    
  4. 接下来,添加以下代码并在其后换行:

    const documents = [
      "I am a day older than I was yesterday.<|endoftext|>",
      "I build applications that use GPT-3.<|endoftext|>",
      "My preferred programming is Python.<|endoftext|>"
    ]
    
  5. 第 16 行 开始添加以下代码,然后换行:

    const endpoint = 'https://api.openai.com/v1/answers';
    
  6. 接下来,从 第 18 行 开始添加以下内容以完成代码:

    router.post('/', (req, res) => {
      // call the OpenAI API
        const data = {
        "documents": documents,
        "question": req.body.question,
        "search_model": "ada",
        "model": "curie",
        "examples_context": "My favorite programming language is Python.",
        "examples": [["How old are you?", "I'm a day older than I was yesterday."], ["What languages do you know?", "I speak English and write code in Python."]],
        "max_tokens": 15,
        "temperature": 0,
        "return_prompt": false,
        "expand": ["completion"],
        "stop": ["\n", "<|endoftext|>"],
      }
      client.post(endpoint, data)
        .then(result => {
          res.send({"answer" : result.data.answers[0]})
        }).catch(result => {
          res.send({"answer" : "Sorry, I don't have an answer."})
        });
    });
    module.exports = router;
    

    当你编辑完routes/answer.js文件后,文件应该像以下屏幕截图所示:

    图 9.10 – 编辑后的 routes/answer.js 文件

    图 9.10 – 编辑后的 routes/answer.js 文件

    我们快要完成了。在测试之前的最后一步是将我们的 OpenAI API 密钥添加为环境变量。

  7. 通过点击挂锁图标并添加一个名为OPENAI_API_KEY的密钥和您的 OpenAI API 密钥的值来将您的 OpenAI API 密钥添加为 REPL 的秘密,就像以下屏幕截图中的示例一样: 图 9.11 – 为 OpenAI API 密钥添加一个秘密

    图 9.11 – 为 OpenAI API 密钥添加一个秘密

  8. 点击Stop按钮,然后点击Run重新启动 Express,然后在问题文本框中输入你最喜欢的食物是什么?,然后点击GET ANSWER按钮。你应该会看到像以下屏幕截图展示的内容——来自 GPT-3 的答案:

图 9.12 – 来自 GPT-3 的答案

图 9.12 – 来自 GPT-3 的答案

现在我们有了一个简单但功能齐全的基于 GPT-3 的问答应用。然而,您可能想知道为什么我们在**你最喜欢的食物是什么?**这个问题上得到了回应(一个答案),当我们还没有给出那个答案。我们将在后面讨论这个问题。

生成相关且真实的答案

GPT-3 是一个语言模型 - 它预测应该跟随提供的提示文本的文本的统计可能性。从某种意义上说,它不是一个知识库,它并不太关心所生成的响应的事实准确性。这并不意味着它不会生成事实性答案;这只是意味着你不能指望所有时间答案都是准确的。但是 Answers 端点可以提供对所生成答案的准确性或相关性的很多控制。

正如我们之前在 介绍 Answers 端点 中讨论的那样,答案将从我们提供的文档中生成。在这一点上,我们是作为端点请求的一部分提供文档的。使用这种方法,如果答案无法从文档中推导出来,由 routes/answer.js 文件定义的引擎 - 我们使用了 Curie 引擎。但是假设我们只希望答案从我们的文档中推导出来,否则我们不希望返回答案。虽然我们无法完全控制这一点,但我们可以使用预先上传的文件使我们接近实现这一点。

当使用 Answers 端点时使用预先上传的文件时,与使用 HTTP 请求提供文档时一样,你不仅仅限于只有 200 个文档。事实上,预先上传的文件可能包含非常多的文档,因为每个组织可以拥有最多 1 GB 的文件空间。因为一个文件可能包含非常多的文档,所以对文件中的文档应用关键字过滤器以缩小可能用于答案的文档范围。从那里开始,文档被排名,然后由模型参数定义的引擎使用以生成答案。当你使用请求参数发送文档时,关键字过滤将被跳过,因为你可以发送的文档数量限制为 200 个。对于我们的 GPT Answers 应用程序,关键字过滤将帮助我们减少回答无关问题的可能性。所以,让我们看一下如何使用 Answers 端点中的文件。

使用 Answers 端点的文件

要使用文件中的文档,我们需要做的第一件事是将文件上传到 OpenAI,以便 Answers 端点可以使用它。该过程涉及创建一个包含我们文档的文件,然后使用 文件端点 将文件上传并获取可在对 Answers 端点发出请求时使用的文件 ID。要创建和上传答案文件,请完成以下步骤:

  1. 创建一个名为 answers.jsonl 的新的jsonl文件,并为文件中的一些答案编写如下格式的答案:

    {"text""I am a day younger than I will be tomorrow"}
    {"text""I like to code in Python."}
    {"text""My favorite food is carrot cake."}
    
  2. 创建另一个名为 files-upload.js 的新文件。

  3. file-upload.js 中添加以下代码:

  4. 需要几个将要使用的模块:

    const fs = require('fs');
    const axios = require('axios');
    const FormData = require('form-data');
    
  5. 接下来,添加以下代码来读取请求的 jsonl 数据:

    const data = new FormData();
    data.append('purpose''answers');
    data.append('file', fs.createReadStream('answers.jsonl'));
    
  6. 添加一个变量用于 HTTP 请求参数:

    const params = {
    method: 'post',
    url: 'https://api.openai.com/v1/files',
    headers: { 
      'Authorization''Bearer ' + process.env.OPENAI_API_KEY, 
      ...data.getHeaders()
    },
    data : data
    }
    
  7. 最后,添加代码以进行 HTTP 请求并记录结果:

    axios(params)
      .then(function(response) {
        console.log(response.data);
      })
      .catch(function(error) {
        console.log(error);
      });
    

    当编辑完 files-upload.js 后,它应该像以下截图中的代码一样:

    图 9.13 – file-upload.js 的完成代码

    图 9.13 – file-upload.js 的完成代码

  8. 在输出窗格中,点击Shell选项卡。

  9. ~/gptanswers-node提示符处,输入以下命令并附上你的 OpenAI API 密钥:

    export OPENAI_API_KEY="your-api-key-goes-here"
    
  10. 接下来,在 shell 中输入以下命令:

    node files-upload.js
    

    运行上述 shell 命令后,你应该会看到类似以下截图的输出结果:

    图 9.14 – files-upload.js 的 Shell 输出

    图 9.14 – files-upload.js 的 Shell 输出

  11. 从 JSON 结果中复制id值(以file-开头的值)到剪贴板。

  12. 点击小锁图标并创建一个名为ANSWERS_FILE的新秘密/环境变量,并将你在上一步中复制的 ID 值粘贴到值输入中,然后点击添加新的秘密按钮。

  13. 打开routes/answer.js并将第 20 行documents参数重命名为file。然后用process.env.ANSWERS_FILE替换documents值。

    上一个更新后,第 20 行应该看起来像以下截图中的第 20 行

    图 9.15 – 使用文件参数的 Answers 端点参数

    图 9.15 – 使用文件参数的 Answers 端点参数

    此时,你已经准备好测试了。

  14. 点击运行按钮,然后在问题输入中输入你最喜欢的食物是什么?,然后点击获取答案按钮。这次你会注意到答案是从我们的答案文件中生成的,就像以下截图所示:

图 9.16 – 从答案文件生成的答案

图 9.16 – 从答案文件生成的答案

但是现在,如果你输入一个与你的文件中的数据完全无关的问题,响应将会是对不起,我没有答案。你可以尝试询问诸如**你们有红色的这个吗?**这样的问题。你应该会看到一个类似以下截图的结果:

图 9.17 – 无法回答的问题

图 9.17 – 无法回答的问题

一个重要的事情要记住的是,答案文件和完成引擎(在我们的案例中是Curie)都用于生成答案。因此,有可能得到一个在你的文件中没有定义的答案。但是,你的答案文件中的数据越多,这种可能性就越小。但是因为我们现在只有三个文档在我们的答案文件中,所以如果你问类似**你最喜欢的度假地点是什么?**这样的问题,你可能会看到一个在你的答案文件中没有定义的答案,就像以下截图所示:

图 9.18 – 不是来自答案文件的答案

图 9.18 – 不是来自答案文件的答案

因此,即使我们在答案文件中提供答案,也不能保证 GPT-3 不会生成不准确的答案。但我们稍后将在本章和第十章使用 OpenAI-Powered 应用程序上线中讨论这一点。

到目前为止,我们有一个完全功能的应用程序。当然,我们可以添加更多功能来完善我们的应用程序,但核心功能已经就位。你需要做的主要事情是向答案文件中添加更多文档。要做到这一点,每次想要添加新数据时,请完成以下步骤:

  1. answers.jsonl 文件添加新文档。

  2. 打开 shell。

  3. 运行以下 shell 命令将你的 API 密钥设置为 shell 可以访问的环境变量:

    export OPENAI_API_KEY="your-api-key-goes-here"
    
  4. 在 shell 中运行以下命令以执行 files-upload.js

    node files-upload.js
    
  5. 通过单击锁图标并替换值为 ANSWERS_FILE 机密,复制文件 ANSWERS_FILE 环境变量。

  6. 单击 停止 按钮,然后单击 运行 按钮重新启动 Express。

再次,你的答案文件中有更多数据将减少出现非事实性答案的机会。但 GPT-3 仍然可能生成明显不是来自你的答案文件的答案。因此,考虑内容过滤仍然很重要,这也是我们将在下一章中更详细介绍的原因。

概要

在本章中,我们介绍了答案端点,并使用 Node.js/JavaScript 构建了一个简单但功能齐全的 Web 应用程序,可以从我们提供的文档中回答问题。对于我们的应用程序,我们创建了一个充当 OpenAI API 代理的 API 和一个提供用户界面的 HTML 页面。

在下一章中,我们将讨论 OpenAI 应用程序审查流程,并根据 OpenAI 的建议实施一些修改。然后,我们将介绍上线所需的步骤!