From e78c9109c4edb5f9a2031643cb267c6041fd4ec4 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 12:51:33 -0500 Subject: [PATCH 01/13] Add structured_output_mode state and mode-aware can_stream() to BedrockConverseProvider --- chatlas/_provider_bedrock_converse.py | 28 ++++++++++++---- tests/test_provider_bedrock_converse.py | 44 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 7 deletions(-) diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 689708b1..37587e6b 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -45,7 +45,11 @@ StandardModelParamNames, StandardModelParams, ) -from ._provider_anthropic import AnthropicProvider +from ._provider_anthropic import ( + AnthropicProvider, + StructuredOutputMode, + supports_structured_outputs, +) from ._provider_bedrock import ( CROSS_REGION_PREFIX, bedrock_base_url, @@ -420,6 +424,7 @@ def __init__( base_url: Optional[str], max_tokens: int = 4096, cache: Literal["auto", "5m", "1h", "none"] = "auto", + structured_output_mode: StructuredOutputMode = "auto", name: str = "AWS/Bedrock", kwargs: Optional[ConverseClientArgs] = None, ): @@ -428,6 +433,7 @@ def __init__( self._aws_region = aws_region self._max_tokens = max_tokens self._cache: Literal["auto", "5m", "1h", "none"] = cache + self._structured_output_mode = structured_output_mode resolved_base_url = base_url or bedrock_base_url("converse", aws_region) # `LazyCredentials` defers the botocore credential chain to the first @@ -562,12 +568,20 @@ async def chat_perform_async( 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 + # Native structured outputs (`outputConfig`) stream as ordinary text + # deltas, so they honor the extracted-JSON contract. The tool-based + # strategy streams tool input in its own event type (and + # `{"data": ...}`-wrapped at that), so it can't -- `Chat` falls back + # to a single non-streaming request there. + if data_model is None: + return True + return self._use_native_structured_output() + + def _use_native_structured_output(self) -> bool: + mode = self._structured_output_mode + return mode == "native" or ( + mode == "auto" and supports_structured_outputs(self.model) + ) def stream_content( self, diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index 975ac88e..53548588 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1891,6 +1891,50 @@ class Person(BaseModel): assert turn.contents[0].value == {"name": "John", "age": 15} +class TestStructuredOutputMode: + """`structured_output_mode` selects native `outputConfig` vs forced tool call.""" + + @staticmethod + def provider( + model: str = "us.anthropic.claude-sonnet-4-6", + mode: Literal["auto", "native", "tool"] = "auto", + ) -> BedrockConverseProvider: + return BedrockConverseProvider( + model=model, + aws_profile=None, + aws_region="us-east-1", + base_url=None, + structured_output_mode=mode, + ) + + def test_can_stream_matrix(self): + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + # No data_model always streams. + assert self.provider().can_stream(None) is True + # "auto" streams on supported Anthropic models ... + assert self.provider().can_stream(Person) is True + # ... but not on unsupported ones. + assert ( + self.provider(model="us.anthropic.claude-sonnet-4").can_stream(Person) + is False + ) + assert self.provider(model="amazon.nova-lite-v1:0").can_stream(Person) is False + # "native" forces streaming even on unsupported models ... + assert ( + self.provider(model="amazon.nova-lite-v1:0", mode="native").can_stream( + Person + ) + is True + ) + # ... and "tool" never streams with a data_model. + assert self.provider(mode="tool").can_stream(Person) is False + + def test_blocked_network_skips_live_converse_before_credential_probe(monkeypatch): class BlockedConfig: def getoption(self, option: str) -> bool: From 6429a260b99d6366d0c5812346caa6bb5ddbe8f2 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 12:53:12 -0500 Subject: [PATCH 02/13] Send outputConfig for native structured outputs on Bedrock Converse --- chatlas/_provider_bedrock_converse.py | 27 ++++++++++- tests/test_provider_bedrock_converse.py | 59 +++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 1 deletion(-) diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 37587e6b..5c7954ed 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -94,6 +94,7 @@ ConverseResponseTypeDef, InferenceConfigurationTypeDef, MessageUnionTypeDef, + OutputConfigTypeDef, SystemContentBlockTypeDef, TokenUsageTypeDef, ToolChoiceTypeDef, @@ -795,10 +796,13 @@ def _chat_perform_args( "inferenceConfig": inference_config, } + use_native_output = data_model is not None and ( + self._use_native_structured_output() + ) data_model_tool: Optional[Tool] = None tool_specs = [converse_tool_spec(tool) for tool in tools.values()] tool_config: Optional[ToolConfigurationTypeDef] = None - if data_model is not None: + if data_model is not None and not use_native_output: data_model_tool = AnthropicProvider.create_data_model_tool(data_model) tool_specs.append(converse_tool_spec(data_model_tool)) @@ -820,6 +824,27 @@ def _chat_perform_args( inference_config.update(extra_inference_config) args.update(extra) + if data_model is not None and use_native_output: + from anthropic import transform_schema + + # After `args.update(extra)`, so chatlas's `outputConfig` wins + # over a user-supplied one (mirroring `ChatAnthropic`). + args["outputConfig"] = cast( + "OutputConfigTypeDef", + { + "textFormat": { + "type": "json_schema", + "structure": { + "jsonSchema": { + # The schema is a JSON *string* on the wire. + "schema": json.dumps(transform_schema(data_model)), + "name": data_model.__name__, + } + }, + } + }, + ) + extra_system = extra.get("system") system = ( list(cast("list[SystemContentBlockTypeDef]", extra_system)) diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index 53548588..0b905bf6 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1934,6 +1934,65 @@ class Person(BaseModel): # ... and "tool" never streams with a data_model. assert self.provider(mode="tool").can_stream(Person) is False + @staticmethod + def _chat_with_fake_response(provider: BedrockConverseProvider) -> dict: + """Chat with a mocked `_converse`; return the captured request args.""" + from unittest.mock import patch + + from chatlas import Chat + + request: dict = {} + + def fake_converse(args): + request.update(args) + return _fake_data_model_converse_response() + + chat = Chat(provider=provider) + with patch.object(provider, "_converse", side_effect=fake_converse): + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + chat.chat_structured("John, age 15", data_model=Person) + return request + + def test_native_mode_sends_output_config(self): + request = self._chat_with_fake_response(self.provider()) + assert "toolConfig" not in request + output_config = request["outputConfig"] + text_format = output_config["textFormat"] + assert text_format["type"] == "json_schema" + json_schema = text_format["structure"]["jsonSchema"] + assert json_schema["name"] == "Person" + schema = json.loads(json_schema["schema"]) + assert schema["type"] == "object" + assert set(schema["properties"]) == {"name", "age"} + + def test_tool_mode_forces_tool_call(self): + request = self._chat_with_fake_response(self.provider(mode="tool")) + assert "outputConfig" not in request + assert request["toolConfig"]["toolChoice"] == { + "tool": {"name": "_structured_tool_call"} + } + + def test_auto_mode_unsupported_model_uses_tool_call(self): + request = self._chat_with_fake_response( + self.provider(model="us.anthropic.claude-sonnet-4") + ) + assert "outputConfig" not in request + assert request["toolConfig"]["toolChoice"] == { + "tool": {"name": "_structured_tool_call"} + } + + def test_native_mode_forces_output_config_on_unsupported_model(self): + request = self._chat_with_fake_response( + self.provider(model="amazon.nova-lite-v1:0", mode="native") + ) + assert "outputConfig" in request + assert "toolConfig" not in request + def test_blocked_network_skips_live_converse_before_credential_probe(monkeypatch): class BlockedConfig: From 07fcc95d919a9a1f638918921246e659294b72ff Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 13:18:27 -0500 Subject: [PATCH 03/13] Fall back to tool-based extraction when Converse rejects outputConfig --- chatlas/_provider_bedrock_converse.py | 180 ++++++++++++++- tests/test_provider_bedrock_converse.py | 281 ++++++++++++++++++++++++ 2 files changed, 456 insertions(+), 5 deletions(-) diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 5c7954ed..cf8a2a3f 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -4,6 +4,7 @@ import base64 import json import os +import warnings from collections.abc import Mapping from functools import cache from typing import ( @@ -63,6 +64,7 @@ SystemTurn, Turn, UserTurn, + caller_stacklevel, check_finish_reason, ) from ._typing_extensions import NotRequired, TypedDict @@ -435,6 +437,9 @@ def __init__( self._max_tokens = max_tokens self._cache: Literal["auto", "5m", "1h", "none"] = cache self._structured_output_mode = structured_output_mode + # Models that have rejected `outputConfig` with a 400 (see + # `_native_retry_args`); only populated in "auto" mode. + self._native_unsupported_models: set[str] = set() resolved_base_url = base_url or bedrock_base_url("converse", aws_region) # `LazyCredentials` defers the botocore credential chain to the first @@ -529,8 +534,18 @@ def chat_perform( ) -> Iterable[dict] | ConverseResponseTypeDef: args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) if stream: - return self._converse_stream(args) - return self._converse(args) + return self._converse_stream_with_retry( + args, stream, turns, tools, data_model, kwargs + ) + try: + return self._converse(args) + except ValueError as error: + retry = self._native_retry_args( + error, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + return self._converse(retry) @overload async def chat_perform_async( @@ -565,8 +580,146 @@ async def chat_perform_async( ) -> AsyncIterable[dict] | ConverseResponseTypeDef: args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) if stream: - return self._converse_stream_async(args) - return await self._converse_async(args) + return self._converse_stream_async_with_retry( + args, stream, turns, tools, data_model, kwargs + ) + try: + return await self._converse_async(args) + except ValueError as error: + retry = self._native_retry_args( + error, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + return await self._converse_async(retry) + + def _native_retry_args( + self, + error: ValueError, + stream: bool, + turns: list[Turn], + tools: dict[str, Tool | ToolBuiltIn], + data_model: Optional[type[BaseModel]], + kwargs: Optional[ConverseSubmitArgs], + ) -> Optional[ConverseRequestTypeDef]: + """Rebuild request args for tool-based extraction after a native-mode 400. + + Converse's `outputConfig` support is per-model in a way that can't be + derived from the model ID (e.g. `claude-sonnet-5` rejects it while + `claude-sonnet-4-6` accepts it), so "auto" mode is optimistic: on the + specific rejection, remember the model as unsupported and retry with + the forced tool call. Returns `None` (caller re-raises) when the + failure wasn't a native-mode attempt -- including explicit "native" + mode, where the user asked for `outputConfig` and gets its error. + """ + if ( + data_model is None + or self._structured_output_mode != "auto" + or not self._use_native_structured_output() + or "output_config" not in str(error) + ): + return None + self._native_unsupported_models.add(self.model) + warnings.warn( + f"Bedrock Converse model '{self.model}' rejected native structured " + "outputs (`outputConfig`); falling back to tool-based extraction. " + "This provider will use tool-based extraction for the model from " + "now on.", + stacklevel=caller_stacklevel(), + ) + # `_use_native_structured_output()` is now False, so this rebuilds the + # args with the forced `_structured_tool_call` instead of `outputConfig`. + return self._chat_perform_args(stream, turns, tools, data_model, kwargs) + + def _converse_stream_with_retry( + self, + args: ConverseRequestTypeDef, + stream: bool, + turns: list[Turn], + tools: dict[str, Tool | ToolBuiltIn], + data_model: Optional[type[BaseModel]], + kwargs: Optional[ConverseSubmitArgs], + ) -> Iterator[dict]: + try: + # `_converse_stream` is a generator, so the request (and any + # error it fails with) doesn't fire until the first pull. + events = self._converse_stream(args) + first = next(events) + except StopIteration: + return + except ValueError as error: + retry = self._native_retry_args( + error, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + # A tool-mode stream retry would yield zero chunks (the bug #451 + # fixed), so retry on the non-streaming endpoint and synthesize + # events that surface the extracted JSON as a single text chunk. + yield from self._response_as_stream_events(self._converse(retry)) + return + yield first + yield from events + + async def _converse_stream_async_with_retry( + self, + args: ConverseRequestTypeDef, + stream: bool, + turns: list[Turn], + tools: dict[str, Tool | ToolBuiltIn], + data_model: Optional[type[BaseModel]], + kwargs: Optional[ConverseSubmitArgs], + ) -> AsyncIterator[dict]: + try: + events = self._converse_stream_async(args) + first = await anext(events) + except StopAsyncIteration: + return + except ValueError as error: + retry = self._native_retry_args( + error, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + for event in self._response_as_stream_events( + await self._converse_async(retry) + ): + yield event + return + yield first + async for event in events: + yield event + + @staticmethod + def _response_as_stream_events( + response: ConverseResponseTypeDef, + ) -> Iterator[dict]: + """Replay a non-streaming response as a minimal Converse event stream. + + Structured output is re-expressed as a text delta (rather than the + tool-use block it arrived as) so `stream_content()` yields the + extracted JSON as a single chunk and `_as_turn`'s native branch + records it as `ContentJson`. + """ + message = response["output"].get("message") + yield {"messageStart": {"role": (message or {}).get("role", "assistant")}} + if message is not None: + for index, block in enumerate(message["content"]): + block = cast(dict, block) + text = block.get("text") + tool_use = block.get("toolUse") or {} + if tool_use.get("name") == "_structured_tool_call": + text = json.dumps(tool_use.get("input", {}).get("data")) + if text is not None: + yield { + "contentBlockDelta": { + "contentBlockIndex": index, + "delta": {"text": text}, + } + } + yield {"contentBlockStop": {"contentBlockIndex": index}} + yield {"messageStop": {"stopReason": response["stopReason"]}} + yield {"metadata": {"usage": response["usage"]}} def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: # Native structured outputs (`outputConfig`) stream as ordinary text @@ -579,6 +732,8 @@ def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: return self._use_native_structured_output() def _use_native_structured_output(self) -> bool: + if self.model in self._native_unsupported_models: + return False mode = self._structured_output_mode return mode == "native" or ( mode == "auto" and supports_structured_outputs(self.model) @@ -949,10 +1104,19 @@ def _as_turn( message = completion["output"].get("message") contents: list[Content] = [] if message is not None: + # Structured output arrives in one of two forms, depending on + # `structured_output_mode`: a `_structured_tool_call` toolUse + # block (tool mode), or as ordinary text (native `outputConfig` + # mode) -- mirroring `AnthropicProvider._as_turn`. + uses_tool_approach = has_data_model and any( + (cast(dict, block).get("toolUse") or {}).get("name") + == "_structured_tool_call" + for block in message["content"] + ) for block in message["content"]: tool_use = cast(dict, block).get("toolUse") if ( - has_data_model + uses_tool_approach and tool_use and tool_use["name"] == "_structured_tool_call" ): @@ -967,6 +1131,12 @@ def _as_turn( "Expected data extraction tool to return a 'data' dictionary." ) contents.append(ContentJson(value=data)) + elif ( + has_data_model + and not uses_tool_approach + and (text := cast(dict, block).get("text")) is not None + ): + contents.append(ContentJson(value=json.loads(text))) elif (content := content_from_converse_block(block)) is not None: contents.append(content) return AssistantTurn( diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index 0b905bf6..ee979343 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1426,12 +1426,16 @@ def provider( model: str = "us.anthropic.claude-sonnet-4-6", cache: Literal["auto", "5m", "1h", "none"] = "auto", ): + # These tests exercise the tool-based structured output strategy, so + # pin `structured_output_mode="tool"` (the default "auto" uses native + # `outputConfig` for this model). return BedrockConverseProvider( model=model, aws_profile=None, aws_region="us-east-1", base_url=None, cache=cache, + structured_output_mode="tool", ) def test_data_model_forces_a_tool_choice(self): @@ -1817,11 +1821,14 @@ class TestStreamWithDataModel: """ def provider(self) -> BedrockConverseProvider: + # The downgrade only happens in tool mode; "auto" uses native + # `outputConfig` for this model, which streams for real. return BedrockConverseProvider( model="us.anthropic.claude-sonnet-4-6", aws_profile=None, aws_region="us-east-1", base_url=None, + structured_output_mode="tool", ) def test_stream_with_data_model_downgrades_gracefully(self): @@ -1993,6 +2000,280 @@ def test_native_mode_forces_output_config_on_unsupported_model(self): assert "outputConfig" in request assert "toolConfig" not in request + @staticmethod + def _fake_native_converse_response(): + return cast( + "ConverseResponseTypeDef", + { + "output": { + "message": { + "role": "assistant", + "content": [{"text": '{"name": "John", "age": 15}'}], + } + }, + "stopReason": "end_turn", + "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2}, + }, + ) + + @staticmethod + def _fake_native_stream_events() -> list[dict]: + return [ + {"messageStart": {"role": "assistant"}}, + { + "contentBlockDelta": { + "contentBlockIndex": 0, + "delta": {"text": '{"name": "Joh'}, + } + }, + { + "contentBlockDelta": { + "contentBlockIndex": 0, + "delta": {"text": 'n", "age": 15}'}, + } + }, + {"contentBlockStop": {"contentBlockIndex": 0}}, + {"messageStop": {"stopReason": "end_turn"}}, + { + "metadata": { + "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2} + } + }, + ] + + def test_native_response_text_becomes_content_json(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=self._fake_native_converse_response(), + ): + chat.chat_structured("John, age 15", data_model=Person) + + 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_native_mode_streams_incrementally(self): + import warnings + 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_stream", + side_effect=lambda args: iter(self._fake_native_stream_events()), + ): + with warnings.catch_warnings(): + # Native mode streams for real: no fallback warning. + warnings.simplefilter("error") + chunks = list(chat.stream("John, age 15", data_model=Person)) + + # Two text deltas arrive as two chunks, joining to the full JSON. + assert chunks == ['{"name": "Joh', 'n", "age": 15}'] + 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 isinstance(turn.contents[0], ContentJson) + assert turn.contents[0].value == {"name": "John", "age": 15} + + @staticmethod + def _native_rejection() -> ValueError: + return ValueError( + "Bedrock Converse request failed with status 400: The model " + "returned the following errors: output_config.format: Extra " + "inputs are not permitted" + ) + + def test_auto_mode_falls_back_to_tool_on_native_rejection(self): + from unittest.mock import patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() # "auto" on a regex-supported model + chat = Chat(provider=provider) + requests: list[dict] = [] + + def fake_converse(args): + requests.append(args) + if "outputConfig" in args: + raise self._native_rejection() + return _fake_data_model_converse_response() + + with patch.object(provider, "_converse", side_effect=fake_converse): + with pytest.warns(UserWarning, match="outputConfig"): + result = chat.chat_structured("John, age 15", data_model=Person) + + assert result == Person(name="John", age=15) + # First attempt is native; the retry uses the forced tool call. + assert len(requests) == 2 + assert "outputConfig" in requests[0] + assert "outputConfig" not in requests[1] + assert requests[1]["toolConfig"]["toolChoice"] == { + "tool": {"name": "_structured_tool_call"} + } + + # The rejection is remembered: no more native attempts, and + # can_stream() now reflects tool mode. + assert provider.can_stream(Person) is False + with patch.object(provider, "_converse", side_effect=fake_converse): + chat.chat_structured("Jane, age 20", data_model=Person) + assert len(requests) == 3 + assert "outputConfig" not in requests[2] + + def test_native_mode_does_not_fall_back(self): + from unittest.mock import patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider(mode="native") + chat = Chat(provider=provider) + + def reject(args): + raise self._native_rejection() + + with patch.object(provider, "_converse", side_effect=reject): + with pytest.raises(ValueError, match="output_config"): + chat.chat_structured("John, age 15", data_model=Person) + + def test_stream_falls_back_to_single_chunk_on_native_rejection(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) + + def fake_stream(args): + if "outputConfig" in args: + raise self._native_rejection() + raise AssertionError("stream retry must use the non-streaming endpoint") + + with patch.object(provider, "_converse_stream", side_effect=fake_stream): + with patch.object( + provider, + "_converse", + return_value=_fake_data_model_converse_response(), + ): + with pytest.warns(UserWarning, match="outputConfig"): + chunks = list(chat.stream("John, age 15", data_model=Person)) + + # #451's contract: the complete JSON as a single chunk. + 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 isinstance(turn.contents[0], ContentJson) + assert turn.contents[0].value == {"name": "John", "age": 15} + + @pytest.mark.asyncio + async def test_stream_async_falls_back_on_native_rejection(self): + from unittest.mock import AsyncMock, patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + async def fake_stream(args): + if "outputConfig" in args: + raise self._native_rejection() + yield # pragma: no cover + + with patch.object(provider, "_converse_stream_async", fake_stream): + with patch.object( + provider, + "_converse_async", + new=AsyncMock(return_value=_fake_data_model_converse_response()), + ): + with pytest.warns(UserWarning, match="outputConfig"): + 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) + + @pytest.mark.asyncio + async def test_native_mode_streams_incrementally_async(self): + from unittest.mock import patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + events = self._fake_native_stream_events() + + async def fake_stream(args): + for event in events: + yield event + + with patch.object(provider, "_converse_stream_async", fake_stream): + 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) + def test_blocked_network_skips_live_converse_before_credential_probe(monkeypatch): class BlockedConfig: From 40c68f9cd41f51b6a01454e2da3a0cadeddfb0b3 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 13:19:41 -0500 Subject: [PATCH 04/13] Expose structured_output_mode on ChatBedrock for the Converse API --- chatlas/_provider_bedrock.py | 19 ++++++++++++++++- tests/test_provider_bedrock_converse.py | 27 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/chatlas/_provider_bedrock.py b/chatlas/_provider_bedrock.py index adcc3ae2..523d8eb5 100644 --- a/chatlas/_provider_bedrock.py +++ b/chatlas/_provider_bedrock.py @@ -12,7 +12,7 @@ from ._content_file import materialize_url_content from ._logging import log_model_default from ._provider import ModelInfo, no_file_management -from ._provider_anthropic import AnthropicProvider +from ._provider_anthropic import AnthropicProvider, StructuredOutputMode from ._provider_openai import OpenAIProvider from ._provider_openai_generic import openai_models_to_info from ._utils import MISSING, MISSING_TYPE, AnyTypeDict, split_http_client_kwargs @@ -50,6 +50,7 @@ def ChatBedrock( base_url: Optional[str] = None, max_tokens: int | MISSING_TYPE = MISSING, cache: Literal["auto", "5m", "1h", "none"] = "auto", + structured_output_mode: StructuredOutputMode = "auto", kwargs: Optional[ "OpenAIClientArgs | AnthropicClientArgs | ConverseClientArgs" ] = None, @@ -131,6 +132,17 @@ def ChatBedrock( Prompt caching for `api="converse"` and `api="messages"`. The Responses API caches automatically, so this must be left at `"auto"` when `api="responses"`. + structured_output_mode + How to extract structured data when a `data_model` is given. `"auto"` + (default) uses Bedrock's native structured outputs API + (`outputConfig`) for models known to support it (currently Anthropic + Claude models), and a forced tool call otherwise; if a model rejects + `outputConfig`, chatlas warns, remembers, and falls back to the tool + call for subsequent requests. `"native"` forces the `outputConfig` + API; `"tool"` forces the tool call. Only applies when + `api="converse"`. Native mode streams structured output + incrementally; tool mode falls back to a single non-streaming + request (with a warning) from `.stream()`/`.stream_async()`. kwargs Additional client arguments. For `api="converse"`, these are raw `httpx.Client` arguments (except `auth` and `base_url`, which @@ -167,6 +179,10 @@ def ChatBedrock( f'Invalid `api` value "{api}". ' 'Must be one of "converse", "messages", or "responses".' ) + if structured_output_mode != "auto" and api != "converse": + raise ValueError( + '`structured_output_mode` is only supported when `api="converse"`.' + ) region = bedrock_region(aws_profile, aws_region) if api != "converse" and bedrock_uses_credential_chain( @@ -214,6 +230,7 @@ def ChatBedrock( base_url=base_url, max_tokens=4096 if isinstance(max_tokens, MISSING_TYPE) else max_tokens, cache=cache, + structured_output_mode=structured_output_mode, kwargs=cast("Optional[ConverseClientArgs]", kwargs), ), system_prompt=system_prompt, diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index ee979343..ad755fc7 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -2101,6 +2101,33 @@ class Person(BaseModel): assert isinstance(turn.contents[0], ContentJson) assert turn.contents[0].value == {"name": "John", "age": 15} + def test_chat_bedrock_forwards_mode_to_converse(self): + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + # Default model (us.anthropic.claude-sonnet-5) matches the native + # support regex, so the mode alone decides can_stream here. + chat = ChatBedrock( + api="converse", aws_region="us-east-1", structured_output_mode="tool" + ) + assert chat.provider.can_stream(Person) is False + chat = ChatBedrock( + api="converse", aws_region="us-east-1", structured_output_mode="native" + ) + assert chat.provider.can_stream(Person) is True + + def test_structured_output_mode_rejected_off_converse(self): + for api in ("messages", "responses"): + with pytest.raises(ValueError, match="structured_output_mode"): + ChatBedrock( + api=api, # type: ignore[arg-type] + aws_region="us-east-1", + structured_output_mode="native", + ) + @staticmethod def _native_rejection() -> ValueError: return ValueError( From 82e8445e7de1a88c57a16706c1a9f249fcd84074 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 13:24:14 -0500 Subject: [PATCH 05/13] Add live streaming structured-output test and CHANGELOG entry --- CHANGELOG.md | 1 + chatlas/_provider_bedrock_converse.py | 2 +- tests/test_provider_bedrock_converse.py | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a25d1b1b..e98ec591 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `.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) +* `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, a model that rejects `outputConfig` triggers a one-time warning and a transparent retry with the previous forced-tool-call behavior, which is then remembered for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#452) * 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 cf8a2a3f..f7764d41 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -672,7 +672,7 @@ async def _converse_stream_async_with_retry( ) -> AsyncIterator[dict]: try: events = self._converse_stream_async(args) - first = await anext(events) + first = await events.__anext__() except StopAsyncIteration: return except ValueError as error: diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index ad755fc7..f85b827c 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -2405,6 +2405,21 @@ async def test_tool_variations_async(self): def test_data_extraction(self): assert_data_extraction(ChatBedrock) + def test_stream_data_extraction_native(self): + # claude-sonnet-4-6 supports native structured outputs, so this + # streams incrementally (no non-streaming fallback). + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + chat = ChatBedrock(model="us.anthropic.claude-sonnet-4-6") + chunks = list(chat.stream("Extract: John is 15 years old.", data_model=Person)) + person = Person.model_validate_json("".join(chunks)) + assert person.name == "John" + assert person.age == 15 + def test_images(self): assert_images_inline(ChatBedrock) assert_images_remote_error(ChatBedrock) From 9c4a410508d85f16858a35960355b27b102601fd Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 13:28:10 -0500 Subject: [PATCH 06/13] Reference PR #463 in CHANGELOG --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e98ec591..b3dd5c25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `.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) -* `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, a model that rejects `outputConfig` triggers a one-time warning and a transparent retry with the previous forced-tool-call behavior, which is then remembered for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#452) +* `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, a model that rejects `outputConfig` triggers a one-time warning and a transparent retry with the previous forced-tool-call behavior, which is then remembered for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#463) * 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. From ccbefd3067c1e84ac535009ec7155003bf800cc9 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 13:41:05 -0500 Subject: [PATCH 07/13] Address Copilot review: args-based retry eligibility, stricter rejection match, close wrapped streams --- chatlas/_provider_bedrock_converse.py | 134 +++++++++++++++--------- tests/test_provider_bedrock_converse.py | 57 ++++++++++ 2 files changed, 143 insertions(+), 48 deletions(-) diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index f7764d41..215b5217 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -541,7 +541,7 @@ def chat_perform( return self._converse(args) except ValueError as error: retry = self._native_retry_args( - error, stream, turns, tools, data_model, kwargs + error, args, stream, turns, tools, data_model, kwargs ) if retry is None: raise @@ -587,7 +587,7 @@ async def chat_perform_async( return await self._converse_async(args) except ValueError as error: retry = self._native_retry_args( - error, stream, turns, tools, data_model, kwargs + error, args, stream, turns, tools, data_model, kwargs ) if retry is None: raise @@ -596,6 +596,7 @@ async def chat_perform_async( def _native_retry_args( self, error: ValueError, + args: ConverseRequestTypeDef, stream: bool, turns: list[Turn], tools: dict[str, Tool | ToolBuiltIn], @@ -611,26 +612,45 @@ def _native_retry_args( the forced tool call. Returns `None` (caller re-raises) when the failure wasn't a native-mode attempt -- including explicit "native" mode, where the user asked for `outputConfig` and gets its error. + + Retry eligibility comes from the failed request's own `outputConfig`, + not the unsupported-model cache: a concurrent request may have + populated the cache while this one was in flight, and it still + deserves its retry. """ if ( data_model is None or self._structured_output_mode != "auto" - or not self._use_native_structured_output() - or "output_config" not in str(error) + or "outputConfig" not in args + or not self._is_native_rejection(error) ): return None - self._native_unsupported_models.add(self.model) - warnings.warn( - f"Bedrock Converse model '{self.model}' rejected native structured " - "outputs (`outputConfig`); falling back to tool-based extraction. " - "This provider will use tool-based extraction for the model from " - "now on.", - stacklevel=caller_stacklevel(), - ) + if self.model not in self._native_unsupported_models: + self._native_unsupported_models.add(self.model) + warnings.warn( + f"Bedrock Converse model '{self.model}' rejected native " + "structured outputs (`outputConfig`); falling back to " + "tool-based extraction. This provider will use tool-based " + "extraction for the model from now on.", + stacklevel=caller_stacklevel(), + ) # `_use_native_structured_output()` is now False, so this rebuilds the # args with the forced `_structured_tool_call` instead of `outputConfig`. return self._chat_perform_args(stream, turns, tools, data_model, kwargs) + @staticmethod + def _is_native_rejection(error: ValueError) -> bool: + # The specific 400 returned by models that lack `outputConfig` support + # (e.g. "... status 400: ... output_config.format: Extra inputs are + # not permitted"). Other errors mentioning `output_config` -- notably + # schema-validation 400s, which imply the model *does* support native + # output -- must propagate rather than disable native mode. + message = str(error) + return ( + "output_config" in message + and "Extra inputs are not permitted" in message + ) + def _converse_stream_with_retry( self, args: ConverseRequestTypeDef, @@ -640,26 +660,35 @@ def _converse_stream_with_retry( data_model: Optional[type[BaseModel]], kwargs: Optional[ConverseSubmitArgs], ) -> Iterator[dict]: + events: Optional[Iterator[dict]] = None try: - # `_converse_stream` is a generator, so the request (and any - # error it fails with) doesn't fire until the first pull. - events = self._converse_stream(args) - first = next(events) - except StopIteration: - return - except ValueError as error: - retry = self._native_retry_args( - error, stream, turns, tools, data_model, kwargs - ) - if retry is None: - raise - # A tool-mode stream retry would yield zero chunks (the bug #451 - # fixed), so retry on the non-streaming endpoint and synthesize - # events that surface the extracted JSON as a single text chunk. - yield from self._response_as_stream_events(self._converse(retry)) - return - yield first - yield from events + try: + # `_converse_stream` is a generator, so the request (and any + # error it fails with) doesn't fire until the first pull. + events = self._converse_stream(args) + first = next(events) + except StopIteration: + return + except ValueError as error: + retry = self._native_retry_args( + error, args, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + # A tool-mode stream retry would yield zero chunks (the bug + # #451 fixed), so retry on the non-streaming endpoint and + # synthesize events that surface the extracted JSON as a + # single text chunk. + yield from self._response_as_stream_events(self._converse(retry)) + return + yield first + yield from events + finally: + # Closing this wrapper (e.g. on cancellation) must also close the + # inner generator, which owns the httpx streaming response. + close = getattr(events, "close", None) + if close is not None: + close() async def _converse_stream_async_with_retry( self, @@ -670,25 +699,34 @@ async def _converse_stream_async_with_retry( data_model: Optional[type[BaseModel]], kwargs: Optional[ConverseSubmitArgs], ) -> AsyncIterator[dict]: + events: Optional[AsyncIterator[dict]] = None try: - events = self._converse_stream_async(args) - first = await events.__anext__() - except StopAsyncIteration: - return - except ValueError as error: - retry = self._native_retry_args( - error, stream, turns, tools, data_model, kwargs - ) - if retry is None: - raise - for event in self._response_as_stream_events( - await self._converse_async(retry) - ): + try: + events = self._converse_stream_async(args) + first = await events.__anext__() + except StopAsyncIteration: + return + except ValueError as error: + retry = self._native_retry_args( + error, args, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + for event in self._response_as_stream_events( + await self._converse_async(retry) + ): + yield event + return + yield first + async for event in events: yield event - return - yield first - async for event in events: - yield event + finally: + # `async for` doesn't forward `aclose()`, so closing this wrapper + # (e.g. on cancellation) would leave the inner generator -- and + # its httpx streaming response -- open until GC. + aclose = getattr(events, "aclose", None) + if aclose is not None: + await aclose() @staticmethod def _response_as_stream_events( diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index f85b827c..0c74c9b9 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -2177,6 +2177,63 @@ def fake_converse(args): assert len(requests) == 3 assert "outputConfig" not in requests[2] + def test_schema_validation_error_does_not_fall_back(self): + # A 400 mentioning `output_config` that isn't the "unsupported" + # rejection (e.g. the model rejecting the schema itself) means the + # model *does* support native output: propagate, don't fall back. + from unittest.mock import patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + def reject(args): + raise ValueError( + "Bedrock Converse request failed with status 400: The model " + "returned the following errors: output_config.format.schema: " + "value is not a valid JSON Schema" + ) + + with patch.object(provider, "_converse", side_effect=reject): + with pytest.raises(ValueError, match="not a valid JSON Schema"): + chat.chat_structured("John, age 15", data_model=Person) + + # The model is not (wrongly) remembered as unsupported. + assert provider.can_stream(Person) is True + + def test_in_flight_native_request_still_retries_after_marking(self): + # A concurrent request can mark the model unsupported while another + # native request is in flight; that request's own 400 must still + # fall back (eligibility comes from its args, not the cache). + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + turns = [UserTurn("John, age 15")] + args = provider._chat_perform_args( + stream=False, turns=turns, tools={}, data_model=Person + ) + assert "outputConfig" in args + + provider._native_unsupported_models.add(provider.model) + retry = provider._native_retry_args( + self._native_rejection(), args, False, turns, {}, Person, None + ) + assert retry is not None + assert "outputConfig" not in retry + assert retry["toolConfig"]["toolChoice"] == { + "tool": {"name": "_structured_tool_call"} + } + def test_native_mode_does_not_fall_back(self): from unittest.mock import patch From bc9572c409b4cd7ede5491669160fb1e597220e1 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 13:58:36 -0500 Subject: [PATCH 08/13] Address Copilot review round 2: non-stream service for tool-args in stream wrapper, JSON-only synthesis, drop user outputConfig in tool mode --- chatlas/_provider_bedrock_converse.py | 42 ++++++- tests/test_provider_bedrock_converse.py | 161 ++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 3 deletions(-) diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 215b5217..3e3a4693 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -660,6 +660,14 @@ def _converse_stream_with_retry( data_model: Optional[type[BaseModel]], kwargs: Optional[ConverseSubmitArgs], ) -> Iterator[dict]: + if data_model is not None and "outputConfig" not in args: + # A tool-based structured request can't stream (tool input + # arrives in its own event type, not as text), so serve it via + # the non-streaming endpoint. `Chat` normally downgrades these + # via `can_stream()`, but a concurrent request can mark the model + # unsupported after that check and before args were built. + yield from self._response_as_stream_events(self._converse(args)) + return events: Optional[Iterator[dict]] = None try: try: @@ -699,6 +707,14 @@ async def _converse_stream_async_with_retry( data_model: Optional[type[BaseModel]], kwargs: Optional[ConverseSubmitArgs], ) -> AsyncIterator[dict]: + if data_model is not None and "outputConfig" not in args: + # See the sync variant: tool-based structured requests can't + # stream, so serve them via the non-streaming endpoint. + for event in self._response_as_stream_events( + await self._converse_async(args) + ): + yield event + return events: Optional[AsyncIterator[dict]] = None try: try: @@ -742,12 +758,25 @@ def _response_as_stream_events( message = response["output"].get("message") yield {"messageStart": {"role": (message or {}).get("role", "assistant")}} if message is not None: - for index, block in enumerate(message["content"]): + blocks = message["content"] + has_structured_tool = any( + (cast(dict, block).get("toolUse") or {}).get("name") + == "_structured_tool_call" + for block in blocks + ) + for index, block in enumerate(blocks): block = cast(dict, block) - text = block.get("text") tool_use = block.get("toolUse") or {} if tool_use.get("name") == "_structured_tool_call": - text = json.dumps(tool_use.get("input", {}).get("data")) + text: Optional[str] = json.dumps( + tool_use.get("input", {}).get("data") + ) + elif has_structured_tool: + # Prose alongside the structured tool call would corrupt + # the extracted-JSON stream; drop it from the events. + continue + else: + text = block.get("text") if text is not None: yield { "contentBlockDelta": { @@ -1017,6 +1046,13 @@ def _chat_perform_args( inference_config.update(extra_inference_config) args.update(extra) + if data_model is not None and not use_native_output: + # A caller-supplied raw `outputConfig` can't be honored for a + # tool-based structured request (and would break the fallback in + # `_native_retry_args`, whose rebuild re-applies `kwargs`). + extra.pop("outputConfig", None) + args.pop("outputConfig", None) + if data_model is not None and use_native_output: from anthropic import transform_schema diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index 0c74c9b9..b85176c6 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -2128,6 +2128,167 @@ def test_structured_output_mode_rejected_off_converse(self): structured_output_mode="native", ) + @staticmethod + def _fake_mixed_converse_response(): + # Prose alongside the structured tool call. + return cast( + "ConverseResponseTypeDef", + { + "output": { + "message": { + "role": "assistant", + "content": [ + {"text": "Here is the extracted data:"}, + { + "toolUse": { + "toolUseId": "toolu_x", + "name": "_structured_tool_call", + "input": {"data": {"name": "John", "age": 15}}, + } + }, + ], + } + }, + "stopReason": "tool_use", + "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2}, + }, + ) + + def test_stream_fallback_with_mixed_text_and_tool_response(self): + # The synthesized stream must carry only the extracted JSON -- the + # prose would corrupt `"".join(chunks)` and crash `_as_turn`. + 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) + + def fake_stream(args): + if "outputConfig" in args: + raise self._native_rejection() + raise AssertionError("stream retry must use the non-streaming endpoint") + + with patch.object(provider, "_converse_stream", side_effect=fake_stream): + with patch.object( + provider, + "_converse", + return_value=self._fake_mixed_converse_response(), + ): + with pytest.warns(UserWarning, match="outputConfig"): + 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 isinstance(turn.contents[0], ContentJson) + assert turn.contents[0].value == {"name": "John", "age": 15} + + @pytest.mark.asyncio + async def test_stream_async_fallback_with_mixed_response(self): + from unittest.mock import AsyncMock, patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + async def fake_stream(args): + if "outputConfig" in args: + raise self._native_rejection() + yield # pragma: no cover + + with patch.object(provider, "_converse_stream_async", fake_stream): + with patch.object( + provider, + "_converse_async", + new=AsyncMock(return_value=self._fake_mixed_converse_response()), + ): + with pytest.warns(UserWarning, match="outputConfig"): + 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) + + def test_tool_mode_args_served_via_non_streaming_in_stream_wrapper(self): + # Race: the model is marked unsupported after `can_stream()` returns + # True but before args are built, so tool-mode args reach the stream + # wrapper. It must serve them via the non-streaming endpoint (a + # tool-mode stream would yield zero chunks). + from unittest.mock import patch + + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider(mode="tool") + turns = [UserTurn("John, age 15")] + args = provider._chat_perform_args( + stream=True, turns=turns, tools={}, data_model=Person + ) + assert "outputConfig" not in args + + def fail_stream(args): + raise AssertionError("must use the non-streaming endpoint") + + with patch.object(provider, "_converse_stream", side_effect=fail_stream): + with patch.object( + provider, + "_converse", + return_value=_fake_data_model_converse_response(), + ): + events = list( + provider._converse_stream_with_retry( + args, True, turns, {}, Person, None + ) + ) + + text = "".join( + e["contentBlockDelta"]["delta"]["text"] + for e in events + if "contentBlockDelta" in e + ) + assert Person.model_validate_json(text) == Person(name="John", age=15) + + def test_tool_mode_drops_user_supplied_output_config(self): + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + provider = self.provider(mode="tool") + args = provider._chat_perform_args( + stream=False, + turns=[UserTurn("John, age 15")], + tools={}, + data_model=Person, + kwargs={"outputConfig": {"textFormat": {}}}, # type: ignore[typeddict-item] + ) + assert "outputConfig" not in args + assert args["toolConfig"]["toolChoice"] == { + "tool": {"name": "_structured_tool_call"} + } + @staticmethod def _native_rejection() -> ValueError: return ValueError( From 87ea81d5ba1a30f6d8fcb84ee3ad44d7280b6e41 Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 14:23:24 -0500 Subject: [PATCH 09/13] Simplify: probe semantics replace in-stream fallback machinery "auto" mode now streams natively only once a model has proven it accepts outputConfig; Chat's existing non-streaming fallback doubles as the probe, so no extra request is spent and the verdict is cached either way. Deletes the stream-retry wrappers, response-as-stream-events synthesis, and their generator-lifetime handling (-156/+38 provider lines). --- CHANGELOG.md | 2 +- chatlas/_provider_bedrock_converse.py | 192 ++++------------- tests/test_provider_bedrock_converse.py | 269 ++++++------------------ 3 files changed, 102 insertions(+), 361 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b3dd5c25..bcf5ed90 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `.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) -* `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, a model that rejects `outputConfig` triggers a one-time warning and a transparent retry with the previous forced-tool-call behavior, which is then remembered for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#463) +* `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, the first structured request to a model doubles as a non-streaming probe: a model that accepts `outputConfig` streams natively from then on, while a rejection triggers a one-time warning, a transparent retry with the previous forced-tool-call behavior, and tool mode for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#463) * 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 3e3a4693..18029d21 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -437,9 +437,11 @@ def __init__( self._max_tokens = max_tokens self._cache: Literal["auto", "5m", "1h", "none"] = cache self._structured_output_mode = structured_output_mode - # Models that have rejected `outputConfig` with a 400 (see - # `_native_retry_args`); only populated in "auto" mode. + # Models that have rejected `outputConfig` with a 400, and models + # that have accepted it (see `_native_retry_args`/`can_stream`); + # only populated in "auto" mode. self._native_unsupported_models: set[str] = set() + self._native_verified_models: set[str] = set() resolved_base_url = base_url or bedrock_base_url("converse", aws_region) # `LazyCredentials` defers the botocore credential chain to the first @@ -534,11 +536,9 @@ def chat_perform( ) -> Iterable[dict] | ConverseResponseTypeDef: args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) if stream: - return self._converse_stream_with_retry( - args, stream, turns, tools, data_model, kwargs - ) + return self._converse_stream(args) try: - return self._converse(args) + response = self._converse(args) except ValueError as error: retry = self._native_retry_args( error, args, stream, turns, tools, data_model, kwargs @@ -546,6 +546,12 @@ def chat_perform( if retry is None: raise return self._converse(retry) + # A successful request that carried `outputConfig` proves the model + # accepts it, so "auto" mode may stream natively from now on (see + # `can_stream`). + if "outputConfig" in args and self._structured_output_mode == "auto": + self._native_verified_models.add(self.model) + return response @overload async def chat_perform_async( @@ -580,11 +586,9 @@ async def chat_perform_async( ) -> AsyncIterable[dict] | ConverseResponseTypeDef: args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) if stream: - return self._converse_stream_async_with_retry( - args, stream, turns, tools, data_model, kwargs - ) + return self._converse_stream_async(args) try: - return await self._converse_async(args) + response = await self._converse_async(args) except ValueError as error: retry = self._native_retry_args( error, args, stream, turns, tools, data_model, kwargs @@ -592,6 +596,9 @@ async def chat_perform_async( if retry is None: raise return await self._converse_async(retry) + if "outputConfig" in args and self._structured_output_mode == "auto": + self._native_verified_models.add(self.model) + return response def _native_retry_args( self, @@ -605,13 +612,17 @@ def _native_retry_args( ) -> Optional[ConverseRequestTypeDef]: """Rebuild request args for tool-based extraction after a native-mode 400. - Converse's `outputConfig` support is per-model in a way that can't be - derived from the model ID (e.g. `claude-sonnet-5` rejects it while - `claude-sonnet-4-6` accepts it), so "auto" mode is optimistic: on the - specific rejection, remember the model as unsupported and retry with - the forced tool call. Returns `None` (caller re-raises) when the - failure wasn't a native-mode attempt -- including explicit "native" - mode, where the user asked for `outputConfig` and gets its error. + Converse's `outputConfig` support is per-model in a way that can't + be derived from the model ID (e.g. `claude-sonnet-5` rejects it + while `claude-sonnet-4-6` accepts it), so "auto" mode is optimistic: + on the specific rejection, remember the model as unsupported and + retry with the forced tool call. Returns `None` (caller re-raises) + when the failure wasn't a native-mode attempt -- including explicit + "native" mode, where the user asked for `outputConfig` and gets its + error. (Only called from the non-streaming paths: `can_stream()` + keeps unverified native attempts out of the streaming paths, so a + structured stream never carries `outputConfig` until the model has + accepted one.) Retry eligibility comes from the failed request's own `outputConfig`, not the unsupported-model cache: a concurrent request may have @@ -651,143 +662,6 @@ def _is_native_rejection(error: ValueError) -> bool: and "Extra inputs are not permitted" in message ) - def _converse_stream_with_retry( - self, - args: ConverseRequestTypeDef, - stream: bool, - turns: list[Turn], - tools: dict[str, Tool | ToolBuiltIn], - data_model: Optional[type[BaseModel]], - kwargs: Optional[ConverseSubmitArgs], - ) -> Iterator[dict]: - if data_model is not None and "outputConfig" not in args: - # A tool-based structured request can't stream (tool input - # arrives in its own event type, not as text), so serve it via - # the non-streaming endpoint. `Chat` normally downgrades these - # via `can_stream()`, but a concurrent request can mark the model - # unsupported after that check and before args were built. - yield from self._response_as_stream_events(self._converse(args)) - return - events: Optional[Iterator[dict]] = None - try: - try: - # `_converse_stream` is a generator, so the request (and any - # error it fails with) doesn't fire until the first pull. - events = self._converse_stream(args) - first = next(events) - except StopIteration: - return - except ValueError as error: - retry = self._native_retry_args( - error, args, stream, turns, tools, data_model, kwargs - ) - if retry is None: - raise - # A tool-mode stream retry would yield zero chunks (the bug - # #451 fixed), so retry on the non-streaming endpoint and - # synthesize events that surface the extracted JSON as a - # single text chunk. - yield from self._response_as_stream_events(self._converse(retry)) - return - yield first - yield from events - finally: - # Closing this wrapper (e.g. on cancellation) must also close the - # inner generator, which owns the httpx streaming response. - close = getattr(events, "close", None) - if close is not None: - close() - - async def _converse_stream_async_with_retry( - self, - args: ConverseRequestTypeDef, - stream: bool, - turns: list[Turn], - tools: dict[str, Tool | ToolBuiltIn], - data_model: Optional[type[BaseModel]], - kwargs: Optional[ConverseSubmitArgs], - ) -> AsyncIterator[dict]: - if data_model is not None and "outputConfig" not in args: - # See the sync variant: tool-based structured requests can't - # stream, so serve them via the non-streaming endpoint. - for event in self._response_as_stream_events( - await self._converse_async(args) - ): - yield event - return - events: Optional[AsyncIterator[dict]] = None - try: - try: - events = self._converse_stream_async(args) - first = await events.__anext__() - except StopAsyncIteration: - return - except ValueError as error: - retry = self._native_retry_args( - error, args, stream, turns, tools, data_model, kwargs - ) - if retry is None: - raise - for event in self._response_as_stream_events( - await self._converse_async(retry) - ): - yield event - return - yield first - async for event in events: - yield event - finally: - # `async for` doesn't forward `aclose()`, so closing this wrapper - # (e.g. on cancellation) would leave the inner generator -- and - # its httpx streaming response -- open until GC. - aclose = getattr(events, "aclose", None) - if aclose is not None: - await aclose() - - @staticmethod - def _response_as_stream_events( - response: ConverseResponseTypeDef, - ) -> Iterator[dict]: - """Replay a non-streaming response as a minimal Converse event stream. - - Structured output is re-expressed as a text delta (rather than the - tool-use block it arrived as) so `stream_content()` yields the - extracted JSON as a single chunk and `_as_turn`'s native branch - records it as `ContentJson`. - """ - message = response["output"].get("message") - yield {"messageStart": {"role": (message or {}).get("role", "assistant")}} - if message is not None: - blocks = message["content"] - has_structured_tool = any( - (cast(dict, block).get("toolUse") or {}).get("name") - == "_structured_tool_call" - for block in blocks - ) - for index, block in enumerate(blocks): - block = cast(dict, block) - tool_use = block.get("toolUse") or {} - if tool_use.get("name") == "_structured_tool_call": - text: Optional[str] = json.dumps( - tool_use.get("input", {}).get("data") - ) - elif has_structured_tool: - # Prose alongside the structured tool call would corrupt - # the extracted-JSON stream; drop it from the events. - continue - else: - text = block.get("text") - if text is not None: - yield { - "contentBlockDelta": { - "contentBlockIndex": index, - "delta": {"text": text}, - } - } - yield {"contentBlockStop": {"contentBlockIndex": index}} - yield {"messageStop": {"stopReason": response["stopReason"]}} - yield {"metadata": {"usage": response["usage"]}} - def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: # Native structured outputs (`outputConfig`) stream as ordinary text # deltas, so they honor the extracted-JSON contract. The tool-based @@ -796,7 +670,15 @@ def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: # to a single non-streaming request there. if data_model is None: return True - return self._use_native_structured_output() + if self._structured_output_mode == "native": + return True + if not self._use_native_structured_output(): + return False + # Converse's `outputConfig` support can't be derived from the model + # ID, so "auto" proves it first: until a native request has + # succeeded, `Chat`'s non-streaming fallback doubles as the probe + # (and records the verdict either way). + return self.model in self._native_verified_models def _use_native_structured_output(self) -> bool: if self.model in self._native_unsupported_models: diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index b85176c6..0e0b619f 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1923,14 +1923,23 @@ class Person(BaseModel): # No data_model always streams. assert self.provider().can_stream(None) is True - # "auto" streams on supported Anthropic models ... - assert self.provider().can_stream(Person) is True - # ... but not on unsupported ones. + # "auto" on a regex-supported model probes first: it can't stream + # until a native request has succeeded ... + unverified = self.provider() + assert unverified.can_stream(Person) is False + # ... and streams natively once verified. + unverified._native_verified_models.add(unverified.model) + assert unverified.can_stream(Person) is True + # Models the regex doesn't match never probe ... assert ( self.provider(model="us.anthropic.claude-sonnet-4").can_stream(Person) is False ) assert self.provider(model="amazon.nova-lite-v1:0").can_stream(Person) is False + # ... nor do models that already rejected `outputConfig`. + rejected = self.provider() + rejected._native_unsupported_models.add(rejected.model) + assert rejected.can_stream(Person) is False # "native" forces streaming even on unsupported models ... assert ( self.provider(model="amazon.nova-lite-v1:0", mode="native").can_stream( @@ -2079,7 +2088,7 @@ class Person(BaseModel): name: str age: int - provider = self.provider() + provider = self.provider(mode="native") chat = Chat(provider=provider) with patch.object( provider, @@ -2101,66 +2110,10 @@ class Person(BaseModel): assert isinstance(turn.contents[0], ContentJson) assert turn.contents[0].value == {"name": "John", "age": 15} - def test_chat_bedrock_forwards_mode_to_converse(self): - from pydantic import BaseModel - - class Person(BaseModel): - name: str - age: int - - # Default model (us.anthropic.claude-sonnet-5) matches the native - # support regex, so the mode alone decides can_stream here. - chat = ChatBedrock( - api="converse", aws_region="us-east-1", structured_output_mode="tool" - ) - assert chat.provider.can_stream(Person) is False - chat = ChatBedrock( - api="converse", aws_region="us-east-1", structured_output_mode="native" - ) - assert chat.provider.can_stream(Person) is True - - def test_structured_output_mode_rejected_off_converse(self): - for api in ("messages", "responses"): - with pytest.raises(ValueError, match="structured_output_mode"): - ChatBedrock( - api=api, # type: ignore[arg-type] - aws_region="us-east-1", - structured_output_mode="native", - ) - - @staticmethod - def _fake_mixed_converse_response(): - # Prose alongside the structured tool call. - return cast( - "ConverseResponseTypeDef", - { - "output": { - "message": { - "role": "assistant", - "content": [ - {"text": "Here is the extracted data:"}, - { - "toolUse": { - "toolUseId": "toolu_x", - "name": "_structured_tool_call", - "input": {"data": {"name": "John", "age": 15}}, - } - }, - ], - } - }, - "stopReason": "tool_use", - "usage": {"inputTokens": 1, "outputTokens": 1, "totalTokens": 2}, - }, - ) - - def test_stream_fallback_with_mixed_text_and_tool_response(self): - # The synthesized stream must carry only the extracted JSON -- the - # prose would corrupt `"".join(chunks)` and crash `_as_turn`. + def test_auto_mode_first_request_probes_native_support(self): from unittest.mock import patch from chatlas import Chat - from chatlas._content import ContentJson from pydantic import BaseModel class Person(BaseModel): @@ -2170,30 +2123,30 @@ class Person(BaseModel): provider = self.provider() chat = Chat(provider=provider) - def fake_stream(args): - if "outputConfig" in args: - raise self._native_rejection() - raise AssertionError("stream retry must use the non-streaming endpoint") - - with patch.object(provider, "_converse_stream", side_effect=fake_stream): - with patch.object( - provider, - "_converse", - return_value=self._fake_mixed_converse_response(), - ): - with pytest.warns(UserWarning, match="outputConfig"): - chunks = list(chat.stream("John, age 15", data_model=Person)) - + # Unverified: the first structured stream downgrades to a + # non-streaming request, which doubles as the native probe. + with patch.object( + provider, + "_converse", + return_value=self._fake_native_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 isinstance(turn.contents[0], ContentJson) - assert turn.contents[0].value == {"name": "John", "age": 15} - @pytest.mark.asyncio - async def test_stream_async_fallback_with_mixed_response(self): - from unittest.mock import AsyncMock, patch + # Verified: subsequent streams go native and stream incrementally. + assert provider.can_stream(Person) is True + with patch.object( + provider, + "_converse_stream", + side_effect=lambda args: iter(self._fake_native_stream_events()), + ): + chunks = list(chat.stream("John, age 15", data_model=Person)) + assert chunks == ['{"name": "Joh', 'n", "age": 15}'] + + def test_auto_mode_probe_rejection_turns_off_native(self): + from unittest.mock import patch from chatlas import Chat from pydantic import BaseModel @@ -2205,70 +2158,47 @@ class Person(BaseModel): provider = self.provider() chat = Chat(provider=provider) - async def fake_stream(args): + def fake_converse(args): if "outputConfig" in args: raise self._native_rejection() - yield # pragma: no cover + return _fake_data_model_converse_response() - with patch.object(provider, "_converse_stream_async", fake_stream): - with patch.object( - provider, - "_converse_async", - new=AsyncMock(return_value=self._fake_mixed_converse_response()), - ): - with pytest.warns(UserWarning, match="outputConfig"): - chunks = [ - chunk - async for chunk in await chat.stream_async( - "John, age 15", data_model=Person - ) - ] + with patch.object(provider, "_converse", side_effect=fake_converse): + # Downgrade warning (the probe) + rejection warning (the retry). + with pytest.warns(UserWarning): + chunks = list(chat.stream("John, age 15", data_model=Person)) person = Person.model_validate_json("".join(chunks)) assert person == Person(name="John", age=15) + assert provider.can_stream(Person) is False - def test_tool_mode_args_served_via_non_streaming_in_stream_wrapper(self): - # Race: the model is marked unsupported after `can_stream()` returns - # True but before args are built, so tool-mode args reach the stream - # wrapper. It must serve them via the non-streaming endpoint (a - # tool-mode stream would yield zero chunks). - from unittest.mock import patch - + def test_chat_bedrock_forwards_mode_to_converse(self): from pydantic import BaseModel class Person(BaseModel): name: str age: int - provider = self.provider(mode="tool") - turns = [UserTurn("John, age 15")] - args = provider._chat_perform_args( - stream=True, turns=turns, tools={}, data_model=Person + # Default model (us.anthropic.claude-sonnet-5) matches the native + # support regex, so the mode alone decides can_stream here. + chat = ChatBedrock( + api="converse", aws_region="us-east-1", structured_output_mode="tool" ) - assert "outputConfig" not in args + assert chat.provider.can_stream(Person) is False + chat = ChatBedrock( + api="converse", aws_region="us-east-1", structured_output_mode="native" + ) + assert chat.provider.can_stream(Person) is True - def fail_stream(args): - raise AssertionError("must use the non-streaming endpoint") - - with patch.object(provider, "_converse_stream", side_effect=fail_stream): - with patch.object( - provider, - "_converse", - return_value=_fake_data_model_converse_response(), - ): - events = list( - provider._converse_stream_with_retry( - args, True, turns, {}, Person, None - ) + def test_structured_output_mode_rejected_off_converse(self): + for api in ("messages", "responses"): + with pytest.raises(ValueError, match="structured_output_mode"): + ChatBedrock( + api=api, # type: ignore[arg-type] + aws_region="us-east-1", + structured_output_mode="native", ) - text = "".join( - e["contentBlockDelta"]["delta"]["text"] - for e in events - if "contentBlockDelta" in e - ) - assert Person.model_validate_json(text) == Person(name="John", age=15) - def test_tool_mode_drops_user_supplied_output_config(self): from pydantic import BaseModel @@ -2366,7 +2296,7 @@ def reject(args): chat.chat_structured("John, age 15", data_model=Person) # The model is not (wrongly) remembered as unsupported. - assert provider.can_stream(Person) is True + assert provider.model not in provider._native_unsupported_models def test_in_flight_native_request_still_retries_after_marking(self): # A concurrent request can mark the model unsupported while another @@ -2415,79 +2345,6 @@ def reject(args): with pytest.raises(ValueError, match="output_config"): chat.chat_structured("John, age 15", data_model=Person) - def test_stream_falls_back_to_single_chunk_on_native_rejection(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) - - def fake_stream(args): - if "outputConfig" in args: - raise self._native_rejection() - raise AssertionError("stream retry must use the non-streaming endpoint") - - with patch.object(provider, "_converse_stream", side_effect=fake_stream): - with patch.object( - provider, - "_converse", - return_value=_fake_data_model_converse_response(), - ): - with pytest.warns(UserWarning, match="outputConfig"): - chunks = list(chat.stream("John, age 15", data_model=Person)) - - # #451's contract: the complete JSON as a single chunk. - 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 isinstance(turn.contents[0], ContentJson) - assert turn.contents[0].value == {"name": "John", "age": 15} - - @pytest.mark.asyncio - async def test_stream_async_falls_back_on_native_rejection(self): - from unittest.mock import AsyncMock, patch - - from chatlas import Chat - from pydantic import BaseModel - - class Person(BaseModel): - name: str - age: int - - provider = self.provider() - chat = Chat(provider=provider) - - async def fake_stream(args): - if "outputConfig" in args: - raise self._native_rejection() - yield # pragma: no cover - - with patch.object(provider, "_converse_stream_async", fake_stream): - with patch.object( - provider, - "_converse_async", - new=AsyncMock(return_value=_fake_data_model_converse_response()), - ): - with pytest.warns(UserWarning, match="outputConfig"): - 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) - @pytest.mark.asyncio async def test_native_mode_streams_incrementally_async(self): from unittest.mock import patch @@ -2499,7 +2356,7 @@ class Person(BaseModel): name: str age: int - provider = self.provider() + provider = self.provider(mode="native") chat = Chat(provider=provider) events = self._fake_native_stream_events() @@ -2632,7 +2489,9 @@ class Person(BaseModel): name: str age: int - chat = ChatBedrock(model="us.anthropic.claude-sonnet-4-6") + chat = ChatBedrock( + model="us.anthropic.claude-sonnet-4-6", structured_output_mode="native" + ) chunks = list(chat.stream("Extract: John is 15 years old.", data_model=Person)) person = Person.model_validate_json("".join(chunks)) assert person.name == "John" From 1a7e82b615c5f1ed6291b28ab769a16f5686675c Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 15:24:55 -0500 Subject: [PATCH 10/13] Don't advertise ordinary tools during structured extraction Extraction is one-shot (chat_structured() never executes tools, and tool mode forces the structured call up front), so an ordinary tool call where JSON was required can only fail. Registered tools are no longer advertised when a data_model is present, and a caller-supplied toolConfig is dropped (tool mode's forced choice is still re-asserted). --- chatlas/_provider_bedrock_converse.py | 23 ++++++-- tests/test_provider_bedrock_converse.py | 75 ++++++++++++++++++++++++- 2 files changed, 92 insertions(+), 6 deletions(-) diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 18029d21..3beddeda 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -904,11 +904,18 @@ def _chat_perform_args( self._use_native_structured_output() ) data_model_tool: Optional[Tool] = None - tool_specs = [converse_tool_spec(tool) for tool in tools.values()] + if data_model is None: + tool_specs = [converse_tool_spec(tool) for tool in tools.values()] + else: + # Extraction is one-shot: `chat_structured()` never executes + # tools (and tool mode forces the structured call up front), so + # advertising ordinary tools can only produce an ordinary tool + # call where JSON was required. + tool_specs = [] + if not use_native_output: + data_model_tool = AnthropicProvider.create_data_model_tool(data_model) + tool_specs.append(converse_tool_spec(data_model_tool)) tool_config: Optional[ToolConfigurationTypeDef] = None - if data_model is not None and not use_native_output: - data_model_tool = AnthropicProvider.create_data_model_tool(data_model) - tool_specs.append(converse_tool_spec(data_model_tool)) if tool_specs: tool_config = {"tools": tool_specs} @@ -928,6 +935,14 @@ def _chat_perform_args( inference_config.update(extra_inference_config) args.update(extra) + if data_model is not None: + # chatlas owns the request shape during extraction: a + # caller-supplied `toolConfig` (e.g. a toolChoice forcing an + # ordinary tool) contradicts one-shot extraction just as much as + # registered tools would. (Tool mode's own forced choice is + # re-asserted later in this method.) + extra.pop("toolConfig", None) + args.pop("toolConfig", None) if data_model is not None and not use_native_output: # A caller-supplied raw `outputConfig` can't be honored for a # tool-based structured request (and would break the fallback in diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index 0e0b619f..a3f7875b 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1470,8 +1470,12 @@ def get_weather(city: str) -> str: if "toolSpec" in tool ] - assert tool_name in tool_names - assert weather_tool.name in tool_names + # The structured tool is forced, and ordinary registered tools are + # not advertised at all (extraction is one-shot; `chat_structured()` + # never executes tools). + assert tool_name == "_structured_tool_call" + assert tool_names == ["_structured_tool_call"] + assert weather_tool.name not in tool_names def test_data_model_tool_choice_overrides_request_tool_config(self): from pydantic import BaseModel @@ -2199,6 +2203,73 @@ def test_structured_output_mode_rejected_off_converse(self): structured_output_mode="native", ) + def test_data_model_does_not_advertise_registered_tools(self): + # Extraction is one-shot (`chat_structured()` never executes tools), + # so an ordinary tool call where JSON was required can only fail. + from chatlas._tools import Tool + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + def get_weather(city: str) -> str: + """Get the weather for a city.""" + return city + + weather_tool = Tool.from_func(get_weather) + tools = {weather_tool.name: weather_tool} + turns = [UserTurn("John, age 15")] + + # Native mode: no tools advertised at all. + args = self.provider()._chat_perform_args( + stream=False, turns=turns, tools=tools, data_model=Person + ) + assert "outputConfig" in args + assert "toolConfig" not in args + + # Tool mode: only the structured tool, still forced. + args = self.provider(mode="tool")._chat_perform_args( + stream=False, turns=turns, tools=tools, data_model=Person + ) + tool_names = [t["toolSpec"]["name"] for t in args["toolConfig"]["tools"]] + assert tool_names == ["_structured_tool_call"] + assert args["toolConfig"]["toolChoice"] == { + "tool": {"name": "_structured_tool_call"} + } + + def test_data_model_drops_caller_supplied_tool_config(self): + # An explicit toolChoice for an ordinary tool would make extraction + # fail deterministically; chatlas owns the request shape during + # extraction. + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + tool_config = { + "tools": [ + { + "toolSpec": { + "name": "get_weather", + "description": "Get the weather.", + "inputSchema": {"json": {"type": "object"}}, + } + } + ], + "toolChoice": {"tool": {"name": "get_weather"}}, + } + args = self.provider()._chat_perform_args( + stream=False, + turns=[UserTurn("John, age 15")], + tools={}, + data_model=Person, + kwargs={"toolConfig": tool_config}, # type: ignore[typeddict-item] + ) + assert "outputConfig" in args + assert "toolConfig" not in args + def test_tool_mode_drops_user_supplied_output_config(self): from pydantic import BaseModel From 4f26beb5e1d43380830c5397c51149f8cd64d25f Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 15:59:43 -0500 Subject: [PATCH 11/13] Scope one-shot extraction policy to chat_structured() at the Chat layer chat_structured()/chat_structured_async() never execute tools, so they now advertise none (with a warning) via a tools override on _submit_turns/_submit_turns_async, instead of dropping them at the provider level -- which would have silently broken the working .stream() multi-step extraction flow (verified live: tool call, tool result, streamed JSON). The Bedrock provider again advertises registered tools for data_model requests; caller-supplied contradictory kwargs (toolConfig, and outputConfig in tool mode) are still stripped. --- CHANGELOG.md | 1 + chatlas/_chat.py | 39 ++++++++++++++--- chatlas/_provider_bedrock_converse.py | 42 +++++++----------- tests/test_provider_bedrock_converse.py | 58 +++++++++++++++++++------ 4 files changed, 95 insertions(+), 45 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf5ed90..23037ee0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `.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) +* `chat_structured()` and `chat_structured_async()` no longer advertise registered tools to the model (with a warning). Extraction never executes tools, so previously the model could answer with an ordinary tool call, failing extraction with `Data extraction failed: 0 data results received.` Multi-step extraction (tools, then JSON) remains available via `.stream()`/`.stream_async()` with a `data_model`, which do run the tool loop. (#463) * `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, the first structured request to a model doubles as a non-streaming probe: a model that accepts `outputConfig` streams natively from then on, while a rejection triggers a one-time warning, a transparent retry with the previous forced-tool-call behavior, and tool mode for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#463) * 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. diff --git a/chatlas/_chat.py b/chatlas/_chat.py index dfaf4f2c..6c263e29 100644 --- a/chatlas/_chat.py +++ b/chatlas/_chat.py @@ -1660,6 +1660,7 @@ def _submit_and_extract_data( stream=stream, kwargs=kwargs, controller=StreamController(), + tools=self._tools_for_extraction(), ) ) @@ -1763,6 +1764,7 @@ async def _submit_and_extract_data_async( stream=stream, kwargs=kwargs, controller=StreamController(), + tools=self._tools_for_extraction(), ) ) @@ -2911,6 +2913,7 @@ def _submit_turns( *, controller: StreamController, _otel_parent: Optional[Span] = None, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> Generator[str, None, None]: ... @overload @@ -2925,6 +2928,7 @@ def _submit_turns( content_mode: Literal["all"], controller: StreamController, _otel_parent: Optional[Span] = None, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> Generator[str | Content, None, None]: ... def _submit_turns( @@ -2938,8 +2942,10 @@ def _submit_turns( _otel_parent: Optional[Span] = None, *, controller: StreamController, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> Generator[str | Content, None, None]: - if any(isinstance(x, Tool) and x._is_async for x in self._tools.values()): + tools = self._tools if tools is None else tools + if any(isinstance(x, Tool) and x._is_async for x in tools.values()): raise ValueError("Cannot use async tools in a synchronous chat") request_turns = [*self._turns, user_turn] @@ -2982,7 +2988,7 @@ def emit(x: str | Content): response = self.provider.chat_perform( stream=True, turns=provider_turns, - tools=self._tools, + tools=tools, data_model=data_model, kwargs=all_kwargs, ) @@ -3032,7 +3038,7 @@ def emit(x: str | Content): response = self.provider.chat_perform( stream=False, turns=provider_turns, - tools=self._tools, + tools=tools, data_model=data_model, kwargs=all_kwargs, ) @@ -3075,6 +3081,7 @@ def _submit_turns_async( *, controller: StreamController, _otel_parent: Optional[Span] = None, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> AsyncGenerator[str, None]: ... @overload @@ -3089,6 +3096,7 @@ def _submit_turns_async( content_mode: Literal["all"], controller: StreamController, _otel_parent: Optional[Span] = None, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> AsyncGenerator[str | Content, None]: ... async def _submit_turns_async( @@ -3102,7 +3110,9 @@ async def _submit_turns_async( _otel_parent: Optional[Span] = None, *, controller: StreamController, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> AsyncGenerator[str | Content, None]: + tools = self._tools if tools is None else tools request_turns = [*self._turns, user_turn] provider_turns = normalize_turns_for_provider(request_turns) chat_span = start_chat_span( @@ -3143,7 +3153,7 @@ def emit(x: str | Content): response = await self.provider.chat_perform_async( stream=True, turns=provider_turns, - tools=self._tools, + tools=tools, data_model=data_model, kwargs=all_kwargs, ) @@ -3195,7 +3205,7 @@ def emit(x: str | Content): response = await self.provider.chat_perform_async( stream=False, turns=provider_turns, - tools=self._tools, + tools=tools, data_model=data_model, kwargs=all_kwargs, ) @@ -3226,6 +3236,25 @@ def emit(x: str | Content): finally: end_span(chat_span) + def _tools_for_extraction(self) -> dict[str, Tool | ToolBuiltIn]: + """Tools to advertise for one-shot structured extraction (none). + + `.chat_structured()` never executes tools, so an ordinary tool call + where JSON was required can only fail extraction. Multi-step + extraction (tools, then JSON) remains available via `.stream()` with + a `data_model`, which does run the tool loop. + """ + if not self._tools: + return self._tools + warnings.warn( + "Registered tools are not advertised during structured data " + "extraction (`.chat_structured()` never executes tools, so an " + "ordinary tool call would fail extraction). Use `.stream()` with " + "a `data_model` to combine tool use with extraction.", + stacklevel=caller_stacklevel(), + ) + return {} + def _resolve_stream( self, stream: bool, diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index 3beddeda..d1e79c3c 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -904,18 +904,11 @@ def _chat_perform_args( self._use_native_structured_output() ) data_model_tool: Optional[Tool] = None - if data_model is None: - tool_specs = [converse_tool_spec(tool) for tool in tools.values()] - else: - # Extraction is one-shot: `chat_structured()` never executes - # tools (and tool mode forces the structured call up front), so - # advertising ordinary tools can only produce an ordinary tool - # call where JSON was required. - tool_specs = [] - if not use_native_output: - data_model_tool = AnthropicProvider.create_data_model_tool(data_model) - tool_specs.append(converse_tool_spec(data_model_tool)) + tool_specs = [converse_tool_spec(tool) for tool in tools.values()] tool_config: Optional[ToolConfigurationTypeDef] = None + if data_model is not None and not use_native_output: + data_model_tool = AnthropicProvider.create_data_model_tool(data_model) + tool_specs.append(converse_tool_spec(data_model_tool)) if tool_specs: tool_config = {"tools": tool_specs} @@ -927,28 +920,25 @@ def _chat_perform_args( args["toolConfig"] = tool_config extra = dict(cast(dict, kwargs or {})) - # Merge inferenceConfig rather than replacing it outright, so a - # per-request override (e.g. from `set_model_params(temperature=...)`) - # doesn't silently drop `maxTokens`. - extra_inference_config = extra.pop("inferenceConfig", None) - if extra_inference_config: - inference_config.update(extra_inference_config) - args.update(extra) - if data_model is not None: - # chatlas owns the request shape during extraction: a - # caller-supplied `toolConfig` (e.g. a toolChoice forcing an - # ordinary tool) contradicts one-shot extraction just as much as - # registered tools would. (Tool mode's own forced choice is - # re-asserted later in this method.) + # A caller-supplied `toolConfig` (e.g. a toolChoice forcing an + # ordinary tool) contradicts extraction: `chat_structured()` + # never executes tools, and in the streaming tool loop a forced + # choice would re-fire on every submission. (Tool mode's own + # forced choice is re-asserted later in this method.) extra.pop("toolConfig", None) - args.pop("toolConfig", None) if data_model is not None and not use_native_output: # A caller-supplied raw `outputConfig` can't be honored for a # tool-based structured request (and would break the fallback in # `_native_retry_args`, whose rebuild re-applies `kwargs`). extra.pop("outputConfig", None) - args.pop("outputConfig", None) + # Merge inferenceConfig rather than replacing it outright, so a + # per-request override (e.g. from `set_model_params(temperature=...)`) + # doesn't silently drop `maxTokens`. + extra_inference_config = extra.pop("inferenceConfig", None) + if extra_inference_config: + inference_config.update(extra_inference_config) + args.update(extra) if data_model is not None and use_native_output: from anthropic import transform_schema diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index a3f7875b..4be6d5a9 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1470,12 +1470,8 @@ def get_weather(city: str) -> str: if "toolSpec" in tool ] - # The structured tool is forced, and ordinary registered tools are - # not advertised at all (extraction is one-shot; `chat_structured()` - # never executes tools). - assert tool_name == "_structured_tool_call" - assert tool_names == ["_structured_tool_call"] - assert weather_tool.name not in tool_names + assert tool_name in tool_names + assert weather_tool.name in tool_names def test_data_model_tool_choice_overrides_request_tool_config(self): from pydantic import BaseModel @@ -2203,9 +2199,10 @@ def test_structured_output_mode_rejected_off_converse(self): structured_output_mode="native", ) - def test_data_model_does_not_advertise_registered_tools(self): - # Extraction is one-shot (`chat_structured()` never executes tools), - # so an ordinary tool call where JSON was required can only fail. + def test_data_model_request_advertises_registered_tools(self): + # At the provider level, tools are advertised so multi-step + # extraction can work through the streaming tool loop; `Chat` decides + # what to send (see the chat_structured test below). from chatlas._tools import Tool from pydantic import BaseModel @@ -2221,23 +2218,56 @@ def get_weather(city: str) -> str: tools = {weather_tool.name: weather_tool} turns = [UserTurn("John, age 15")] - # Native mode: no tools advertised at all. + # Native mode: tools advertised alongside `outputConfig`. args = self.provider()._chat_perform_args( stream=False, turns=turns, tools=tools, data_model=Person ) assert "outputConfig" in args - assert "toolConfig" not in args + tool_names = [t["toolSpec"]["name"] for t in args["toolConfig"]["tools"]] + assert weather_tool.name in tool_names - # Tool mode: only the structured tool, still forced. + # Tool mode: tools advertised, but the structured call is forced. args = self.provider(mode="tool")._chat_perform_args( stream=False, turns=turns, tools=tools, data_model=Person ) - tool_names = [t["toolSpec"]["name"] for t in args["toolConfig"]["tools"]] - assert tool_names == ["_structured_tool_call"] assert args["toolConfig"]["toolChoice"] == { "tool": {"name": "_structured_tool_call"} } + def test_chat_structured_does_not_advertise_registered_tools(self): + # `chat_structured()` never executes tools, so `Chat` doesn't + # advertise them (with a warning); `.stream()` still does. + from unittest.mock import patch + + from chatlas import Chat + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + def get_weather(city: str) -> str: + """Get the weather for a city.""" + return city + + provider = self.provider() + chat = Chat(provider=provider) + chat.register_tool(get_weather) + + request: dict = {} + + def fake_converse(args): + request.update(args) + return self._fake_native_converse_response() + + with patch.object(provider, "_converse", side_effect=fake_converse): + with pytest.warns(UserWarning, match="not advertised"): + result = chat.chat_structured("John, age 15", data_model=Person) + + assert result == Person(name="John", age=15) + assert "outputConfig" in request + assert "toolConfig" not in request + def test_data_model_drops_caller_supplied_tool_config(self): # An explicit toolChoice for an ordinary tool would make extraction # fail deterministically; chatlas owns the request shape during From b7700877ca0d84341bd31fcfb6afc30cede92b4f Mon Sep 17 00:00:00 2001 From: Carson Date: Fri, 16 Oct 2026 16:04:29 -0500 Subject: [PATCH 12/13] Keep tool specs for extraction when history contains tool use Bedrock Converse 400s on requests with toolUse/toolResult history but no toolConfig (verified live), so chat_structured() after a tool-using conversation was broken by the one-shot policy. New Provider.tool_history_requires_config() hook (True for Converse) makes Chat keep the registered specs in that case; clean-history extraction still drops them with a warning. --- CHANGELOG.md | 2 +- chatlas/_chat.py | 9 +++++ chatlas/_provider.py | 12 +++++++ chatlas/_provider_bedrock_converse.py | 6 ++++ tests/test_provider_bedrock_converse.py | 48 +++++++++++++++++++++++++ 5 files changed, 76 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23037ee0..401ffac3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,7 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `.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) -* `chat_structured()` and `chat_structured_async()` no longer advertise registered tools to the model (with a warning). Extraction never executes tools, so previously the model could answer with an ordinary tool call, failing extraction with `Data extraction failed: 0 data results received.` Multi-step extraction (tools, then JSON) remains available via `.stream()`/`.stream_async()` with a `data_model`, which do run the tool loop. (#463) +* `chat_structured()` and `chat_structured_async()` no longer advertise registered tools to the model (with a warning), unless the conversation history contains tool use and the provider requires tool specs for such requests (e.g. Bedrock Converse, which rejects them otherwise). Extraction never executes tools, so previously the model could answer with an ordinary tool call, failing extraction with `Data extraction failed: 0 data results received.` Multi-step extraction (tools, then JSON) remains available via `.stream()`/`.stream_async()` with a `data_model`, which do run the tool loop. (#463) * `ChatBedrock()` with the default Converse API now uses Bedrock's native structured outputs API (`outputConfig`) for models that support it (currently Anthropic Claude models), restoring true incremental streaming from `.stream()`/`.stream_async()` with `data_model` for those models. Since Converse's support varies by model in ways that can't be derived from the model ID, the first structured request to a model doubles as a non-streaming probe: a model that accepts `outputConfig` streams natively from then on, while a rejection triggers a one-time warning, a transparent retry with the previous forced-tool-call behavior, and tool mode for subsequent requests. Pass the new `structured_output_mode="tool"` to force the tool-call behavior, or `"native"` to force `outputConfig` (which surfaces the model's error instead of falling back). (#463) * 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. diff --git a/chatlas/_chat.py b/chatlas/_chat.py index 6c263e29..19115d26 100644 --- a/chatlas/_chat.py +++ b/chatlas/_chat.py @@ -3246,6 +3246,15 @@ def _tools_for_extraction(self) -> dict[str, Tool | ToolBuiltIn]: """ if not self._tools: return self._tools + if self.provider.tool_history_requires_config() and any( + isinstance(content, (ContentToolRequest, ContentToolResult)) + for turn in self._turns + for content in turn.contents + ): + # The provider (e.g. Bedrock Converse) rejects requests with + # tool-call history but no tool specs, so extraction can't drop + # them here. + return self._tools warnings.warn( "Registered tools are not advertised during structured data " "extraction (`.chat_structured()` never executes tools, so an " diff --git a/chatlas/_provider.py b/chatlas/_provider.py index e4ca4cc8..72d64775 100644 --- a/chatlas/_provider.py +++ b/chatlas/_provider.py @@ -316,6 +316,18 @@ async def chat_perform_async( kwargs: SubmitInputArgsT, ) -> AsyncIterable[ChatCompletionChunkT] | ChatCompletionT: ... + def tool_history_requires_config(self) -> bool: + """ + Whether requests must include tool specs when conversation history + contains tool call/result blocks. + + Bedrock Converse rejects such requests without a `toolConfig`; most + APIs don't care. [](`~chatlas.Chat`) uses this to decide whether + one-shot structured extraction can drop registered tools from the + request. + """ + return False + def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: """ Whether a streaming request is supported for the given inputs. diff --git a/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index d1e79c3c..72091fd1 100644 --- a/chatlas/_provider_bedrock_converse.py +++ b/chatlas/_provider_bedrock_converse.py @@ -662,6 +662,12 @@ def _is_native_rejection(error: ValueError) -> bool: and "Extra inputs are not permitted" in message ) + def tool_history_requires_config(self) -> bool: + # Converse 400s with "The toolConfig field must be defined when using + # toolUse and toolResult content blocks" (it doesn't check that the + # specs match the history's tool names). + return True + def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: # Native structured outputs (`outputConfig`) stream as ordinary text # deltas, so they honor the extracted-JSON contract. The tool-based diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index 4be6d5a9..4a149845 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -2268,6 +2268,54 @@ def fake_converse(args): assert "outputConfig" in request assert "toolConfig" not in request + def test_chat_structured_after_tool_use_keeps_tool_config(self): + # Converse requires `toolConfig` when history contains toolUse/ + # toolResult blocks, so extraction can't drop the registered specs + # there (and shouldn't warn). + import warnings + from unittest.mock import patch + + from chatlas import Chat + from chatlas._content import ContentToolRequest, ContentToolResult + from chatlas._turn import AssistantTurn + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + def get_weather(city: str) -> str: + """Get the weather for a city.""" + return city + + provider = self.provider() + chat = Chat(provider=provider) + chat.register_tool(get_weather) + tool_request = ContentToolRequest( + id="toolu_x", name="get_weather", arguments={"city": "Paris"} + ) + chat.add_turn(UserTurn("What's the weather in Paris?")) + chat.add_turn(AssistantTurn([tool_request])) + chat.add_turn( + UserTurn([ContentToolResult(value="72F and sunny", request=tool_request)]) + ) + + request: dict = {} + + def fake_converse(args): + request.update(args) + return self._fake_native_converse_response() + + with patch.object(provider, "_converse", side_effect=fake_converse): + with warnings.catch_warnings(): + warnings.simplefilter("error") # no "not advertised" warning + result = chat.chat_structured("Extract the weather.", data_model=Person) + + assert isinstance(result, Person) + tool_names = [t["toolSpec"]["name"] for t in request["toolConfig"]["tools"]] + assert "get_weather" in tool_names + assert "outputConfig" in request + def test_data_model_drops_caller_supplied_tool_config(self): # An explicit toolChoice for an ordinary tool would make extraction # fail deterministically; chatlas owns the request shape during From 829e30d9731f455db147956ca399ced1e75c4e81 Mon Sep 17 00:00:00 2001 From: Carson Date: Mon, 9 Nov 2026 11:12:37 -0600 Subject: [PATCH 13/13] ci: retrigger workflows (synchronize event dropped)