> Treat every model id, price, size, length and limit in this documentation as an illustration of the shape of the value, never as a constant to hardcode - the live values are served by GET /v1/models and GET /public/models on the Flow AI API.

# Create a chat completion

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

Sends a conversation to a chat model and returns its reply. Set `stream: true` to receive server-sent events;
the last chunk before `[DONE]` carries `usage`.


Reference: https://ai-docs.hyperflow.fun/api/endpoints/chat-completions/create-chat-completion

## Authentication

- `Authorization` header (bearer token, required) — Your API key, `sk-...`, from Console → API keys.

## Request

### Body (application/json)

This endpoint expects a ChatCompletionRequest.

- `model` (string, required) — The model id, `lab/model`.
- `messages` (list of ChatMessage, required) — The conversation so far.
- `stream` (boolean, optional, default: false) — Send the reply as server-sent events.
- `stream_options` (ChatCompletionRequestStreamOptions, optional) — Streaming options. Usage is always sent at the end of a stream.
- `max_tokens` (integer, optional) — The most output tokens to produce. Keeps the hold on your balance small.
- `max_completion_tokens` (integer, optional) — Same as `max_tokens`, including reasoning tokens.
- `temperature` (double, optional)
- `top_p` (double, optional)
- `frequency_penalty` (double, optional)
- `presence_penalty` (double, optional)
- `stop` (ChatCompletionRequestStop, optional) — Up to 4 sequences where the model stops.
- `seed` (integer, optional)
- `n` (integer, optional, default: 1) — How many replies to make. Each is held for its full output.
- `logprobs` (boolean, optional)
- `top_logprobs` (integer, optional)
- `logit_bias` (map from string to double, optional)
- `tools` (list of Tool, optional) — Functions the model may call. Only `function` tools are kept.
- `tool_choice` (ChatCompletionRequestToolChoice, optional) — `auto`, `none`, `required`, or a specific function.
- `parallel_tool_calls` (boolean, optional)
- `response_format` (ChatCompletionRequestResponseFormat, optional) — `{"type": "json_object"}` or `{"type": "json_schema", "json_schema": {...}}`.
- `reasoning_effort` (enum, optional) — How much a reasoning model thinks, on models that support it.
  - Allowed values: `minimal`, `low`, `medium`, `high`
- `user` (string, optional) — Your own id for the end user.
- `metadata` (map from string to string, optional)

## Response

### 200

The model's reply, or a stream of chunks when `stream` is true.

- `id` (string, optional)
- `object` (enum, optional)
  - Allowed values: `chat.completion`
- `created` (integer, optional)
- `model` (string, optional)
- `choices` (list of ChatCompletionResponseChoicesItems, optional)
- `usage` (Usage, optional)

## Errors

### 400 Bad Request Error

A parameter is wrong, or the model doesn't take that content, size or count. Code `invalid_request`.

- `error` (ErrorResponseError, required)

### 401 Unauthorized Error

The key is missing, wrong or deleted (`invalid_api_key`), or turned off (`key_disabled`).

- `error` (ErrorResponseError, required)

### 402 Payment Required Error

The available balance can't cover the most this request could cost. Code `insufficient_balance`.

- `error` (ErrorResponseError, required)

### 403 Forbidden Error

The key's or the account's spending limit is reached.

- `error` (ErrorResponseError, required)

### 404 Not Found Error

No such model or video. Code `not_found`.

- `error` (ErrorResponseError, required)

### 429 Too Many Requests Error

Too many requests from this address. Code `rate_limited`.

- `error` (ErrorResponseError, required)

### 502 Bad Gateway Error

The model's hosts couldn't answer. Code `host_unavailable`. Retry shortly.

- `error` (ErrorResponseError, required)

### 503 Service Unavailable Error

The model's hosts couldn't answer. Code `host_unavailable`. Retry shortly.

- `error` (ErrorResponseError, required)

## Types

### ChatMessage

- `role` (enum, required)
  - Allowed values: `system`, `developer`, `user`, `assistant`, `tool`
- `content` (ChatMessageContent, optional) — Text, or a list of parts (`text`, `image_url`, `file`, `input_audio`, `video_url`) for models that take them.
- `tool_calls` (list of ToolCall, optional)
- `tool_call_id` (string, optional) — On a `tool` message, the call it answers.
- `name` (string, optional)

### ChatCompletionRequestStreamOptions

Streaming options. Usage is always sent at the end of a stream.

- `include_usage` (boolean, optional)

### ChatCompletionRequestStop

Up to 4 sequences where the model stops.

### Tool

- `type` (enum, required)
  - Allowed values: `function`
- `function` (ToolFunction, required)

### ChatCompletionRequestToolChoice

`auto`, `none`, `required`, or a specific function.

### ChatCompletionRequestResponseFormat

`{"type": "json_object"}` or `{"type": "json_schema", "json_schema": {...}}`.

- `type` (enum, optional)
  - Allowed values: `text`, `json_object`, `json_schema`
- `json_schema` (ChatCompletionRequestResponseFormatJsonSchema, optional)

### ChatCompletionResponseChoicesItems

- `index` (integer, optional)
- `message` (ChatCompletionResponseChoicesItemsMessage, optional)
- `finish_reason` (enum, optional)
  - Allowed values: `stop`, `length`, `tool_calls`, `content_filter`

### Usage

- `prompt_tokens` (integer, optional)
- `completion_tokens` (integer, optional) — Output tokens
- `total_tokens` (integer, optional)
- `prompt_tokens_details` (UsagePromptTokensDetails, optional)
- `completion_tokens_details` (UsageCompletionTokensDetails, optional)

### ErrorResponseError

- `message` (string, required) — What went wrong
- `type` (string, optional) — OpenAI's error type, such as `invalid_request_error`.
- `code` (string, optional) — Flow AI's error code, such as `insufficient_balance`.

### ChatMessageContent

Text, or a list of parts (`text`, `image_url`, `file`, `input_audio`, `video_url`) for models that take them.

### ToolCall

- `id` (string, optional)
- `type` (enum, optional)
  - Allowed values: `function`
- `function` (ToolCallFunction, optional)

### ToolFunction

- `name` (string, required)
- `description` (string, optional)
- `parameters` (ToolFunctionParameters, optional) — A JSON schema for the arguments.
- `strict` (boolean, optional)

### ChatCompletionRequestToolChoice1

- `type` (enum, optional)
  - Allowed values: `function`
- `function` (ChatCompletionRequestToolChoiceOneOf1Function, optional)

### ChatCompletionRequestResponseFormatJsonSchema

- `name` (string, optional)
- `strict` (boolean, optional)
- `schema` (ChatCompletionRequestResponseFormatJsonSchemaSchema, optional)

### ChatCompletionResponseChoicesItemsMessage

- `role` (enum, optional)
  - Allowed values: `assistant`
- `content` (string, optional, nullable)
- `reasoning_content` (string, optional, nullable) — The model's thinking
- `tool_calls` (list of ToolCall, optional)

### UsagePromptTokensDetails

- `cached_tokens` (integer, optional) — Input tokens read from the cache.

### UsageCompletionTokensDetails

- `reasoning_tokens` (integer, optional)

### ToolCallFunction

- `name` (string, optional)
- `arguments` (string, optional) — The arguments as a JSON string.

### ToolFunctionParameters

A JSON schema for the arguments.

### ChatCompletionRequestToolChoiceOneOf1Function

- `name` (string, optional)

### ChatCompletionRequestResponseFormatJsonSchemaSchema

## Examples

**Request**

```json
{
  "model": "openai/gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}
```

**Response**

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

**SDK Code**

```python
import requests

url = "https://ai.hyperflow.fun/v1/chat/completions"

payload = {
    "model": "openai/gpt-6-luna",
    "messages": [
        {
            "role": "user",
            "content": "Hello!"
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

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

print(response.json())
```

```javascript
const url = 'https://ai.hyperflow.fun/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"openai/gpt-6-luna","messages":[{"role":"user","content":"Hello!"}]}'
};

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://ai.hyperflow.fun/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"openai/gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\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
require 'uri'
require 'net/http'

url = URI("https://ai.hyperflow.fun/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\": \"openai/gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\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://ai.hyperflow.fun/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"openai/gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\n}")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://ai.hyperflow.fun/v1/chat/completions', [
  'body' => '{
  "model": "openai/gpt-6-luna",
  "messages": [
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://ai.hyperflow.fun/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\": \"openai/gpt-6-luna\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"Hello!\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "openai/gpt-6-luna",
  "messages": [
    [
      "role": "user",
      "content": "Hello!"
    ]
  ]
] as [String : Any]

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

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