Timeout Control

Timeout Control 是 Agent Runtime 中防止执行无限挂起的机制,包括单步超时、整体超时、LLM 调用超时和工具执行超时。

#type / concept #status / evergreen #tech / ai #tech / architecture

[!info] related notes

Timeout Control

一句话定义

Timeout Control 是 Agent Runtime 中防止执行无限挂起的机制。LLM 可能响应很慢,工具可能卡死,网络可能中断——没有超时控制,Agent 可能永远等下去。

核心原理

超时层次

层次超时时间说明
整体 Run 超时5-10 分钟一次 Run 的最大执行时间
单步 Step 超时60-120 秒一个 Step 的最大执行时间
LLM 调用超时30-60 秒一次 LLM API 调用的超时
工具执行超时10-60 秒一次工具执行的超时
首 token 超时10-15 秒LLM 开始返回第一个 token 的超时

Python 实现

class TimeoutController:
    def __init__(self, run_timeout=300, step_timeout=120, llm_timeout=60):
        self.run_timeout = run_timeout
        self.step_timeout = step_timeout
        self.llm_timeout = llm_timeout
        self.run_start = None
        self.step_start = None

    def start_run(self):
        self.run_start = time.time()

    def check_run_timeout(self):
        if time.time() - self.run_start > self.run_timeout:
            raise RunTimeoutError()

    async def with_step_timeout(self, coro):
        try:
            return await asyncio.wait_for(coro, timeout=self.step_timeout)
        except asyncio.TimeoutError:
            raise StepTimeoutError()

    async def with_llm_timeout(self, coro):
        try:
            return await asyncio.wait_for(coro, timeout=self.llm_timeout)
        except asyncio.TimeoutError:
            raise LLMTimeoutError()

Go 后端的超时控制

func (h *ChatHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
    // 整体超时
    ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
    defer cancel()

    // 调用 AI Service
    stream, err := h.aiService.Chat(ctx, request)
    if err != nil {
        if ctx.Err() == context.DeadlineExceeded {
            http.Error(w, "Request timeout", 504)
        }
        return
    }
}

常见坑

  1. 不做超时控制: 工具卡死导致 Agent 永远等待
  2. 超时太短: LLM 还没来得及响应就超时了
  3. 超时后不清理: 超时了但底层资源没有释放
  4. 不做首 token 超时: LLM 连接成功但迟迟不返回内容

参考资料

创建于 2026/6/30 更新于 2026/7/15