Skip to content

Commit 4ba2e8a

Browse files
authored
docs: improve typing in lifecycle hook example code (#2002)
1 parent 8f4c2cd commit 4ba2e8a

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

examples/basic/lifecycle_example.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import asyncio
22
import random
3-
from typing import Any, Optional
3+
from typing import Any, Optional, cast
44

55
from pydantic import BaseModel
66

@@ -15,6 +15,7 @@
1515
function_tool,
1616
)
1717
from agents.items import ModelResponse, TResponseInputItem
18+
from agents.tool_context import ToolContext
1819

1920

2021
class LoggingHooks(AgentHooks[Any]):
@@ -71,16 +72,22 @@ async def on_agent_end(self, context: RunContextWrapper, agent: Agent, output: A
7172

7273
async def on_tool_start(self, context: RunContextWrapper, agent: Agent, tool: Tool) -> None:
7374
self.event_counter += 1
75+
# While this type cast is not ideal,
76+
# we don't plan to change the context arg type in the near future for backwards compatibility.
77+
tool_context = cast(ToolContext[Any], context)
7478
print(
75-
f"### {self.event_counter}: Tool {tool.name} started. name={context.tool_name}, call_id={context.tool_call_id}, args={context.tool_arguments}. Usage: {self._usage_to_str(context.usage)}" # type: ignore[attr-defined]
79+
f"### {self.event_counter}: Tool {tool.name} started. name={tool_context.tool_name}, call_id={tool_context.tool_call_id}, args={tool_context.tool_arguments}. Usage: {self._usage_to_str(tool_context.usage)}"
7680
)
7781

7882
async def on_tool_end(
7983
self, context: RunContextWrapper, agent: Agent, tool: Tool, result: str
8084
) -> None:
8185
self.event_counter += 1
86+
# While this type cast is not ideal,
87+
# we don't plan to change the context arg type in the near future for backwards compatibility.
88+
tool_context = cast(ToolContext[Any], context)
8289
print(
83-
f"### {self.event_counter}: Tool {tool.name} finished. result={result}, name={context.tool_name}, call_id={context.tool_call_id}, args={context.tool_arguments}. Usage: {self._usage_to_str(context.usage)}" # type: ignore[attr-defined]
90+
f"### {self.event_counter}: Tool {tool.name} finished. result={result}, name={tool_context.tool_name}, call_id={tool_context.tool_call_id}, args={tool_context.tool_arguments}. Usage: {self._usage_to_str(tool_context.usage)}"
8491
)
8592

8693
async def on_handoff(

0 commit comments

Comments
 (0)