在 Agent SDK 中使用钩子系统——在代理操作前后执行自定义逻辑。
钩子系统
钩子让你能在代理的关键操作前后插入自定义逻辑:
- pre-call:在调用 Claude API 之前
- post-call:在收到 Claude 回复之后
- pre-tool:在执行工具之前
- post-tool:在工具执行之后
- on-error:发生错误时
实现
class AgentHooks:
def pre_call(self, messages):
"""在 API 调用前处理消息。"""
print(f"即将发送 {len(messages)} 条消息")
return messages
def post_call(self, response):
"""处理 API 回复。"""
print(f"收到回复: {len(response.content)} 个内容块")
return response
def pre_tool(self, tool_name, tool_input):
"""在工具执行前。"""
print(f"即将执行: {tool_name}")
return True # 返回 False 可以取消
def post_tool(self, tool_name, result):
"""处理工具结果。"""
print(f"工具 {tool_name} 完成")
return result
def on_error(self, error):
"""处理错误。"""
print(f"错误: {error}")
使用场景
- 日志记录:记录每次操作
- 安全检查:在工具执行前验证参数
- 结果过滤:过滤或转换工具输出
- 指标收集:跟踪调用次数和耗时
- 错误恢复:从错误中优雅恢复
下一步
- Agent SDK 技能
- 钩子系统:Claude Code 中的钩子