# Streaming (/vi/docs/concepts/streaming)

Nhận token ngay khi mô hình sinh ra, qua server-sent events.



Đặt `"stream": true` và phản hồi sẽ đến dưới dạng [server-sent events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) thay vì một body JSON duy nhất. Mỗi định dạng giữ cấu trúc sự kiện riêng:

| Endpoint               | Định dạng stream                                                                                  |
| ---------------------- | ------------------------------------------------------------------------------------------------- |
| `/v1/chat/completions` | Các dòng `data:` chứa đối tượng `chat.completion.chunk`, kết thúc bằng `data: [DONE]`             |
| `/v1/responses`        | Các sự kiện phân loại theo `type`, chẳng hạn `response.output_text.delta` và `response.completed` |
| `/v1/messages`         | Sự kiện Anthropic: `message_start`, `content_block_delta`, `message_stop`                         |

## Mức sử dụng token khi streaming [#token-usage-in-streams]

Với chat completions, thêm `"stream_options": { "include_usage": true }` để nhận một chunk cuối chứa số token. Stream của Responses và Messages báo mức sử dụng trong các sự kiện kết thúc.

## Ví dụ [#example]

<Tabs items="[&#x22;Python&#x22;, &#x22;TypeScript&#x22;]">
  <Tab value="Python">
    ```python
    stream = client.chat.completions.create(
        model="deepseek-v4-1-flash",
        messages=[{"role": "user", "content": "Write a haiku about rivers."}],
        stream=True,
    )
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
    ```
  </Tab>

  <Tab value="TypeScript">
    ```ts
    const stream = await client.chat.completions.create({
      model: "deepseek-v4-1-flash",
      messages: [{ role: "user", content: "Write a haiku about rivers." }],
      stream: true,
    });
    for await (const chunk of stream) {
      process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
    }
    ```
  </Tab>
</Tabs>
