ChatGPT API 开发人员实施指南

在技​​术以惊人的速度发展的世界中,ChatGPT API 已经成为游戏规则的改变者,为开发人员开辟了无限的可能性。ChatGPT API 使将类人人工智能的强大功能集成到您的应用程序中成为可能。

在本教程中,您将学习如何在应用程序中利用 ChatGPT API 构建内容生成工具,该工具可以获取用户对文章的要求并相应地生成文章。

在您的应用程序中实现 ChatGPT API

设置启动应用程序

为了帮助您快速入门,我们已经构建了内容生成工具的前端。您可以通过在本地计算机上运行以下命令来克隆它:

bash
git clone https://github.com/krharsh17/contentgpt.git

克隆项目后,通过运行以下命令将终端的工作目录更改为项目的根目录:

bash
cd contentgpt

接下来,通过运行以下命令安装项目所需的依赖项:

bash
yarn install

安装依赖项后,您可以使用以下命令运行应用程序:

bash
yarn dev

用户界面如下所示:

 

您将在该文件中找到此 UI 的完整代码pages/index.js。有三个输入字段要求用户输入文章的标题、文章的间距和首选字数。用户输入这些详细信息并单击最后的蓝色按钮后,应用程序就会向其/api/generate端点发送请求。该端点尚未实现,您将在此处集成 ChatGPT API。应用程序期望/api/generate端点使用以下格式的 JSON 对象进行响应:

json
{
  "content": "<article content here>"
}

您现在已准备好将 ChatGPT API 集成到您的应用程序中。

ChatGPT API 集成

GPT-4 API 的访问,而 Completions 端点则不提供。

使用 GPT 等大型语言模型 (LLM) 时,正确表述提示非常重要。出于本文的目的,您将使用以下提示来指导模型:

json
[
  {
    "role": "system",
    "content": "You are a content generation tool. After the user provides you with the topic name, article length, and pitch of the article, you will generate the article and respond with ONLY the article in Markdown format and no other extra text."
  },
  {
    "role": "user",
    "content": "Write an article on the topic <your topic here>. The article should be close to <your word length here> words in length. Here is a pitch describing the contents of the article: <your pitch here>"
  }
]

This provides the model 这为模型提供了两条输入消息作为提示。第一条消息定义了它的功能,即充当内容生成工具,并且仅响应所需的输出,没有其他支持文本,例如“当然!这是您的文章:”或 ChatGPT 经常在其响应中包含的任何类似内容。这是一条系统消息,意味着它是应用程序向模型提供的内部指令。

第二条消息要求模型根据给定的描述撰写文章。这是一条用户消息,意味着这是用户给出的、模型需要采取行动(响应)的消息。您可以在OpenAI 的转换指南中了解有关消息角色的更多信息。

请随意修改提示以生成更具体的响应。您的提示越具体,模型就越有可能以正确的内容做出响应。

在开始编写 API 调用以与 ChatGPT API 交互之前,您需要首先获取 OpenAI API 密钥。

获得 API 密钥后,创建一个.env在项目中调用的新文件,并按以下格式将密钥存储在其中:

bash
OPENAI_API_KEY=<your key here>

您现在可以通过在您的服务器环境中访问此密钥process.env.OPENAI_API_KEY

使用 REST API

您现在可以继续编写在应用程序中使用 ChatGPT API 的逻辑。要了解如何集成聊天端点,您通常必须查阅 ChatGPT API 的 API 参考。然而,为了避免研究该方法的体力劳动,您将让Pieces Copilot开始工作。

如果您还不知道,Pieces是一款开发人员生产力工具,可帮助您组织和丰富代码片段,以便您可以轻松引用并共享它们。为了提高开发人员的工作效率,Pieces 最近推出了他们的 copilot,这是一个聊天机器人,它利用人工智能和通过检索增强生成对工作流程的上下文理解,帮助您在开发应用程序时快速找到解决方案和实施。

要尝试一下,您首先需要设置 Pieces。安装 Pieces 桌面应用程序后,您可以通过单击转到... > Copilot 聊天导航到 Pieces Copilot 部分:

 

您将看到一个聊天屏幕。您现在可以输入以下消息,要求 Pieces Copilot 为您提供在 Next.js 应用程序中集成 ChatGPT API 的过程:

text
How to integrate the ChatGPT REST API in a Next.js app through server functions? Make use of inbuilt packages only and do not install any external dependencies

您会注意到 Pieces Copilot 详细解释了整个过程,并提供了设置客户端和服务器逻辑的说明:

 

您可以通过发送以下文本作为下一条消息来进一步缩短此输出:

text
Provide the server-side code only

您现在会注意到,copilot 为您提供了正确的服务器端代码来帮助您在演示应用程序中设置集成:

 

经过一些修改,最终的代码片段应如下所示:

js
export default function handler(req, res) {
  const {
    title, purpose, length
  } = JSON.parse(req.body)
  
  const baseURL = "https://api.openai.com/v1"

  const endpoint = "/chat/completions"

  const apiKey = process.env.OPENAI_API_KEY

  const requestBody = {
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "system",
        "content": "You are a content generation tool. After the user provides you with the topic name, article length, and pitch of the article, you will generate the article and respond with ONLY the article in Markdown format and no other extra text."
      },
      {
        "role": "user",
        "content": "Write an article on the topic \"" + title + "\". The article should be close to " + length + " words in length. Here is a pitch describing the contents of the article: " + purpose
      }
    ],
    max_tokens: length * 1.5
  }

  fetch(baseURL + endpoint, {
    method: "POST",
    body: JSON.stringify(requestBody),
    headers: {
      "Authorization": "Bearer " + apiKey,
      "Content-Type": 'application/json'
    }
  }).then(r => r.json())
     .then(r => {
        console.log(r)
        res.status(200).json({content: r.choices[0].message.content})
    })
    .catch(e => {
      console.log(e)
      res.status(500).json({content: "The article could not be generated. Error: " + JSON.stringify(e)})
    })

}

您需要将此代码段保存在pages/api/generate.jsNext.js 项目的文件中。您现在可以使用该yarn dev命令运行该应用程序,这就是该工具应如何运行。

Copilot 的功能远不止代码生成。在浏览器中使用它来解释您在线找到的代码片段,或者在 IDE 中使用它来帮助您理解整个存储库。另外,它同时利用云和本地 LLM,因此您可以根据您的安全限制选择使用哪个 LLM 来回答问题和生成代码。对于企业客户,我们还提供将您的自定义 API 密钥输入到 Pieces 中的选项。

使用 Node.js 平台库

正如您在上面的代码片段中看到的,REST API 管理起来非常麻烦,并且在处理实际项目时,您很可能需要在 API 上编写一个包装器,以便您可以在项目中方便地使用它。也就是说,OpenAI 提供了一要安装它,请在项目的根目录中运行以下命令:

bash
yarn add openai

接下来,将文件中的代码替换pages/api/generate.js为以下代码片段:

js
// Import the package
const OpenAI = require("openai")

export default function handler(req, res) {
    const {
        title, purpose, length
    } = JSON.parse(req.body)

    // Initialize the package with the API key
    const openai = new OpenAI({
        apiKey: process.env.OPENAI_API_KEY,
    });

    // The body remains the same as with the REST API
    const requestBody = {
        "model": "gpt-3.5-turbo",
        "messages": [
            {
                "role": "system",
                "content": "You are a content generation tool. After the user provides you with the topic name, article length, and pitch of the article, you will generate the article and respond with ONLY the article in Markdown format and no other extra text."
            },
            {
                "role": "user",
                "content": "Write an article on the topic \"" + title + "\". The article should be close to " + length + " words in length. Here is a pitch describing the contents of the article: " + purpose
            }
        ],
    }

    // Instead of making a fetch call, you use the package's method instead
    openai.chat.completions.create(requestBody)
        .then(completion => {
            console.log(completion)
            res.status(200).json({content: completion.choices[0].message.content})
        })
        .catch(e => {
            console.log(e)
            res.status(500).json({content: "The article could not be generated. Error: " + JSON.stringify(e)})
        })

}

您现在可以重新启动开发服务器并尝试再次运行该应用程序。它应该继续正常运行。这是因为即使您在实现中从 REST API 更改为 Node.js 包,集成逻辑仍然保持不变。在这里查看它的实际效果。

您现在已成功将 ChatGPT API 集成到内容生成应用程序中。请随意使用演示应用程序,尝试不同的 GPT 模型,或为提示添加更多特异性以获得更好的结果。您可以在此 GitHub 存储库的已完成分支上找到该应用程序的完整代码。

结论

本文演示了如何使用 REST API 和 Node.js SDK 在 Next.js 应用程序中使用 ChatGPT API。在此过程中,您还学习了如何使用Pieces Copilot通过快速生成代码来提高工作效率,而不是花时间筛选 ChatGPT API 文档。

开发人员生产力是Pieces提供的所有产品和服务的核心焦点。您还可以尝试Pieces 提供的Microsoft Teams 集成,使您能够提出与代码相关的问题并直接从 Microsoft Teams 工作区生成代码。请务必尝试 Pieces 并将API 参考保存在 Pieces 中以保持井井有条

  • 31
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值