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