From 624bc7e02d39e2701a8c4d7a161ce5cc11c96f84 Mon Sep 17 00:00:00 2001 From: Carson Date: Mon, 12 Oct 2026 17:28:28 -0500 Subject: [PATCH] Fall back to non-streaming for structured output on Bedrock Converse Bedrock Converse extracts structured data through a forced tool call (like Anthropic's tool mode), and Converse streams tool input in its own event type rather than as text. As a result, streaming with a data_model silently yielded zero chunks, violating the `"".join(chunks)` contract. Override `can_stream()` so `Chat` transparently downgrades to a single non-streaming request (with a warning), yielding the complete JSON as one chunk. --- CHANGELOG.md | 1 + chatlas/_provider_bedrock_converse.py | 8 ++ tests/test_provider_bedrock_converse.py | 110 ++++++++++++++++++++++++ 3 files changed, 119 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b98a3cb9..a25d1b1b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `ChatCloudflare()` no longer errors when a response (or a streamed chunk of one) consists only of a number, which Cloudflare sends as a JSON number instead of a string (e.g. `"content": 2`). The content is now coerced to a string instead of breaking text display, chunk merging, and final-turn assembly. * `.stream()` and `.stream_async()` with `data_model` no longer crash when the provider can't stream structured output — notably `ChatAnthropic()` with `structured_output_mode="tool"`, and older Claude models under the default `"auto"` mode. chatlas now warns and transparently falls back to a single non-streaming request, yielding the complete JSON as one chunk, so `data_model.model_validate_json("".join(chunks))` keeps working unchanged. (#317) * `echo="all"` no longer displays structured-output JSON twice (once as the response text and again as a fenced code block). (#317) +* `ChatBedrock()` with the default Converse API previously yielded zero chunks from `.stream()`/`.stream_async()` with `data_model` (its structured output is extracted through a tool call, which can't stream). It now gets the same non-streaming fallback as `ChatAnthropic(structured_output_mode="tool")`: a warning, then the complete JSON as a single chunk. (#451) * Structured-output requests to most OpenAI-compatible providers no longer include OpenAI's `strict` flag, which causes some backends to reject the request. Requests to OpenAI, `ChatGroq()`, `ChatAzureOpenAICompletions()`, and `ChatPosit()` models with an `openai/` prefix are unchanged. If structured output becomes less reliable for your provider (for example, OpenAI models behind a proxy), pass the new `strict=True` argument to `ChatOpenAICompletions()`, `ChatOpenRouter()`, `ChatPortkey()`, or `ChatHuggingFace()`. * `Chat.get_tokens()` no longer errors when the conversation ends with a user turn that has no completed assistant response yet (e.g. after a failed request or `add_turn()`), when assistant turns don't strictly alternate with user turns, or when the history holds a single user turn (which now returns an empty list). Token accounting is now driven off complete assistant turns instead of assuming strict user/assistant alternation. * `ChatBedrockAnthropic(reasoning=)` now accepts an effort level (`"low"`, `"medium"`, `"high"`, `"xhigh"` or `"max"`) to enable adaptive thinking, as `ChatAnthropic()` already did. It previously only took a token budget, which its default model (Claude Sonnet 5) rejects, so there was no way to turn on thinking with that model. diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 665e72c1..689708b1 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -561,6 +561,14 @@ async def chat_perform_async( return self._converse_stream_async(args) return await self._converse_async(args) + def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: + # Structured data extraction is tool-based (a forced `toolChoice` on a + # tool whose input is `{"data": ...}`-wrapped), and Converse streams + # tool input in its own event type rather than as text, so a streamed + # response can't honor the extracted-JSON contract (`"".join(chunks)` + # would be empty). Fall back to a single non-streaming request. + return data_model is None + def stream_content( self, chunk: dict, diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index c9f7cd64..975ac88e 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1781,6 +1781,116 @@ def assert_cache_point(self, args, *, expected: bool): assert (cache_point in system) is expected +def _fake_data_model_converse_response(): + return cast( + "ConverseResponseTypeDef", + { + "output": { + "message": { + "role": "assistant", + "content": [ + { + "toolUse": { + "toolUseId": "toolu_x", + "name": "_structured_tool_call", + "input": {"data": {"name": "John", "age": 15}}, + } + } + ], + } + }, + "stopReason": "tool_use", + "usage": { + "inputTokens": 1, + "outputTokens": 1, + "totalTokens": 2, + }, + }, + ) + + +class TestStreamWithDataModel: + """ + Converse structured output is tool-based, so it can't stream incrementally; + `Chat` should downgrade to a non-streaming request that yields the full + JSON as a single chunk (see `Provider.can_stream`). + """ + + def provider(self) -> BedrockConverseProvider: + return BedrockConverseProvider( + model="us.anthropic.claude-sonnet-4-6", + aws_profile=None, + aws_region="us-east-1", + base_url=None, + ) + + def test_stream_with_data_model_downgrades_gracefully(self): + from unittest.mock import patch + + from chatlas import Chat + from chatlas._content import ContentJson + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + with patch.object( + provider, "_converse", return_value=_fake_data_model_converse_response() + ): + with pytest.warns(UserWarning, match="streaming"): + chunks = list(chat.stream("John, age 15", data_model=Person)) + + person = Person.model_validate_json("".join(chunks)) + assert person == Person(name="John", age=15) + + turn = chat.get_last_turn() + assert turn is not None + assert len(turn.contents) == 1 + assert isinstance(turn.contents[0], ContentJson) + assert turn.contents[0].value == {"name": "John", "age": 15} + + @pytest.mark.asyncio + async def test_stream_async_with_data_model_downgrades_gracefully(self): + from unittest.mock import AsyncMock, patch + + from chatlas import Chat + from chatlas._content import ContentJson + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + with patch.object( + provider, + "_converse_async", + new=AsyncMock(return_value=_fake_data_model_converse_response()), + ): + with pytest.warns(UserWarning, match="streaming"): + chunks = [ + chunk + async for chunk in await chat.stream_async( + "John, age 15", data_model=Person + ) + ] + + person = Person.model_validate_json("".join(chunks)) + assert person == Person(name="John", age=15) + + turn = chat.get_last_turn() + assert turn is not None + assert len(turn.contents) == 1 + assert isinstance(turn.contents[0], ContentJson) + assert turn.contents[0].value == {"name": "John", "age": 15} + + def test_blocked_network_skips_live_converse_before_credential_probe(monkeypatch): class BlockedConfig: def getoption(self, option: str) -> bool: