> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hitheo.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 流式

> Theo 如何通過 SSE 流式返回響應、如何消費這些事件，以及如何在生成過程中取消。

Theo 通過 **Server-Sent Events (SSE)** 流式返回響應。在任意補全請求上設置 `stream: true`，即可在事件發生時實時接收，而不必等待完整響應。

SSE 與 OpenAI 和 Anthropic 使用的協議相同——任何能解析 `text/event-stream` 的 HTTP 客戶端都可以使用。SDK 會將其封裝為一個異步可迭代對象。

## 為什麼要使用流式？

* **快速模式下首個令牌延遲低於 300ms**——用戶能立即看到輸出，而不是乾等一個加載動畫。
* **智能體循環的透明度**——`tool` 和 `artifact` 事件會在 Theo 使用工具或生成文件的那一刻觸發，因此你可以渲染出實時的"Theo 正在瀏覽…"或"已生成圖片"卡片。
* **優雅的取消**——關閉 HTTP 連接（或在 SDK 中調用 `stream.cancel()`）即可停止為不想要的令牌計費。

## 事件流

一次正常的對話輪次會按以下順序發出事件：

1. `thinking` —— 一個心跳信號，用於讓代理服務器刷新響應。
2. `meta` —— 解析後的模式、品牌化的模型、路由遙測信息、`conversation_id`、`request_id`。
3. `skills`（可選）—— 本輪觸發了哪些技能。
4. `genui_meta`（可選）—— 僅當 `resolved_mode === "genui"` 時出現。
5. `tool` / `artifact` —— 隨發生順序出現（可能交錯）。
6. `token` —— 每個文本塊一個。
7. `done` —— 完整內容、後續建議、用量、`conversation_id`、`request_id`。

如果出現任何失敗，服務器會發出一個 `error` 事件，其負載**與 REST 錯誤信封格式一致**（`{ error: { message, type, code, request_id } }`），隨後關閉流。無需特殊處理——複用你現有的 HTTP 錯誤處理路徑即可。

關於各事件的 JSON schema、傳輸格式規則，以及流式過程中出現 429 的示例，請參見[流式補全（API 參考）](/api-reference/completions/streaming)。

## SDK 流式

SDK 會返回一個 `TheoStream`。它是異步可迭代的，因此可以直接使用 `for await`。流結束後，它會以屬性形式暴露 `conversationId`、`usage`、`model` 和 `requestId`。

```typescript theme={null}
const stream = theo.stream({
  prompt: "Explain how TCP/IP works",
});

for await (const event of stream) {
  switch (event.type) {
    case "meta":     console.log("Mode:", event.data.resolved_mode); break;
    case "token":    process.stdout.write(event.token); break;
    case "tool":     console.log("Tool:", event.data.name, event.data.status); break;
    case "artifact": renderArtifact(event.data); break;
    case "error":    console.error("Stream error:", event.data.error); break;
    case "done":     console.log("\nCost:", event.data.usage.cost_cents); break;
  }
}

// Final metadata — populated from meta + done events.
console.log("conversation_id:", stream.conversationId);
console.log("usage:", stream.usage);
console.log("request_id:", stream.requestId);
```

### 在生成過程中取消

`TheoStream.cancel()` 會中止底層的 HTTP 連接，使服務器停止生成並停止計費。迭代器會在下一個事件邊界處結束。

```typescript theme={null}
const stream = theo.stream({ prompt: "Write a 5000-word essay…" });
// Wire up your UI's "Stop generating" button:
cancelButton.onclick = () => stream.cancel();
for await (const event of stream) {
  // ...
}
```

這是實現聊天界面"停止"按鈕最簡潔的方式——無需笨拙的 HTTP 連接拆除邏輯，也不用自行編寫 AbortController 的傳遞鏈路。

## 原始 SSE（curl / fetch）

請使用規範的 `www` 主機，以避免某些 HTTP 客戶端在處理 apex 到 www 的重定向時會剝離 `Authorization` 頭（參見[401 故障排查](/troubleshooting/401-errors)）：

```bash theme={null}
curl -N -X POST https://www.hitheo.ai/api/v1/completions \
  -H "Authorization: Bearer $THEO_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Write a haiku about code", "stream": true}'
```

響應體是一串 SSE 事件流：

```
event: meta
data: {"id":"cmpl_abc","resolved_mode":"fast","model":{"id":"theo-1-flash","label":"Theo Flash","engine":"theo-core"},"conversation_id":null,"request_id":"req_9f2e1a", ...}

event: token
data: {"token":"Lines"}

event: token
data: {"token":" of"}

event: done
data: {"id":"cmpl_abc","content":"Lines of code","usage":{"cost_cents":0.01,"prompt_tokens":8,"completion_tokens":2,"total_tokens":10}, ...}
```

## 多輪對話

`conversation_id` 會同時出現在 `meta` 和 `done` 事件中。如果你在請求中傳入了一個，它會被原樣回傳；如果沒有傳入，則為 `null`（服務器不會為 API 密鑰調用方自動創建持久化對話，除非你顯式調用 `POST /api/v1/conversations`）。

SDK 會自動捕獲該 ID——在流完成後讀取 `stream.conversationId` 即可。

## E.V.I. 流式

E.V.I. 實例（`theo.evi(...)`）支持使用相同的 `TheoStream` 接口進行流式傳輸：

```typescript theme={null}
const evi = theo.evi({
  persona: "You are Kai, a coding assistant...",
});

const stream = evi.stream({
  prompt: "Debug this React hook",
});

for await (const event of stream) {
  if (event.type === "token") process.stdout.write(event.token);
}
console.log("request_id:", stream.requestId);
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.