> 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/tai-lieu-api/introduction/gemini-compatibility.md).

# Tương thích Gemini

Trỏ SDK `@google/genai` chính thức hoặc client `fetch`/`curl` dùng Gemini REST API đến Avis. Đặt Avis API key trong `apiKey` (xem phần Xác thực).

### Base URL

```
https://api.avis.net/api/gemini
```

> SDK `@google/genai` tự động thêm `/v1beta` vào `baseUrl`. Hãy truyền `https://api.avis.net/api/gemini`, **không phải** `.../api/gemini/v1beta`, để tránh lặp phần đường dẫn này.

### Chuyển đổi một ứng dụng hiện có

```typescript
import { GoogleGenAI } from '@google/genai'

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

### Endpoints

| Method | Path                                                      | Streaming | Mô tả                                                     |
| ------ | --------------------------------------------------------- | --------- | --------------------------------------------------------- |
| `HEAD` | `/api/gemini`                                             | —         | Kiểm tra kết nối (không cần xác thực)                     |
| `GET`  | `/api/gemini/v1beta/models`                               | —         | Liệt kê các mô hình khả dụng                              |
| `POST` | `/api/gemini/v1beta/models/{model}:generateContent`       | —         | Tạo nội dung                                              |
| `POST` | `/api/gemini/v1beta/models/{model}:streamGenerateContent` | ✅         | Tạo nội dung, dạng stream                                 |
| `POST` | `/api/gemini/v1beta/models/{model}:embedContent`          | —         | Embed một nội dung; trả về một `embedding` (số ít)        |
| `POST` | `/api/gemini/v1beta/models/{model}:batchEmbedContents`    | —         | Embed nhiều nội dung; trả về mảng `embeddings` (số nhiều) |

#### `GET /v1beta/models`

```typescript
const models = await fetch('https://api.avis.net/api/gemini/v1beta/models', {
  headers: {
    Authorization: `Bearer ${process.env.AVIS_API_KEY}`,
  },
}).then((r) => r.json())

console.log(models.data[0])
```

#### `POST /models/{model}:generateContent`

```typescript
const response = await ai.models.generateContent({
  model: 'gemini-2.0-flash',
  contents: 'Explain quantum entanglement in one sentence.',
})
console.log(response.text)
```

```json
{
  "candidates": [
    {
      "content": { "parts": [{ "text": "Hello! How can I help you today?" }], "role": "model" },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": { "promptTokenCount": 2, "candidatesTokenCount": 10 }
}
```

#### `candidates[].finishReason`

`finishReason` cho biết vì sao một candidate ngừng tạo nội dung.

Các giá trị phổ biến:

| Giá trị                     | Ý nghĩa                                               |
| --------------------------- | ----------------------------------------------------- |
| `STOP`                      | Dừng tự nhiên / hoàn tất bình thường                  |
| `MAX_TOKENS`                | Đã chạm giới hạn token                                |
| `SAFETY`                    | Bị hệ thống an toàn dừng lại                          |
| `RECITATION`                | Dừng do chính sách về trích dẫn lại nội dung          |
| `LANGUAGE`                  | Dừng do ngôn ngữ không được hỗ trợ/không được phép    |
| `BLOCKLIST`                 | Bị chặn bởi quy tắc danh sách chặn                    |
| `PROHIBITED_CONTENT`        | Bị chặn bởi chính sách nội dung bị cấm                |
| `SPII`                      | Bị chặn do xử lý thông tin nhận dạng cá nhân nhạy cảm |
| `MALFORMED_FUNCTION_CALL`   | Dừng vì đầu ra function/tool call bị sai định dạng    |
| `OTHER`                     | Lý do dừng khác                                       |
| `FINISH_REASON_UNSPECIFIED` | Không có lý do dừng cụ thể                            |

Ghi chú:

* Giá trị được chuyển tiếp nguyên vẹn như upstream trả về.
* Danh sách enum đầy đủ và cập nhật mới nhất: <https://ai.google.dev/api/generate-content#FinishReason>

#### `POST /models/{model}:streamGenerateContent`

```typescript
const stream = await ai.models.generateContentStream({
  model: 'gemini-2.0-flash',
  contents: 'Explain quantum entanglement in one sentence.',
})

for await (const chunk of stream) {
  process.stdout.write(chunk.text ?? '')
}
```

#### `POST /models/{model}:embedContent`

```typescript
const response = await ai.models.embedContent({
  model: 'gemini-embedding-2',
  contents: { parts: [{ text: 'The quick brown fox jumps over the lazy dog.' }] },
})
console.log(response.embedding.values)
```

Với các mô hình embedding thông thường, chỉ văn bản và `outputDimensionality` được áp dụng; `taskType` và `title` sẽ bị từ chối. `gemini-embedding-2` và `gemini-embedding-2-preview` còn nhận content part hình ảnh, âm thanh, PDF và video:

```typescript
import { readFileSync } from 'node:fs'

const response = await ai.models.embedContent({
  model: 'gemini-embedding-2',
  contents: {
    parts: [
      { text: 'What is in this image?' },
      {
        inlineData: {
          mimeType: 'image/png',
          data: readFileSync('image.png').toString('base64'),
        },
      },
    ],
  },
})
console.log(response.embedding.values)
```

Đầu vào hình ảnh không chỉ được hỗ trợ trên Gemini: `voyage-multimodal-3-5` và `llama-nemotron-embed-vl-1b-v2` cũng nhận theo cùng cấu trúc này. `gemini-embedding-2` và `gemini-embedding-2-preview` cho phép tối đa 6 hình ảnh mỗi request.

Âm thanh chỉ dành riêng cho Gemini (chỉ `gemini-embedding-2`/`-preview`), giới hạn một part mỗi request, chỉ `audio/wav`, tối đa 180 giây:

```typescript
const response = await ai.models.embedContent({
  model: 'gemini-embedding-2',
  contents: {
    parts: [
      { text: 'Transcribe the sentiment of this clip.' },
      {
        inlineData: {
          mimeType: 'audio/wav',
          data: readFileSync('clip.wav').toString('base64'),
        },
      },
    ],
  },
})
console.log(response.embedding.values)
```

Video cũng chỉ dành riêng cho Gemini, giới hạn một part mỗi request, chỉ MP4/MOV, tối đa 120 giây:

```typescript
const response = await ai.models.embedContent({
  model: 'gemini-embedding-2',
  contents: {
    parts: [
      { text: 'Describe the action in this clip.' },
      {
        inlineData: {
          mimeType: 'video/mp4',
          data: readFileSync('clip.mp4').toString('base64'),
        },
      },
    ],
  },
})
console.log(response.embedding.values)
```

Với âm thanh và video, không hỗ trợ tham chiếu `fileData`/`fileUri` (URL); chỉ chấp nhận dữ liệu base64 nhúng trực tiếp. Gửi âm thanh hoặc video đến mô hình embedding khác sẽ trả về `400`.

#### `POST /models/{model}:batchEmbedContents`

```typescript
const response = await ai.models.batchEmbedContents({
  model: 'gemini-embedding-2',
  requests: [
    { content: { parts: [{ text: 'first document' }] } },
    { content: { parts: [{ text: 'second document' }] } },
  ],
})
console.log(response.embeddings.map((e) => e.values))
```

Tất cả request trong cùng một lô phải dùng chung `outputDimensionality`.

### Hỗ trợ các trường

Proxy này hoạt động như một **lớp chuyển tiếp mỏng**. Các trường request chủ yếu tuân theo định nghĩa upstream gốc của Gemini và được chuyển tiếp nguyên vẹn. Việc một trường có được áp dụng hay không phụ thuộc vào nhà cung cấp và mô hình được chọn.

### Response của `/v1beta/models`

| Trường                                  | Kiểu            | Bắt buộc | Ghi chú                                                                                                                                                              |
| --------------------------------------- | --------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                                    | `string`        | ✅        | ID trong danh mục nhà cung cấp, ví dụ `google/gemini-2.0-flash`. Với lệnh gọi theo đường dẫn Gemini, dùng tên gốc sau dấu gạch chéo.                                 |
| `name`                                  | `string`        | —        | Tên mô hình dễ đọc                                                                                                                                                   |
| `inputModalities`                       | `array<string>` | —        | Các loại dữ liệu đầu vào được mô hình hỗ trợ                                                                                                                         |
| `outputModalities`                      | `array<string>` | —        | Các loại dữ liệu đầu ra được mô hình hỗ trợ                                                                                                                          |
| `capabilitiesProviderId`                | `string`        | —        | Bản ghi nhà cung cấp được chọn theo độ ưu tiên để xác định khả năng                                                                                                  |
| `capabilities`                          | `object`        | —        | Đối tượng khả năng thực tế của bản ghi nhà cung cấp có độ ưu tiên cao nhất. Nếu không có nghĩa là không bị ràng buộc.                                                |
| `capabilities.text.supportedParameters` | `array<string>` | —        | Với mô hình văn bản: các tham số tạo nội dung được chấp nhận (ví dụ `maxTokens`, `temperature`, `topP`, `tools`, `thinking`).                                        |
| `capabilities.params`                   | `object`        | —        | Giới hạn/ràng buộc của từng tham số, theo tên trường trong request. Với mô hình hình ảnh/video, đọc từ `capabilities.image.params` hoặc `capabilities.video.params`. |
| `capabilities.inputs`                   | `object`        | —        | Các đầu vào dạng content-part được chấp nhận (vai trò, loại media, giới hạn).                                                                                        |
| `capabilities.strictParams`             | `boolean`       | —        | Khi là `true`, các tham số có kiểm soát mà không được hỗ trợ sẽ bị từ chối.                                                                                          |
| `chatPricing`                           | `object`        | —        | Metadata giá chat thực tế của bản ghi nhà cung cấp được chọn                                                                                                         |
| `imagePricing`                          | `object`        | —        | Metadata giá hình ảnh thực tế của bản ghi nhà cung cấp được chọn                                                                                                     |
| `videoPricing`                          | `object`        | —        | Metadata giá video thực tế của bản ghi nhà cung cấp được chọn                                                                                                        |
| `threeDPricing`                         | `object`        | —        | Metadata giá 3D thực tế của bản ghi nhà cung cấp được chọn                                                                                                           |
| `embeddingPricing`                      | `object`        | —        | Metadata giá embedding thực tế của bản ghi nhà cung cấp được chọn                                                                                                    |

#### Cấu trúc giá trị của `capabilities.params`

Với các mô hình hình ảnh/video, hãy dùng `capabilities.image.params` hoặc `capabilities.video.params` của từng mô hình thay vì cố định các giới hạn dùng chung cho mọi mô hình.

| `type`  | Trường bổ sung                                        | Ý nghĩa                                                                                        |
| ------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `enum`  | `values: string[]`, `default?`                        | Giá trị phải là một trong các `values`.                                                        |
| `range` | `min`, `max`, `default?`, `unit?`, `steps?: number[]` | Giá trị phải nằm giữa `min` và `max`. Khi có `steps`, chỉ các giá trị chính xác đó mới hợp lệ. |
| `int`   | `min`, `max`, `default?`                              | Giá trị phải là một số nguyên nằm giữa `min` và `max`.                                         |
| `bool`  | `default?`                                            | Giá trị phải là `true` hoặc `false`.                                                           |

### `/v1beta/models/{model}:generateContent`

| Trường              | Kiểu               | Bắt buộc | Ghi chú                                                                                                                                                 |
| ------------------- | ------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model` (path)      | `string`           | ✅        | Model ID gốc của Gemini trong đường dẫn, ví dụ `gemini-2.0-flash`                                                                                       |
| `contents`          | `array \| string`  | ✅        | Nội dung prompt/tin nhắn                                                                                                                                |
| `generationConfig`  | `object`           | —        | Tùy chọn tạo nội dung (ví dụ `temperature`, `topP`, `topK`, `maxOutputTokens`, `stopSequences`, `responseMimeType`, `responseSchema`, `thinkingConfig`) |
| `systemInstruction` | `object \| string` | —        | Khối chỉ dẫn hệ thống                                                                                                                                   |
| `safetySettings`    | `array`            | —        | Cấu hình chính sách an toàn                                                                                                                             |
| `tools`             | `array`            | —        | Định nghĩa tool/function calling                                                                                                                        |
| `toolConfig`        | `object`           | —        | Cấu hình hành vi của tool                                                                                                                               |
| `cachedContent`     | `string`           | —        | Tham chiếu tới prompt/nội dung đã được cache                                                                                                            |

### `/v1beta/models/{model}:streamGenerateContent`

| Trường         | Kiểu                | Bắt buộc | Ghi chú                                                           |
| -------------- | ------------------- | -------- | ----------------------------------------------------------------- |
| `model` (path) | `string`            | ✅        | Model ID gốc của Gemini trong đường dẫn, ví dụ `gemini-2.0-flash` |
| Body request   | `object`            | ✅        | Cùng schema request như `:generateContent`                        |
| Kiểu response  | `text/event-stream` | ✅        | Các chunk response dạng stream từ upstream                        |

### `/v1beta/models/{model}:embedContent`

| Trường                        | Kiểu      | Bắt buộc | Ghi chú                                                                                                                                                                                             |
| ----------------------------- | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model` (path)                | `string`  | ✅        | Model ID có khả năng tạo embedding, ví dụ `gemini-embedding-2`                                                                                                                                      |
| `contents`                    | `object`  | ✅        | `{ parts: [...] }`. Các part có thể là `{ text }` hoặc `{ inlineData: { mimeType, data } }`. Hình ảnh được nhiều mô hình chấp nhận; âm thanh/PDF/video chỉ dành cho `gemini-embedding-2`/`-preview` |
| `config.outputDimensionality` | `integer` | —        | Số chiều của vector đầu ra                                                                                                                                                                          |
| `config.taskType`             | —         | —        | Bị từ chối — không được áp dụng trong embedding đã chuẩn hóa                                                                                                                                        |
| `config.title`                | —         | —        | Bị từ chối — không được áp dụng trong embedding đã chuẩn hóa                                                                                                                                        |

Response: `{ embedding: { values: number[] } }`.

### `/v1beta/models/{model}:batchEmbedContents`

| Trường         | Kiểu     | Bắt buộc | Ghi chú                                                      |
| -------------- | -------- | -------- | ------------------------------------------------------------ |
| `model` (path) | `string` | ✅        | Model ID có khả năng tạo embedding                           |
| `requests`     | `array`  | ✅        | Mảng không rỗng gồm các `{ content: { parts: [...] }, ... }` |

Response: `{ embeddings: [{ values: number[] }, ...] }`, theo thứ tự của request.


---

# 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/tai-lieu-api/introduction/gemini-compatibility.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.
