> For the complete documentation index, see [llms.txt](https://docs.avis.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.avis.net/vi/huong-dan/get-started/first-api-call.md).

# Thực hiện lệnh gọi API đầu tiên

Hướng dẫn này giúp bạn đi từ chưa có tài khoản đến API request hoạt động được trong khoảng năm phút. Bạn sẽ đăng nhập, nạp credit, tạo API key, chọn mô hình và gửi một HTTP request thông thường. Không cần SDK.

***

## Trước khi bắt đầu

Bạn sẽ cần:

* Một tài khoản Google, hoặc một địa chỉ email có thể nhận mã xác minh
* Phương thức thanh toán qua **MoMo** hoặc **VNPAY** (để nạp credit)
* Một terminal có `curl`, **hoặc** Python 3 với `requests`, **hoặc** Node.js 18+

***

## Bước 1: Đăng nhập

Truy cập [avis.net](https://www.avis.net) và nhấn **Login**. Đăng nhập bằng Google hoặc bằng mã email dùng một lần. Nếu đây là lần đăng nhập đầu tiên, tài khoản của bạn sẽ được tạo tự động.

Xem [Cách đăng nhập/ đăng ký](/vi/huong-dan/get-started/avis-login-signup.md) để có hướng dẫn đầy đủ.

***

## Bước 2: Nạp credit

Request được thanh toán từ số dư credit trả trước. Nếu số dư là 0, API sẽ trả về **403 Forbidden**.

Nhấn **Top Up** trên thanh trên cùng, chọn MoMo hoặc VNPAY, nhập số tiền rồi thanh toán. Một khoản nhỏ là đủ để thử nghiệm.

Xem [Cách nạp tiền vào số dư](/vi/huong-dan/get-started/avis-topup.md).

***

## Bước 3: Tạo API key

Trên thanh bên của Console, mở **API Key** và nhấn **Create New API Keys**. Đặt tên cho key, chẳng hạn `local-testing`, rồi thiết lập **giới hạn chi tiêu hằng ngày** thấp trong khi thử nghiệm. Sao chép key ngay khi nó hiển thị, vì sau đó bạn không thể xem lại.

Lưu key vào biến môi trường để key không bao giờ xuất hiện trong code:

```bash
# macOS / Linux
export AVIS_API_KEY="paste-your-key-here"

# Windows (PowerShell)
$env:AVIS_API_KEY="paste-your-key-here"
```

Xem [Cách lấy API Key](/vi/huong-dan/get-started/avis-api-key.md).

***

## Bước 4: Chọn mô hình

Mở **Models** trên thanh bên của Console và tìm mô hình bạn muốn. Sao chép chính xác **Model ID** như hiển thị. Bạn sẽ truyền giá trị này vào `model` trong request.

**Mẹo:** Nếu chưa chắc nên chọn mô hình nào, hãy thử vài mô hình trong [Playground](https://github.com/coin98/documentation/tree/docs_avis_vi/guide/get-started/playground.md) trước. Không cần viết code, và bạn chỉ trả tiền cho những gì bạn tạo ra.

***

## Bước 5: Gửi request đầu tiên

Mọi request AVIS đều là HTTPS `POST` thông thường với body JSON. Bạn không cần cài SDK. Gửi key trong header `Authorization` và đặt Model ID đã sao chép ở Bước 4 vào `model`.

{% tabs %}
{% tab title="cURL" %}

```bash
curl https://api.avis.net/api/openai/v1/chat/completions \
  -H "Authorization: Bearer $AVIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-4.1-mini",
    "messages": [{"role": "user", "content": "Say hello in Vietnamese."}]
  }'
```

**Lưu ý:** Lệnh này được viết cho macOS, Linux và Git Bash. Trên Windows PowerShell, hãy dùng tab Python hoặc JavaScript.
{% endtab %}

{% tab title="Python" %}

```python
import os
import requests

response = requests.post(
    "https://api.avis.net/api/openai/v1/chat/completions",
    headers={"Authorization": f"Bearer {os.environ['AVIS_API_KEY']}"},
    json={
        "model": "openai/gpt-4.1-mini",  # thay bằng Model ID từ trang Models
        "messages": [{"role": "user", "content": "Say hello in Vietnamese."}],
    },
)
response.raise_for_status()

print(response.json()["choices"][0]["message"]["content"])
```

Nếu bạn thấy `ModuleNotFoundError: No module named 'requests'`, hãy chạy `pip install requests`.
{% endtab %}

{% tab title="JavaScript" %}
Lưu đoạn code này thành `hello.mjs` và chạy `node hello.mjs`. Node.js 18+ đã có sẵn `fetch`, nên không cần cài đặt gì thêm.

```javascript
const response = await fetch('https://api.avis.net/api/openai/v1/chat/completions', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${process.env.AVIS_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'openai/gpt-4.1-mini', // thay bằng Model ID từ trang Models
    messages: [{ role: 'user', content: 'Say hello in Vietnamese.' }],
  }),
})

if (!response.ok) throw new Error(`${response.status}: ${await response.text()}`)

const data = await response.json()
console.log(data.choices[0].message.content)
```

{% endtab %}
{% endtabs %}

**Mẹo:** Endpoint này hoạt động với **mọi** mô hình trong danh mục, không chỉ các mô hình OpenAI. Để thử Claude hoặc Gemini, bạn chỉ cần đổi giá trị `model`, ví dụ `anthropic/claude-sonnet-4-5`.

Nếu nhận được phản hồi, tức là thiết lập của bạn đã hoạt động.

***

## Bước 6: Kiểm tra chi phí

Mở **Dashboard** trên thanh bên của Console. Request của bạn xuất hiện trong **Total requests**, và chi phí xuất hiện trong **Total cost**, được chia theo từng mô hình. Dashboard tự động làm mới mỗi 30 phút, vì vậy một request vừa gửi có thể cần một lúc mới hiển thị.

Để kiểm tra mức sử dụng bằng code, hãy gọi `GET /api/compat/v1/usage`. Xem [Mức sử dụng](/vi/tai-lieu-api/introduction/use.md).

***

## Bạn đã dùng SDK?

Nếu ứng dụng của bạn đã dùng SDK chính thức của OpenAI, Anthropic hoặc Gemini, bạn không cần viết lại code. Chỉ cần đổi **API key** và **base URL**, phần còn lại giữ nguyên.

{% tabs %}
{% tab title="OpenAI SDK" %}

```typescript
const client = new OpenAI({
  apiKey: process.env.AVIS_API_KEY,
  baseURL: 'https://api.avis.net/api/openai/v1',
})
```

```python
client = OpenAI(
    api_key=os.environ["AVIS_API_KEY"],
    base_url="https://api.avis.net/api/openai/v1",
)
```

{% endtab %}

{% tab title="Anthropic SDK" %}

```typescript
const client = new Anthropic({
  apiKey: process.env.AVIS_API_KEY,
  baseURL: 'https://api.avis.net/api/anthropic',
})
```

{% endtab %}

{% tab title="Gemini SDK" %}

```typescript
const ai = new GoogleGenAI({
  apiKey: process.env.AVIS_API_KEY,
  httpOptions: { baseUrl: 'https://api.avis.net/api/gemini' },
})
```

**Lưu ý:** Không thêm `/v1beta` vào base URL. Gemini SDK sẽ tự thêm cho bạn.
{% endtab %}
{% endtabs %}

Chi tiết đầy đủ: [Tương thích OpenAI](/vi/tai-lieu-api/introduction/openai-compatibility.md), [Tương thích Anthropic](/vi/tai-lieu-api/introduction/anthropic-compatibility.md), [Tương thích Gemini](/vi/tai-lieu-api/introduction/gemini-compatibility.md).

***

## Khắc phục sự cố

| Lỗi                       | Ý nghĩa                                           | Cách xử lý                                                                                                       |
| ------------------------- | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| **401 Unauthorized**      | Key bị thiếu, gõ sai hoặc đã bị xóa               | Đảm bảo `AVIS_API_KEY` được đặt trong cùng terminal mà bạn chạy code, và header là `Authorization: Bearer <key>` |
| **400 Bad Request**       | Model ID sai hoặc body request không hợp lệ       | Sao chép lại model ID từ trang **Models** và kiểm tra JSON có hợp lệ không                                       |
| **403 Forbidden**         | Số dư credit bằng 0 hoặc âm                       | Nạp thêm tiền vào số dư                                                                                          |
| **429 Too Many Requests** | Key này đã chạm một trong các giới hạn chi tiêu   | Tăng giới hạn trên trang **API Key**, hoặc chờ đến khi chu kỳ ngày/tuần/tháng được đặt lại                       |
| **502 / 503**             | Nhà cung cấp mô hình phía upstream đang gặp sự cố | Thử lại sau một lúc, hoặc chuyển sang mô hình khác                                                               |

Xem [Lỗi](/vi/tai-lieu-api/introduction/errors.md) để có danh sách đầy đủ.

***

## Tiếp theo

* Tạo hình ảnh, video hoặc âm thanh, xem [Endpoints](https://github.com/coin98/documentation/tree/docs_avis_vi/api-reference/endpoints.md).
* Stream phản hồi theo từng token, xem [Streaming](/vi/tai-lieu-api/introduction/streaming.md).
* Dùng AVIS trong Claude Code, Codex CLI hoặc trình soạn thảo của bạn, xem [Tích hợp](/vi/tich-hop/overview.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.avis.net/vi/huong-dan/get-started/first-api-call.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
