使用whisper.js调用OpenAI API遇ERR_FR_MAX_BODY_LENGTH_EXCEEDED错误求助
解决Whisper API转写大音频时的maxBodyLength超限错误
使用whisper.js转写WAV文件时,出现错误:Error [ERR_FR_MAX_BODY_LENGTH_EXCEEDED]: Request body larger than maxBodyLength limit。按提示在Configuration中添加maxBodyLength: Infinity后问题仍未解决,求可行解决方法。
原代码如下:
require('dotenv').config(); const { Configuration, OpenAIApi } = require("openai"); const fs = require("fs"); const configuration = new Configuration({ apiKey: "YOUR_API_KEY", maxBodyLength: Infinity, }); const openai = new OpenAIApi(configuration); async function createTranscription(audioFileName) { const resp = await openai.createTranscription( fs.createReadStream(audioFileName), "whisper-1" ); return resp.data.text; } async function main() { try { const audioFileName = '/Users/rahulsharma/Desktop/whisper/output_dir/stream.wav'; const transcription = await createTranscription(audioFileName); console.log(transcription); } catch (e) { console.error(e); } } main();
解决步骤
1. 确认并遵守OpenAI API的文件大小限制
Whisper API本身限制单文件最大为25MB,这是API层面的硬限制,和请求体配置无关。如果你的音频文件超过25MB,必须先处理文件:
- 压缩音频:将WAV转成MP3、OGG等压缩格式,或降低采样率(如从48kHz降到16kHz)、比特率,大幅减小文件体积
- 分割音频:用工具(如ffmpeg)把大音频切成多个小于25MB的片段,分别转写后拼接结果
2. 正确配置Axios请求体限制
OpenAI Node.js SDK基于Axios实现请求,直接在Configuration中设置maxBodyLength可能不生效,需手动创建Axios实例并配置后传入SDK:
修改后的代码示例:
require('dotenv').config(); const { Configuration, OpenAIApi } = require("openai"); const fs = require("fs"); const axios = require("axios"); // 创建自定义Axios实例,解除请求体和内容长度限制 const customAxios = axios.create({ maxBodyLength: Infinity, maxContentLength: Infinity }); const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, // 建议改用环境变量存储密钥,避免硬编码风险 }); // 将自定义Axios实例传入OpenAIApi const openai = new OpenAIApi(configuration, undefined, customAxios); async function createTranscription(audioFileName) { const resp = await openai.createTranscription( fs.createReadStream(audioFileName), "whisper-1" ); return resp.data.text; } async function main() { try { const audioFileName = '/Users/rahulsharma/Desktop/whisper/output_dir/stream.wav'; const transcription = await createTranscription(audioFileName); console.log(transcription); } catch (e) { console.error(e); } } main();
注意事项
- 即使配置了Axios的长度限制,仍需确保文件大小不超过Whisper API的25MB上限,否则会触发API层面的错误
- 硬编码API密钥存在安全风险,建议改用
.env文件通过process.env.OPENAI_API_KEY读取
内容的提问来源于stack exchange,提问作者Dismay
相关产品推荐
相关产品推荐

