## Create Chat Completion

Generate a response from an AI model given a conversation history.

### Request

```
POST https://api.modelstack.cc/v1/chat/completions
```

### Headers

| Header          | Required | Description           |
| --------------- | -------- | --------------------- |
| `Authorization` | Yes      | `Bearer your_api_key` |
| `Content-Type`  | Yes      | `application/json`    |

### Body Parameters

<ParamField body="model" type="string" required>
  The model ID to use (e.g., `claude-sonnet-4-6`, `gpt-5.4`, `gemini-3.1-pro`).
  See [Supported Models](/docs/models/supported-models) for the full list.
</ParamField>

<ParamField body="messages" type="array" required>
  An array of message objects representing the conversation history.

  Each message object has:

  - `role` (string): One of `system`, `user`, or `assistant`
  - `content` (string): The message content
</ParamField>

<ParamField body="stream" type="boolean" default="false">
  If `true`, responses are streamed back as Server-Sent Events (SSE).
</ParamField>

<ParamField body="temperature" type="number" default="1.0">
  Sampling temperature between 0 and 2. Lower values make output more focused
  and deterministic.
</ParamField>

<ParamField body="max_tokens" type="integer">
  Maximum number of tokens to generate in the response.
</ParamField>

<ParamField body="top_p" type="number" default="1.0">
  Nucleus sampling parameter. An alternative to temperature.
</ParamField>

<ParamField body="stop" type="string | array">
  Up to 4 sequences where the API will stop generating further tokens.
</ParamField>

### Example Request

<CodeGroup>

```bash cURL
curl https://api.modelstack.cc/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    "temperature": 0.7,
    "max_tokens": 500
  }'
```

```python Python
from openai import OpenAI

client = OpenAI(
    api_key="your_api_key",
    base_url="https://api.modelstack.cc/v1"
)

response = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    temperature=0.7,
    max_tokens=500
)

print(response.choices[0].message.content)
```

```javascript Node.js
import OpenAI from 'openai'

const client = new OpenAI({
  apiKey: 'your_api_key',
  baseURL: 'https://api.modelstack.cc/v1',
})

const response = await client.chat.completions.create({
  model: 'claude-sonnet-4-6',
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Explain quantum computing in simple terms.' },
  ],
  temperature: 0.7,
  max_tokens: 500,
})

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

</CodeGroup>

### Response

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1699000000,
  "model": "claude-sonnet-4-6",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Quantum computing uses quantum bits (qubits) instead of classical bits..."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 25,
    "completion_tokens": 150,
    "total_tokens": 175
  }
}
```

### Response Fields

| Field                     | Type    | Description                           |
| ------------------------- | ------- | ------------------------------------- |
| `id`                      | string  | Unique identifier for the completion  |
| `object`                  | string  | Always `chat.completion`              |
| `created`                 | integer | Unix timestamp of creation            |
| `model`                   | string  | The model used                        |
| `choices`                 | array   | Array of completion choices           |
| `choices[].message`       | object  | The generated message                 |
| `choices[].finish_reason` | string  | `stop`, `length`, or `content_filter` |
| `usage`                   | object  | Token usage statistics                |

## Streaming

Set `"stream": true` to receive Server-Sent Events (SSE) as the model generates tokens.

### Streaming Request

```bash
curl https://api.modelstack.cc/v1/chat/completions \
  -H "Authorization: Bearer your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "messages": [{"role": "user", "content": "Write a haiku about coding."}],
    "stream": true
  }'
```

### Streaming Response

Each event is a JSON object prefixed with `data: `:

```
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Lines"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```

### Streaming with Python

```python
stream = client.chat.completions.create(
    model="claude-sonnet-4-6",
    messages=[{"role": "user", "content": "Write a haiku about coding."}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")
```

### Streaming with Node.js

```javascript
const stream = await client.chat.completions.create({
  model: 'claude-sonnet-4-6',
  messages: [{ role: 'user', content: 'Write a haiku about coding.' }],
  stream: true,
})

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