安全公告 — 恶意 litellm 版本 1.82.7 与 1.82.8 已从 PyPI 移除(存在 API 密钥外泄风险)。请卸载、轮换已暴露凭据,并升级至安全版本(如 1.82.9+)。运行 pip show litellm 以确认。 PyPI · README

钩子

AgenticX 钩子系统。

钩子系统

概述

AgenticX 为不同执行面暴露 两层钩子

层级包路径用途
Core hooksagenticx/core/hooks/围绕 LLM工具 调用的同步拦截
Runtime hooksagenticx/runtime/hooks/挂载于 `AgentRuntime`异步 生命周期钩子

Core Hooks(`agenticx/core/hooks/`)

Core hooks 是普通 callable,可在 全局`Agent` 实例上注册。

LLM 钩子

上下文类型:`LLMCallHookContext`

调用前字段:

字段说明
agent_id智能体标识
task_id可选任务 ID
messages消息列表(可原地修改)
model可选模型名
temperature可选采样温度
max_tokens可选 token 上限
iteration循环迭代索引

注册方式:

python
1from agenticx.core.hooks import (
2 LLMCallHookContext,
3 register_before_llm_call_hook,
4 register_after_llm_call_hook,
5)
6
7def log_before_llm(ctx: LLMCallHookContext) -> bool:
8 # Mutate ctx.messages in place if needed
9 return True # False blocks the LLM call
10
11register_before_llm_call_hook(log_before_llm)

工具钩子

上下文类型:`ToolCallHookContext`

调用前字段:

字段说明
agent_id智能体标识
tool_name被调用的工具名
tool_args参数字典(可原地修改)
iteration循环迭代

Runtime Hooks(`agenticx/runtime/hooks/`)

Runtime hooks 是 `AgentHook` 子类上的 async 方法,由 `HookRegistry` 协调调度。

`AgentHook` 基类

方法职责
before_model(messages, session)LLM 调用前转换消息序列
after_model(response, session)模型返回后观察或产生副作用
before_tool_call(tool_name, arguments, session)返回 HookOutcome(blocked=True) 可否决调用
after_tool_call(tool_name, result, session)替换工具返回字符串
on_compaction(compacted_count, summary, session)上下文压缩完成后
on_agent_end(final_text, session)智能体轮次结束

`HookOutcome`

python
1@dataclass
2class HookOutcome:
3 blocked: bool = False
4 reason: str = ""

示例:拦截工具

python
1from agenticx.runtime.hooks import AgentHook, HookOutcome
2
3class DenyShellHook(AgentHook):
4 async def before_tool_call(self, tool_name, arguments, session):
5 if tool_name in {"run_terminal_cmd", "bash"}:
6 return HookOutcome(blocked=True, reason="Shell tools disabled")
7 return None
8
9runtime.hooks.register(DenyShellHook(), priority=100)

Core 与 Runtime 钩子对比

维度CoreRuntime
执行模型同步 callableAgentHook 上的 async 方法
拦截 LLMbefore 钩子返回 Falsebefore_model 中转换
拦截工具before 钩子返回 FalseHookOutcome(blocked=True)
注册表模块级列表 + Agent.llm_hooks带数值优先级的 HookRegistry
典型用途日志、策略、改写流式生命周期、记忆钩子