javascriptnode.jsaxiosopenai-apiopenai-whisper

OpenAI transcription API bad request


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

    const data = new FormData();

    console.log('buffer: ', buffer);
    console.log('typeof buffer: ', typeof buffer);

    const filename = new Date().getTime().toString() + '.webm';
    data.append('model', 'whisper-1');
    data.append('file', bufferToStream(buffer));
    
    console.log('data: ', data);

    let config = {
        method: "post",
        maxBodyLength: Infinity,
        url: "https://api.openai.com/v1/audio/transcriptions",
        headers: {
        Authorization:
            `Bearer ${process.env.OPENAI_API_KEY}`,
            "Content-Type": "multipart/form-data",
            ...data.getHeaders(),
        },
        data: data,
    };

    await axios.request(config)

I am trying to post a file to openAI to get transcription. But I constantly get 400 bad request error.

I am using JavaScript (not TypeScript) so I can't use the FormData package, at least I have tried it and it didn't help me.

Error: Data after transformation must be a string, an Array Buffer, a Buffer, or a Stream

I tried Postman and it works, which provides me with the following code snippet:

const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
let data = new FormData();
data.append('model', 'whisper-1');
data.append('file', fs.createReadStream('/Users/UserName/Downloads/session-1708252969167.webm'));

let config = {
  method: 'post',
  maxBodyLength: Infinity,
  url: 'https://api.openai.com/v1/audio/transcriptions',
  headers: { 
    'Authorization': {{OPENAI_API_KEY}}, 
    'Cookie': '__cf_bm=5L5OJyh1Yd28yUT9Uv0TT9F5POhL1fzeraSZF1C.9OA-1708337727-1.0-AV+XT0hftIn7mtJxICJduMQBpFcB9UQvbil6GmgI2BX7rw0BZRvuseeN0QgeuIt7KyNTxGJs/xcWIKMpkQdvzC4=; _cfuvid=3uLOzYX3DlLxSjGMLDqD0qcGIj.4zkEXt2czm9OiEfU-1708251423683-0.0-604800000', 
    ...data.getHeaders()
  },
  data : data
};

axios.request(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

I tried this code snippet as well, but it throw me a 400 error.

What did I do wrong?


Solution

  • This code will work

    Save as trans.js

    const axios = require('axios');
    const fs = require('fs');
    const FormData = require('form-data');
    
    // Function to make the API call
    async function callOpenAI() {
      try {
        const fileStream = fs.createReadStream('audio.webm');
    
        const formData = new FormData();
        formData.append('file', fileStream);
        formData.append('model', 'whisper-1');
    
        const response = await axios.post('https://api.openai.com/v1/audio/transcriptions', formData, {
          headers: {
            'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
            ...formData.getHeaders() // Get headers manually
          }
        });
    
        console.log(response.data);
      } catch (error) {
        console.error('Error:', error.response.data);
      }
    }
    
    // Call the function
    callOpenAI();
    

    Check API by Postman

    enter image description here

    enter image description here

    Set environment variable for API KEY

    On Git Bash

    OPENAI_API_KEY=[your API KEY]
    

    enter image description here

    Install dependencies

    npm install axios fs form-data
    

    Run it

    node trans.js
    

    Result

    enter image description here