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