Team with Tool Hooks
This example demonstrates how to use tool hooks with teams and agents for intercepting and monitoring tool function calls, providing logging, timing, and other observability features.
Code
1import time2from typing import Any, Callable, Dict34from kern.agent import Agent5from kern.models.openai import OpenAIResponses6from kern.team import Team7from kern.tools.hackernews import HackerNewsTools8from kern.tools.yfinance import YFinanceTools9from kern.utils.log import logger101112def logger_hook(function_name: str, function_call: Callable, arguments: Dict[str, Any]):13 """14 Tool hook that logs function calls and measures execution time.1516 Args:17 function_name: Name of the function being called18 function_call: The actual function to call19 arguments: Arguments passed to the function2021 Returns:22 The result of the function call23 """24 if function_name == "delegate_task_to_member":25 member_id = arguments.get("member_id")26 logger.info(f"Delegating task to member {member_id}")2728 # Start timer29 start_time = time.time()30 result = function_call(**arguments)31 # End timer32 end_time = time.time()33 duration = end_time - start_time34 logger.info(f"Function {function_name} took {duration:.2f} seconds to execute")35 return result363738# News agent with tool hooks39news_agent = Agent(40 name="News Agent",41 id="news-agent",42 role="Search HackerNews for information",43 model=OpenAIResponses(id="gpt-5.2"),44 tools=[HackerNewsTools(cache_results=True)],45 instructions=[46 "Find information about the company on HackerNews",47 ],48 tool_hooks=[logger_hook],49)5051# Finance agent with tool hooks52finance_agent = Agent(53 name="Finance Agent",54 id="finance-agent",55 role="Get stock prices and financial data",56 model=OpenAIResponses(id="gpt-5.2"),57 tools=[YFinanceTools(cache_results=True)],58 instructions=[59 "Get stock prices and financial information",60 ],61 tool_hooks=[logger_hook],62)6364# Create team with tool hooks65research_team = Team(66 name="Research Team",67 model=OpenAIResponses(id="gpt-5.2"),68 members=[69 news_agent,70 finance_agent,71 ],72 markdown=True,73 instructions=[74 "You are a team that researches companies.",75 "Use the news agent for HackerNews discussions and finance agent for stock data.",76 ],77 show_members_responses=True,78 tool_hooks=[logger_hook],79)8081if __name__ == "__main__":82 research_team.print_response(83 "Research NVIDIA - get the stock price and find any HackerNews discussions.",84 stream=True,85 )Usage
Create a Python file
Create team_with_tool_hooks.py with the code above.
Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-ai openai yfinanceExport your OpenAI API key
1export OPENAI_API_KEY="your_openai_api_key_here"1$Env:OPENAI_API_KEY="your_openai_api_key_here"Run Team
1python team_with_tool_hooks.py