Tool Hooks

Use tool_hooks to add middleware that wraps every tool call.

1"""
2Tool Hooks
3=============================
4
5Use tool_hooks to add middleware that wraps every tool call.
6
7Tool hooks act as middleware: each hook receives the tool name, arguments,
8and a next_func callback. The hook must call next_func(**args) to continue
9the chain, and can inspect or modify args before and the result after.
10"""
11
12import time
13
14from kern.agent import Agent
15from kern.models.openai import OpenAIResponses
16from kern.tools.websearch import WebSearchTools
17
18
19def 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() - start
24 print(f"[timing_hook] {function_name} took {elapsed:.3f}s")
25 return result
26
27
28def 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)
32
33
34# ---------------------------------------------------------------------------
35# Create Agent
36# ---------------------------------------------------------------------------
37agent = Agent(
38 model=OpenAIResponses(id="gpt-5.2"),
39 tools=[WebSearchTools()],
40 # Hooks are applied to every tool call in middleware order
41 tool_hooks=[logging_hook, timing_hook],
42 markdown=True,
43)
44
45# ---------------------------------------------------------------------------
46# Run Agent
47# ---------------------------------------------------------------------------
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 repo
2git clone https://github.com/kern-ai/kern.git
3cd kern/cookbook/02_agents/09_hooks
4
5# Create and activate virtual environment
6./scripts/demo_setup.sh
7source .venvs/demo/bin/activate
8
9python tool_hooks.py