DSPy: The framework for programming—not prompting—language models
Python
Close the LM findings still open on main: streamify errors, dead-loop pools, strict schemas (#10451)
Maxime Rivest40a6e168914a
diff --git a/dspy/clients/execution.py b/dspy/clients/execution.pyindex dccc74a6c..9f59bc712 100644--- a/dspy/clients/execution.py+++ b/dspy/clients/execution.py@@ -174,12 +174,12 @@ def _canonical(call, *, compat=None):if key not in CLIENT_KEYS | {"n", "rollout_id", "num_generations", "prompt_cache"} and val is not None}format_ = body.get("response_format")if isinstance(format_, type) and issubclass(format_, pydantic.BaseModel):- from dspy.clients.legacy_requests import _close_object_schemas+ from dspy.clients.legacy_requests import _strict_json_schema- # Match the legacy Responses path's preparation of generated schemas.- # Raw caller-supplied schemas remain unchanged.+ # A generated schema is sent strict, so it is shaped as strict mode+ # takes it. Raw caller-supplied schemas remain unchanged.body["response_format"] = {"type": "json_schema", "json_schema": {- "name": format_.__name__, "schema": _close_object_schemas(format_.model_json_schema()), "strict": True,+ "name": format_.__name__, "schema": _strict_json_schema(format_.model_json_schema()), "strict": True,}}request = request_from_openai_chat(body, compat=compat)prompt_cache = call.legacy.get("prompt_cache")@@ -341,6 +341,8 @@ def _select_engine(lm, call, asynchronous):with lm._engine_lock:backend = lm._engine_store.get(key)if backend is None:+ if loop is not None:+ lm._reap_closed_loops()provider = resolution.providerapi_keys = {provider: clients["api_key"]} if "api_key" in clients else Noneurl = clients.get("api_base") or clients.get("base_url")@@ -531,6 +533,25 @@ def _accept_legacy(state, result):state.result = result+def _hint_responses_api(lm, exc):+ """OpenAI serves function tools for its reasoning models on the Responses+ API only, and says so in its refusal ("use /v1/responses"). DSPy has the+ switch — model_type="responses" — so the error names it. No endpoint is+ chosen for the caller: which models need it is OpenAI's policy, not+ DSPy's to guess."""+ from dspy.utils.exceptions import LMInvalidRequestError++ if not isinstance(exc, LMInvalidRequestError) or getattr(lm, "model_type", None) != "chat":+ return+ message = getattr(exc, "message", "") or ""+ if "/v1/responses" not in message or "DSPy:" in message:+ return+ hint = " DSPy: construct the LM with model_type='responses' to use the Responses API for this model."+ exc.message = message + hint+ if exc.args and isinstance(exc.args[0], str):+ exc.args = (exc.args[0] + hint, *exc.args[1:])++def _account_failed_call(lm, results, primary):if settings.usage_tracker:for result in results:@@ -624,6 +645,7 @@ def execute(lm, call):_store(lm, call, result, False)return resultexcept BaseException as exc:+ _hint_responses_api(lm, exc)_account_failed_call(lm, results, exc)raise@@ -699,6 +721,7 @@ async def aexecute(lm, call):await asyncio.to_thread(_store, lm, call, result, True)return resultexcept BaseException as exc:+ _hint_responses_api(lm, exc)_account_failed_call(lm, results, exc)raisediff --git a/dspy/clients/legacy_requests.py b/dspy/clients/legacy_requests.pyindex a7aaa5cc8..236869104 100644--- a/dspy/clients/legacy_requests.py+++ b/dspy/clients/legacy_requests.py@@ -10,6 +10,55 @@ from typing import Anyimport pydantic+def _strict_json_schema(schema: Any, *, root: dict | None = None) -> Any:+ """The schema as OpenAI's strict structured outputs take it — the rules of+ the OpenAI SDK's ``to_strict_json_schema``: every property required,+ objects closed, ``None`` defaults dropped, a lone ``allOf`` and a ``$ref``+ with siblings unravelled. A generated pydantic schema with defaults or an+ optional submodel was refused by the API before this.+ """+ if not isinstance(schema, dict):+ return schema+ root = schema if root is None else root+ out = dict(schema)+ for key in ("$defs", "definitions"):+ if isinstance(out.get(key), dict):+ out[key] = {name: _strict_json_schema(sub, root=root) for name, sub in out[key].items()}+ if out.get("type") == "object" and "additionalProperties" not in out:+ out["additionalProperties"] = False+ if isinstance(out.get("properties"), dict):+ out["required"] = list(out["properties"])+ out["properties"] = {name: _strict_json_schema(sub, root=root) for name, sub in out["properties"].items()}+ if isinstance(out.get("items"), dict):+ out["items"] = _strict_json_schema(out["items"], root=root)+ if isinstance(out.get("anyOf"), list):+ out["anyOf"] = [_strict_json_schema(item, root=root) for item in out["anyOf"]]+ if isinstance(out.get("allOf"), list):+ if len(out["allOf"]) == 1:+ out.update(_strict_json_schema(out.pop("allOf")[0], root=root))+ else:+ out["allOf"] = [_strict_json_schema(item, root=root) for item in out["allOf"]]+ if "default" in out and out["default"] is None:+ del out["default"]+ ref = out.get("$ref")+ if isinstance(ref, str) and len(out) > 1:+ resolved = _resolve_ref(root, ref)+ if isinstance(resolved, dict):+ out = {**_strict_json_schema(resolved, root=root), **{k: v for k, v in out.items() if k != "$ref"}}+ return out+++def _resolve_ref(root: dict, ref: str) -> Any:+ if not ref.startswith("#/"):+ raise ValueError(f"Unexpected $ref format {ref!r}; only internal references are supported")+ node: Any = root+ for part in ref[2:].split("/"):+ node = node.get(part) if isinstance(node, dict) else None+ if node is None:+ raise ValueError(f"Could not resolve $ref {ref!r}")+ return node++def _close_object_schemas(schema: Any) -> Any:if not isinstance(schema, dict):return schema@@ -111,7 +160,10 @@ def chat_to_responses(request: dict[str, Any]) -> dict[str, Any]:format_ = data.pop("response_format", None)if format_ is not None:if isinstance(format_, type) and issubclass(format_, pydantic.BaseModel):- format_ = {"name": format_.__name__, "type": "json_schema", "schema": _close_object_schemas(format_.model_json_schema())}+ # The same contract as the canonical path: a generated schema is+ # sent strict and shaped for strict mode, on either engine.+ format_ = {"name": format_.__name__, "type": "json_schema",+ "schema": _strict_json_schema(format_.model_json_schema()), "strict": True}data["text"] = {**data.get("text", {}), "format": format_}# The former config serializer omitted absent common generation parameters.for key in ("temperature", "top_p", "n", "logprobs", "reasoning", "tool_choice"):diff --git a/dspy/clients/lm.py b/dspy/clients/lm.pyindex 7b817bf8f..c38c5d3ff 100644--- a/dspy/clients/lm.py+++ b/dspy/clients/lm.py@@ -257,6 +257,12 @@ class LM(BaseLM):"""_check_engines(engine, async_engine)_refuse_client_settings(engine, kwargs)+ if not isinstance(model, str) or not model:+ raise ValueError("model must be a non-empty string")+ _, separator, rest = model.partition("/")+ if separator and not rest:+ # "openai/" selected LiteLLM silently and failed at call time.+ raise ValueError(f"model {model!r} has a provider prefix but no model id after it")if isinstance(num_retries, bool) or not isinstance(num_retries, int) or num_retries < 0:raise ValueError("num_retries must be a nonnegative integer")if prompt_cache is not None:@@ -387,13 +393,29 @@ class LM(BaseLM):"""Configured engine selection ('auto', 'lm15', 'litellm', or an engine object)."""return self._engine_spec+ def _reap_closed_loops(self):+ """Drop async pools whose event loop has closed (under the engine lock).++ Their coroutines can no longer run, so they cannot be aclose()d; the+ engine is simply released, and lm15's pool finalizers close the sockets+ when it is collected. Called on close(), aclose(), and when a new+ loop's pool is created, so a long-lived LM used across many+ asyncio.run() calls does not keep one pool per finished loop.+ """+ dead = [key for key in self._engine_store if key[0] is not None and key[0].is_closed()]+ for key in dead:+ self._engine_store.pop(key)+def close(self):"""Close owned synchronous engine pools after active calls have finished.- Custom engines are borrowed. Async pools must be closed with aclose().- Copies share owned pools; closing one releases those shared resources.+ Custom engines are borrowed. A live event loop's async pools must be+ closed with aclose() on that loop; pools of loops that have already+ closed are released here. Copies share owned pools; closing one+ releases those shared resources."""with self._engine_lock:+ self._reap_closed_loops()keys = [key for key in self._engine_store if key[0] is None]engines = [self._engine_store.pop(key) for key in keys]from contextlib import ExitStack@@ -409,6 +431,7 @@ class LM(BaseLM):loop = asyncio.get_running_loop()with self._engine_lock:+ self._reap_closed_loops()keys = [key for key in self._engine_store if key[0] is loop]engines = [self._engine_store.pop(key) for key in keys]try:diff --git a/dspy/dsp/utils/settings.py b/dspy/dsp/utils/settings.pyindex 61aa81ace..ee951c558 100644--- a/dspy/dsp/utils/settings.py+++ b/dspy/dsp/utils/settings.py@@ -283,13 +283,11 @@ class Settings:"verified sources within a trusted environment.")try:- modules_to_serialize = modules_to_serialize or []- for module in modules_to_serialize:- cloudpickle.register_pickle_by_value(module)+ from dspy.utils.pickle_by_value import serialize_by_valueexclude_keys = exclude_keys or []data = {key: value for key, value in self.config.items() if key not in exclude_keys}- with open(path, "wb") as f:+ with serialize_by_value(modules_to_serialize), open(path, "wb") as f:cloudpickle.dump(data, f)except Exception as e:raise RuntimeError(diff --git a/dspy/primitives/base_module.py b/dspy/primitives/base_module.pyindex 2d2dc57b5..a58336846 100644--- a/dspy/primitives/base_module.py+++ b/dspy/primitives/base_module.py@@ -7,6 +7,7 @@ from pathlib import Pathimport cloudpickleimport orjson+from dspy.utils.pickle_by_value import serialize_by_valuefrom dspy.utils.saving import get_dependency_versions# NOTE: Note: It's important (temporary decision) to maintain named_parameters that's different in behavior from@@ -213,11 +214,7 @@ class BaseModule:logger.warning("Loading untrusted .pkl files can run arbitrary code, which may be dangerous. To avoid "'this, prefer saving using json format using module.save("module.json").')try:- modules_to_serialize = modules_to_serialize or []- for module in modules_to_serialize:- cloudpickle.register_pickle_by_value(module)-- with open(path / "program.pkl", "wb") as f:+ with serialize_by_value(modules_to_serialize), open(path / "program.pkl", "wb") as f:cloudpickle.dump(self, f)except Exception as e:raise RuntimeError(diff --git a/dspy/streaming/streamify.py b/dspy/streaming/streamify.pyindex b3a64e517..1a5aae5f8 100644--- a/dspy/streaming/streamify.py+++ b/dspy/streaming/streamify.py@@ -35,6 +35,23 @@ if TYPE_CHECKING:from dspy.primitives.module import Module+def _single_failure(exc: BaseException) -> BaseException | None:+ """The one exception inside a (possibly nested) exception group, or None+ when ``exc`` is not a group or holds several distinct failures."""+ if not hasattr(exc, "exceptions"):+ return None+ leaves: list[BaseException] = []+ pending = [exc]+ while pending:+ current = pending.pop()+ children = getattr(current, "exceptions", None)+ if children is None:+ leaves.append(current)+ else:+ pending.extend(children)+ return leaves[0] if len(leaves) == 1 else None++def streamify(program: "Module",status_message_provider: StatusMessageProvider | None = None,@@ -184,6 +201,19 @@ def streamify(await stream.send(prediction)async def async_streamer(*args, **kwargs):+ try:+ async for value in _stream_program(args, kwargs):+ yield value+ except BaseException as exc:+ # The task group reports failures as an exception group. One+ # failure is the program's own exception; callers wrote+ # `except dspy.LMError`, and it must catch it.+ leaf = _single_failure(exc)+ if leaf is None:+ raise+ raise leaf from None++ async def _stream_program(args, kwargs):send_stream, receive_stream = anyio.create_memory_object_stream(16)async with anyio.create_task_group() as tg, send_stream, receive_stream:tg.start_soon(generator, args, kwargs, send_stream)diff --git a/dspy/utils/pickle_by_value.py b/dspy/utils/pickle_by_value.pynew file mode 100644index 000000000..ff0e0d49e--- /dev/null+++ b/dspy/utils/pickle_by_value.py@@ -0,0 +1,57 @@+"""Serialize modules by value for the duration of one save.++cloudpickle's ``register_pickle_by_value`` is process-wide state keyed by+module name and lasts until unregistered. DSPy's ``save(modules_to_serialize=...)``+registered and never unregistered, so one save changed how every later+pickle in the process treated any module of that name — including a+program saved without ``modules_to_serialize`` that then loaded where the+module was absent, instead of failing (surfaced by two tests sharing a+module name under xdist).++The registration now lasts exactly as long as the saves that need it.+Because the registry is shared by every thread, ownership is counted here+under one lock: a module is registered on the first active save that asks+for it and unregistered when the last of them finishes, so a save that+overlaps another never loses the registration mid-dump. A module the+caller registered themselves before any save is theirs and is never+unregistered.+"""++import threading+from contextlib import contextmanager++import cloudpickle++_lock = threading.Lock()+_active: dict[str, int] = {} # module name -> saves currently relying on DSPy's registration+++@contextmanager+def serialize_by_value(modules):+ modules = list(modules or [])+ owned: list = []+ with _lock:+ registry = set(cloudpickle.list_registry_pickle_by_value())+ for module in modules:+ name = module.__name__+ if _active.get(name, 0) == 0 and name in registry:+ continue # registered by the caller, not by a save: not ours to count or remove+ if _active.get(name, 0) == 0:+ cloudpickle.register_pickle_by_value(module)+ _active[name] = _active.get(name, 0) + 1+ owned.append(module)+ try:+ yield+ finally:+ with _lock:+ for module in owned:+ name = module.__name__+ remaining = _active.get(name, 0) - 1+ if remaining > 0:+ _active[name] = remaining+ continue+ _active.pop(name, None)+ try:+ cloudpickle.unregister_pickle_by_value(module)+ except ValueError:+ pass # the caller unregistered it during the savediff --git a/tests/clients/test_lm.py b/tests/clients/test_lm.pyindex f863b52e5..1e5b7ccf7 100644--- a/tests/clients/test_lm.py+++ b/tests/clients/test_lm.py@@ -1434,10 +1434,13 @@ def test_responses_api_with_pydantic_model_input():assert "text" in call_argsresponse_format = call_args["text"]["format"]+ # The same strict contract as the native path: closed, every property+ # required, strict: true.assert response_format == {"name": TestModel.__name__,"type": "json_schema","schema": {**TestModel.model_json_schema(), "additionalProperties": False},+ "strict": True,}@@ -1741,3 +1744,27 @@ def test_lm_responses_does_not_validate_reasoning_temperature_client_side():sent = responses.call_args.kwargsassert sent["temperature"] == 0.7assert sent["reasoning"] == {"effort": "low", "summary": "auto"}++[email protected]("model", ["openai/", "anthropic/", ""])+def test_empty_model_id_is_refused_at_construction(model):+ # "openai/" selected LiteLLM silently and failed at call time.+ with pytest.raises(ValueError, match="model"):+ dspy.LM(model, api_key="k")+++def test_responses_only_refusal_names_model_type():+ # OpenAI serves function tools for its reasoning models on the Responses+ # API only and says "use /v1/responses"; DSPy's error names its switch.+ from dspy.clients.execution import _hint_responses_api+ from dspy.utils.exceptions import LMInvalidRequestError++ exc = LMInvalidRequestError("Function tools are not supported in /v1/chat/completions; use /v1/responses", model="m")+ lm = dspy.LM("openai/gpt-5.6-luna", api_key="k", model_type="responses", max_tokens=16000)+ _hint_responses_api(lm, exc)+ assert "DSPy:" not in str(exc) # already on the Responses API+ lm = dspy.LM("openai/gpt-5.6-luna", api_key="k", max_tokens=16000)+ _hint_responses_api(lm, exc)+ _hint_responses_api(lm, exc)+ assert str(exc).count("DSPy:") == 1+ assert "model_type='responses'" in str(exc) and "/v1/responses" in str(exc)diff --git a/tests/clients/test_lm_async_execution.py b/tests/clients/test_lm_async_execution.pyindex 49f10e787..68e20fdff 100644--- a/tests/clients/test_lm_async_execution.py+++ b/tests/clients/test_lm_async_execution.py@@ -166,6 +166,41 @@ def test_same_lm_on_successive_loops(endpoint):assert lm._engine_store == {}+def _open_fds():+ import os++ return len(os.listdir("/proc/self/fd")) if os.path.isdir("/proc/self/fd") else None+++def test_close_releases_pools_of_closed_loops(endpoint):+ # A loop that has finished can no longer aclose() its pool; close()+ # releases it and the sockets are closed, not only the sync pool's.+ import gc++ lm = native_lm(endpoint)+ for _ in range(3):+ asyncio.run(lm.acall("alpha"))+ lm("alpha")+ async_pools = [key for key in lm._engine_store if key[0] is not None]+ assert len(async_pools) == 1 and async_pools[0][0].is_closed() # earlier loops were evicted as each new one came+ before = _open_fds()+ lm.close()+ gc.collect()+ assert lm._engine_store == {}+ if before is not None:+ assert _open_fds() < before+++def test_a_new_loop_evicts_pools_of_closed_loops(endpoint):+ # A long-lived LM used from many asyncio.run() calls does not keep one+ # pool per finished loop; the next loop's pool replaces them.+ lm = native_lm(endpoint)+ for _ in range(4):+ asyncio.run(lm.acall("alpha"))+ assert len([key for key in lm._engine_store if key[0] is not None]) == 1+ lm.close()++@pytest.mark.asyncio@pytest.mark.parametrize("asynchronous", [False, True])@pytest.mark.parametrize("streaming", [False, True])diff --git a/tests/clients/test_lm_schema_conversion.py b/tests/clients/test_lm_schema_conversion.pyindex f0fe7f019..289c1c1f4 100644--- a/tests/clients/test_lm_schema_conversion.py+++ b/tests/clients/test_lm_schema_conversion.py@@ -7,7 +7,7 @@ import pytestimport dspyfrom dspy.clients.execution import _canonical, prepare-from dspy.clients.legacy_requests import chat_to_responses+from dspy.clients.legacy_requests import _strict_json_schema, chat_to_responses@pytest.mark.parametrize("asynchronous", [False, True])@@ -46,3 +46,58 @@ def test_raw_schema_is_not_rewritten(additional_properties):assert _canonical(call).config.response_format["schema"] == original["json_schema"]["schema"]assert format_ == original+++# ─── a generated response_format schema is shaped for OpenAI strict mode ──+++class _Inner(pydantic.BaseModel):+ note: str = "n/a"+++class _Record(pydantic.BaseModel):+ name: str+ count: int = 0+ tag: str | None = None+ inner: _Inner | None = None+ items: list[_Inner] = []+++def test_strict_schema_requires_every_property_and_drops_none_defaults():+ # OpenAI strict mode rejected any pydantic model with defaults or an+ # optional submodel ("required must include every key"). The shape now+ # follows the OpenAI SDK's own to_strict_json_schema rules.+ schema = _strict_json_schema(_Record.model_json_schema())+ assert schema["required"] == ["name", "count", "tag", "inner", "items"]+ assert schema["additionalProperties"] is False+ assert "default" not in schema["properties"]["tag"] # None default dropped+ assert schema["properties"]["count"]["default"] == 0 # a value default is kept, as the OpenAI SDK keeps it+ inner = schema["$defs"]["_Inner"]+ assert inner["required"] == ["note"] and inner["additionalProperties"] is False+ assert {"$ref": "#/$defs/_Inner"} in schema["properties"]["inner"]["anyOf"]+++def test_strict_schema_unravels_a_ref_with_siblings_and_a_lone_allof():+ schema = {"type": "object", "properties": {"a": {"$ref": "#/$defs/A", "description": "d"},+ "b": {"allOf": [{"$ref": "#/$defs/A"}]}},+ "$defs": {"A": {"type": "string"}}}+ out = _strict_json_schema(schema)+ assert out["properties"]["a"] == {"type": "string", "description": "d"}+ assert out["properties"]["b"] == {"$ref": "#/$defs/A"} # a bare ref stays a ref+ assert out["required"] == ["a", "b"]+++def test_pydantic_response_format_is_sent_strict_on_both_paths():+ lm = dspy.LM("openai/gpt-4o", engine="lm15", api_key="k", cache=False)+ request = _canonical(prepare(lm, "hi", None, {"response_format": _Record}))+ fmt = request.config.response_format+ assert fmt["type"] == "json_schema" and fmt.get("strict") is True+ assert fmt["schema"]["required"] == ["name", "count", "tag", "inner", "items"]+ # The forced LiteLLM Responses path converts the legacy body itself and+ # must mean the same contract.+ data = chat_to_responses({"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "hi"}],+ "response_format": _Record})+ fmt = data["text"]["format"]+ assert fmt["type"] == "json_schema" and fmt["strict"] is True+ assert fmt["schema"]["required"] == ["name", "count", "tag", "inner", "items"]+ assert "default" not in fmt["schema"]["properties"]["tag"]diff --git a/tests/primitives/test_base_module.py b/tests/primitives/test_base_module.pyindex f8401df2b..290f32b5a 100644--- a/tests/primitives/test_base_module.py+++ b/tests/primitives/test_base_module.py@@ -542,3 +542,81 @@ def test_forward_through_call_no_warning(capsys):module(x="test")captured = capsys.readouterr()assert "directly is discouraged" not in captured.err+++def test_modules_to_serialize_registration_does_not_outlive_the_save(tmp_path):+ # cloudpickle's by-value registry is process-wide and keyed by module+ # name. A save must not leave a module registered, or every later pickle+ # of any module by that name in the process is by value.+ import sys++ import cloudpickle++ (tmp_path / "scoped_module.py").write_text("def f():\n return 1\n")+ sys.path.insert(0, str(tmp_path))+ try:+ import scoped_module++ assert "scoped_module" not in cloudpickle.list_registry_pickle_by_value()+ dspy.Predict("q -> a").save(tmp_path / "prog", save_program=True, modules_to_serialize=[scoped_module])+ assert "scoped_module" not in cloudpickle.list_registry_pickle_by_value()+ # A registration the caller made themselves is theirs to keep.+ cloudpickle.register_pickle_by_value(scoped_module)+ try:+ dspy.Predict("q -> a").save(tmp_path / "prog2", save_program=True, modules_to_serialize=[scoped_module])+ assert "scoped_module" in cloudpickle.list_registry_pickle_by_value()+ finally:+ cloudpickle.unregister_pickle_by_value(scoped_module)+ finally:+ sys.modules.pop("scoped_module", None)+ sys.path.remove(str(tmp_path))+++def test_overlapping_saves_share_one_by_value_registration(tmp_path):+ # The registry is process-wide. A save that overlaps another must keep+ # the module registered until the last of them is done, or the later+ # one pickles the rest of its objects by reference (greptile on+ # dspy#10451).+ import sys+ import threading++ import cloudpickle++ from dspy.utils.pickle_by_value import serialize_by_value++ (tmp_path / "shared_module.py").write_text("def f():\n return 1\n")+ sys.path.insert(0, str(tmp_path))+ try:+ import shared_module++ def registered():+ return "shared_module" in cloudpickle.list_registry_pickle_by_value()++ # Nested on one thread.+ with serialize_by_value([shared_module]):+ with serialize_by_value([shared_module]):+ assert registered()+ assert registered() # the inner save finishing does not strip the outer one+ assert not registered()++ # Two threads: A enters, B enters, A leaves while B is still saving.+ b_entered, a_left = threading.Event(), threading.Event()+ seen = {}++ def save_b():+ with serialize_by_value([shared_module]):+ b_entered.set()+ a_left.wait(5)+ seen["during_b_after_a_left"] = registered()++ worker = threading.Thread(target=save_b)+ with serialize_by_value([shared_module]):+ worker.start()+ assert b_entered.wait(5)+ a_left.set()+ worker.join(5)+ assert seen["during_b_after_a_left"] is True+ assert not registered()+ finally:+ sys.modules.pop("shared_module", None)+ sys.path.remove(str(tmp_path))diff --git a/tests/streaming/test_streaming.py b/tests/streaming/test_streaming.pyindex cd3904f72..c71080f57 100644--- a/tests/streaming/test_streaming.py+++ b/tests/streaming/test_streaming.py@@ -2078,3 +2078,55 @@ async def test_streaming_reasoning_fallback():assert final_prediction.reasoning.content == "Let's think step by step about this question."# Verify Reasoning object is str-likeassert str(final_prediction.reasoning) == "Let's think step by step about this question."+++# ─── errors inside streamify are the program's own exception ─────────+++class _FailingEngine:+ def complete(self, request):+ from dspy.lm15 import AuthError++ raise AuthError("bad key", provider="x")++ def stream(self, request):+ from dspy.lm15 import AuthError++ raise AuthError("bad key", provider="x")+ yield # a generator that fails before its first event+++def test_streamify_raises_the_public_error_itself():+ # The task group reported every failure as an exception group, so+ # `except dspy.LMError` missed it.+ lm = dspy.LM("custom/failing", engine=_FailingEngine(), cache=False, num_retries=0)+ stream = dspy.streamify(dspy.Predict("q -> a"), async_streaming=False)+ with dspy.context(lm=lm), pytest.raises(dspy.LMAuthError) as info:+ for _ in stream(q="x"):+ pass+ assert not hasattr(info.value, "exceptions") # not a group+++async def test_async_streamify_raises_the_public_error_itself():+ lm = dspy.LM("custom/failing", engine=_FailingEngine(), cache=False, num_retries=0)+ stream = dspy.streamify(dspy.Predict("q -> a"), async_streaming=True)+ with dspy.context(lm=lm), pytest.raises(dspy.LMAuthError):+ async for _ in stream(q="x"):+ pass+++def test_streamify_keeps_a_group_of_several_failures():+ import builtins++ from dspy.streaming.streamify import _single_failure++ group_class = getattr(builtins, "BaseExceptionGroup", None)+ if group_class is None: # Python 3.10: anyio's backport+ import exceptiongroup++ group_class = exceptiongroup.BaseExceptionGroup++ assert _single_failure(group_class("two", [ValueError("a"), ValueError("b")])) is None+ assert isinstance(_single_failure(group_class("outer", [group_class("inner", [KeyError("k")])])), KeyError)+ assert _single_failure(ValueError("plain")) is None