# Bắt đầu nhanh

> Tạo hình ảnh đầu tiên và lưu vào tệp: đăng nhập, tạo khóa, gửi tác vụ, kiểm tra trạng thái tác vụ định kỳ, tải kết quả xuống.

Khi hoàn thành các bước trên trang này, bạn sẽ có một tệp PNG trên máy, được tạo bằng một lệnh gọi API. Bạn cần một địa chỉ email, số dư lớn hơn 0 và `curl` cùng [`jq`](https://jqlang.org) (hoặc Python 3 với `requests`, hoặc Node.js 18+). Nếu tài khoản đã có tiền, quá trình này mất khoảng hai phút.

Mỗi trang dưới đây hướng dẫn cách gửi một yêu cầu cho nhóm mô hình tương ứng: [API Seedance](https://kerox.ai/vi/seedance-api), [API Kling](https://kerox.ai/vi/kling-api), [API tạo ảnh bằng AI](https://kerox.ai/vi/ai-image-generator-api), [API chuyển văn bản thành video](https://kerox.ai/vi/text-to-video-api) và [API chuyển ảnh thành video](https://kerox.ai/vi/image-to-video-api).

<a id="key"></a>

## Lấy khóa và nạp tiền
1. Đăng nhập vào [Console](https://kerox.ai/vi/console/api-keys) bằng mã 6 chữ số mà chúng tôi gửi qua email. Lần đăng nhập đầu tiên sẽ tạo tài khoản.
2. Mở **API** → **Khóa API** và tạo một khóa. Khóa đầy đủ chỉ hiển thị một lần khi bạn tạo: hãy sao chép ngay lúc đó.
3. Mở **Ví** và kiểm tra số dư khả dụng. Để thêm tiền, hãy nạp tại đó bằng thẻ hoặc Alipay: [Nạp tiền](https://kerox.ai/vi/docs/pricing-billing.md#topups). Tác vụ sẽ bị từ chối với HTTP `402` khi số dư không đủ cho chi phí ước tính.

Đặt khóa vào một biến môi trường. Mọi yêu cầu đều gửi khóa dưới dạng `Authorization: Bearer <your-api-key>`; hãy giữ khóa trên máy chủ, tuyệt đối không đưa vào ứng dụng chạy trên trình duyệt. Xoay vòng khóa và giới hạn tùy chọn: [Khóa API](https://kerox.ai/vi/docs/authentication.md).


```bash
export KEROX_API_KEY="kx_live_your_api_key_here"
```


<a id="submit"></a>

## Gửi, kiểm tra trạng thái, tải xuống
Một script thực hiện toàn bộ quy trình: `POST /v1/tasks` trả về HTTP `201` kèm `id` và `status: "processing"` của tác vụ; script gọi `GET /v1/tasks/{id}` 3 giây một lần để kiểm tra trạng thái cho đến khi `status` là `succeeded` hoặc `failed`, sau đó lưu tệp hoặc in ra lý do thất bại. Sau 10 phút, client sẽ ngừng chờ. Hãy giữ lại ID tác vụ đã in ra và kiểm tra lại trạng thái sau. Hết thời gian chờ phía máy chủ sẽ hiển thị là `failed` với `error.code: "timeout"`. Chỉ gửi yêu cầu thay thế sau khi đã xác nhận thất bại ([Hết thời gian chờ](https://kerox.ai/vi/docs/tasks.md#retention)).


```bash
# Needs curl and jq. KEROX_API_KEY is your key.
set -euo pipefail
API=https://api.kerox.ai/v1
AUTH="Authorization: Bearer $KEROX_API_KEY"
BODY='{
  "model": "bytedance/seedream-5.5",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "resolution": "2K"
  }
}'

# 1. Submit: HTTP 201 with the task's id.
TASK_ID=$(curl -sS --fail-with-body -X POST "$API/tasks" \
  -H "$AUTH" -H "Content-Type: application/json" -d "$BODY" | jq -r .id)
echo "Submitted $TASK_ID"

# 2. Poll every 3 seconds, for up to 10 minutes.
DEADLINE=$(( $(date +%s) + 600 ))
STATUS=processing
while [ "$STATUS" = "processing" ] && [ "$(date +%s)" -lt "$DEADLINE" ]; do
  sleep 3
  REM=$(( DEADLINE - $(date +%s) ))
  [ "$REM" -le 0 ] && break
  [ "$REM" -gt 30 ] && REM=30
  TASK=$(curl -sS --fail-with-body --max-time "$REM" "$API/tasks/$TASK_ID" -H "$AUTH")
  STATUS=$(echo "$TASK" | jq -r .status)
done

# 3. Save the file, or show why it failed.
if [ "$STATUS" = "processing" ]; then
  echo "Still running: TASK_ID=$TASK_ID, read it later with GET /v1/tasks/{id}"
  exit 1
elif [ "$STATUS" != "succeeded" ]; then
  echo "Task $TASK_ID is $STATUS: $(echo "$TASK" | jq -c .error)"
  exit 1
fi
curl -sS --fail-with-body -o result.png "$(echo "$TASK" | jq -r '.outputs[0].url')"
echo "Saved result.png"
```
```python
# pip install requests
import os
import time
import requests

API = "https://api.kerox.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['KEROX_API_KEY']}"}

# 1. Submit: HTTP 201 with the task's id.
resp = requests.post(
    f"{API}/tasks",
    headers=HEADERS,
    json={
        "model": "bytedance/seedream-5.5",
        "input": {
            "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
            "resolution": "2K",
        },
    },
    timeout=60,
)
if resp.status_code != 201:
    raise SystemExit(f"HTTP {resp.status_code}: {resp.json()['error']}")
task = resp.json()
print("Submitted", task["id"])

# 2. Poll every 3 seconds, for up to 10 minutes.
deadline = time.time() + 600
while task["status"] == "processing" and time.time() < deadline:
    time.sleep(3)
    remaining = max(1, min(30, deadline - time.time()))
    poll = requests.get(f"{API}/tasks/{task['id']}", headers=HEADERS, timeout=remaining)
    poll.raise_for_status()
    task = poll.json()

# 3. Save the file, or show why it failed.
if task["status"] == "processing":
    raise SystemExit(f"Still running: task {task['id']}, read it again later")
if task["status"] != "succeeded":
    raise SystemExit(f"Task {task['id']} is {task['status']}: {task['error']}")
file = requests.get(task["outputs"][0]["url"], timeout=60)
file.raise_for_status()
with open("result.png", "wb") as fh:
    fh.write(file.content)
print("Saved result.png")
```
```javascript
// Node.js 18 or later: fetch is built in.
import fs from 'node:fs/promises';

const API = 'https://api.kerox.ai/v1';
const headers = { Authorization: `Bearer ${process.env.KEROX_API_KEY}` };

// 1. Submit: HTTP 201 with the task's id.
const res = await fetch(`${API}/tasks`, {
  method: 'POST',
  headers: { ...headers, 'Content-Type': 'application/json' },
  body: JSON.stringify({
    model: 'bytedance/seedream-5.5',
    input: {
      prompt: 'editorial portrait of a ceramicist in morning sunlight, 35mm film',
      resolution: '2K',
    },
  }),
});
let task = await res.json();
if (res.status !== 201) throw new Error(`HTTP ${res.status}: ${task.error.message}`);
console.log('Submitted', task.id);

// 2. Poll every 3 seconds, for up to 10 minutes.
const deadline = Date.now() + 10 * 60 * 1000;
while (task.status === 'processing' && Date.now() < deadline) {
  await new Promise((resolve) => setTimeout(resolve, 3000));
  const poll = await fetch(`${API}/tasks/${task.id}`, {
    headers,
    signal: AbortSignal.timeout(Math.max(1000, Math.min(30_000, deadline - Date.now()))),
  });
  if (!poll.ok) throw new Error(`HTTP ${poll.status}`);
  task = await poll.json();
}

// 3. Save the file, or show why it failed.
if (task.status === 'processing') {
  throw new Error(`Still running: task ${task.id}, read it later with GET /v1/tasks/{id}`);
}
if (task.status !== 'succeeded') {
  throw new Error(`Task ${task.id} is ${task.status}: ${JSON.stringify(task.error)}`);
}
const file = await fetch(task.outputs[0].url);
if (!file.ok) throw new Error(`Download failed: HTTP ${file.status}`);
await fs.writeFile('result.png', Buffer.from(await file.arrayBuffer()));
console.log('Saved result.png');
```


Nếu yêu cầu gửi tác vụ trả về bất kỳ mã nào khác `201`, nội dung phản hồi là một đối tượng lỗi: ý nghĩa của từng mã và cách xử lý có trong [Lỗi](https://kerox.ai/vi/docs/errors.md#next-steps).

> **Lưu kết quả trong vòng 7 ngày**
>
> Các tệp được tạo sẽ không còn sử dụng được sau 7 ngày kể từ khi tác vụ hoàn tất (`expires_at`). Hãy lưu mọi thứ bạn cần vào kho lưu trữ của riêng bạn ([Thời gian lưu trữ](https://kerox.ai/vi/docs/tasks.md#retention)).

<a id="webhook"></a>

### Không muốn kiểm tra trạng thái liên tục? Hãy truyền `webhook_url`
Yêu cầu mặc định bên dưới kiểm tra trạng thái tác vụ định kỳ. Để nhận callback, hãy chỉ định endpoint nhận HTTPS công khai của riêng bạn khi gửi tác vụ và giữ lại ID tác vụ để có thể tự kiểm tra trạng thái nếu callback đến chậm. Xem [Webhook](https://kerox.ai/vi/docs/webhooks.md).


```json
{
  "model": "bytedance/seedream-5.5",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "resolution": "2K"
  }
}
```


<a id="result"></a>

## Đọc kết quả
Tác vụ mà script đọc ở cuối có dạng như sau. Khi `succeeded`, các tệp nằm trong `outputs`, mỗi mục một tệp, mỗi tệp kèm `type` và `url`; `cost` là số tiền đã quyết toán tính bằng USD (giá: [Mô hình](https://kerox.ai/vi/docs/models.md)). Khi `failed`, lý do nằm trong `error` và khoản tạm giữ được hoàn lại. `input` cho biết hệ thống đã chuyển yêu cầu của bạn sang những tham số riêng nào của mô hình (ở đây `resolution` trở thành `size`). Mọi trường: [Đối tượng tác vụ](https://kerox.ai/vi/docs/tasks.md#submit-response).


```json
{
  "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
  "object": "task",
  "model": "bytedance/seedream-5.5",
  "status": "succeeded",
  "source": "api",
  "format": "unified",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "size": "2K"
  },
  "outputs": [
    {
      "type": "image",
      "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
      "content_type": "image/png",
      "width": 2048,
      "height": 2048
    }
  ],
  "outputs_deleted": false,
  "error": null,
  "cost": {
    "amount": "0.0280",
    "currency": "USD",
    "status": "settled"
  },
  "metadata": null,
  "warnings": [],
  "created_at": "2026-11-20T08:01:02Z",
  "started_at": "2026-11-20T08:01:02Z",
  "completed_at": "2026-11-20T08:01:10Z",
  "expires_at": "2026-11-27T08:01:10Z"
}
```


<a id="next"></a>

## Bước tiếp theo
- [Webhook](https://kerox.ai/vi/docs/webhooks.md): Hệ thống tự động gửi tác vụ đến máy chủ của bạn khi tác vụ hoàn tất.
- [Tệp &amp; đầu vào](https://kerox.ai/vi/docs/files.md): Tải lên ảnh tham chiếu và dùng ảnh đó trong một tác vụ.
- [Máy chủ MCP](https://kerox.ai/vi/docs/mcp.md): Cho phép Claude Code hoặc Cursor gọi Kerox.
