DSPy: The framework for programming—not prompting—language models
Python
fix: propagate sync streaming errors (#9864)
Yufeng He661467b77a9f
diff --git a/dspy/streaming/streamify.py b/dspy/streaming/streamify.pyindex 90a055baa..70bdbab16 100644--- a/dspy/streaming/streamify.py+++ b/dspy/streaming/streamify.py@@ -232,6 +232,7 @@ def apply_sync_streaming(async_generator: AsyncGenerator) -> Generator:"""Convert the async streaming generator to a sync generator."""queue = Queue() # Queue to hold items from the async generatorstop_sentinel = object() # Sentinel to signal the generator is complete+ exception_sentinel = object()# To propagate prediction request ID context to the child threadcontext = contextvars.copy_context()@@ -243,6 +244,8 @@ def apply_sync_streaming(async_generator: AsyncGenerator) -> Generator:try:async for item in async_generator:queue.put(item)+ except BaseException as exc:+ queue.put((exception_sentinel, exc))finally:# Signal completionqueue.put(stop_sentinel)@@ -258,6 +261,8 @@ def apply_sync_streaming(async_generator: AsyncGenerator) -> Generator:item = queue.get() # Block until an item is availableif item is stop_sentinel:break+ if isinstance(item, tuple) and len(item) == 2 and item[0] is exception_sentinel:+ raise item[1]yield itemdiff --git a/tests/streaming/test_streaming.py b/tests/streaming/test_streaming.pyindex 315aa5b1c..829a63c76 100644--- a/tests/streaming/test_streaming.py+++ b/tests/streaming/test_streaming.py@@ -415,6 +415,21 @@ def test_sync_status_streaming():assert status_messages[1].message == "Tool calling finished! Querying the LLM with tool calling results..."+def test_apply_sync_streaming_propagates_generator_exceptions():+ class StreamFailureError(RuntimeError):+ pass++ async def failing_stream():+ yield "first"+ raise StreamFailureError("stream broke")++ sync_output = dspy.streaming.apply_sync_streaming(failing_stream())++ assert next(sync_output) == "first"+ with pytest.raises(StreamFailureError, match="stream broke"):+ next(sync_output)++@pytest.mark.anyioasync def test_stream_listener_returns_correct_chunk_chat_adapter():class MyProgram(dspy.Module):