1616
1717import inspect
1818import logging
19- import sys
2019from typing import Any
2120from typing import AsyncGenerator
2221from typing import Awaitable
4342from ..events .event_actions import EventActions
4443from ..features import experimental
4544from ..features import FeatureName
46- from ..telemetry import tracing
47- from ..telemetry .tracing import tracer
45+ from ..telemetry import _instrumentation
4846from ..utils .context_utils import Aclosing
4947from .base_agent_config import BaseAgentConfig
5048from .callback_context import CallbackContext
@@ -286,11 +284,8 @@ async def run_async(
286284 Event: the events generated by the agent.
287285 """
288286
289- cm = tracer .start_as_current_span (f'invoke_agent { self .name } ' )
290- span = cm .__enter__ ()
291- try :
292- ctx = self ._create_invocation_context (parent_context )
293- tracing .trace_agent_invocation (span , self , ctx )
287+ ctx = self ._create_invocation_context (parent_context )
288+ async with _instrumentation .record_agent_invocation (ctx , self ):
294289 if event := await self ._handle_before_agent_callback (ctx ):
295290 yield event
296291 if ctx .end_invocation :
@@ -305,23 +300,6 @@ async def run_async(
305300
306301 if event := await self ._handle_after_agent_callback (ctx ):
307302 yield event
308- except BaseException :
309- try :
310- cm .__exit__ (* sys .exc_info ())
311- except ValueError :
312- logger .warning (
313- 'Failed to detach context during generator cleanup, likely due to'
314- ' cancellation.'
315- )
316- raise
317- else :
318- try :
319- cm .__exit__ (None , None , None )
320- except ValueError :
321- logger .warning (
322- 'Failed to detach context during generator cleanup, likely due to'
323- ' cancellation.'
324- )
325303
326304 @final
327305 async def run_live (
@@ -338,9 +316,8 @@ async def run_live(
338316 Event: the events generated by the agent.
339317 """
340318
341- with tracer .start_as_current_span (f'invoke_agent { self .name } ' ) as span :
342- ctx = self ._create_invocation_context (parent_context )
343- tracing .trace_agent_invocation (span , self , ctx )
319+ ctx = self ._create_invocation_context (parent_context )
320+ async with _instrumentation .record_agent_invocation (ctx , self ):
344321 if event := await self ._handle_before_agent_callback (ctx ):
345322 yield event
346323 if ctx .end_invocation :
0 commit comments