> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.kontinent.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.kontinent.ai/_mcp/server.

# Create a chat completion

POST https://api.kontinent.ai/v1/chat/completions
Content-Type: application/json

OpenAI chat-completions schema, passed through to the upstream provider.

- Request body limit is **2 MiB** (oversized bodies return `400 invalid_request`).
- `stream: true` returns Server-Sent Events (`text/event-stream`):
  `data: {chunk}\n\n` events terminated by `data: [DONE]`. The gateway
  injects `stream_options: {"include_usage": true}` upstream, so the
  final chunk before `[DONE]` carries `usage`.
- Streams have no overall deadline; an idle upstream is cut after 90 s
  of silence.
- If the model defines fallback models, upstream 429/5xx/connect errors
  are retried on the next provider **only before the first byte** is
  streamed. After the first byte, errors surface as a dropped connection.
- Disconnecting mid-stream still bills for tokens generated so far.
- Parameters unsupported by a given provider are stripped, not rejected.


Reference: https://docs.kontinent.ai/api-reference/endpoints/chat/create-chat-completion

## OpenAPI Specification

```yaml
openapi: 3.1.0
info:
  title: Kontinent API
  version: 1.0.0
paths:
  /v1/chat/completions:
    post:
      operationId: createChatCompletion
      summary: Create a chat completion
      description: >
        OpenAI chat-completions schema, passed through to the upstream provider.


        - Request body limit is **2 MiB** (oversized bodies return `400
        invalid_request`).

        - `stream: true` returns Server-Sent Events (`text/event-stream`):
          `data: {chunk}\n\n` events terminated by `data: [DONE]`. The gateway
          injects `stream_options: {"include_usage": true}` upstream, so the
          final chunk before `[DONE]` carries `usage`.
        - Streams have no overall deadline; an idle upstream is cut after 90 s
          of silence.
        - If the model defines fallback models, upstream 429/5xx/connect errors
          are retried on the next provider **only before the first byte** is
          streamed. After the first byte, errors surface as a dropped connection.
        - Disconnecting mid-stream still bills for tokens generated so far.

        - Parameters unsupported by a given provider are stripped, not rejected.
      tags:
        - chat
      parameters:
        - name: Authorization
          in: header
          description: |
            A Kontinent API key: `Authorization: Bearer sk-kt-<43 base62 chars>`
            (49 chars total). Shown once at creation; only a SHA-256 hash is
            stored. No expiry; revocation takes effect within ~30 s.
          required: true
          schema:
            type: string
      responses:
        '200':
          description: >-
            A chat completion. When `stream` is `true`, the response is an SSE
            stream instead.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ChatCompletion'
        '400':
          description: Malformed body, body over 2 MiB, or missing `model`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: Bad or revoked API key. Do not retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '402':
          description: Organization balance is at or below zero. Top up, then retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: Unknown or disabled model id.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: >
            Rate limited. `rate_limit_exceeded` is the per-key RPM limit
            (sliding

            60 s window); `upstream_rate_limited` means the provider throttled
            us.

            Back off and retry.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '500':
          description: Gateway error. Retriable.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '502':
          description: >
            Upstream provider failure. `upstream_error` is a provider
            5xx/connect

            failure (retriable); `upstream_auth_error` means the provider
            rejected

            our credentials (our problem, not yours).
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ChatCompletionRequest'
servers:
  - url: https://api.kontinent.ai
    description: Production
  - url: http://localhost:4000
    description: Local development
components:
  schemas:
    MessageRole:
      type: string
      enum:
        - system
        - user
        - assistant
        - tool
      title: MessageRole
    Message:
      type: object
      properties:
        role:
          $ref: '#/components/schemas/MessageRole'
        content:
          type: string
        name:
          type: string
      required:
        - role
        - content
      title: Message
    ChatCompletionRequestStop:
      oneOf:
        - type: string
        - type: array
          items:
            type: string
      title: ChatCompletionRequestStop
    ChatCompletionRequest:
      type: object
      properties:
        model:
          type: string
          description: >-
            Kontinent model id in `provider/model` form. Discover via `GET
            /v1/models`.
        messages:
          type: array
          items:
            $ref: '#/components/schemas/Message'
        stream:
          type: boolean
          default: false
          description: If true, partial deltas are sent as Server-Sent Events.
        temperature:
          type: number
          format: double
        top_p:
          type: number
          format: double
        max_tokens:
          type: integer
          description: Maximum number of tokens to generate in the completion.
        stop:
          $ref: '#/components/schemas/ChatCompletionRequestStop'
        'n':
          type: integer
          default: 1
      required:
        - model
        - messages
      title: ChatCompletionRequest
    ChatCompletionChoicesItems:
      type: object
      properties:
        index:
          type: integer
        message:
          $ref: '#/components/schemas/Message'
        finish_reason:
          type: string
      title: ChatCompletionChoicesItems
    Usage:
      type: object
      properties:
        prompt_tokens:
          type: integer
        completion_tokens:
          type: integer
        total_tokens:
          type: integer
      title: Usage
    ChatCompletion:
      type: object
      properties:
        id:
          type: string
        object:
          type: string
        created:
          type: integer
        model:
          type: string
        choices:
          type: array
          items:
            $ref: '#/components/schemas/ChatCompletionChoicesItems'
        usage:
          $ref: '#/components/schemas/Usage'
      title: ChatCompletion
    ErrorError:
      type: object
      properties:
        message:
          type: string
        type:
          type: string
        code:
          type: string
      title: ErrorError
    Error:
      type: object
      properties:
        error:
          $ref: '#/components/schemas/ErrorError'
      title: Error
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: |
        A Kontinent API key: `Authorization: Bearer sk-kt-<43 base62 chars>`
        (49 chars total). Shown once at creation; only a SHA-256 hash is
        stored. No expiry; revocation takes effect within ~30 s.

```

## Examples

### Simple completion



**Request**

```json
{
  "model": "mistral/mistral-large-latest",
  "messages": [
    {
      "role": "user",
      "content": "Hallo!"
    }
  ]
}
```

**Response**

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1721822400,
  "model": "mistral/mistral-large-latest",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "system",
        "content": "string",
        "name": "string"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1
  }
}
```

**SDK Code**

```python Simple completion
import requests

url = "https://api.kontinent.ai/v1/chat/completions"

payload = {
    "model": "mistral/mistral-large-latest",
    "messages": [
        {
            "role": "user",
            "content": "Hallo!"
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Simple completion
const url = 'https://api.kontinent.ai/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"mistral/mistral-large-latest","messages":[{"role":"user","content":"Hallo!"}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Simple completion
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.kontinent.ai/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"mistral/mistral-large-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hallo!\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Simple completion
require 'uri'
require 'net/http'

url = URI("https://api.kontinent.ai/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"mistral/mistral-large-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hallo!\"\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java Simple completion
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.kontinent.ai/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"mistral/mistral-large-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hallo!\"\n    }\n  ]\n}")
  .asString();
```

```php Simple completion
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.kontinent.ai/v1/chat/completions', [
  'body' => '{
  "model": "mistral/mistral-large-latest",
  "messages": [
    {
      "role": "user",
      "content": "Hallo!"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Simple completion
using RestSharp;

var client = new RestClient("https://api.kontinent.ai/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"mistral/mistral-large-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hallo!\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Simple completion
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "mistral/mistral-large-latest",
  "messages": [
    [
      "role": "user",
      "content": "Hallo!"
    ]
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.kontinent.ai/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```

### Streaming completion



**Request**

```json
{
  "model": "mistral/mistral-small-latest",
  "messages": [
    {
      "role": "user",
      "content": "Write a haiku about Europe."
    }
  ],
  "stream": true
}
```

**Response**

```json
{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1721822400,
  "model": "mistral/mistral-large-latest",
  "choices": [
    {
      "index": 1,
      "message": {
        "role": "system",
        "content": "string",
        "name": "string"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 1,
    "total_tokens": 1
  }
}
```

**SDK Code**

```python Streaming completion
import requests

url = "https://api.kontinent.ai/v1/chat/completions"

payload = {
    "model": "mistral/mistral-small-latest",
    "messages": [
        {
            "role": "user",
            "content": "Write a haiku about Europe."
        }
    ],
    "stream": True
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Streaming completion
const url = 'https://api.kontinent.ai/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"mistral/mistral-small-latest","messages":[{"role":"user","content":"Write a haiku about Europe."}],"stream":true}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Streaming completion
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.kontinent.ai/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"mistral/mistral-small-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Write a haiku about Europe.\"\n    }\n  ],\n  \"stream\": true\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Streaming completion
require 'uri'
require 'net/http'

url = URI("https://api.kontinent.ai/v1/chat/completions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"mistral/mistral-small-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Write a haiku about Europe.\"\n    }\n  ],\n  \"stream\": true\n}"

response = http.request(request)
puts response.read_body
```

```java Streaming completion
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.kontinent.ai/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"mistral/mistral-small-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Write a haiku about Europe.\"\n    }\n  ],\n  \"stream\": true\n}")
  .asString();
```

```php Streaming completion
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.kontinent.ai/v1/chat/completions', [
  'body' => '{
  "model": "mistral/mistral-small-latest",
  "messages": [
    {
      "role": "user",
      "content": "Write a haiku about Europe."
    }
  ],
  "stream": true
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp Streaming completion
using RestSharp;

var client = new RestClient("https://api.kontinent.ai/v1/chat/completions");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"mistral/mistral-small-latest\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Write a haiku about Europe.\"\n    }\n  ],\n  \"stream\": true\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Streaming completion
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "mistral/mistral-small-latest",
  "messages": [
    [
      "role": "user",
      "content": "Write a haiku about Europe."
    ]
  ],
  "stream": true
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.kontinent.ai/v1/chat/completions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```