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