#Using GPT's API with Javascript?

3 messages · Page 1 of 1 (latest)

neon canyon
#

Hello, is it possible to code a script that uses OpenAI's GPT API using Javascript? I just need the simplest of scripts to test out if it works, but I keep facing issues running it.

last condor
hot glacier
#

Example From my app.js

async function openAIChat(messages, memory = []) {
  const url = 'https://api.openai.com/v1/chat/completions';
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${OPENAI_API_KEY}`
  };

  try {
    const data = {
      //stream: true,
      messages: [
        { role: 'system', content: personality },
        ...memory,
        ...messages.map(({ role, content }) => ({ role, content }))
      ],
      model: 'gpt-3.5-turbo'
    };

    if (debugging) {
      const logData = { ...data };
      console.log('Sending request to OpenAI API:', logData);
    }

    const response = await axios.post(url, data, { headers });

    if (debugging) {
      console.log('Received response from OpenAI API:', response.data);
    }

    return response.data;
  } catch (error) {
    console.error('OpenAI API Error:', error.message);
    throw new Error('Failed to communicate with the OpenAI API');
  }
}```