cheapaimodel

Streaming

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

Sao chép

Đặt "stream": true và phản hồi sẽ đến dưới dạng 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/completionsCác dòng data: chứa đối tượng chat.completion.chunk, kết thúc bằng data: [DONE]
/v1/responsesCác sự kiện phân loại theo type, chẳng hạn response.output_text.delta và response.completed
/v1/messagesSự kiện Anthropic: message_start, content_block_delta, message_stop

Mức sử dụng token khi streaming

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ụ

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)
Sao chép
Mở trong

Trên trang này