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

调用OpenAI转录API时持续收到400错误的问题排查

问题分析与修复方案

核心错误点

  • 重复设置Content-Type导致格式冲突
    你手动添加了"Content-Type": "multipart/form-data",但form-data的getHeaders()方法已经会生成包含正确boundary的Content-Type头(比如multipart/form-data; boundary=----WebKitFormBoundaryxxx),手动设置会覆盖或冲突,导致OpenAI无法解析请求体。
  • Buffer转Stream可能存在问题
    直接传递Buffer给form-data的append方法即可,不需要额外转成Stream;如果一定要转Stream,必须确保Stream是可正常读取的。另外,传递Buffer时最好指定文件名和文件类型,帮助API正确识别。
  • Postman生成代码中的冗余Cookie
    Postman生成的代码里带了自身的Cookie,OpenAI API不需要这个,保留会增加不必要的请求头,可能干扰请求。

修正后的代码

方案1:直接使用Buffer上传

const FormData = require('form-data');
const axios = require('axios');

async function transcribeAudio(buffer) {
    const data = new FormData();
    const filename = `${Date.now()}.webm`;

    // 注意:append file时指定filename和contentType
    data.append('model', 'whisper-1');
    data.append('file', buffer, {
        filename: filename,
        contentType: 'audio/webm'
    });

    const config = {
        method: "post",
        maxBodyLength: Infinity,
        url: "https://api.openai.com/v1/audio/transcriptions",
        headers: {
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
            // 只需要扩展form-data的headers,不要手动加Content-Type
            ...data.getHeaders()
        },
        data: data,
    };

    try {
        const response = await axios.request(config);
        console.log(response.data);
        return response.data;
    } catch (error) {
        console.error('请求失败:', error.response?.data || error.message);
    }
}

方案2:如果必须使用Stream(比如大文件)

先确保你的bufferToStream实现正确:

function bufferToStream(buffer) {
    const { Readable } = require('stream');
    const stream = new Readable();
    stream.push(buffer);
    stream.push(null); // 标记流结束
    return stream;
}

然后在append时指定文件名和类型:

data.append('file', bufferToStream(buffer), {
    filename: filename,
    contentType: 'audio/webm'
});

验证步骤

  • 确认process.env.OPENAI_API_KEY已正确加载,且密钥具备调用Whisper API的权限。
  • 检查Buffer完整性:将Buffer写入本地文件,确认能正常播放,排除音频文件损坏的问题。
  • 移除所有不必要的请求头(比如Postman生成的Cookie),只保留Authorization和form-data生成的头。

内容的提问来源于stack exchange,提问作者Terry Windwalker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 23:43:33