← Back to API List

Create Chat Completion with GPT-4o

POST/v1/chat/completionsOpenAI

Creates a model response for the given chat conversation using GPT-4o, OpenAI's most advanced multimodal model.

text generationchatgpt-4multimodaladvanced
Official Documentation

Headers

Content-TypestringRequired

Set to `application/json`.

AuthorizationstringRequired

Bearer token authentication with your OpenAI API key.

Request Body

modelstringRequired

ID of the model to use.

Example: gpt-4o

top_pnumber

Nucleus sampling parameter.

Defaults to: 1

Example: 0.9

messagesarray of objectRequired

A list of messages comprising the conversation so far.

max_tokensinteger

The maximum number of tokens to generate.

Example: 150

temperaturenumber

Controls randomness. 0 is deterministic, 1 is creative.

Defaults to: 1

Example: 0.7

Response Body

idstring

Unique identifier for the chat completion.

modelstring

The model used for completion.

usageobject

Usage statistics for the completion request.

objectstring

Object type, always "chat.completion".

choicesarray of object

List of completion choices returned by the model.

createdinteger

Unix timestamp of creation time.

Code Examples

cURL

cURL
curl https://api.openai.com/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_OPENAI_API_KEY" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is quantum computing?"}
    ],
    "max_tokens": 150,
    "temperature": 0.7
  }'

Node.js

JavaScript
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "What is quantum computing?"}
    ],
    model: "gpt-4o",
    max_tokens: 150,
    temperature: 0.7,
  });

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

main();

Example Response

JSON

JSON
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1677652288,
  "model": "gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Quantum computing is a revolutionary technology that uses quantum mechanics principles to process information. Unlike classical computers that use bits (0 or 1), quantum computers use quantum bits or 'qubits' that can exist in multiple states simultaneously through superposition."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 20,
    "completion_tokens": 45,
    "total_tokens": 65
  }
}