Skip to content

The agent engineering platform.

core: in astream_events v2 always await task even if already finished (#22916)

Nuno Campos338180f38350
diff --git a/libs/core/langchain_core/tracers/event_stream.py b/libs/core/langchain_core/tracers/event_stream.py
index ad2d4eb692..b7c6fa0359 100644
--- a/libs/core/langchain_core/tracers/event_stream.py
+++ b/libs/core/langchain_core/tracers/event_stream.py
@@ -940,9 +940,10 @@ async def _astream_events_implementation_v2(
yield event
finally:
- # Wait for the runnable to finish, if not cancelled (eg. by break)
- if task.cancel():
- try:
- await task
- except asyncio.CancelledError:
- pass
+ # Cancel the task if it's still running
+ task.cancel()
+ # Await it anyway, to run any cleanup code, and propagate any exceptions
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass