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

# Create a chat completion

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

Generate a chat completion from one of the available models. Mixlayer’s API is OpenAI-compatible, so existing OpenAI client libraries work without modification — see [Client Libraries](/client-libraries) for examples.

Set `reasoning_effort` to `default`, `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`, or omit it for the model default. Some models also support numeric reasoning effort. Check the model's [Mixlayer documentation page](/models) for supported values and ranges. Models reject unsupported efforts; see [Reasoning](/reasoning#model-mappings) for model-specific mappings and legacy boolean controls.

Set `stream` to true to receive JSON chunks as server-sent events; the stream ends with `data: [DONE]`.

Reference: https://docs.mixlayer.com/api-reference/inference-ap-is/chat-completions/chat-completions

## Authentication

- `Authorization` header (bearer token, required) — Mixlayer API key or console user session supplied as a Bearer token.

## Request

### Body (application/json)

This endpoint expects a ChatCompletionsRequest.

- `messages` (list of ChatCompletionRequestMessage, required) — Message objects in turn order. Each message has a `role` and `content`.
- `model` (string, required) — Model identifier.
- `web_search_options` (ChatWebSearchOptions, optional, nullable) — Chat Completions request shape for hosted web search.
- `frequency_penalty` (float, optional, nullable) — Penalizes tokens proportional to how often they have appeared. Positive values reduce repetition.
- `max_completion_tokens` (integer, optional, nullable) — Maximum tokens to generate. Takes precedence over `max_tokens`.
- `max_tokens` (integer, optional, nullable) — Legacy alias for `max_completion_tokens`.
- `metadata` (any, optional) — Developer-supplied metadata stored with the response when `store` is true.
- `parallel_tool_calls` (boolean, optional, nullable) — Whether the model may emit multiple tool calls in one generation leg.
- `presence_penalty` (float, optional, nullable) — Penalizes tokens that have appeared at all. Positive values encourage topical novelty.
- `reasoning` (ChatReasoningParam, optional, nullable) — Reasoning configuration accepting the legacy boolean and object forms.
- `reasoning_effort` (ChatCompletionsRequestReasoningEffort, optional, nullable) — Reasoning effort: `default`, `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. Some models also support numeric reasoning effort. Check the model's [Mixlayer documentation page](/models) for supported values and ranges. Omit for the model default. See [Reasoning](/reasoning#model-mappings) for model-specific mappings and unsupported values.
- `repetition_penalty` (float, optional, nullable) — Multiplicative penalty on tokens already in the context. `1.0` applies no penalty.
- `response_format` (GenerationResponseFormat, optional, nullable)
- `seed` (long, optional, nullable) — Best-effort deterministic sampling seed.
- `stop` (list of string, optional, nullable) — Sequences that halt generation. The stop sequence is not included in the output.
- `store` (boolean, optional, default: false) — Persist the completed request and response for later use.
- `stream` (boolean, optional, default: false) — If `true`, stream the response as Server-Sent Events. Defaults to `false`.
- `stream_options` (StreamOptions, optional, nullable)
- `temperature` (float, optional, nullable) — Controls randomness. Lower values make output more deterministic; higher values make it more diverse.
- `thinking` (boolean, optional, nullable) — Legacy boolean reasoning switch.
- `tools` (list of GenerationTool, optional, nullable) — Function tools the model may call.
- `top_k` (integer, optional, nullable) — Only consider the top-`k` most likely tokens at each step.
- `top_p` (float, optional, nullable) — Only consider tokens whose cumulative probability is below this value.

## Response

### 200

A complete response or a stream of completion chunks, selected by the request's `stream` field

- `choices` (list of ChatChoice, required) — Generated completion choices.
- `created` (long, required) — Unix timestamp when the completion was created.
- `id` (string, required) — Unique identifier for the chat completion.
- `model` (string, required) — Model used to generate the completion.
- `object` (enum, required) — Object type, always `chat.completion`.
  - Allowed values: `chat.completion`
- `usage` (Usage, required) — Token usage for the request.

## Errors

### 400 Bad Request Error

Invalid request or model

- `error` (OpenAIErrorDetails, required)

### 401 Unauthorized Error

Missing or invalid API key

- `error` (OpenAIErrorDetails, required)

### 402 Payment Required Error

Billing is required

- `error` (OpenAIErrorDetails, required)

### 403 Forbidden Error

The API key lacks inference permission

- `error` (OpenAIErrorDetails, required)

### 429 Too Many Requests Error

Rate limit exceeded

- `error` (OpenAIErrorDetails, required)

### 500 Internal Server Error

Generation failed

- `error` (OpenAIErrorDetails, required)

## Types

### ChatCompletionRequestMessage

Message supplied to the Chat Completions API.

### ChatWebSearchOptions

Chat Completions request shape for hosted web search.

- `category` (enum, optional, nullable) — Exa content category accepted by the public web-search options.
  - Allowed values: `company`, `people`, `research paper`, `news`, `personal site`, `financial report`
- `filters` (WebSearchFilters, optional, nullable) — Domain allow/block filters for hosted web search.
- `max_characters` (integer, optional)
- `max_results` (integer, optional)
- `user_location` (ChatWebSearchUserLocation, optional, nullable) — Chat Completions wrapper for an approximate user location.

### ChatReasoningParam

Reasoning configuration accepting the legacy boolean and object forms.

### ChatCompletionsRequestReasoningEffort

Reasoning effort: `default`, `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, or `max`. Some models also support numeric reasoning effort. Check the model's [Mixlayer documentation page](/models) for supported values and ranges. Omit for the model default. See [Reasoning](/reasoning#model-mappings) for model-specific mappings and unsupported values.

### GenerationResponseFormat

- `type` (enum, required) — Output format: `text`, `json_object`, or `json_schema`.
  - Allowed values: `text`, `json_object`, `json_schema`
- `json_schema` (GenerationResponseFormatJsonSchema, optional, nullable)

### StreamOptions

- `include_obfuscation` (boolean, optional, nullable) — Accepted for OpenAI compatibility; obfuscation is not added by the gateway.
- `include_usage` (boolean, optional, default: false) — Include a final usage-only chunk before the `[DONE]` event.

### GenerationTool

- `function` (GenerationToolFunction, required) — Function definition invoked by the model.
- `type` (enum, required) — Tool type. Currently only `function` is supported.
  - Allowed values: `function`

### ChatChoice

- `index` (integer, required) — Index of this choice in the response.
- `message` (ChatMessage, required) — Generated assistant message.
- `finish_reason` (string, optional, nullable) — Why generation stopped: `stop` or `tool_calls`.

### Usage

Token usage returned by regular and streaming completion endpoints.

- `completion_tokens` (integer, required) — Number of generated tokens.
- `prompt_tokens` (integer, required) — Number of input tokens.
- `prompt_tokens_details` (PromptTokensDetails, required) — Detailed input-token usage.
- `total_tokens` (integer, required) — Total input and generated tokens.
- `completion_tokens_details` (CompletionTokensDetails, optional) — Detailed completion usage; reasoning tokens are included in completion_tokens.
- `server_tool_use` (map from string to long, optional)

### OpenAIErrorDetails

- `message` (string, required)
- `type` (string, required)
- `code` (string, optional, nullable)

### ChatCompletionRequestMessage0

System instructions.

- `content` (ChatMessageContent, required) — System message content.
- `role` (enum, required)
  - Allowed values: `system`

### ChatCompletionRequestMessage1

End-user input.

- `content` (ChatMessageContent, required) — User message content.
- `role` (enum, required)
  - Allowed values: `user`

### ChatCompletionRequestMessage2

Prior assistant output or tool calls.

- `role` (enum, required)
  - Allowed values: `assistant`
- `content` (ChatMessageContent, optional, nullable)
- `reasoning_content` (string, optional, nullable) — Reasoning content returned by a reasoning model.
- `tool_calls` (list of ChatToolCall, optional, nullable) — Tool calls requested by the assistant.

### ChatCompletionRequestMessage3

Result returned for an assistant tool call.

- `content` (ChatMessageContent, required) — Tool result content.
- `role` (enum, required)
  - Allowed values: `tool`
- `tool_call_id` (string, required) — Tool call being answered.

### WebSearchFilters

Domain allow/block filters for hosted web search.

- `allowed_domains` (list of string, optional)
- `blocked_domains` (list of string, optional)

### ChatWebSearchUserLocation

Chat Completions wrapper for an approximate user location.

- `approximate` (WebSearchUserLocationFields, required) — Optional approximate-location fields shared by Chat requests.
- `type` (string, required)

### ChatReasoningParam1

Reasoning effort and token budget for each generation leg.

- `effort` (ReasoningEffortParam, optional, nullable) — Named reasoning effort or a DeepSeek V4.1 integer effort from 1 through 100.
- `max_tokens` (integer, optional, nullable) — Maximum reasoning tokens, within the total output budget; must be positive.

### GenerationResponseFormatJsonSchema

- `schema` (any, optional) — JSON Schema the model output must match.
- `strict` (boolean, optional, nullable) — Whether the schema is enforced strictly. Defaults to true.

### GenerationToolFunction

- `description` (string, required) — Description of what the function does.
- `name` (string, required) — Function name. Must contain only letters, digits, underscores, or hyphens and be at most 256 characters, including internal qualified names such as `namespace__member`.
- `parameters` (any, required) — JSON Schema describing the function arguments.
- `strict` (boolean, optional, nullable) — Whether generated arguments must strictly match the schema.

### ChatMessage

Assistant message returned by the Chat Completions API.

- `content` (string, required) — Generated assistant text.
- `role` (enum, required) — Message author role, always `assistant`.
  - Allowed values: `assistant`
- `reasoning_content` (string, optional, nullable) — Reasoning content supplied by or returned from a reasoning model.
- `sources` (list of ChatWebSearchSource, optional, nullable)
- `tool_calls` (list of ChatToolCall, optional, nullable) — Tool calls requested by an assistant message.

### PromptTokensDetails

Breakdown of input tokens used by completion endpoints.

- `audio_tokens` (integer, required) — Number of audio input tokens.
- `cached_tokens` (integer, required) — Number of cached input tokens.

### CompletionTokensDetails

Breakdown of generated tokens

- `reasoning_tokens` (integer, optional, nullable) — Count of reasoning tokens

### ChatMessageContent

### ChatToolCall

- `function` (ChatToolCallFunction, required) — Function call generated by the model.
- `id` (string, required) — Tool call identifier.
- `type` (string, required) — Tool type, always `function`.
- `index` (integer, optional) — Index of this tool call.

### WebSearchUserLocationFields

Optional approximate-location fields shared by Chat requests.

- `city` (string, optional, nullable)
- `country` (string, optional, nullable)
- `region` (string, optional, nullable)
- `timezone` (string, optional, nullable)

### ReasoningEffortParam

Named reasoning effort or a DeepSeek V4.1 integer effort from 1 through 100.

### ChatWebSearchSource

URL and title extension returned by Chat Completions.

- `title` (string, required)
- `url` (string, required)

### ChatToolCallFunction

- `arguments` (string, required) — Function arguments serialized as JSON.
- `name` (string, required) — Name of the function to call.

## Examples

**Request**

```json
{
  "messages": [
    {
      "content": "string",
      "role": "system"
    }
  ],
  "model": "string"
}
```

**Response**

```json
{
  "choices": [
    {
      "index": 1,
      "message": {
        "content": "string",
        "role": "assistant",
        "reasoning_content": "string",
        "sources": [
          {
            "title": "string",
            "url": "string"
          }
        ],
        "tool_calls": [
          {
            "function": {
              "arguments": "string",
              "name": "string"
            },
            "id": "string",
            "type": "string",
            "index": 1
          }
        ]
      },
      "finish_reason": "string"
    }
  ],
  "created": 1,
  "id": "string",
  "model": "string",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 1,
    "prompt_tokens": 1,
    "prompt_tokens_details": {
      "audio_tokens": 1,
      "cached_tokens": 1
    },
    "total_tokens": 1,
    "completion_tokens_details": {
      "reasoning_tokens": 1
    },
    "server_tool_use": {}
  }
}
```

**SDK Code**

```python
import requests

url = "https://mixlayer.ai/v1/chat/completions"

payload = {
    "messages": [
        {
            "content": "string",
            "role": "system"
        }
    ],
    "model": "string"
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://mixlayer.ai/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"messages":[{"content":"string","role":"system"}],"model":"string"}'
};

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

```go
package main

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

func main() {

	url := "https://mixlayer.ai/v1/chat/completions"

	payload := strings.NewReader("{\n  \"messages\": [\n    {\n      \"content\": \"string\",\n      \"role\": \"system\"\n    }\n  ],\n  \"model\": \"string\"\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
require 'uri'
require 'net/http'

url = URI("https://mixlayer.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  \"messages\": [\n    {\n      \"content\": \"string\",\n      \"role\": \"system\"\n    }\n  ],\n  \"model\": \"string\"\n}"

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

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

HttpResponse<String> response = Unirest.post("https://mixlayer.ai/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"messages\": [\n    {\n      \"content\": \"string\",\n      \"role\": \"system\"\n    }\n  ],\n  \"model\": \"string\"\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://mixlayer.ai/v1/chat/completions', [
  'body' => '{
  "messages": [
    {
      "content": "string",
      "role": "system"
    }
  ],
  "model": "string"
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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