Skip to main content

Installation

npm install openai

Basic Chat

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-xxx',
  baseURL: 'https://crazyrouter.com/v1',
});

async function main() {
  const response = await client.chat.completions.create({
    model: 'gpt-4o',
    messages: [
      { role: 'system', content: 'You are a helpful assistant.' },
      { role: 'user', content: 'Explain what Node.js is in one sentence' },
    ],
  });

  console.log(response.choices[0].message.content);
}

main();

Streaming Output

async function streamChat() {
  const stream = await client.chat.completions.create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: 'Write a poem about programming' }],
    stream: true,
  });

  for await (const chunk of stream) {
    const content = chunk.choices[0]?.delta?.content || '';
    process.stdout.write(content);
  }
  console.log();
}

streamChat();

Multi-turn Conversation

const messages = [
  { role: 'system', content: 'You are a JavaScript expert.' },
];

async function chat(userInput) {
  messages.push({ role: 'user', content: userInput });

  const response = await client.chat.completions.create({
    model: 'gpt-4o',
    messages,
  });

  const reply = response.choices[0].message.content;
  messages.push({ role: 'assistant', content: reply });
  return reply;
}

async function main() {
  console.log(await chat('What is a Promise?'));
  console.log(await chat('How is it different from async/await?'));
}

main();

CommonJS Usage

const OpenAI = require('openai');

const client = new OpenAI({
  apiKey: 'sk-xxx',
  baseURL: 'https://crazyrouter.com/v1',
});

client.chat.completions
  .create({
    model: 'gpt-4o',
    messages: [{ role: 'user', content: 'Hello' }],
  })
  .then((res) => console.log(res.choices[0].message.content));
The Node.js openai package requires version 4.x or above. If using an older version, refer to the OpenAI official migration guide to upgrade.