From 9459a48b0aacc006ba66ce3544d987965618c75c Mon Sep 17 00:00:00 2001 From: Kazuhiro Sera Date: Fri, 26 Sep 2025 15:33:48 +0900 Subject: [PATCH] Add agent hooks to lifecycle_example --- examples/basic/lifecycle_example.py | 30 ++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/examples/basic/lifecycle_example.py b/examples/basic/lifecycle_example.py index 1429872b8..874ff629b 100644 --- a/examples/basic/lifecycle_example.py +++ b/examples/basic/lifecycle_example.py @@ -4,10 +4,36 @@ from pydantic import BaseModel -from agents import Agent, RunContextWrapper, RunHooks, Runner, Tool, Usage, function_tool +from agents import ( + Agent, + AgentHooks, + RunContextWrapper, + RunHooks, + Runner, + Tool, + Usage, + function_tool, +) from agents.items import ModelResponse, TResponseInputItem +class LoggingHooks(AgentHooks[Any]): + async def on_start( + self, + context: RunContextWrapper[Any], + agent: Agent[Any], + ) -> None: + print(f"#### {agent.name} is starting.") + + async def on_end( + self, + context: RunContextWrapper[Any], + agent: Agent[Any], + output: Any, + ) -> None: + print(f"#### {agent.name} produced output: {output}.") + + class ExampleHooks(RunHooks): def __init__(self): self.event_counter = 0 @@ -92,6 +118,7 @@ class FinalResult(BaseModel): instructions="Multiply the number by 2 and then return the final result.", tools=[multiply_by_two], output_type=FinalResult, + hooks=LoggingHooks(), ) start_agent = Agent( @@ -100,6 +127,7 @@ class FinalResult(BaseModel): tools=[random_number], output_type=FinalResult, handoffs=[multiply_agent], + hooks=LoggingHooks(), )