openai-node icon indicating copy to clipboard operation
openai-node copied to clipboard

OpenAI request body validation error response is weird

Open renjithspace opened this issue 1 year ago • 0 comments

Confirm this is a Node library issue and not an underlying OpenAI API issue

  • [X] This is an issue with the Node library

Describe the bug

I've sent a request to Create speech API without passing input parameter like below using the openai Node.js library.

fetch("https://api.openai.com/v1/audio/speech", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "tts-1",
    voice: "alloy"
  })
})
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    console.log('Request successful');
  })
  .catch(error => console.error(error));

The error looks like below:

{
"error": {
  "message": "[{'type': 'string_too_short', 'loc': ('body', 'input'), 'msg': 'String should have at least 1 character', 'input': '', 'ctx': {'min_length': 1}}, {'type': 'enum', 'loc': ('body', 'voice'), 'msg': \"Input should be 'nova', 'shimmer', 'echo', 'onyx', 'fable' or 'alloy'\", 'input': '', 'ctx': {'expected': \"'nova', 'shimmer', 'echo', 'onyx', 'fable' or 'alloy'\"}}]",
  "type": "invalid_request_error",
  "param": null,
  "code": null
}
}
  1. Why the error.message is a string?
  2. Why is it a string of pure JS object and not a string of JSON? I tried to parse it with JSON.parse but as it's not a valid JSON, I failed to do so.
  3. How do I get the error message from this? Do I have to use regex for that?

I think an improvement is needed so the developer can get the error message property.

To Reproduce

  1. Run below request
fetch("https://api.openai.com/v1/audio/speech", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "tts-1",
    voice: "alloy"
  })
})
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    console.log('Request successful');
  })
  .catch(error => console.error(error));
  1. Try to log the error message (the string message from the error message object) to the console

Code snippets

fetch("https://api.openai.com/v1/audio/speech", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.OPENAI_API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    model: "tts-1",
    voice: "alloy"
  })
})
  .then(response => {
    if (!response.ok) {
      throw new Error(response.statusText);
    }
    console.log('Request successful');
  })
  .catch(error => console.error(error));

OS

macOs

Node version

Node v21.7.3

Library version

openai 4.68.1

renjithspace avatar Oct 19 '24 03:10 renjithspace