Core API

Chat Completions

Master the Chat Completions API with messages, system prompts, and parameters.

The Chat Completions API

The Chat Completions endpoint is the primary way to interact with GPT models. It takes a conversation history and returns the next assistant message.

Message Roles

  • system: Instructions for the assistant's behavior
  • user: Messages from the human
  • assistant: Previous assistant responses (for multi-turn conversations)

Key Parameters

  • model: Which model to use (gpt-4o, gpt-4o-mini, etc.)
  • messages: Array of message objects
  • max_tokens: Maximum response length
  • temperature: Randomness (0 = deterministic, 2 = very random)
  • top_p: Nucleus sampling (alternative to temperature)
  • n: Number of completions to generate
  • stream: Stream the response token by token
  • response_format: Force JSON output ({ type: "json_object" })

Example

javascript
import OpenAI from 'openai';

const openai = new OpenAI();

// Multi-turn conversation
async function multiTurnConversation() {
  const messages = [
    { role: "system", content: "You are a concise Python tutor." },
    { role: "user", content: "What is a list comprehension?" },
  ];

  const response1 = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages,
  });

  const reply1 = response1.choices[0].message;
  messages.push(reply1);
  console.log("GPT:", reply1.content);

  // Continue conversation
  messages.push({ role: "user", content: "Can you show me an example?" });
  const response2 = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages,
  });
  console.log("GPT:", response2.choices[0].message.content);
}

// Streaming response
async function streamResponse() {
  const stream = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: "Tell me a short story." }],
    stream: true,
  });

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

// JSON mode - force structured output
async function extractInfo(text) {
  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{
      role: "user",
      content: `Extract name, age, and city from: "${text}". Return JSON.`
    }],
    response_format: { type: "json_object" },
  });
  return JSON.parse(response.choices[0].message.content);
}

const info = await extractInfo("John Smith is 35 years old and lives in Seattle.");
console.log(info); // { name: "John Smith", age: 35, city: "Seattle" }
Try it yourself — JAVASCRIPT