> 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/streaming.md).

# Streaming

Streaming là tùy chọn và được triển khai khác nhau tùy giao diện. Với OpenAI và Anthropic, bạn bật hoặc tắt streaming bằng một trường trong body request; Gemini dùng URL riêng.

### Bật / tắt streaming

| Giao diện                                 | Cách stream                                                                                                                                                                                 | Cách nhận một response JSON duy nhất |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| OpenAI (`chat/completions`, `/responses`) | `"stream": true` trong body của request                                                                                                                                                     | `"stream": false` (mặc định)         |
| OpenAI (`images/generations`)             | `"stream": true` — chỉ có hiệu lực khi nhà cung cấp của mô hình được chọn hỗ trợ stream sự kiện hình ảnh; nếu không, request vẫn hoàn tất nhưng trả về dưới dạng một response JSON duy nhất | `"stream": false` (mặc định)         |
| OpenAI (`videos`)                         | Không áp dụng — tạo video luôn là bất đồng bộ (gửi + poll), xem Tương thích OpenAI                                                                                                          | n/a                                  |
| Anthropic (`messages`)                    | `"stream": true` trong body của request                                                                                                                                                     | `"stream": false` (mặc định)         |
| Gemini                                    | Gọi `models/{model}:streamGenerateContent` thay vì `models/{model}:generateContent`                                                                                                         | Gọi `:generateContent`               |

Mọi response dạng stream đều có các header `Content-Type: text/event-stream`, `Cache-Control: no-cache, no-transform` và `Connection: keep-alive`.

### Định dạng SSE & cấu trúc chunk

#### OpenAI (`chat/completions`, `/responses`)

SSE chuẩn kiểu OpenAI: mỗi chunk là một dòng `data:`, mỗi dòng là một JSON delta.

```json
data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hel"}}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"lo!"}}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":2,"total_tokens":11}}

data: [DONE]
```

**Tín hiệu kết thúc:** dòng `data: [DONE]` luôn được gửi làm sự kiện cuối. Avis tự thêm dòng này nếu stream từ upstream kết thúc mà không có tín hiệu đó.

#### Anthropic (`messages`)

Đây là event stream gốc của Anthropic. Endpoint hoạt động như proxy chuyển tiếp mỏng, nên chuỗi sự kiện được giữ nguyên như nhà cung cấp upstream tương thích Anthropic gửi về:

```json
event: message_start
data: {"type":"message_start","message":{"id":"msg_abc","role":"assistant","model":"anthropic/claude-sonnet-4-5","usage":{"input_tokens":10,"output_tokens":1}}}

event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}

event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello!"}}

event: content_block_stop
data: {"type":"content_block_stop","index":0}

event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":12}}

event: message_stop
data: {"type":"message_stop"}
```

**Tín hiệu kết thúc:** sự kiện `event: message_stop`. Giao diện này không có dòng `[DONE]`.

#### Gemini (`:streamGenerateContent`)

Endpoint cũng hoạt động như proxy chuyển tiếp mỏng. Mỗi dòng `data:` là một chunk JSON theo cấu trúc gốc của Gemini:

```json
data: {"candidates":[{"content":{"parts":[{"text":"Hello"}],"role":"model"}}]}

data: {"candidates":[{"content":{"parts":[{"text":"!"}],"role":"model"}},"finishReason":"STOP"],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":10}}
```

**Tín hiệu kết thúc:** không có. Gemini API không phát ra sự kiện kết thúc rõ ràng — client nhận biết stream đã hoàn tất khi kết nối đóng lại (và, nếu có, qua `finishReason` của chunk cuối cùng).

### Xử lý khi kết nối bị ngắt

Nếu client ngắt kết nối giữa chừng, **không thể tiếp tục** stream trên bất kỳ giao diện nào: không có continuation token hay cơ chế phát lại như `previous_response_id`. Nếu cần phần còn lại của response, hãy gửi lại request từ đầu.

Client ngắt kết nối không làm thay đổi cách tính phí. Mức sử dụng được lấy từ một bản sao chạy nền của stream; bản sao này tiếp tục được đọc đến hết, độc lập với kết nối của client. Vì vậy, chi phí của stream mà client chỉ nhận được một phần vẫn được quyết toán chính xác theo nội dung upstream đã tạo.


---

# 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/streaming.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.
