第 14 讲:预算控制与限流——IterationBudget、Credits Tracker、Rate Guard 与费用估算管线

Hermes Agent 源码解析 · 第 14 讲

Hermes Agent 源码解析 第 14 讲:预算控制与限流——IterationBudget、Credits Tracker、Rate Guard 与费用估算管线 基于 Hermes Agent v0.16.0 源码 · 2026-06-27 一、为什么预算控制是 Agent 系统的生命线 前十三讲我们覆盖了 Hermes 从核心架构到认证系统的全链路。这一讲聚焦一个看似低调却决定性的子系统: 预算控制与限流 。 在一个 AI Agent 系统中,一次对话可能触发数十次 API 调用。如果没有预算控制,一个陷入死循环的 Agent 可以在几分钟内消耗掉数百美元。Hermes 的预算体系不是简单的计数器——它是 多层防御架构 ,从迭代次数到费用估算,从限流熔断到工具循环检测,形成了完整的成本控制闭环。 📦 本讲核心文件 agent/iteration_budget.py (62 行)— 迭代预算计数器 agent/credits_tracker.py (794 行)— 积分追踪与通知策略 agent/nous_rate_guard.py (325 行)— 跨会话限流熔断 agent/usage_pricing.py (908 行)— 费用估算管线 agent/error_classifier.py — 计费/限流错误分类 二、IterationBudget:线程安全的迭代预算计数器 iteration_budget.py 仅 62 行代码,却是 Hermes 预算体系的第一道防线。每个 AIAgent 实例(父 Agent 或子 Agent)持有一个独立的 IterationBudget 对象,通过 consume/refund 模式控制迭代次数。 class IterationBudget: def __init__(self, max_total: int): self.max_total = max_total self._used = 0 self._lock = threading.Lock() def consume(self) -> bool: """Try to consume one iteration. Returns True if allowed.""" with self._lock: if self._used >= self.max_total: return False self._used += 1 return True def refund(self) -> None: """Give back one iteration (e.g. for execute_code turns).""" with self._lock: if self._used > 0: self._used -= 1 关键设计细节: 🔹 线程安全 :所有状态变更通过 threading.Lock 保护,Gateway 多会话并发场景下不会数据竞争 🔹 Refund 机制 : execute_code (程序化工具调用)的迭代通过 refund() 返还——程序化调用不消耗模型推理预算,因为它们不经过 LLM 决策 🔹 父子独立预算 :父 Agent 默认 max_iterations=90,子 Agent 默认 delegation.max_iterations=50,各自独立计数 在 conversation_loop.py 中,预算检查是主循环的退出条件之一: while (api_call_count 0) or agent._budget_grace_call: ... if agent._budget_grace_call: agent._budget_grace_call = False elif not agent.iteration_budget.consume(): _turn_exit_reason = "budget_exhausted" agent._safe_print( f"\u26a0\ufe0f Iteration budget exhausted " f"({used}/{max_total} used)") break Grace call 机制 是精妙的设计:当预算耗尽时,Agen…

阅读全文:Hermes Agent 源码解析 第 14 讲