Openai.beta.threads.messages.create "Missing required parameter: 'role'

Hi, I’m new to node.js and OpenAi API.
I have this code:

router.post('/add-message', protect, async (req, res) => {
  const { threadId, content } = req.body;
  try {
    const message = await openai.beta.threads.messages.create({
      thread_id: threadId,
      role: "user", 
      content
    });
    res.json(message);
  } catch (error) {
    console.error('Error adding message to thread:', error);
    res.status(500).json({ message: 'Error adding message to thread' });
  }
});

But I try to test it with curl

curl -X POST http://localhost:5001/api/openai/add-message \
-H "Content-Type: application/json" \
-H "Authorization: Bearer XXXXXXXX" \
-d '{"threadId": "thread_XXXXXXX", "content": "This is a test prompt."}'

I got this error:

Error adding message to thread: BadRequestError: 400 Missing required parameter:                                            'role'.
[...]

  error: {
    message: "Missing required parameter: 'role'.",
    type: 'invalid_request_error',
    param: 'role',
    code: 'missing_required_parameter'
  },
  code: 'missing_required_parameter',
  param: 'role',
  type: 'invalid_request_error'
}

To create an assistant and thread working without any issues.

Try this update on your code:

const message = await openai.beta.threads.messages.create(
      threadId,
      { role: "user", content }
);

See the API reference page

1 Like

Wow! Your solution works! Thank you very much for such a fast answer!