Skip to content

Commit b345761

Browse files
committed
Python: Skip get_final_response in OTel _finalize_stream when stream errored
When a streaming error occurs, _finalize_stream (a cleanup hook registered by AgentTelemetryLayer) was unconditionally calling get_final_response(), which triggers all registered result hooks including after_run context providers. This caused providers to fire incorrectly on error paths. Guard against this by checking result_stream._consumed: True only after StopAsyncIteration (normal completion), False when an exception was raised. The fix applies to both the chat client and agent telemetry layers. Closes microsoft#5231
1 parent 76fe731 commit b345761

1 file changed

Lines changed: 12 additions & 0 deletions

File tree

‎python/packages/core/agent_framework/observability.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1323,6 +1323,12 @@ async def _finalize_stream() -> None:
13231323
from ._types import ChatResponse
13241324

13251325
try:
1326+
if not result_stream._consumed:
1327+
# Stream did not complete normally (e.g., it errored). Skip
1328+
# get_final_response() to avoid firing result hooks such as
1329+
# after_run context providers on error paths. The span is
1330+
# still closed in the finally block below.
1331+
return
13261332
response: ChatResponse[Any] = await result_stream.get_final_response()
13271333
duration = duration_state.get("duration")
13281334
response_attributes = _get_response_attributes(attributes, response)
@@ -1579,6 +1585,12 @@ async def _finalize_stream() -> None:
15791585
from ._types import AgentResponse
15801586

15811587
try:
1588+
if not result_stream._consumed:
1589+
# Stream did not complete normally (e.g., it errored). Skip
1590+
# get_final_response() to avoid firing result hooks such as
1591+
# after_run context providers on error paths. The span is
1592+
# still closed in the finally block below.
1593+
return
15821594
response: AgentResponse[Any] = await result_stream.get_final_response()
15831595
duration = duration_state.get("duration")
15841596
response_attributes = _get_response_attributes(

0 commit comments

Comments
 (0)