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

# Tạo chat completion

POST https://api.tramlabs.io/v1/chat/completions
Content-Type: application/json

Tạo chat completion. Tương thích hoàn toàn với [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat/create).


Reference: https://docs.tramlabs.io/api/endpoints/audio/chat-completions/create-chat-completion

## Authentication

- `Authorization` header (bearer token, required) — API key làm bearer token. Tạo API key tại [Console](https://console.tramlabs.io/keys).

## Request

### Body (application/json)

This endpoint expects a ChatCompletionRequest.

- `model` (string, required) — Model ID (ví dụ: `gemini-3.5-flash`, `deepseek-v4-flash`)
- `messages` (list of ChatMessage, required) — Danh sách messages
- `stream` (boolean, optional, default: false) — Bật streaming (SSE)
- `temperature` (double, optional) — Sampling temperature (0–2)
- `max_tokens` (integer, optional) — Số token tối đa trong response
- `top_p` (double, optional) — Nucleus sampling
- `stop` (ChatCompletionRequestStop, optional) — Stop sequences
- `tools` (list of ChatCompletionRequestToolsItems, optional) — Danh sách tools cho function calling
- `response_format` (ChatCompletionRequestResponseFormat, optional) — Format response (JSON mode)

## Response

### 200

Thành công

- `id` (string, optional)
- `object` (string, optional)
- `choices` (list of ChatCompletionResponseChoicesItems, optional)
- `usage` (Usage, optional)

## Errors

### 400 Bad Request Error

Request không hợp lệ

- `error` (ErrorResponseError, optional)

### 401 Unauthorized Error

API key không hợp lệ hoặc thiếu

- `error` (ErrorResponseError, optional)

### 403 Forbidden Error

Vượt budget hoặc model không được phép

- `error` (ErrorResponseError, optional)

### 429 Too Many Requests Error

Rate limit exceeded

- `error` (ErrorResponseError, optional)

## Types

### ChatMessage

- `role` (enum, required) — Vai trò của message
  - Allowed values: `system`, `user`, `assistant`, `tool`
- `content` (string, required) — Nội dung message

### ChatCompletionRequestStop

Stop sequences

- string
- list of string

### ChatCompletionRequestToolsItems

### ChatCompletionRequestResponseFormat

Format response (JSON mode)

### ChatCompletionResponseChoicesItems

- `index` (integer, optional)
- `message` (ChatMessage, optional)
- `finish_reason` (string, optional)

### Usage

- `prompt_tokens` (integer, optional)
- `completion_tokens` (integer, optional)
- `total_tokens` (integer, optional)

### ErrorResponseError

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

## Examples

**Request**

```json
{
  "model": "gemini-3.5-flash",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}
```

**SDK Code**

```python
import requests

url = "https://api.tramlabs.io/v1/chat/completions"

payload = {
    "model": "gemini-3.5-flash",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "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://api.tramlabs.io/v1/chat/completions';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"gemini-3.5-flash","messages":[{"role":"system","content":"You are a helpful assistant."},{"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://api.tramlabs.io/v1/chat/completions"

	payload := strings.NewReader("{\n  \"model\": \"gemini-3.5-flash\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a helpful assistant.\"\n    },\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://api.tramlabs.io/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\": \"gemini-3.5-flash\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a helpful assistant.\"\n    },\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://api.tramlabs.io/v1/chat/completions")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"gemini-3.5-flash\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a helpful assistant.\"\n    },\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://api.tramlabs.io/v1/chat/completions', [
  'body' => '{
  "model": "gemini-3.5-flash",
  "messages": [
    {
      "role": "system",
      "content": "You are a helpful assistant."
    },
    {
      "role": "user",
      "content": "Hello!"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

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

```csharp
using RestSharp;

var client = new RestClient("https://api.tramlabs.io/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\": \"gemini-3.5-flash\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"You are a helpful assistant.\"\n    },\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": "gemini-3.5-flash",
  "messages": [
    [
      "role": "system",
      "content": "You are a helpful assistant."
    ],
    [
      "role": "user",
      "content": "Hello!"
    ]
  ]
] as [String : Any]

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

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