# Chat completion

The basic call: send a model name and a list of messages, get back the model's reply in choices[0].message.

AI developers · Part 02: OpenAI API · Card 2 of 9 · Last updated 2026-10-13

## Analogy

A POST endpoint that takes the whole chat log as the body and returns the next message. Stateless, like every good REST endpoint.

## Code example

`chat.ts`

```typescript
const res = await client.chat.completions.create({
  model: "gpt-4o-mini",
  temperature: 0.2,
  messages: [
    { role: "system", content: "You are a senior code reviewer. Be brief." },
    { role: "user", content: "Review: const x = arr.map(a => { a * 2 })" },
  ],
});

console.log(res.choices[0].message.content);
```

## In an agent

An agent is this exact call, made over and over inside a loop.

## Questions people ask

### What does a chat completion request send and return?

You send a model name and an ordered list of messages, plus optional settings like temperature or tools. You get back a response whose choices[0].message holds the model's reply, and a usage object with token counts. The endpoint is stateless, so every request must carry the whole conversation.

### How is an agent related to a chat completion?

An agent is the same chat completion call, made again and again inside a loop. Each round, your code adds the model's tool requests and the tool results to the messages, then calls the model again. When the model answers in plain text instead of asking for a tool, the loop stops.

## Related concepts

- [The OpenAI SDK](https://studyvisually.com/learn/tech/ai-developers/openai-api/openai-client)
- [Messages array](https://studyvisually.com/learn/tech/ai-developers/openai-api/messages-array)
- [Usage and cost](https://studyvisually.com/learn/tech/ai-developers/openai-api/usage-and-cost)
- [Structured output](https://studyvisually.com/learn/tech/ai-developers/openai-api/structured-output)

Web page: https://studyvisually.com/learn/tech/ai-developers/openai-api/chat-completion
Study this card in the app: https://studyvisually.com/app/learn?category=ai-developers&card=chat-completion
