OpenAI API key not working in my React App

题意:OpenAI API 密钥在我的 React 应用中不起作用

问题背景:

I am trying to create a chatbot in my react app, and I'm not able to generate an LLM powered response. I've been studying documentation and checking out tutorials but am unable to fix.

我正在尝试在我的 React 应用中创建一个聊天机器人,但无法生成由 LLM 驱动的响应。我一直在研究文档并查看教程,但无法解决问题。

I tried setting up a function for my chatbot, calling the api key, importing openai, setting up the parameters for the gpt-3.5-turbo model including temperature. The catch (error) section has a setResponse of 'Error generating response' and that's all I get after user inputs a question.

我尝试为我的聊天机器人设置一个函数,调用 API 密钥,导入 OpenAI,设置 gpt-3.5-turbo 模型的参数,包括温度。catch(错误)部分设置了 'Error generating response' 作为响应,用户输入问题后,我得到的只有这一条错误信息。

javascript 复制代码
try {
    const response = await openai.createCompletion({
        model: 'gpt-3.5-turbo',
        prompt: question,
        max_tokens: 100,
        n: 1,
        stop: '\n',
        temperature: 1.17,
        headers: {
            Authorization: `Bearer ${API_KEY}`,
        }
});

问题解决:

First of all, as @KenWhite suggested, fix the fundamentals. Use the try...catch statement properly as follows:

首先,正如 @KenWhite 建议的那样,先修正基本问题。正确使用 try...catch 语句,如下所示:

javascript 复制代码
try {
  // Your code here
} catch (error) {
  console.error(error);
}

Problem

Note: OpenAI NodeJS SDK v4 was released on August 16, 2023, and is a complete rewrite of the SDK. See the v3 to v4 migration guide.

注意:OpenAI NodeJS SDK v4 于 2023 年 8 月 16 日发布,并且是 SDK 的一次完全重写。请参阅 v3 到 v4 的迁移指南。

There are a few problems with the code you posted in your question. The solutions to these problems I provide below differ depending on whether you use OpenAI NodeJS SDK v3 or v4.

你问题中发布的代码有一些问题。我提供的解决方案根据你使用的是 OpenAI NodeJS SDK v3 还是 v4 而有所不同。

To check your OpenAI NodeJS SDK version, run the following command:

要检查你的 OpenAI NodeJS SDK 版本,请运行以下命令:

复制代码
npm info openai version

Problem 1: Passing an invalid parameter to the API endpoint

问题 1:向 API 端点传递了无效的参数

You're trying to pass headers as a parameter to the API endpoint, which is not a valid parameter. Remove it.

你正试图将 headers 作为参数传递给 API 端点,但这不是一个有效的参数。请将其删除。

Solution

You need to set the Bearer token as follows... 你需要按照以下方式设置 Bearer 令牌..

• If you have the OpenAI NodeJS SDK v3: 如果你使用的是 OpenAI NodeJS SDK v3

复制代码
import { Configuration, OpenAIApi } from 'openai';

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

• If you have the OpenAI NodeJS SDK v4: 如果你使用的是 OpenAI NodeJS SDK v4

复制代码
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

Problem 2: Using the wrong method name 问题 2:使用了错误的方法名称

You want to use the gpt-3.5-turbo model (i.e., Chat Completions API). Use the proper method name.

你想使用 gpt-3.5-turbo 模型(即 Chat Completions API)。请使用正确的方法名称。

Solution 解决方案

• If you have the OpenAI NodeJS SDK v3:

  • openai.createCompletion <-- Wrong ✘
  • openai.createChatCompletion <-- Correct (works with the Chat Completions API) ✔

• If you have the OpenAI NodeJS SDK v4:

  • openai.completions.create <-- Wrong ✘
  • openai.chat.completions.create <-- Correct (works with the Chat Completions API) ✔

Problem 3: Using the prompt parameter 问题 3:使用了 prompt 参数

You want to use the gpt-3.5-turbo model (i.e., Chat Completions API).

你想使用 gpt-3.5-turbo 模型(即 Chat Completions API)。

The Chat Completions API uses the messages parameter, while the Completions API uses the prompt parameter.

Chat Completions API 使用 messages 参数,而 Completions API 使用 prompt 参数。

Solution

Use the messages parameter instead of the prompt parameter.

使用 messages 参数而不是 prompt 参数。

Final solution

• If you have the OpenAI NodeJS SDK v3, try this:

如果你使用的是 OpenAI NodeJS SDK v3,请尝试以下方法:

javascript 复制代码
import { Configuration, OpenAIApi } from 'openai';

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

try {
  const chatCompletion = await openai.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: 'Hello world' }],
    max_tokens: 100,
    n: 1,
    stop: '\n',
    temperature: 1.17,
  });

  console.log(chatCompletion.data.choices[0].message);
} catch (error) {
  console.error(error);
}

• If you have the OpenAI NodeJS SDK v4, try this:

如果你使用的是 OpenAI NodeJS SDK v4,请尝试以下方法:

javascript 复制代码
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

try {
  const chatCompletion = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: 'Hello world' }],
    max_tokens: 100,
    n: 1,
    stop: '\n',
    temperature: 1.17,
  });

  console.log(chatCompletion.choices[0].message);
} catch (error) {
  console.error(error);
}
相关推荐
ddxu几秒前
AI学习笔记
笔记·学习·ai
plmm烟酒僧3 分钟前
《微信小程序demo开发》第一部分-编写页面逻辑
javascript·微信小程序·小程序·html·微信开发者工具·小程序开发
2601_949720269 分钟前
flutter_for_openharmony手语学习app实战+学习进度实现
javascript·学习·flutter
吉吉安17 分钟前
双层文字扫光效果
前端·javascript·css
小马_xiaoen21 分钟前
WebSocket与SSE深度对比与实战 Demo
前端·javascript·网络·websocket·网络协议
EndingCoder31 分钟前
高级项目:构建一个 CLI 工具
大数据·开发语言·前端·javascript·elasticsearch·搜索引擎·typescript
weixin_4166600733 分钟前
AI 生成复杂公式在 Word 中乱码的原因与解决方案
ai·word·数学公式
摘星编程37 分钟前
OpenHarmony环境下React Native:useDebugValue自定义Hook调试
javascript·react native·react.js
沙丁鱼意大利面37 分钟前
五子棋(javascript)
javascript·css·css3
2601_949847751 小时前
Flutter for OpenHarmony 剧本杀组队App实战:关于我们页面实现
开发语言·javascript·flutter