Timeout Control
Timeout Control 是 Agent Runtime 中防止执行无限挂起的机制,包括单步超时、整体超时、LLM 调用超时和工具执行超时。
#type / concept
#status / evergreen
#tech / ai
#tech / architecture
[!info] related notes
- 所属 MOC: Agent Runtime MOC
- 相关: Run, Cancellation, [[sandbox|Sandbox]]
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
}
}
常见坑
- 不做超时控制: 工具卡死导致 Agent 永远等待
- 超时太短: LLM 还没来得及响应就超时了
- 超时后不清理: 超时了但底层资源没有释放
- 不做首 token 超时: LLM 连接成功但迟迟不返回内容