Repository navigation
Conversation
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ❌ Deployment failed View logs |
instructor | dd86336 | Apr 12 2026, 04:55 PM |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 2 potential issues.
Bugbot Autofix prepared fixes for both issues found in the latest run.
- ✅ Fixed: Fallback reask always writes to wrong kwargs key
- Updated the streaming fallback reask builder to write back to the provider-specific message field (
contents/chat_history+message/messages) and use the correct minimal message shape for each.
- Updated the streaming fallback reask builder to write back to the provider-specific message field (
- ✅ Fixed: Broad except AttributeError masks unrelated errors silently
- Narrowed the streaming fallback to only trigger for AttributeErrors that indicate missing expected response attributes on stream-like responses, re-raising other AttributeErrors.
Preview (4e6afe6049)
diff --git a/instructor/core/retry.py b/instructor/core/retry.py
--- a/instructor/core/retry.py
+++ b/instructor/core/retry.py
@@ -145,6 +145,134 @@
return []
+def _build_streaming_retry_prompt(exception: Exception) -> str:
+ return (
+ f"Validation Error found:\n{exception}\n"
+ "Recall the function correctly, fix the errors"
+ )
+
+
+def _build_streaming_reask_kwargs(
+ kwargs: dict[str, Any], exception: Exception
+) -> dict[str, Any]:
+ """Build a generic retry prompt when the provider-specific reask path cannot inspect a stream."""
+ kwargs_copy = kwargs.copy()
+ retry_prompt = _build_streaming_retry_prompt(exception)
+
+ # Cohere V1 uses chat_history + message (not messages/contents).
+ if "chat_history" in kwargs_copy or "message" in kwargs_copy:
+ chat_history = kwargs_copy.get("chat_history")
+ if isinstance(chat_history, list):
+ chat_history_copy = chat_history.copy()
+ elif chat_history is None:
+ chat_history_copy = []
+ else:
+ chat_history_copy = list(chat_history)
+
+ message = kwargs_copy.get("message")
+ if message is not None and message != "":
+ chat_history_copy.append({"role": "user", "message": message})
+
+ kwargs_copy["chat_history"] = chat_history_copy
+ kwargs_copy["message"] = retry_prompt
+ return kwargs_copy
+
+ # Gemini/GenAI/VertexAI commonly use "contents".
+ if "contents" in kwargs_copy:
+ contents = kwargs_copy.get("contents")
+ if isinstance(contents, list):
+ contents_copy = contents.copy()
+ elif contents is None:
+ contents_copy = []
+ else:
+ contents_copy = list(contents)
+
+ # Preserve the contents item type when possible (optional deps).
+ sample = next((c for c in contents_copy if c is not None), None)
+ module = getattr(type(sample), "__module__", "") if sample is not None else ""
+
+ if module.startswith("google.genai."):
+ try:
+ from google.genai import types # type: ignore[import-not-found]
+
+ contents_copy.append(
+ types.Content(
+ role="user",
+ parts=[types.Part.from_text(text=retry_prompt)],
+ )
+ )
+ except Exception:
+ contents_copy.append({"role": "user", "parts": [retry_prompt]})
+ elif module.startswith("vertexai."):
+ try:
+ import vertexai.generative_models as gm # type: ignore[import-not-found]
+
+ contents_copy.append(
+ gm.Content(role="user", parts=[gm.Part.from_text(retry_prompt)])
+ )
+ except Exception:
+ contents_copy.append({"role": "user", "parts": [retry_prompt]})
+ else:
+ # Gemini (dict) and safe fallback for unknown content types.
+ contents_copy.append({"role": "user", "parts": [retry_prompt]})
+
+ kwargs_copy["contents"] = contents_copy
+ return kwargs_copy
+
+ # Default: OpenAI-style messages.
+ messages = list(kwargs_copy.get("messages") or [])
+ messages.append({"role": "user", "content": retry_prompt})
+ kwargs_copy["messages"] = messages
+ return kwargs_copy
+
+
+def _should_fallback_to_streaming_reask(
+ exception: Exception,
+ response: Any, # noqa: ARG001
+) -> bool:
+ """Return True when a provider reask handler failed because it inspected a stream."""
+ if not isinstance(exception, AttributeError):
+ return False
+
+ expected_attrs = {"choices", "output", "candidates", "parts", "message", "text"}
+ attr_name = getattr(exception, "name", None)
+ if attr_name not in expected_attrs:
+ message = str(exception)
+ if "has no attribute" not in message or not any(
+ f"has no attribute '{a}'" in message for a in expected_attrs
+ ):
+ return False
+
+ response_type = type(response).__name__.lower() if response is not None else ""
+ return "stream" in response_type
+
+
+def _handle_reask_kwargs_with_streaming_fallback(
+ kwargs: dict[str, Any],
+ mode: Mode,
+ response: Any,
+ exception: Exception,
+ failed_attempts: list[Any] | None = None,
+) -> dict[str, Any]:
+ try:
+ return handle_reask_kwargs(
+ kwargs=kwargs,
+ mode=mode,
+ response=response,
+ exception=exception,
+ failed_attempts=failed_attempts,
+ )
+ except AttributeError as e:
+ if _should_fallback_to_streaming_reask(e, response):
+ logger.debug(
+ "Provider reask handler could not inspect streaming response; "
+ "falling back to a generic retry prompt.",
+ exc_info=e,
+ )
+ return _build_streaming_reask_kwargs(kwargs, exception)
+ raise
+
+
def retry_sync(
func: Callable[T_ParamSpec, T_Retval],
response_model: type[T_Model] | None,
@@ -251,8 +379,7 @@
max_attempts=max_attempt_number,
is_last_attempt=True,
)
-
- kwargs = handle_reask_kwargs(
+ kwargs = _handle_reask_kwargs_with_streaming_fallback(
kwargs=kwargs,
mode=mode,
response=response,
@@ -430,8 +557,7 @@
max_attempts=max_attempt_number,
is_last_attempt=True,
)
-
- kwargs = handle_reask_kwargs(
+ kwargs = _handle_reask_kwargs_with_streaming_fallback(
kwargs=kwargs,
mode=mode,
response=response,
diff --git a/instructor/processing/response.py b/instructor/processing/response.py
--- a/instructor/processing/response.py
+++ b/instructor/processing/response.py
@@ -241,7 +241,7 @@
and issubclass(response_model, PartialBase)
and stream
):
- # Return the AsyncGenerator directly for streaming Partial responses.
+ # Preserve streaming behavior for `create_partial()`.
return response_model.from_streaming_response_async( # type: ignore[return-value,arg-type]
cast(AsyncGenerator[Any, None], response),
mode=mode,
@@ -359,12 +359,10 @@
and issubclass(response_model, PartialBase)
and stream
):
- # Collect partial stream to surface validation errors inside retry logic.
- return list(
- response_model.from_streaming_response( # type: ignore
- response,
- mode=mode,
- )
+ # Preserve streaming behavior for `create_partial()`.
+ return response_model.from_streaming_response( # type: ignore[return-value]
+ response,
+ mode=mode,
)
model = response_model.from_response( # type: ignore
diff --git a/tests/test_process_response_streaming.py b/tests/test_process_response_streaming.py
new file mode 100644
--- /dev/null
+++ b/tests/test_process_response_streaming.py
@@ -1,0 +1,134 @@
+from __future__ import annotations
+
+from collections.abc import AsyncGenerator, Generator
+
+import pytest
+from pydantic import BaseModel
+
+from instructor.dsl.iterable import IterableBase
+from instructor.dsl.partial import PartialBase
+from instructor.mode import Mode
+from instructor.processing.response import process_response, process_response_async
+
+
+class DummyCompletion(BaseModel):
+ """Minimal stand-in for a provider completion object."""
+
+
+class DummyIterableModel(BaseModel, IterableBase):
+ tasks: list[int]
+
+ @classmethod
+ def from_response(cls, completion, **kwargs): # noqa: ANN001,ARG003
+ return cls(tasks=[1, 2])
+
+ @classmethod
+ def from_streaming_response( # noqa: ANN001
+ cls, _completion, mode: Mode, **_kwargs
+ ) -> Generator[int, None, None]:
+ del mode
+ yield 1
+ yield 2
+
+ @classmethod
+ async def from_streaming_response_async( # noqa: ANN001
+ cls, _completion, mode: Mode, **_kwargs
+ ) -> AsyncGenerator[int, None]:
+ del mode
+ yield 1
+ yield 2
+
+
+class DummyPartialModel(BaseModel, PartialBase):
+ value: str | None = None
+
+ @classmethod
+ def from_response(cls, completion, **kwargs): # noqa: ANN001,ARG003
+ return cls(value="final")
+
+ @classmethod
+ def from_streaming_response( # noqa: ANN001
+ cls, _completion, mode: Mode, **_kwargs
+ ) -> Generator[BaseModel, None, None]:
+ del mode
+ yield cls(value=None)
+ yield cls(value="streamed")
+
+ @classmethod
+ async def from_streaming_response_async( # noqa: ANN001
+ cls, _completion, mode: Mode, **_kwargs
+ ) -> AsyncGenerator[BaseModel, None]:
+ del mode
+ yield cls(value=None)
+ yield cls(value="streamed")
+
+
+def test_process_response_streaming_returns_generator_for_partial_model():
+ raw = DummyCompletion()
+
+ result = process_response(
+ raw,
+ response_model=DummyPartialModel,
+ stream=True,
+ mode=Mode.TOOLS,
+ )
+
+ assert not isinstance(result, list)
+ assert list(result) == [
+ DummyPartialModel(value=None),
+ DummyPartialModel(value="streamed"),
+ ]
+
+
+@pytest.mark.asyncio
+async def test_process_response_async_streaming_returns_async_generator_for_partial_model():
+ async def completion_stream() -> AsyncGenerator[object, None]:
+ yield object()
+
+ result = await process_response_async(
+ completion_stream(), # type: ignore[arg-type]
+ response_model=DummyPartialModel,
+ stream=True,
+ mode=Mode.TOOLS,
+ )
+
+ collected: list[DummyPartialModel] = []
+ async for item in result:
+ collected.append(item)
+
+ assert collected == [
+ DummyPartialModel(value=None),
+ DummyPartialModel(value="streamed"),
+ ]
+
+
+def test_process_response_streaming_preserves_iterable_generator_behavior():
+ raw = DummyCompletion()
+
+ result = process_response(
+ raw,
+ response_model=DummyIterableModel,
+ stream=True,
+ mode=Mode.TOOLS,
+ )
+
+ assert list(result) == [1, 2]
+
+
+@pytest.mark.asyncio
+async def test_process_response_async_streaming_preserves_iterable_generator_behavior():
+ async def completion_stream() -> AsyncGenerator[object, None]:
+ yield object()
+
+ result = await process_response_async(
+ completion_stream(), # type: ignore[arg-type]
+ response_model=DummyIterableModel,
+ stream=True,
+ mode=Mode.TOOLS,
+ )
+
+ collected: list[int] = []
+ async for item in result:
+ collected.append(item)
+
+ assert collected == [1, 2]
diff --git a/tests/test_streaming_reask_bug.py b/tests/test_streaming_reask_bug.py
--- a/tests/test_streaming_reask_bug.py
+++ b/tests/test_streaming_reask_bug.py
@@ -12,6 +12,13 @@
import pytest
from pydantic import ValidationError, BaseModel, field_validator
+from instructor.core.exceptions import InstructorRetryException
+from instructor.core.retry import (
+ _build_streaming_reask_kwargs,
+ _handle_reask_kwargs_with_streaming_fallback,
+ _should_fallback_to_streaming_reask,
+ retry_sync,
+)
from instructor.mode import Mode
from instructor.processing.response import handle_reask_kwargs
@@ -182,7 +189,143 @@
assert "messages" in result
+ def test_build_streaming_reask_kwargs_preserves_provider_shape(self):
+ """Test that the fallback keeps provider-specific containers when present."""
+ exception = create_mock_validation_error()
+ gemini_kwargs = {
+ "contents": [{"role": "user", "parts": ["test"]}],
+ "tools": [{"type": "function", "function": {"name": "test"}}],
+ }
+ gemini_result = _build_streaming_reask_kwargs(gemini_kwargs, exception)
+
+ assert "contents" in gemini_result
+ assert "messages" not in gemini_result
+ assert gemini_result["contents"][-1]["role"] == "user"
+ assert gemini_result["contents"][-1]["parts"][0].startswith(
+ "Validation Error found:\n"
+ )
+ assert (
+ "Recall the function correctly, fix the errors"
+ in gemini_result["contents"][-1]["parts"][0]
+ )
+
+ cohere_kwargs = {
+ "chat_history": [{"role": "user", "message": "prior"}],
+ "message": "current",
+ }
+ cohere_result = _build_streaming_reask_kwargs(cohere_kwargs, exception)
+
+ assert "chat_history" in cohere_result
+ assert "messages" not in cohere_result
+ assert cohere_result["chat_history"][-1] == {
+ "role": "user",
+ "message": "current",
+ }
+ assert cohere_result["message"].startswith("Validation Error found:\n")
+
+ def test_streaming_fallback_helper_rejects_unrelated_attribute_error(
+ self, monkeypatch
+ ):
+ """Test that only the known stream-inspection AttributeError uses the fallback."""
+ from instructor.core import retry as retry_module
+
+ validation_error = create_mock_validation_error()
+
+ def fake_handle_reask_kwargs(
+ kwargs: dict[str, Any],
+ mode: Mode,
+ response: Any,
+ exception: Exception,
+ failed_attempts: list[Any] | None = None,
+ ) -> dict[str, Any]:
+ del kwargs, mode, response, exception, failed_attempts
+ raise AttributeError("'Stream' object has no attribute 'something_else'")
+
+ monkeypatch.setattr(
+ retry_module, "handle_reask_kwargs", fake_handle_reask_kwargs
+ )
+
+ with pytest.raises(AttributeError, match="something_else"):
+ _handle_reask_kwargs_with_streaming_fallback(
+ kwargs={"messages": [{"role": "user", "content": "test"}]},
+ mode=Mode.TOOLS,
+ response=MockStream(),
+ exception=validation_error,
+ )
+
+ assert not _should_fallback_to_streaming_reask(
+ AttributeError("'Stream' object has no attribute 'something_else'"),
+ MockStream(),
+ )
+
+ def test_retry_sync_falls_back_when_reask_handler_cannot_inspect_stream(
+ self, monkeypatch
+ ):
+ """Test that retry handling falls back to a generic prompt for raw streams."""
+
+ from instructor.core import retry as retry_module
+
+ validation_error = create_mock_validation_error()
+ fallback_calls: list[dict[str, Any]] = []
+
+ def fake_process_response(*args, **kwargs): # noqa: ANN001,ARG001
+ raise validation_error
+
+ def fake_handle_reask_kwargs(
+ kwargs: dict[str, Any],
+ mode: Mode,
+ response: Any,
+ exception: Exception,
+ failed_attempts: list[Any] | None = None, # noqa: ARG001
+ ) -> dict[str, Any]:
+ del kwargs, mode, exception, failed_attempts
+ if response is not None:
+ raise AttributeError("'Stream' object has no attribute 'choices'")
+ return {"messages": [{"role": "user", "content": "fallback"}]}
+
+ def fake_build_streaming_reask_kwargs(
+ kwargs: dict[str, Any], exception: Exception
+ ) -> dict[str, Any]:
+ fallback_calls.append({"kwargs": kwargs.copy(), "exception": exception})
+ return {
+ **kwargs,
+ "messages": [
+ *kwargs.get("messages", []),
+ {"role": "user", "content": "fallback"},
+ ],
+ }
+
+ monkeypatch.setattr(retry_module, "process_response", fake_process_response)
+ monkeypatch.setattr(
+ retry_module, "handle_reask_kwargs", fake_handle_reask_kwargs
+ )
+ monkeypatch.setattr(
+ retry_module,
+ "_build_streaming_reask_kwargs",
+ fake_build_streaming_reask_kwargs,
+ )
+
+ def fake_func(*args, **kwargs): # noqa: ANN001,ARG001
+ return MockStream()
+
+ with pytest.raises(InstructorRetryException):
+ retry_sync(
+ func=fake_func,
+ response_model=None,
+ args=(),
+ kwargs={
+ "messages": [{"role": "user", "content": "test"}],
+ "stream": True,
+ },
+ mode=Mode.TOOLS,
+ max_retries=1,
+ )
+
+ assert fallback_calls
+ assert fallback_calls[0]["kwargs"]["messages"][0]["content"] == "test"
+
+
@pytest.mark.skipif(
not pytest.importorskip("openai", reason="openai not installed"),
reason="openai not installed",
@@ -204,7 +347,7 @@
return instructor.from_openai(OpenAI())
def test_streaming_with_retries_and_failing_validator(self, client):
- """Test that streaming with retries doesn't crash on validation failure.
+ """Test that streaming validation failures surface without stream crashes.
This test verifies that the reask handler doesn't crash with
"'Stream' object has no attribute 'choices'" when validation fails
@@ -221,11 +364,8 @@
def always_fail(cls, v: str) -> str: # noqa: ARG003
raise ValueError("This validator always fails for testing")
- # This should not crash with AttributeError about Stream.choices
- # It should raise InstructorRetryException after retries are exhausted
- from instructor.core.exceptions import InstructorRetryException
-
- with pytest.raises(InstructorRetryException):
+ # This should not crash with AttributeError about Stream.choices.
+ with pytest.raises(ValidationError):
list(
client.chat.completions.create_partial(
model="gpt-4o-mini",You can send follow-ups to the cloud agent here.
Reviewed by Cursor Bugbot for commit 2ec86cc. Configure here.
| } | ||
| ) | ||
| kwargs_copy["messages"] = messages | ||
| return kwargs_copy |
There was a problem hiding this comment.
Fallback reask always writes to wrong kwargs key
Medium Severity
_build_streaming_reask_kwargs always writes the updated messages to kwargs_copy["messages"], regardless of which key the provider actually uses. extract_messages correctly reads from "contents" (Gemini/VertexAI) or "chat_history" (Cohere V1), but the result is always stored back under "messages". This leaves the original provider-specific key unchanged, so the retry prompt is silently lost for non-OpenAI providers. Additionally, the appended message uses OpenAI format ("content" string) rather than the provider-specific format (e.g., Gemini expects "parts" list).
Reviewed by Cursor Bugbot for commit 2ec86cc. Configure here.
| "Provider reask handler could not inspect streaming response; " | ||
| "falling back to a generic retry prompt." | ||
| ) | ||
| kwargs = _build_streaming_reask_kwargs(kwargs, e) |
There was a problem hiding this comment.
Broad except AttributeError masks unrelated errors silently
Low Severity
The bare except AttributeError around handle_reask_kwargs catches any AttributeError from anywhere within that call chain, not just the intended 'Stream' object has no attribute 'choices' scenario. If a provider-specific reask handler has a genuine bug that raises AttributeError for an unrelated reason, it gets silently swallowed with only a DEBUG log, and the generic fallback is used instead. This makes real bugs in reask handlers very difficult to diagnose.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 2ec86cc. Configure here.
- Streaming fallback now updates provider-specific message keys and shapes\n- Narrow AttributeError fallback to streaming-missing-attrs cases
## Summary - accumulate declared, nested, and unknown numeric OpenAI/Anthropic usage fields across retries while preserving non-numeric metadata - add corrective feedback when a Responses API retry receives no tool call - preserve raw iterable type hints through sync and async v2 parallel-tool wrappers - strengthen API-key-free coverage for current and future SDK usage counters ## Consolidated and superseded items - closes #2493 - consolidates contributor work from #2498, #2500, and #2501 with original commit authorship preserved - supersedes #2497 because it drops unknown `model_extra` counters - supersedes #2499 because its hand-maintained provider field lists would drift as SDKs evolve ## Validation - focused changed-surface suite: `110 passed` - broad offline v2/coverage suite: `2368 passed, 91 skipped, 73 deselected` - Ruff check and format check: passed - scoped `ty check`: passed - `uv lock --check`: passed - pre-commit hooks and `git diff --check`: passed The 73 deselected tests require live provider credentials. An unfiltered local run confirmed its 22 failures were provider network connections in the restricted environment; GitHub provider jobs remain the authoritative validation for those paths. ## Intentionally skipped - provider additions or expansions: #2436, #2435, #2423, #2409, #2384, #2322, #2306, #2298, #2283, #2168, #2086; issues #2408, #2383, #2365, #2260, #2084, #2076 - broad architecture, product, security, or streaming decisions: #2394, #2392, #2357, #2356, #2355, #2351, #2321, #2307, #2287, #2263; issues #2479, #2403, #2393, #2391, #2316, #2272, #2056 - dependency batch: #2433 - nontrivial examples and editorial/resource additions: #2468, #2405, #2401, #2354, #2346, #2311, #2305; issue #2404 These remain open because they need dedicated product, architecture, provider, security, dependency, or editorial review and are not required for the `1.15.5` patch release. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes retry usage totals and reask message content on failure paths; scope is limited and heavily covered by tests, with no auth or data-store changes. > > **Overview** > Bundles three v2 retry and wrapper fixes for a patch release. > > **Retry usage accounting** replaces hand-maintained token field sums with generic `_accumulate_models` on Pydantic usage objects. Numeric fields (including nested models and `model_extra` counters) add across retries; booleans and other non-numeric metadata are not treated as billable. OpenAI and Anthropic paths share this logic. > > **OpenAI Responses reask** appends a user correction when `RESPONSES_TOOLS` validation fails but the output has no tool calls (e.g. reasoning-only), so retries include feedback instead of repeating the same request. > > **Parallel tools** in `patch_v2` skips `prepare_response_model` and does not replace `response_model` with the handler’s prepared wrapper for parallel modes, keeping raw `Iterable[...]` hints so schemas and parsed results include every member type. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit bbddca1. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
|
Closing as stale and superseded by current |


Summary
Make sync
create_partial()preserve true streaming behavior instead of buffering the full partial stream, and add a safer retry fallback when a streaming response cannot be inspected by provider-specific reask helpers.Tests
uv run pytest tests/test_process_response_streaming.py tests/test_list_response_wrapper.py tests/test_streaming_reask_bug.py -quv run pytest tests/test_process_response_streaming.py tests/test_streaming_reask_bug.py -qNote
Medium Risk
Changes streaming return types for
PartialBasemodels and alters retry re-ask handling on validation failures, which can impact downstream consumers and retry behavior in streaming flows.Overview
Preserves true streaming for
create_partial()by stoppingprocess_responsefrom bufferingPartialBasestreaming results into a list, returning the generator/async-generator instead.Hardens retry logic for streaming validation failures by catching
AttributeErrorwhen provider-specifichandle_reask_kwargscan’t inspect a raw stream and falling back to a generic “retry with validation error” message builder.Adds focused tests to assert generator behavior for
PartialBase/IterableBasein sync+async processing and to verify the new retry fallback path for uninspectable streaming responses (and adjusts the integration test expectation accordingly).Reviewed by Cursor Bugbot for commit 2ec86cc. Configure here.