使用OpenAI API调用时遭遇400错误的排查解决求助
问题背景
我正在开发一个基于ChatGPT的Node.js工具,功能包括:
- 爬取博客内容
- 通过Google API翻译内容
- 用GPT生成内容摘要
- 将内容连同原链接发布到Bluesky账号
执行npm i openai安装依赖后,运行时触发400错误:
Error: Request failed with status code 400
at createError (C:\Users\node_modules\openai\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\node_modules\openai\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\node_modules\openai\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
相关核心代码(OpenAI调用部分):
// Summarize the translated text using OpenAI's GPT engine const completions = await openaiApi.createCompletion({ engine: 'text-davinci-003', prompt: `Summarize this text in ${summaryLength} words or fewer: ${translation}`, maxTokens: summaryLength, temperature: 0, topP: 1, frequencyPenalty: 0, });
解决方法
400错误是OpenAI API请求格式或参数不符合要求导致的,针对代码可从以下方向排查修复:
1. 验证API密钥有效性
- 确认
.env文件中的OPENAI_API_KEY无拼写错误、多余空格,且密钥在OpenAI后台处于可用状态 - 检查密钥是否有权限调用
text-davinci-003模型
2. 修正maxTokens参数逻辑
maxTokens指生成内容的最大token数,token数≠单词数(英文单词平均约1.3个token),且需保证prompt+生成内容的总token数不超过模型上限(text-davinci-003为4096):
maxTokens: Math.min(Math.floor(summaryLength * 1.5), 1000), // 按单词数1.5倍估算token,上限1000
3. 截断过长的prompt
若翻译后的博客内容过长,会导致prompt总token数超限,需提前截断:
// 简单按每4个字符≈1token估算,预留足够空间给生成内容 const maxPromptChars = 3500 * 4; const truncatedTranslation = translation.length > maxPromptChars ? translation.slice(0, maxPromptChars) + '...' : translation; const completions = await openaiApi.createCompletion({ engine: 'text-davinci-003', prompt: `Summarize this text in ${summaryLength} words or fewer: ${truncatedTranslation}`, maxTokens: Math.min(Math.floor(summaryLength * 1.5), 1000), temperature: 0, topP: 1, frequencyPenalty: 0, presencePenalty: 0, // 补充可选参数避免默认值冲突 });
4. 捕获详细错误信息
修改catch块打印OpenAI返回的具体错误响应,精准定位问题:
catch (error) { if (error.response) { console.error('OpenAI API 详细错误:', error.response.data); } console.error(error); throw new Error('Failed to fetch and translate the blog'); }
内容的提问来源于stack exchange,提问作者hithatrail

