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

# 超時與重試

> SDK 如何為一次性調用和流式請求應用超時策略、何時進行重試，以及如何調整這兩者。

SDK 會為一次性（unary）調用和流式請求應用不同的超時策略，並且只在確認安全的情況下才會重試。本頁是該行為的唯一權威說明。

## 默認值

| 選項 | 默認值 | 適用範圍 |
| - | - | - |
| `timeoutMs` | `30_000`（30 秒） | **一次性**請求的總時長；同時也是流式請求的連接/首字節等待預算。 |
| `streamIdleTimeoutMs` | `120_000`（120 秒） | 流式請求的**空閒**（數據塊之間）超時。不是總時長上限。 |
| `maxRetries` | `2` | 冪等調用中針對 `429` / `5xx` 的重試次數。 |
| 可在客戶端上配置以上任意一項： | | |

```typescript theme={null}
import { Theo } from "@hitheo/sdk";

const theo = new Theo({
  apiKey: process.env.THEO_API_KEY!,
  timeoutMs: 60_000,          // unary total-duration budget
  streamIdleTimeoutMs: 180_000, // allow longer gaps between stream chunks
  maxRetries: 2,
});
```

## 一次性請求

一次性調用（`complete`、`images`、`code`、`documents`、`job`、列表端點等）從頭到尾受 `timeoutMs` 約束。一旦超時，SDK 會中止該請求並拋出 `TheoTimeoutError`（`error.kind === "timeout"`，`error.timeoutMs` 攜帶對應的預算值）。

## 流式請求

`stream()` **不受**總時長超時限制——一個健康的長流可以運行數分鐘。取而代之的是：

* `timeoutMs` 用於保護**連接/首字節**階段。如果響應頭始終未到達，你會收到一個 `TheoTimeoutError`（"Stream did not start…"）。
* `streamIdleTimeoutMs` 用於保護**數據塊之間的間隔**。該計時器會在每個數據塊到達時重置；如果流靜默的時間超過該窗口，SDK 會將其中止，異步迭代器會拋出 `TheoTimeoutError`。

```typescript theme={null}
const stream = theo.stream({ prompt: "Write a long essay about TCP." });
try {
  for await (const event of stream) {
    if (event.type === "token") process.stdout.write(event.token);
  }
} catch (err) {
  // TheoTimeoutError only fires if the stream stalls for > streamIdleTimeoutMs
}
```

<Note>
  `TheoStream.cancel()` 與超時不同。取消會讓迭代器乾淨地結束（不會拋出異常）；而超時會拋出 `TheoTimeoutError`。
</Note>

## 重試策略

SDK 會在以下情況自動重試：

* **429** — 觸發限流（遵循 `Retry-After`，最長等待 60 秒）
* **5xx** — 服務器錯誤（指數退避：1 秒、2 秒、4 秒，上限 8 秒）
  除 `429` 外，其他 `4xx` 錯誤**不會**重試。

### 寫操作超時不會重試

<Warning>
  超時的 **POST** 請求（`complete`、`research`、`video` 等）**永遠不會**被重試。重新發起一次非冪等的生成請求，可能會導致同一份工作被重複執行——並被重複計費。對這些方法而言，超時是終態；只有冪等的讀操作（`GET`/`HEAD`）才會在超時後重試。
</Warning>

如果你需要在自己的重試邏輯中保證至多執行一次的語義，可以發送 `Idempotency-Key` 請求頭（平台範圍內均支持），這樣重放請求會複用原始結果，而不會重新生成。

## 按模式給出的建議

* `fast` / `auto`：默認的 30 秒完全夠用。
* `think` / `code`：可能需要更長時間——針對較大的提示詞，可將 `timeoutMs` 調高（例如 60–120 秒）。
* `research` / `video`：**不要**將這兩種模式發送給 `complete()` / `stream()`。它們是異步的，以任務（job）形式運行——請使用 `theo.research()` / `theo.video()` 搭配 `theo.waitForJob()`。如果你直接調用，SDK 會立即拋出 `TheoUsageError`。參見[異步任務](/guides/async-jobs)。

## 錯誤

以上所有情況都會通過 SDK 的錯誤體系體現出來。關於 `TheoTimeoutError`、`TheoCancelledError`、`TheoUsageError` 以及 `kind` 判別字段，請參見[錯誤處理](/sdk-reference/error-handling)。


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