Skip to content

Commit ac64c02

Browse files
authored
Add agent hooks to lifecycle_example (#1809)
1 parent 7b2ba37 commit ac64c02

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

examples/basic/lifecycle_example.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,36 @@
44

55
from pydantic import BaseModel
66

7-
from agents import Agent, RunContextWrapper, RunHooks, Runner, Tool, Usage, function_tool
7+
from agents import (
8+
Agent,
9+
AgentHooks,
10+
RunContextWrapper,
11+
RunHooks,
12+
Runner,
13+
Tool,
14+
Usage,
15+
function_tool,
16+
)
817
from agents.items import ModelResponse, TResponseInputItem
918

1019

20+
class LoggingHooks(AgentHooks[Any]):
21+
async def on_start(
22+
self,
23+
context: RunContextWrapper[Any],
24+
agent: Agent[Any],
25+
) -> None:
26+
print(f"#### {agent.name} is starting.")
27+
28+
async def on_end(
29+
self,
30+
context: RunContextWrapper[Any],
31+
agent: Agent[Any],
32+
output: Any,
33+
) -> None:
34+
print(f"#### {agent.name} produced output: {output}.")
35+
36+
1137
class ExampleHooks(RunHooks):
1238
def __init__(self):
1339
self.event_counter = 0
@@ -92,6 +118,7 @@ class FinalResult(BaseModel):
92118
instructions="Multiply the number by 2 and then return the final result.",
93119
tools=[multiply_by_two],
94120
output_type=FinalResult,
121+
hooks=LoggingHooks(),
95122
)
96123

97124
start_agent = Agent(
@@ -100,6 +127,7 @@ class FinalResult(BaseModel):
100127
tools=[random_number],
101128
output_type=FinalResult,
102129
handoffs=[multiply_agent],
130+
hooks=LoggingHooks(),
103131
)
104132

105133

0 commit comments

Comments
 (0)