Tool Hooks
Use tool_hooks to add middleware that wraps every tool call.
1"""2Tool Hooks3=============================45Use tool_hooks to add middleware that wraps every tool call.67Tool hooks act as middleware: each hook receives the tool name, arguments,8and a next_func callback. The hook must call next_func(**args) to continue9the chain, and can inspect or modify args before and the result after.10"""1112import time1314from kern.agent import Agent15from kern.models.openai import OpenAIResponses16from kern.tools.websearch import WebSearchTools171819def timing_hook(function_name: str, func: callable, args: dict):20 """Measure and print the execution time of each tool call."""21 start = time.time()22 result = func(**args)23 elapsed = time.time() - start24 print(f"[timing_hook] {function_name} took {elapsed:.3f}s")25 return result262728def logging_hook(function_name: str, func: callable, args: dict):29 """Log the tool name and arguments before execution."""30 print(f"[logging_hook] Calling {function_name} with args: {list(args.keys())}")31 return func(**args)323334# ---------------------------------------------------------------------------35# Create Agent36# ---------------------------------------------------------------------------37agent = Agent(38 model=OpenAIResponses(id="gpt-5.2"),39 tools=[WebSearchTools()],40 # Hooks are applied to every tool call in middleware order41 tool_hooks=[logging_hook, timing_hook],42 markdown=True,43)4445# ---------------------------------------------------------------------------46# Run Agent47# ---------------------------------------------------------------------------48if __name__ == "__main__":49 agent.print_response(50 "What is the current population of Tokyo?",51 stream=True,52 )Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/09_hooks45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python tool_hooks.py