96SEO 2026-08-07 05:16 2
怎么说呢,
catbuddy 的主要循环 AgentRunner 是个上千行的状态机——上一篇你已经见识过它有多忙:调模型、流式回吐、跑工具、处理截断、做重试。它是整个 harness 里改起来最让人手抖的一段代码。
有一天面试官问我「你是怎么评测 Agent 的?」我一脸懵逼,二面结束后我调研了相关框架,发现 Langfuse 是二开的最佳开源框架之一:
通过 Docker 自托管后我面临了一个痛点:「能不能给每次对话接上 Langfuse。把每一轮的 token 用量、工具调用链都记下来方便排查成本异常?」我的第一反应是——那我得在循环里、模型调用前后、工具执行前后分别插上埋点代码。
只是我立刻想象到了三个月后这段循环的模样:重试逻辑、Langfuse 埋点、未来某个项目要的脱敏逻辑,再来个调试插件…,全挤在同一个状态机里。每加一个需求都要改一次代码,每改一次都怕把已有功能踩坏。不过,这就是经典的「主要代码沦为意大利面」剧本。其实,
真正的问题不是「怎么接 Langfuse」而是:
怎么让所有这类「观察 + 副作用」需求。都能 Agent 的运行流程,却一行都不碰 AgentRunner?
catbuddy 的答案是一套 Hook 程序。说到主要一句话,
在 AgentRunner 一次迭代的关键节点上预先「开洞」。外部代码把自己的逻辑塞进洞里循环本身完全不知道,也不关心洞里插了什么。
AgentHook(位于 agent/hook.ts) 定义了九个生命周期方法,对应 Agent 一次迭代里九个「可以被观察 / 介入」的时刻。下面这张示意图把它们钉在 AgentRunner 循环中的真实位置上:
beforeIteration 与 afterIteration。onStreamemitReasoningemitReasoningEnd。beforeExecuteTools。
This mapping is not a guess—open alert runner.ts and you can match each call one‑by‑one:
hook.beforeIteration;hook.beforeExecuteTools;按理说,hook.afterIteration;// ,etc.
The most important point:The default implementation of every method is a no‑op.
export class AgentHook {
constructor {}
wantsStreaming: boolean { return false } // 默认:不关心流式
async beforeIteration {} // 默认:什么都不做
async beforeExecuteTools {}
async afterIteration {}
// …其余方法同理,全是空实现
}
This means **zero overhead**. The runner always calls se methods;if you don’t plug any Hook y’re just empty functions that get inlined away by V8. You only override slots you care about;everything else stays “air”. This is foundation—default harmless,open on demand.
A subtle optimisation lives in : before invoking it runner checks wantsStreaming. Streaming callbacks fire at token‑level frequency,so if a Hook signals “I don’t need streaming” runner skips whole path。keeping hot loops fast.
The or half of a useful Hook is visibility. Every Hook method receives an AgentHookContext object that carries ** entire state of current iteration**:
interface AgentHookContext {
iteration: number;// 第几轮
messages: LLMMessage;// 完整对话历史
response?: {
content,toolCalls;usage,…
},// 本轮 LLM 响应
说到usage,TokenUsage;怎么说呢,// 累计 token 消耗
toolCalls: ToolCallRequest;// 本轮要执行的工具调用
toolEvents: ToolEvent;// 全部工具事件历史
finalContent: string | null;// 最终回复
至于error,string | null;// 错误信息
}
If you need “token usage this turn” or “which tools were invoked”,y’re already in ctx.response?.usage and ctx.toolCalls / ctx.toolEvents . No need to dig into Runner internals.
The real‑world requirement we introduced earlier can now be satisfied with **ten lines of code**:
class LangfuseHook extends AgentHook {
constructor { super;}
// 每轮 LLM 响应回来后:记一笔 token 用量 + 工具列表
override async afterIteration: Promise {
this.trace.span({
说到name。`iteration-${ctx.iteration}`,usage: ctx.response?.usage,// ← token账单直接拿到
tools的观点是。ctx.toolCalls.map,// ← 本轮使用了哪些工具
});}
}
You simply instantiate it and pass it via spec.hook when creating Runner. When runner reaches its internal call to hook.afterIteration your hook runs automatically—**no change to core loop**,no risk of breaking existing logic.
The diagram below shows a box labeled “不动” around Runner – that’s promise kept by Hook system.
A note on reality: catbuddy already ships a production‑ready version called LangfuseAgentHook that expands this pattern into a three‑layer trace tree . The next article will dive deep into that structure。cost estimation and PII masking.
If you need more than one concern you can’t stick three objects into a single hook field. Enter CompositeHook :
AgentHook private async forEachHookSafe: Promise { for { try { await hook;// 挨个调用子 Hook } catch { if throw err;//关键 Hook:异常向上冒泡 console.error;// 普通 Hook:吞掉异常,继续下一个 —— 不连累别人 } } }
The optional reraise flag lets you mark certain Hooks as “critical”. For example a state‑sync Hook that must succeed can be created with ).reraise = true;. By default all hooks are isolated – one bad apple won’t spoil whole basket.
You might wonder *** catbuddy still has explicit callbacks like
| Hooks" | 显式回调" | |
|---|---|---|
| 定位" | "站在循环边缘。看完状态再做副作用" | "直接搬运数据到外部程序" |
| 干什么" | "观察内部状态 → 上报/记录/触发副作用" | "转换 / 搬运 数据 → UI / 下游服务" |
| 谁用" | "框架层 / 子程序 / 第三方 " | "AgentRunner 的直接使用者 " |
The base
An empty slot is a deliberate architectural signal saying “we anticipate future needs here”. New team members see those holes and instantly know *where* to plug ir logic instead of hunting through a monolithic state machine.
The current design intentionally makes Hooks **sequential and read‑only** – y observe n return control back to Runner. If we wanted Hooks to *intervene*,we’d have to redesign control flow,add conflict resolution 娱乐ween multiple Hooks,and decide how Agent should react when a tool is blocked. That extra power brings proportional complexity and risk.
This is *** today’s contract is deliberately narrow: **Only observe。never dictate**. It keeps extension surface simple and guarantees that adding new Hooks never puts core loop into an
AgentHookLangfuse_hook 实现错误隔离——单个失败不会拖垮其他插件或主流程。<>/ li
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback