cheapaimodel

串流

透過 server-sent events 在 token 生成的同時接收。

複製

設定 "stream": true,回應就會以 server-sent events 送達,而不是單一的 JSON 主體。各格式保有自己的事件結構:

端點串流格式
/v1/chat/completions由 chat.completion.chunk 物件組成的 data: 行,以 data: [DONE] 結尾
/v1/responses具型別的事件,例如 response.output_text.delta 與 response.completed
/v1/messagesAnthropic 事件:message_start、content_block_delta、message_stop

串流中的 token 用量

Chat completions 請加上 "stream_options": { "include_usage": true },即可在最後一個 chunk 取得 token 數。Responses 與 Messages 的串流會在結尾事件中回報用量。

範例

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)
複製
開啟方式

本頁內容