Skip to content

Commit ec7ad25

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 dd3d085 commit ec7ad25

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
@@ -1329,6 +1329,12 @@ async def _finalize_stream() -> None:
13291329
from ._types import ChatResponse
13301330

13311331
try:
1332+
if not result_stream._consumed:
1333+
# Stream did not complete normally (e.g., it errored). Skip
1334+
# get_final_response() to avoid firing result hooks such as
1335+
# after_run context providers on error paths. The span is
1336+
# still closed in the finally block below.
1337+
return
13321338
response: ChatResponse[Any] = await result_stream.get_final_response()
13331339
duration = duration_state.get("duration")
13341340
response_attributes = _get_response_attributes(attributes, response)
@@ -1644,6 +1650,12 @@ async def _finalize_stream() -> None:
16441650
from ._types import AgentResponse
16451651

16461652
try:
1653+
if not result_stream._consumed:
1654+
# Stream did not complete normally (e.g., it errored). Skip
1655+
# get_final_response() to avoid firing result hooks such as
1656+
# after_run context providers on error paths. The span is
1657+
# still closed in the finally block below.
1658+
return
16471659
response: AgentResponse[Any] = await result_stream.get_final_response()
16481660
duration = duration_state.get("duration")
16491661
response_attributes = _get_response_attributes(

0 commit comments

Comments
 (0)