SuperAPI AI 工具集

nooa-middleware-hooks

通用与其它

查看项目

更新于 10-16 02:33

技能介绍

用途:为 NOOA 智能体运行时提供三种拦截面,用于护栏、输入输出改写、阻断、审计与可观测性。

主要能力:

  1. 中间件 agent.event_manager.intercept(kind, fn),可改变行为。三种 kind:agent_call(一次被追踪的异步 agent 方法调用)、llm_call(runtime.generate() 内一次 LLM 往返)、execute_python(runtime.execute_code() 中一个 CodeAct 单元)。中间件签名为 async def mw(ctx, nxt) -> ctx,按注册顺序执行,先注册者最外层;嵌套顺序为 agent_call → 每轮 llm_call → 每单元 execute_python。可短路(不调用 nxt),但必须设置输出槽 ctx.result 或 ctx.response,否则抛 RuntimeError;抛异常即阻断并向上传播。intercept() 返回取消函数。按 agent 注册,子 agent 各自独立。
  2. 观察者 agent.event_manager.on(event_type, fn),事件记录后触发,不能改变事件,异常隔离;支持通配符 "*"。可用运行时事件如 BeforeTurn/AfterTurn、LLMCallStart/LLMCallEnd,LLMResponse 携带 token、成本、模型与推理元数据。
  3. InstrumentationHooks:set_hooks(obj)(nooa.runtime.hooks),成对的 before_/after_ 回调,覆盖 agent_call、generation、code_execution、method_invocation、tool_execution,以及 on_messages_built。钩子异常被吞掉并记 WARNING,耗时计入追踪开销。全局单槽、按 async context 作用域;enable_tracing() 会占用该槽,后调用 set_hooks 会静默替换追踪。

使用方式:在 init(super().init() 之后)或已构造的 agent 实例上安装中间件,不要装在类上。示例:unsubscribe = agent.event_manager.intercept("llm_call", redact_secrets),之后 unsubscribe() 移除。

限制与注意:agent_call 覆盖范围窄于“所有 agent 方法”,仅覆盖元类为被追踪异步方法生成的包装;同步 def、被 @no_trace 跳过包装的方法、staticmethod/classmethod 及继承自非 Agent 基类的方法不产生 AgentCallContext,护栏无法阻断它们。上下文窗口错误会归档事件、重建消息并重试,llm_call 中间件可能每逻辑轮运行多次,需保持幂等。execute_python 有重入保护。after_agent_call 的 context 可能为 None。不要用钩子写业务逻辑,不要用中间件取 LLMResponse 已能提供的指标。

适用场景:护栏与脱敏、缓存与短路、审计与计时、追踪导出(通常应使用 tracing exporter 而非原始钩子)。