You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用中OpenAI API Key失效,无法生成LLM响应求助

React聊天机器人调用GPT-3.5-Turbo报错的解决方案

核心问题分析

你的代码存在几个关键错误,导致调用LLM接口失败:

  • API方法误用:gpt-3.5-turbo是聊天模型,必须使用openai.createChatCompletion方法,而非openai.createCompletion(后者仅适用于text-davinci-003等文本补全模型)。
  • 参数不匹配:聊天模型需要messages参数替代prompt,格式为包含角色标识的数组。
  • 无效的stop参数:代码中stop设置为空换行,属于非法配置,会触发请求解析错误。
  • 冗余headers配置:openai库会自动处理API Key的鉴权,无需手动添加Authorization请求头。

修正后的代码示例

try {
  // 先确保openai实例已正确初始化
  // const openai = new OpenAI({ apiKey: API_KEY });
  const response = await openai.createChatCompletion({
    model: 'gpt-3.5-turbo',
    messages: [
      { role: 'user', content: question }
    ],
    max_tokens: 100,
    n: 1,
    temperature: 1.17,
    // 如需设置停止序列,使用合法值,比如:stop: ['\n']
  });
  // 正确提取机器人响应内容
  const botReply = response.data.choices[0].message.content.trim();
  setResponse(botReply);
} catch (error) {
  // 打印具体错误信息,方便定位问题
  console.error('接口错误详情:', error.response?.data || error.message);
  setResponse('Error generating response');
}

额外注意事项

  1. 初始化openai实例时,建议直接传入API Key:const openai = new OpenAI({ apiKey: process.env.REACT_APP_OPENAI_API_KEY });(React环境变量需以REACT_APP_为前缀)。
  2. catch块中打印error.response?.data,能获取OpenAI返回的具体错误原因(比如API Key无效、额度不足、参数格式错误等),便于快速排查问题。

内容的提问来源于stack exchange,提问作者Andrew Escudero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:13:17