> ## 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.complete(request)`

通过完整的编排管道发送提示词，并返回完整的响应。

```typescript theme={null}
const res = await theo.complete({
  prompt: "Explain microservices architecture",
  mode: "auto",           // or "fast", "think", "code", "research", etc.
  skills: ["deep-research"],
  conversation_id: "conv_abc123",  // optional — continue a conversation
  persona: { system_prompt: "You are a senior architect..." },
  tools: [/* inline tool definitions */],
  temperature: 0.7,
  max_iterations: 8,
  metadata: { source: "my-app" },
});

console.log(res.content);                  // Generated text
console.log(res.model.label);              // "Theo Reason"
console.log(res.resolved_mode);            // "think"
console.log(res.tools_used);               // [{ name, status, description? }]
console.log(res.usage.cost_cents);         // 0.15
console.log(res.usage.prompt_tokens);      // 42
console.log(res.usage.completion_tokens);  // 128
console.log(res.usage.total_tokens);       // 170
console.log(res.usage.cached);             // true when served from semantic cache
console.log(res.conversation_id);          // server-side conversation id or null
console.log(res.request_id);               // mirror of the X-Request-Id header
```

### CompletionRequest

| 字段 | 类型 | 必需 | 默认值 | 描述 |
| - | - | - | - | - |
| `prompt` | `string` | ✅ | — | 提示词文本 |
| `mode` | `ChatMode` | — | `"auto"` | 执行模式 |
| `conversation_id` | `string \| null` | — | — | 继续一个已持久化的对话（接受 null） |
| `conversation` | `InlineConversation` | — | — | 供无状态调用方使用的内联历史记录信封 |
| `skills` | `string[]` | — | — | 要激活的技能 slug |
| `tools` | `ToolDef[]` | — | — | 内联工具定义 |
| `persona` | `PersonaInput` | — | `"theo"` | 角色覆盖 |
| `personality_config` | `PersonalityConfigInput` | — | — | 特质强度 + 无审查模式覆盖 |
| `response_style` | `ResponseStyleInput` | — | — | 格式 / 精确度 / 意图覆盖 |
| `theo_branding` | `boolean` | — | — | 设为 `false` 会从此响应中移除 Theo 的个性/品牌元素 |
| `brand_soul` | `boolean` | — | — | 设为 `false` 会为此请求禁用该 API 密钥的 Brand Soul |
| `temperature` | `number` | — | — | 采样温度 |
| `max_iterations` | `number` | — | `8` | 智能体循环的最大迭代次数 |
| `stream` | `boolean` | — | `false` | 启用 SSE 流式传输 |
| `model_overrides` | `Record<string, string>` | — | — | 按模式覆盖模型 |
| `metadata` | `Record<string, unknown>` | — | — | 自定义元数据 |
| `attachments` | `CompletionAttachment[]` | — | — | 用于视觉分析的图片附件 |
| `image_model` | `TheoImageEngine` | — | — | 当模式解析为 `image` 时，固定使用某个 Theo 图像子引擎 |
| `image_quality` | `TheoImageQuality` | — | — | `"draft" \| "standard" \| "hd"` |
| `stealth_model` | `string` | — | — | 固定使用某个 stealth 模型（仅限 stealth 模式） |
| `stealth_aspect` | `TheoStealthAspect` | — | — | stealth 图片宽高比 |
| `stealth_duration` | `TheoStealthDuration` | — | — | stealth 视频时长 |
| 在任何可选字段的位置传入 `null`，都会被视为该字段不存在（与 OpenAI / Anthropic / Stripe 的行为一致）。 | | | | |

### CompletionResponse.usage

```typescript theme={null}
interface CompletionUsage {
  cost_cents: number;           // markup-inclusive
  prompt_tokens: number;        // always 0 for non-text modes
  completion_tokens: number;    // always 0 for non-text modes
  total_tokens: number;
  cached?: boolean;             // true when served from the semantic cache
}
```

对于 image / video / tts / stt 模式，令牌计数始终为 `0`。在这些模式下，请将 `cost_cents` 作为唯一的用量指标。

## `theo.stream(request)`

返回一个 `TheoStream`——一个可异步迭代的句柄，带有 `cancel()` 方法，并会在事件到达时逐步填充最终的元数据属性。

```typescript theme={null}
const stream = theo.stream({ prompt: "Explain DNS" });

// Hook up a "Stop generating" button
stopButton.onclick = () => stream.cancel();

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;
  }
}

// Populated from meta + done events:
console.log("conversation_id:", stream.conversationId);
console.log("usage:", stream.usage);
console.log("model:", stream.model);
console.log("request_id:", stream.requestId);
console.log("full content:", stream.content); // accumulated from token events
console.log("was cancelled?", stream.isCancelled);
```

### TheoStream

| 成员 | 类型 | 描述 |
| - | - | - |
| `[Symbol.asyncIterator]()` | `AsyncIterator<StreamEvent>` | 标准异步迭代——可与 `for await` 配合使用 |
| `cancel()` | `void` | 中止底层的 HTTP 连接；停止生成并停止计费 |
| `isCancelled` | `boolean` | 调用 `cancel()` 后为 `true` |
| `requestId` | `string \| null` | 服务端请求 id（来自 `done` 事件或 `X-Request-Id` 响应头） |
| `model` | `{ id, label, engine } \| null` | 由 `meta` 事件填充 |
| `resolvedMode` | `ChatMode \| null` | 经过意图分类后的模式（来自 `meta`） |
| `conversationId` | `string \| null` | 由 `meta` / `done` 填充（对无状态调用方为 null） |
| `usage` | `CompletionUsage \| null` | 由 `done` 事件填充 |
| `content` | `string` | 从 `token` 事件累积得到的文本内容 |

### StreamEvent（判别联合类型）

`switch (event.type)` 会自动收窄 `event.data` 的类型。

| `event.type` | `event.data` 的结构 |
| - | - |
| `meta` | `StreamMetaData` — id, mode, resolved\_mode, model, tools, artifacts, brand?, routing?, conversation\_id, request\_id |
| `token` | `{ token: string }` — 为方便起见，也可通过 `event.token` 访问 |
| `tool` | `{ name, status, description? }` |
| `artifact` | `Record<string, unknown>` — 具体结构因产物类型而异（image / video / document / code） |
| `skills` | `{ active: Array<{ id, slug, name, intensity? }> }` |
| `genui_meta` | `{ library, tools[] }`（仅 GenUI 模式） |
| `done` | `StreamDoneData` — id, content, follow\_ups, structured\_output?, skills\_active?, routing?, usage, conversation\_id, request\_id |
| `error` | `{ error: { message, type, code, request_id } }` — 与 REST 错误信封格式一致 |
| 如需了解完整的传输格式以及流式过程中出现 429 的示例，请参阅[流式补全（API 参考）](/api-reference/completions/streaming)。 | |


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