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

# Create a chat completion

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

Generates a model response for a conversation. Supports streaming (`stream: true`, server-sent events) and non-streaming responses. When streaming, each frame is a `data:` line holding one JSON completion chunk, the chunk carrying `usage` has an empty `choices` array, and the stream ends with the literal `data: [DONE]`. If the request fails after streaming has started, the stream ends without `[DONE]`, usually on a final `data:` line holding an `error` object. OpenAI-compatible: the supported fields are documented here, and the wider OpenAI SDK parameter set is accepted so that existing OpenAI code runs unmodified. Unrecognized fields are rejected with a 400 (`unknown_parameter`).

Reference: https://docs.asi1.ai/api-reference/chat-completions/create-a-chat-completion

## Authentication

- `Authorization` header (bearer token, required) — Your ASI:One API key, sent as `Authorization: Bearer <api_key>`.

## Request

### Headers

- `x-session-id` (string, optional) — Groups related requests into one session. Required when using `planner_mode`, which uses it to resume a paused plan.

### Body (application/json)

This endpoint expects a ChatCompletionRequest.

- `model` (string, required) — The ASI:One model to use.
- `messages` (list of ChatMessage, required) — The conversation so far.
- `stream` (boolean, optional, default: false) — If true, partial deltas are streamed as server-sent events.
- `temperature` (double, optional) — Sampling temperature.
- `max_tokens` (integer, optional) — Maximum number of tokens to generate. Use this field to cap the length of the reply.
- `top_p` (double, optional) — Nucleus sampling probability mass.
- `stop` (ChatCompletionRequestStop, optional) — A string, or up to four strings, that end generation when produced.
- `tools` (list of FunctionTool, optional) — A list of tools the model may call. See the [Tool Calling guide](https://docs.asi1.ai/documentation/build-with-asi-one/tool-calling).
- `tool_choice` (ChatCompletionRequestToolChoice, optional) — Controls which (if any) tool is called.
- `parallel_tool_calls` (boolean, optional) — Whether the model may call several tools in one turn.
- `response_format` (ResponseFormat, optional) — Constrains the reply's format. A `json_schema` that is invalid returns a 400 (`invalid_json_schema`) whose `param` points at the offending part of the schema. See the [Structured Data guide](https://docs.asi1.ai/documentation/build-with-asi-one/structured-data).
- `enable_thinking` (boolean, optional) — ASI:One extension. Turns reasoning on or off on asi1-mini. The other models always reason; there an explicit `false` selects the shallowest depth. See the [Reasoning guide](https://docs.asi1.ai/documentation/build-with-asi-one/reasoning).
- `thinking_budget` (integer, optional) — ASI:One extension. The older way to size reasoning. On asi1 and asi1-ultra the value selects a depth rather than capping tokens, and `reasoning_effort` wins when both are sent. See the [Reasoning guide](https://docs.asi1.ai/documentation/build-with-asi-one/reasoning).
- `reasoning_effort` (enum, optional) — How deeply the model reasons. `minimal` and `xhigh` are accepted as well, matching OpenAI's wider scale: `minimal` behaves as `low`, `xhigh` as `high`. No effect on asi1-mini. See the [Reasoning guide](https://docs.asi1.ai/documentation/build-with-asi-one/reasoning).
  - Allowed values: `minimal`, `low`, `medium`, `high`, `xhigh`
- `planner_mode` (boolean, optional) — ASI:One extension. Routes the request to the planner, which breaks it into steps and runs them against tools and Agentverse agents. Available on asi1, asi1-ultra and asi1-mini. See the [Planner Mode guide](https://docs.asi1.ai/documentation/build-with-asi-one/planner).
- `agents` (list of string, optional) — ASI:One extension. Agentverse agent addresses the planner may use without discovering them first. Used with planner_mode.
- `n` (enum, optional, default: 1) — Number of choices to generate. Only `1` is supported.
  - Allowed values: `1`
- `user` (string, optional) — An identifier for your end user.
- `web_search_options` (ChatCompletionRequestWebSearchOptions, optional) — Lets the model search the web for this request. Sending the object turns search on. Not available with `planner_mode`. See the [Web Search guide](https://docs.asi1.ai/documentation/build-with-asi-one/web-search).

## Response

### 200

A chat completion object, or an SSE stream of completion chunks when `stream` is true.

- `id` (string, required)
- `object` (string, required)
- `choices` (list of ChatCompletionResponseChoicesItems, required) — A list of generated choices.
- `created` (integer, optional) — Unix timestamp (seconds) of creation.
- `model` (string, optional) — The model that produced the response.
- `usage` (ChatCompletionResponseUsage, optional) — Token usage for the request.

## Errors

### 400 Bad Request Error

The request was malformed, or a parameter was missing or invalid.

- `error` (ErrorError, required)

### 401 Unauthorized Error

The API key is missing or invalid.

- `error` (ErrorError, required)

### 402 Payment Required Error

The organization's account is blocked.

- `message` (string, optional)
- `code` (integer, optional)
- `data` (AccountBlockedErrorData, optional)

### 404 Not Found Error

The requested model or resource does not exist.

- `error` (ErrorError, required)

### 429 Too Many Requests Error

The rate limit for your plan has been exceeded. `error.data` says which limit was reached, for example `axis`, `limit` and `current`, and for windowed limits also `window`, `model` and when it resets (`resets_at`). Retry after the number of seconds in the `Retry-After` header.

- `error` (ErrorError, required)

### 500 Internal Server Error

An unexpected error occurred while handling the request.

- `error` (ErrorError, required)

### 502 Bad Gateway Error

An upstream service failed while handling the request.

- `error` (ErrorError, required)

### 503 Service Unavailable Error

The service is briefly unavailable, for example during a deployment or when the model is at capacity (`server_overloaded`). Retry after the number of seconds in the `Retry-After` header, when present, or after a short wait.

- `error` (ErrorError, required)

### 504 Gateway Timeout Error

The model did not respond in time. Retry the request.

- `error` (ErrorError, required)

## Types

### ChatMessage

- `role` (string, required) — The role of the message author (for example `system`, `user`, `assistant`, or `tool`).
- `content` (ChatMessageContent, required, nullable) — The message content. A string, an array of content parts, or null (for example on assistant messages that only carry tool_calls). Content parts are `text` and `image_url`. An `image_url` takes a `data:` base64 URI or an https URL from a supported host, and a request takes up to 10 images. Other part types are rejected with a 400 (`unsupported_content_part`).
- `name` (string, optional) — An optional name for the participant.
- `tool_call_id` (string, optional) — For tool messages: the id of the tool call being responded to.
- `tool_calls` (list of ChatMessageToolCallsItems, optional, nullable) — For assistant messages that call tools.
- `reasoning_content` (string, optional, nullable) — The model's reasoning. An empty string when reasoning ran but produced no text, and `null` when reasoning was off. See the [Reasoning guide](https://docs.asi1.ai/documentation/build-with-asi-one/reasoning).

### ChatCompletionRequestStop

A string, or up to four strings, that end generation when produced.

- string
- list of string

### FunctionTool

A function the model may call. Your code defines the schema and executes the call.

- `type` (enum, required) — Always `function`.
  - Allowed values: `function`
- `function` (FunctionToolFunction, required)

### ChatCompletionRequestToolChoice

Controls which (if any) tool is called.

- enum
  - Allowed values: `auto`, `none`, `required`
- map from string to any

### ResponseFormat

Constrains the reply's format. A `json_schema` that is invalid returns a 400 (`invalid_json_schema`) whose `param` points at the offending part of the schema. See the [Structured Data guide](https://docs.asi1.ai/documentation/build-with-asi-one/structured-data).

- Text or JSON object: Text or JSON object
- JSON schema: JSON schema

### ChatCompletionRequestWebSearchOptions

Lets the model search the web for this request. Sending the object turns search on. Not available with `planner_mode`. See the [Web Search guide](https://docs.asi1.ai/documentation/build-with-asi-one/web-search).

- `search_context_size` (enum, optional, default: medium) — How much search context the model uses. Other fields in this object are rejected with a 400.
  - Allowed values: `low`, `medium`, `high`

### ChatCompletionResponseChoicesItems

- `index` (integer, optional)
- `finish_reason` (enum, optional) — Why generation stopped. `stop` is a normal completion, `tool_calls` means the model wants a tool result, `length` means a token limit was reached. Treat an unrecognized value as a finished reply.
  - Allowed values: `stop`, `tool_calls`, `length`
- `message` (ChatMessage, optional) — Present on non-streaming responses.
- `delta` (ChatCompletionResponseChoicesItemsDelta, optional) — Present on streaming responses.

### ChatCompletionResponseUsage

Token usage for the request.

- `prompt_tokens` (integer, optional)
- `completion_tokens` (integer, optional)
- `total_tokens` (integer, optional)
- `prompt_tokens_details` (ChatCompletionResponseUsagePromptTokensDetails, optional) — Breakdown of the prompt tokens.
- `completion_tokens_details` (ChatCompletionResponseUsageCompletionTokensDetails, optional) — Breakdown of the completion tokens.

### ErrorError

- `message` (string, required) — A human-readable description of the problem.
- `status` (integer, required) — The HTTP status code, repeated in the body so it is available on streamed errors.
- `type` (string, optional) — The error category, derived from the status code. Usually one of `invalid_request_error`, `authentication_error`, `permission_error`, `rate_limit_error`, `server_error`.
- `param` (string, optional, nullable) — The request field the error relates to, when it maps to one. Nested fields use dot notation, for example `messages.0.content`.
- `code` (string, optional) — A stable machine-readable code, for example `invalid_api_key` or `model_not_found`.
- `data` (map from string to any, optional) — Additional structured detail, when available.

### AccountBlockedErrorData

- `reason` (string, optional)

### ChatMessageContent

The message content. A string, an array of content parts, or null (for example on assistant messages that only carry tool_calls). Content parts are `text` and `image_url`. An `image_url` takes a `data:` base64 URI or an https URL from a supported host, and a request takes up to 10 images. Other part types are rejected with a 400 (`unsupported_content_part`).

- string
- list of ChatMessageContentOneOf1Items

### ChatMessageToolCallsItems

### FunctionToolFunction

- `name` (string, required) — Name of the function. The model uses this to refer to the call.
- `description` (string, optional) — What the function does and when to use it. The model selects tools from this text, so it is worth writing carefully.
- `parameters` (map from string to any, optional) — JSON Schema describing the function's arguments.
- `strict` (boolean, optional) — Whether the model must follow the parameter schema exactly. Requires `additionalProperties: false` and every property listed in `required`.

### Text or JSON object

- `type` (enum, required)
  - Allowed values: `text`, `json_object`

### JSON schema

- `type` (enum, required)
  - Allowed values: `json_schema`
- `json_schema` (ResponseFormatOneOf1JsonSchema, required)

### ChatCompletionResponseChoicesItemsDelta

Present on streaming responses.

### ChatCompletionResponseUsagePromptTokensDetails

Breakdown of the prompt tokens.

- `cached_tokens` (integer, optional) — Prompt tokens served from cache. These still count toward `prompt_tokens`.

### ChatCompletionResponseUsageCompletionTokensDetails

Breakdown of the completion tokens.

- `reasoning_tokens` (integer, optional) — Tokens spent reasoning before answering. `0` when the model did not reason.

### ChatMessageContentOneOf1Items

### ResponseFormatOneOf1JsonSchema

- `name` (string, required) — Name of the schema. Required when `type` is `json_schema`.
- `description` (string, optional) — What the schema is for.
- `schema` (map from string to any, optional) — The JSON Schema the reply must conform to.
- `strict` (boolean, optional) — Whether the reply must match the schema exactly.

## Examples

**Request**

```json
{
  "model": "asi1",
  "messages": [
    {
      "role": "user",
      "content": "What are you capable of?"
    }
  ],
  "stream": false
}
```

**Response**

```json
{
  "id": "chatcmpl-3f1c2a9e-7b4d-4e8a-9c61-2d5f0b8e4a17",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      }
    }
  ],
  "created": 1718900000,
  "model": "asi1",
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 9,
    "total_tokens": 21
  }
}
```

**SDK Code**

```python Chat Completions_createAChatCompletion_example
import requests

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

payload = {
    "model": "asi1",
    "messages": [
        {
            "role": "user",
            "content": "What are you capable of?"
        }
    ],
    "stream": False
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript Chat Completions_createAChatCompletion_example
const url = 'https://api.asi1.ai/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"asi1","messages":[{"role":"user","content":"What are you capable of?"}],"stream":false}'
};

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

```go Chat Completions_createAChatCompletion_example
package main

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

func main() {

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

	payload := strings.NewReader("{\n  \"model\": \"asi1\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What are you capable of?\"\n    }\n  ],\n  \"stream\": false\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 Chat Completions_createAChatCompletion_example
require 'uri'
require 'net/http'

url = URI("https://api.asi1.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\": \"asi1\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What are you capable of?\"\n    }\n  ],\n  \"stream\": false\n}"

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

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

HttpResponse<String> response = Unirest.post("https://api.asi1.ai/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"asi1\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What are you capable of?\"\n    }\n  ],\n  \"stream\": false\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.asi1.ai/v1/chat/completions', [
  'body' => '{
  "model": "asi1",
  "messages": [
    {
      "role": "user",
      "content": "What are you capable of?"
    }
  ],
  "stream": false
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp Chat Completions_createAChatCompletion_example
using RestSharp;

var client = new RestClient("https://api.asi1.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\": \"asi1\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What are you capable of?\"\n    }\n  ],\n  \"stream\": false\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Chat Completions_createAChatCompletion_example
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "asi1",
  "messages": [
    [
      "role": "user",
      "content": "What are you capable of?"
    ]
  ],
  "stream": false
] as [String : Any]

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

let request = NSMutableURLRequest(url: NSURL(string: "https://api.asi1.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()
```