探索 Node.js 中的 ChatGPT API:最详尽和直接的指南

发表时间: 2023-03-06 15:24

const {Configuration, OpenAIApi} = require("openai"); require("dotenv").config(); /** * model: the name of the model you want to use (e.g., gpt-3.5-turbo) * messages: a list of message objects, where each object has at least two fields: * role: the role of the messenger (either system, user, or assistant) * content: the content of the message (e.g., Write me a beautiful poem) */ const run = async () => { const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration); const completion = await openai.createChatCompletion({ model: "gpt-3.5-turbo", messages: [ {role: "system", content: "You are a helpful assistant."}, // #1 Initial Prompt {role: "user", content: "Who won the world series in 2020?"}, // #2 This is an example question { role: "assistant", // #3 thie is an example answer content: "The Los Angeles Dodgers won the World Series in 2020.", }, {role: "user", content: "Where was it played?"}, // #4 This is the actual question ], }); console.log(completion.data.choices[0].message); }; run();

在此 node.js 示例中,我将向您展示如何通过正确构造消息来使用 ChatGPT API,并解释其背后的原因。

进行聊天 API 调用时,您必须提供两个基本输入:

  1. 模型:您要使用的模型的名称(例如,gpt-3.5-turbo)。
  2. 消息:包含至少两个字段的消息对象列表
  • 角色:信使的角色,可以是系统、用户或助理。(我认为没有其他选择)
  • 内容:消息的内容。

要从 ChatGPT 获得所需的输出,您必须执行以下步骤:

  1. 初始提示:虽然是可选的,但此步骤设置了聊天的整体基调。如果需要,您可以跳过它。
  2. 示例问题:建议为 ChatGPT 提供示例交互,以帮助它生成所需的输出。
  3. 示例答案:这是您向 ChatGPT 显示预期输出的地方。如果您在步骤 1 中指定了特定格式(例如 JSON),请在此阶段使用 ChatGPT 进行确认。
  4. 实际问题:这是您输入想要回答的问题的地方。

一直想知道当我不传递任何 id 来识别它时如何保持对话的一致性,但我意识到我的方法是有点不对劲。因为,每个交互都有结构化的提示以获得所需的结果,并且被视为一个单一的任务,我应该更关注的是拥有一个具有一致行为的工程提示列表,并让它们以编程方式与其他人一起工作,而不是将责任传递给聊天GPT。