|
| 1 | +"""Test for streaming reask bug fix. |
| 2 | +
|
| 3 | +Bug: When using streaming mode with max_retries > 1, if validation fails, |
| 4 | +the reask handlers crash with "'Stream' object has no attribute 'choices'" |
| 5 | +because they expect a ChatCompletion but receive a Stream object. |
| 6 | +
|
| 7 | +GitHub Issue: https://github.com/jxnl/instructor/issues/1991 |
| 8 | +""" |
| 9 | + |
| 10 | +import pytest |
| 11 | +from unittest.mock import MagicMock |
| 12 | +from pydantic import ValidationError, BaseModel, field_validator |
| 13 | + |
| 14 | +from instructor.mode import Mode |
| 15 | +from instructor.processing.response import handle_reask_kwargs |
| 16 | + |
| 17 | + |
| 18 | +class MockStream: |
| 19 | + """Mock Stream object that mimics openai.Stream behavior.""" |
| 20 | + |
| 21 | + def __iter__(self): |
| 22 | + return iter([]) |
| 23 | + |
| 24 | + def __next__(self): |
| 25 | + raise StopIteration |
| 26 | + |
| 27 | + |
| 28 | +def create_mock_validation_error(): |
| 29 | + """Create a real Pydantic ValidationError for testing.""" |
| 30 | + |
| 31 | + class TestModel(BaseModel): |
| 32 | + name: str |
| 33 | + |
| 34 | + @field_validator("name") |
| 35 | + @classmethod |
| 36 | + def must_have_space(cls, v): |
| 37 | + if " " not in v: |
| 38 | + raise ValueError("must contain space") |
| 39 | + return v |
| 40 | + |
| 41 | + try: |
| 42 | + TestModel(name="John") |
| 43 | + except ValidationError as e: |
| 44 | + return e |
| 45 | + |
| 46 | + |
| 47 | +class TestStreamingReaskBug: |
| 48 | + """Tests for the streaming reask bug fix.""" |
| 49 | + |
| 50 | + def test_reask_tools_with_stream_object_does_not_crash(self): |
| 51 | + """Test that reask_tools handles Stream objects without crashing. |
| 52 | +
|
| 53 | + Previously, this would crash with: |
| 54 | + "'Stream' object has no attribute 'choices'" |
| 55 | + """ |
| 56 | + mock_stream = MockStream() |
| 57 | + kwargs = { |
| 58 | + "messages": [{"role": "user", "content": "test"}], |
| 59 | + "tools": [{"type": "function", "function": {"name": "test"}}], |
| 60 | + } |
| 61 | + exception = create_mock_validation_error() |
| 62 | + |
| 63 | + # This should not raise an AttributeError |
| 64 | + result = handle_reask_kwargs( |
| 65 | + kwargs=kwargs, |
| 66 | + mode=Mode.TOOLS, |
| 67 | + response=mock_stream, |
| 68 | + exception=exception, |
| 69 | + ) |
| 70 | + |
| 71 | + # Should return modified kwargs with error message |
| 72 | + assert "messages" in result |
| 73 | + assert len(result["messages"]) > 1 # Original + error message |
| 74 | + |
| 75 | + def test_reask_anthropic_tools_with_stream_object(self): |
| 76 | + """Test that Anthropic reask handler handles Stream objects.""" |
| 77 | + mock_stream = MockStream() |
| 78 | + kwargs = { |
| 79 | + "messages": [{"role": "user", "content": "test"}], |
| 80 | + } |
| 81 | + exception = create_mock_validation_error() |
| 82 | + |
| 83 | + result = handle_reask_kwargs( |
| 84 | + kwargs=kwargs, |
| 85 | + mode=Mode.ANTHROPIC_TOOLS, |
| 86 | + response=mock_stream, |
| 87 | + exception=exception, |
| 88 | + ) |
| 89 | + |
| 90 | + assert "messages" in result |
| 91 | + |
| 92 | + def test_reask_with_none_response(self): |
| 93 | + """Test that reask handlers handle None response gracefully.""" |
| 94 | + kwargs = { |
| 95 | + "messages": [{"role": "user", "content": "test"}], |
| 96 | + } |
| 97 | + exception = create_mock_validation_error() |
| 98 | + |
| 99 | + result = handle_reask_kwargs( |
| 100 | + kwargs=kwargs, |
| 101 | + mode=Mode.TOOLS, |
| 102 | + response=None, |
| 103 | + exception=exception, |
| 104 | + ) |
| 105 | + |
| 106 | + assert "messages" in result |
| 107 | + |
| 108 | + def test_reask_md_json_with_stream_object(self): |
| 109 | + """Test that MD_JSON reask handler handles Stream objects.""" |
| 110 | + mock_stream = MockStream() |
| 111 | + kwargs = { |
| 112 | + "messages": [{"role": "user", "content": "test"}], |
| 113 | + } |
| 114 | + exception = create_mock_validation_error() |
| 115 | + |
| 116 | + result = handle_reask_kwargs( |
| 117 | + kwargs=kwargs, |
| 118 | + mode=Mode.MD_JSON, |
| 119 | + response=mock_stream, |
| 120 | + exception=exception, |
| 121 | + ) |
| 122 | + |
| 123 | + assert "messages" in result |
| 124 | + |
| 125 | + |
| 126 | +@pytest.mark.skipif( |
| 127 | + not pytest.importorskip("openai", reason="openai not installed"), |
| 128 | + reason="openai not installed", |
| 129 | +) |
| 130 | +class TestStreamingReaskIntegration: |
| 131 | + """Integration tests that require OpenAI API key.""" |
| 132 | + |
| 133 | + @pytest.fixture |
| 134 | + def client(self): |
| 135 | + """Create instructor client if API key available.""" |
| 136 | + import os |
| 137 | + |
| 138 | + if not os.getenv("OPENAI_API_KEY"): |
| 139 | + pytest.skip("OPENAI_API_KEY not set") |
| 140 | + |
| 141 | + import instructor |
| 142 | + from openai import OpenAI |
| 143 | + |
| 144 | + return instructor.from_openai(OpenAI()) |
| 145 | + |
| 146 | + def test_streaming_with_retries_and_failing_validator(self, client): |
| 147 | + """Test that streaming with retries doesn't crash on validation failure.""" |
| 148 | + |
| 149 | + class StrictUser(BaseModel): |
| 150 | + name: str |
| 151 | + age: int |
| 152 | + |
| 153 | + @field_validator("name") |
| 154 | + @classmethod |
| 155 | + def name_must_have_space(cls, v: str) -> str: |
| 156 | + if v and " " not in v: |
| 157 | + raise ValueError("Name must have first and last name") |
| 158 | + return v |
| 159 | + |
| 160 | + # This should not crash with AttributeError |
| 161 | + # It may raise InstructorRetryException after retries exhausted, which is expected |
| 162 | + from instructor.core.exceptions import InstructorRetryException |
| 163 | + |
| 164 | + with pytest.raises(InstructorRetryException): |
| 165 | + list( |
| 166 | + client.chat.completions.create_partial( |
| 167 | + model="gpt-4o-mini", |
| 168 | + max_retries=2, |
| 169 | + messages=[ |
| 170 | + { |
| 171 | + "role": "user", |
| 172 | + "content": "Extract: John is 25. Return name='John' (no last name).", |
| 173 | + } |
| 174 | + ], |
| 175 | + response_model=StrictUser, |
| 176 | + ) |
| 177 | + ) |
0 commit comments