# Create a chat completion

Source: https://router.africa/docs/api-reference/create-chat-completion

`POST https://api.router.africa/v1/chat/completions`

OpenAI-compatible chat completions. Set `stream: true` to receive
server-sent events.

Only one choice is returned: `n`, if sent, must be `1`.

An error before the first token is an ordinary HTTP error. An error
after streaming has started cannot change the `200`; it is sent as a
final event, `data: {"error": {...}}` (same envelope as every other
error), and the stream ends.

## Authentication

Send your key as `Authorization: Bearer YOUR_KEY`. Never put a key in the URL or the body: the request is refused with `key_not_in_header`.

## Parameters

- `Authorization` (header, string, required): Bearer YOUR_KEY.
- `Idempotency-Key` (header, string): router.africa extension, not part of OpenAI's API. A client-chosen string (for example a UUID). A repeat of a finished request with the same key and the same API key returns the first result instead of running (and charging) again. A repeat while the first is still running returns `409` `request_in_progress`. Without this header an identical body is treated the same way.

## Request body

- `model` (string, required): A model id from `GET /v1/models`, for example `openai/gpt-4.1-mini`.
- `messages` (ChatMessage[], required): Min items: 1
  - `role` ("system" | "developer" | "user" | "assistant" | "tool", required)
  - `content` (string | any[] | null): Text, or an array of content parts.
- `stream` (boolean): Default: `false`
- `max_tokens` (integer): Output cap. Defaults to the model's default. A value above the model's ceiling is silently lowered to the ceiling; it is not an error. Greater than 0
- `n` (1)
- `temperature` (number)
- `top_p` (number)
- `stop` (string | string[])
- `presence_penalty` (number)
- `frequency_penalty` (number)
- `seed` (integer)
- `response_format` (object)
- `tools` (object[])
- `tool_choice` (string | object)
- `parallel_tool_calls` (boolean)
- `logprobs` (boolean)
- `top_logprobs` (integer)
- `user` (string): Max length: 256

## Example request

**curl**

```bash
curl https://api.router.africa/v1/chat/completions \
  -H "Authorization: Bearer $ROUTER_AFRICA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4.1-mini",
    "messages": [
      {
        "role": "user",
        "content": "Habari! Say hello in Swahili."
      }
    ],
    "max_tokens": 100
  }'
```

**Python**

```python
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.router.africa/v1",
    api_key=os.environ["ROUTER_AFRICA_API_KEY"],
)

completion = client.chat.completions.create(
    model="openai/gpt-4.1-mini",
    messages=[{"role": "user", "content": "Habari! Say hello in Swahili."}],
    max_tokens=100,
)
print(completion.choices[0].message.content)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.router.africa/v1",
  apiKey: process.env.ROUTER_AFRICA_API_KEY,
});

const completion = await client.chat.completions.create({
  model: "openai/gpt-4.1-mini",
  messages: [{ role: "user", content: "Habari! Say hello in Swahili." }],
  max_tokens: 100,
});
console.log(completion.choices[0].message.content);
```

## Response

The completion, or a stream of chunks when `stream` is true.

- `id` (string, required)
- `object` ("chat.completion", required)
- `created` (integer)
- `model` (string, required)
- `choices` (object[], required)
  - `index` (integer, required)
  - `message` (ChatMessage, required)
    - `role` ("system" | "developer" | "user" | "assistant" | "tool", required)
    - `content` (string | any[] | null): Text, or an array of content parts.
  - `finish_reason` (string | null, required)
- `usage` (Usage)
  - `prompt_tokens` (integer, required)
  - `completion_tokens` (integer, required)
  - `total_tokens` (integer, required)

```json
{
  "id": "chatcmpl-0192f0e0",
  "object": "chat.completion",
  "created": 1767225600,
  "model": "openai/gpt-4.1-mini",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Habari!"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 3,
    "total_tokens": 15
  }
}
```

## Streaming

Server-sent events. Each `data:` line is one JSON
`ChatCompletionChunk` (or, last, an error envelope), then
`data: [DONE]`.

Event schema `ChatCompletionChunk`:

- `id` (string, required)
- `object` ("chat.completion.chunk", required)
- `created` (integer)
- `model` (string, required)
- `choices` (object[], required)
  - `index` (integer, required)
  - `delta` (object, required)
  - `finish_reason` (string | null)
- `usage` (Usage | null)
  - `Usage` (Usage)
    - `prompt_tokens` (integer, required)
    - `completion_tokens` (integer, required)
    - `total_tokens` (integer, required)

Event schema `Error`:

- `error` (object, required)
  - `code` (integer, required): The HTTP status, as a number.
  - `message` (string, required): Safe to show to a user.
  - `metadata` (object, required)
    - `error_type` ("invalid_request" | "context_length_exceeded" | "authentication" | "payment_required" | "permission_denied" | "content_policy_violation" | "not_found" | "payload_too_large" | "rate_limit_exceeded" | "timeout" | "server" | "provider_unavailable" | "provider_overloaded", required): The portable category. Branch on this for retry logic.
    - `reason` ("invalid_body" | "key_not_in_header" | "context_length_exceeded" | "missing_api_key" | "invalid_api_key" | "insufficient_credits" | "key_spend_cap_exceeded" | "account_suspended" | "content_policy_violation" | "model_not_found" | "route_not_found" | "upstream_timeout" | "request_in_progress" | "payload_too_large" | "rate_limited" | "concurrency_limited" | "edge_rate_limited" | "internal_error" | "provider_error" | "service_unavailable" | "provider_overloaded", required): The specific cause. Branch on this for user-facing handling.
    - `model` (string): On `model_not_found`, the model id that was sent.

```text
data: {"id":"chatcmpl-0192f0e0","object":"chat.completion.chunk","created":1767225600,"model":"openai/gpt-4.1-mini","choices":[{"index":0,"delta":{"role":"assistant","content":"Habari"},"finish_reason":null}]}

data: {"id":"chatcmpl-0192f0e0","object":"chat.completion.chunk","created":1767225600,"model":"openai/gpt-4.1-mini","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":12,"completion_tokens":3,"total_tokens":15}}

data: [DONE]

```

## Errors

### 400

The request is malformed or fails validation.

400 invalid_body

```json
{
  "error": {
    "code": 400,
    "message": "Request body is invalid: `messages` is required.",
    "metadata": {
      "error_type": "invalid_request",
      "reason": "invalid_body"
    }
  }
}
```

400 key_not_in_header

```json
{
  "error": {
    "code": 400,
    "message": "Send your API key in the Authorization header, not the URL or body.",
    "metadata": {
      "error_type": "invalid_request",
      "reason": "key_not_in_header"
    }
  }
}
```

400 context_length_exceeded

```json
{
  "error": {
    "code": 400,
    "message": "The request is too long for `openai/gpt-4.1-mini`'s context window. Shorten the input and retry.",
    "metadata": {
      "error_type": "context_length_exceeded",
      "reason": "context_length_exceeded"
    }
  }
}
```

### 401

The API key is missing or not valid. One answer for unknown, malformed, revoked, expired and pending keys.

401 missing_api_key

```json
{
  "error": {
    "code": 401,
    "message": "You didn't provide an API key. Send it as `Authorization: Bearer YOUR_KEY`.",
    "metadata": {
      "error_type": "authentication",
      "reason": "missing_api_key"
    }
  }
}
```

401 invalid_api_key

```json
{
  "error": {
    "code": 401,
    "message": "Incorrect API key provided: sk-ra-…abcd. Check your keys at https://app.router.africa.",
    "metadata": {
      "error_type": "authentication",
      "reason": "invalid_api_key"
    }
  }
}
```

### 402

Not enough credits, or the key's spend cap is reached. Do not retry until the cause is fixed.

402 insufficient_credits

```json
{
  "error": {
    "code": 402,
    "message": "This workspace doesn't have enough credits for this request. Add credits at https://app.router.africa.",
    "metadata": {
      "error_type": "payment_required",
      "reason": "insufficient_credits"
    }
  }
}
```

402 key_spend_cap_exceeded

```json
{
  "error": {
    "code": 402,
    "message": "This API key has reached its spend limit. Raise the limit or use another key.",
    "metadata": {
      "error_type": "payment_required",
      "reason": "key_spend_cap_exceeded"
    }
  }
}
```

### 403

The account is suspended, or the provider refused the content.

403 account_suspended

```json
{
  "error": {
    "code": 403,
    "message": "This account is suspended. Contact support.",
    "metadata": {
      "error_type": "permission_denied",
      "reason": "account_suspended"
    }
  }
}
```

403 content_policy_violation

```json
{
  "error": {
    "code": 403,
    "message": "The request was blocked by the model provider's content policy.",
    "metadata": {
      "error_type": "content_policy_violation",
      "reason": "content_policy_violation"
    }
  }
}
```

### 404

The model is unknown, off or not allowed for this key (one answer for all three), or the path does not exist.

404 model_not_found

```json
{
  "error": {
    "code": 404,
    "message": "The model `acme/unknown-model` does not exist or you do not have access to it.",
    "metadata": {
      "error_type": "not_found",
      "reason": "model_not_found",
      "model": "acme/unknown-model"
    }
  }
}
```

404 route_not_found

```json
{
  "error": {
    "code": 404,
    "message": "No such endpoint. Check the URL and method.",
    "metadata": {
      "error_type": "not_found",
      "reason": "route_not_found"
    }
  }
}
```

### 408

The model provider took too long, after retries and fallbacks.

408 upstream_timeout

```json
{
  "error": {
    "code": 408,
    "message": "The model provider took too long to respond.",
    "metadata": {
      "error_type": "timeout",
      "reason": "upstream_timeout"
    }
  }
}
```

### 409

An identical request (same body, or same `Idempotency-Key`) is still running. Wait and retry; the first request's result is returned.

409 request_in_progress

```json
{
  "error": {
    "code": 409,
    "message": "An identical request is already in progress.",
    "metadata": {
      "error_type": "invalid_request",
      "reason": "request_in_progress"
    }
  }
}
```

### 413

The request body is over 16 MiB.

413 payload_too_large

```json
{
  "error": {
    "code": 413,
    "message": "The request body is too large. Send less than 16 MiB.",
    "metadata": {
      "error_type": "payload_too_large",
      "reason": "payload_too_large"
    }
  }
}
```

### 429

Rate limit reached. Back off and honour `Retry-After`. No `x-ratelimit-*` headers are sent.

429 rate_limited

```json
{
  "error": {
    "code": 429,
    "message": "Rate limit reached for this API key. Retry after 20 seconds.",
    "metadata": {
      "error_type": "rate_limit_exceeded",
      "reason": "rate_limited"
    }
  }
}
```

429 concurrency_limited

```json
{
  "error": {
    "code": 429,
    "message": "Too many requests are running at once for this account. Wait for some to finish, then retry.",
    "metadata": {
      "error_type": "rate_limit_exceeded",
      "reason": "concurrency_limited"
    }
  }
}
```

429 edge_rate_limited

```json
{
  "error": {
    "code": 429,
    "message": "Too many requests from this address. Retry after 60 seconds.",
    "metadata": {
      "error_type": "rate_limit_exceeded",
      "reason": "edge_rate_limited"
    }
  }
}
```

### 500

A fault on our side. Retry once, then contact support with the request id.

500 internal_error

```json
{
  "error": {
    "code": 500,
    "message": "Something went wrong on our side. Reference: 0192f0e0-7b1a-7c3e-9d4f-5a6b7c8d9e0f.",
    "metadata": {
      "error_type": "server",
      "reason": "internal_error"
    }
  }
}
```

### 502

The model provider returned an error after fallbacks.

502 provider_error

```json
{
  "error": {
    "code": 502,
    "message": "The model provider returned an error.",
    "metadata": {
      "error_type": "provider_unavailable",
      "reason": "provider_error"
    }
  }
}
```

### 503

Temporarily unavailable; refused before any model was called.

503 service_unavailable

```json
{
  "error": {
    "code": 503,
    "message": "The service is temporarily unavailable.",
    "metadata": {
      "error_type": "server",
      "reason": "service_unavailable"
    }
  }
}
```

### 529

The model provider is overloaded and fallbacks are exhausted.

529 provider_overloaded

```json
{
  "error": {
    "code": 529,
    "message": "The model provider is overloaded. Retry shortly.",
    "metadata": {
      "error_type": "provider_overloaded",
      "reason": "provider_overloaded"
    }
  }
}
```
