diff --git a/CHANGELOG.md b/CHANGELOG.md index 944c4d9d..afddf8c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -49,6 +49,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 * `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), 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) +* `ChatBedrock(api="messages")` now supports `structured_output_mode` with the same semantics as the Converse path. Mantle's `output_config` support also varies by model in ways that can't be derived from the model ID (and differs from both the Anthropic API and Converse), so `"auto"` uses the same probe behavior: the first structured request doubles as a non-streaming probe, a rejection triggers a one-time warning and a transparent retry with the forced tool call, and the verdict is remembered. Previously, the default `"auto"` mode sent `output_config` to every Claude 4.5+ model, which mantle rejects for some (e.g. `anthropic.claude-haiku-4-5`) with a 400 error. (#465) * 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_anthropic.py b/chatlas/_provider_anthropic.py index b66a4f71..ddce19e8 100644 --- a/chatlas/_provider_anthropic.py +++ b/chatlas/_provider_anthropic.py @@ -520,10 +520,28 @@ def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: return True return self._use_native_structured_output() - def _use_native_structured_output(self) -> bool: + def _structured_output_model( + self, kwargs: Optional["SubmitInputArgs"] + ) -> Optional[str]: + """The model whose capabilities decide the structured-output strategy. + + `None` (the default) keys the strategy on the provider's configured + model, which is also what `can_stream()` sees (request kwargs aren't + available to that hook), keeping the two consistent. Providers whose + native support is tracked per serving model (Bedrock's mantle + endpoint) override this to honor a per-request `model` override, + paired with a loud stream-time guard for the case `can_stream()` + can't see. + """ + return None + + def _use_native_structured_output(self, model: Optional[str] = None) -> bool: + # `model` is the effective request model, which request kwargs may + # have overridden; verdicts and support checks should reflect the + # model that will actually serve the request. mode = self._structured_output_mode return mode == "native" or ( - mode == "auto" and supports_structured_outputs(self.model) + mode == "auto" and supports_structured_outputs(model or self.model) ) def _chat_perform_args( @@ -536,7 +554,9 @@ def _chat_perform_args( ) -> "SubmitInputArgs": tool_schemas = [self._anthropic_tool_schema(tool) for tool in tools.values()] - use_native = self._use_native_structured_output() + use_native = self._use_native_structured_output( + self._structured_output_model(kwargs) + ) if data_model is not None and use_native: from anthropic import transform_schema diff --git a/chatlas/_provider_bedrock.py b/chatlas/_provider_bedrock.py index 09fed7ae..e5a3adb8 100644 --- a/chatlas/_provider_bedrock.py +++ b/chatlas/_provider_bedrock.py @@ -3,8 +3,9 @@ import json import os import re +import warnings from importlib import resources -from typing import TYPE_CHECKING, Any, Literal, Optional, cast +from typing import TYPE_CHECKING, Any, Literal, Optional, cast, overload import httpx @@ -19,9 +20,11 @@ ) from ._provider_openai import OpenAIProvider from ._provider_openai_generic import openai_models_to_info +from ._turn import caller_stacklevel from ._utils import MISSING, MISSING_TYPE, AnyTypeDict, split_http_client_kwargs if TYPE_CHECKING: + from anthropic import BadRequestError from botocore.credentials import Credentials from botocore.session import Session from pydantic import BaseModel @@ -142,12 +145,13 @@ def ChatBedrock( 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 + (`outputConfig` for `api="converse"`, `output_config` for + `api="messages"`) 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 + the native API, chatlas warns, remembers, and falls back to the tool + call for subsequent requests. `"native"` forces the native API; + `"tool"` forces the tool call. Not supported when + `api="responses"`. Native mode streams structured output incrementally; tool mode falls back to a single non-streaming request (with a warning) from `.stream()`/`.stream_async()`. kwargs @@ -186,9 +190,9 @@ def ChatBedrock( f'Invalid `api` value "{api}". ' 'Must be one of "converse", "messages", or "responses".' ) - if structured_output_mode != "auto" and api != "converse": + if structured_output_mode != "auto" and api == "responses": raise ValueError( - '`structured_output_mode` is only supported when `api="converse"`.' + '`structured_output_mode` is not supported when `api="responses"`.' ) region = bedrock_region(aws_profile, aws_region) @@ -253,6 +257,7 @@ def ChatBedrock( # The Messages API caches via cache_control blocks, which have no # "auto" equivalent; all Claude models support caching. cache="5m" if cache == "auto" else cache, + structured_output_mode=structured_output_mode, kwargs=cast("Optional[AnthropicClientArgs]", kwargs), ), system_prompt=system_prompt, @@ -327,6 +332,7 @@ def __init__( base_url: Optional[str], max_tokens: int = 4096, cache: Literal["5m", "1h", "none"] = "5m", + structured_output_mode: StructuredOutputMode = "auto", name: str = "AWS/Bedrock", kwargs: Optional["AnthropicClientArgs"] = None, ): @@ -348,7 +354,13 @@ def __init__( model=model, max_tokens=max_tokens, cache=cache, + structured_output_mode=structured_output_mode, ) + # Models that have rejected `output_config` 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() sync_kwargs, async_kwargs = split_http_client_kwargs( bedrock_client_kwargs( @@ -387,9 +399,35 @@ def _chat_perform_args( stream: bool, turns: list["Turn"], tools: dict[str, "Tool | ToolBuiltIn"], - data_model: Optional["type[BaseModel]"] = None, + data_model: Optional[type[BaseModel]] = None, kwargs: Optional["AnthropicSubmitInputArgs"] = None, ) -> "AnthropicSubmitInputArgs": + if data_model is not None and kwargs: + # Caller kwargs that contradict extraction are dropped (from a + # copy; the caller's mapping is unchanged): + # - a native `format`, since the schema comes from `data_model` + # (native mode rebuilds it; tool mode must not send one, or + # the tool-call request 400s too). Independent settings like + # `effort` are kept. + # - a raw `tools` list, which would replace the generated + # schemas (the registered specs plus, in tool mode, the + # extraction tool that `tool_choice` forces), invalidating + # the request. + # - a `tool_choice`, which either forces an ordinary tool where + # extraction needs JSON (native mode) or is overridden anyway + # (tool mode) -- and can dangle once `tools` is dropped. + new_kwargs = dict(kwargs) + output_config = new_kwargs.get("output_config") + if isinstance(output_config, dict) and "format" in output_config: + new_output_config = cast(dict[str, Any], dict(output_config)) + new_output_config.pop("format", None) + if new_output_config: + new_kwargs["output_config"] = new_output_config + else: + new_kwargs.pop("output_config") + new_kwargs.pop("tools", None) + new_kwargs.pop("tool_choice", None) + kwargs = cast("AnthropicSubmitInputArgs", new_kwargs) return bedrock_anthropic_version( super()._chat_perform_args(stream, turns, tools, data_model, kwargs) ) @@ -398,6 +436,277 @@ def _chat_perform_args( def _as_content_block(content: "Content") -> "ContentBlockParam": return AnthropicProvider._as_content_block(materialize_url_content(content)) + # -- Native structured-output probing ------------------------------------ + # + # Mantle's `output_config` support is per-model in a way that can't be + # derived from the model ID, and differs from both the Anthropic API and + # Converse (verified live 2026-10-16: `claude-opus-5` accepts it while + # `claude-haiku-4-5` and `claude-opus-4-8` 400 with + # "output_config.format: Extra inputs are not permitted"). So "auto" mode + # is optimistic, exactly like the Converse provider: the first native + # attempt doubles as the probe, the specific rejection is remembered, and + # the request is retried with the forced tool call. + + @overload + def chat_perform( + self, + *, + stream: Literal[False], + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]] = None, + kwargs: Optional["AnthropicSubmitInputArgs"] = None, + ): ... + + @overload + def chat_perform( + self, + *, + stream: Literal[True], + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]] = None, + kwargs: Optional["AnthropicSubmitInputArgs"] = None, + ): ... + + def chat_perform( + self, + *, + stream: bool, + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]] = None, + kwargs: Optional["AnthropicSubmitInputArgs"] = None, + ): + from anthropic import BadRequestError + + args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) + if stream: + # No retry here: `can_stream()` keeps unverified native attempts + # out of the streaming paths, so a structured stream only carries + # `output_config` once the model has accepted one (or in explicit + # "native" mode, whose errors the user asked for). + self._check_streamable_strategy(args, data_model) + return self._client.messages.create(**args) # type: ignore + try: + response = self._client.messages.create(**args) # type: ignore + except BadRequestError as error: + retry = self._native_retry_args( + error, args, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + return self._client.messages.create(**retry) # type: ignore + # A successful request that carried `output_config.format` proves the + # model accepts it, so "auto" mode may stream natively from now on + # (see `can_stream`). The verdict belongs to the model that actually + # served the request, which `kwargs` may have overridden. + if self._carries_native_format(args) and self._structured_output_mode == "auto": + self._native_verified_models.add(cast(str, args.get("model")) or self.model) + return response + + @overload + async def chat_perform_async( + self, + *, + stream: Literal[False], + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]] = None, + kwargs: Optional["AnthropicSubmitInputArgs"] = None, + ): ... + + @overload + async def chat_perform_async( + self, + *, + stream: Literal[True], + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]] = None, + kwargs: Optional["AnthropicSubmitInputArgs"] = None, + ): ... + + async def chat_perform_async( + self, + *, + stream: bool, + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]] = None, + kwargs: Optional["AnthropicSubmitInputArgs"] = None, + ): + from anthropic import BadRequestError + + args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) + if stream: + self._check_streamable_strategy(args, data_model) + return await self._async_client.messages.create(**args) # type: ignore + try: + response = await self._async_client.messages.create(**args) # type: ignore + except BadRequestError as error: + retry = self._native_retry_args( + error, args, stream, turns, tools, data_model, kwargs + ) + if retry is None: + raise + return await self._async_client.messages.create(**retry) # type: ignore + if self._carries_native_format(args) and self._structured_output_mode == "auto": + self._native_verified_models.add(cast(str, args.get("model")) or self.model) + return response + + def _check_streamable_strategy( + self, + args: "AnthropicSubmitInputArgs", + data_model: Optional[type[BaseModel]], + ) -> None: + # `Chat` consults `can_stream()` -- keyed on the configured model, + # since that hook can't see request kwargs -- before allowing a + # stream. A per-request `model` override can still (a) select the + # tool-based strategy, whose streamed tool-call input would + # silently violate the extracted-JSON contract, or (b) bypass the + # native probe, whose rejection would surface mid-stream where the + # fallback retry can't reach it. Fail loudly instead of sending + # the request. + if data_model is None: + return + model = cast(str, args.get("model")) or self.model + if not self._carries_native_format(args): + raise ValueError( + "Can't stream structured data extraction: the request model " + f"'{model}' uses tool-based extraction, which can't stream " + "(this stream was allowed based on the configured model " + f"'{self.model}'). Use a non-streaming method " + "(`.chat()`/`.chat_structured()`), or drop the per-request " + "`model` override." + ) + if ( + self._structured_output_mode == "auto" + and model not in self._native_verified_models + ): + # The probe happens on non-streaming requests, so a stream can + # only go native for a model that has already accepted + # `output_config` -- otherwise the rejection would surface + # mid-stream, where the fallback retry can't reach it. + raise ValueError( + "Can't stream structured data extraction: the request model " + f"'{model}' hasn't completed the native-output probe, so it " + "can't stream yet (this stream was allowed based on the " + f"configured model '{self.model}'). Make one non-streaming " + "request with this model first (e.g. `.chat_structured()`), " + "or drop the per-request `model` override." + ) + + def _native_retry_args( + self, + error: "BadRequestError", + args: "AnthropicSubmitInputArgs", + stream: bool, + turns: list["Turn"], + tools: dict[str, "Tool | ToolBuiltIn"], + data_model: Optional[type[BaseModel]], + kwargs: Optional["AnthropicSubmitInputArgs"], + ) -> Optional["AnthropicSubmitInputArgs"]: + """Rebuild request args for tool-based extraction after a native 400. + + Since mantle's `output_config` support can't be derived from the + model ID, "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 `output_config` 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 `output_config` until the model has accepted one.) + + Retry eligibility comes from the failed request's own + `output_config.format`, 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._carries_native_format(args) + or not self._is_native_rejection(error) + ): + return None + # The verdict belongs to the model that actually served (and + # rejected) the request, which `kwargs` may have overridden. + model = cast(str, args.get("model")) or self.model + if model not in self._native_unsupported_models: + self._native_unsupported_models.add(model) + warnings.warn( + f"Bedrock model '{model}' rejected native structured " + "outputs (`output_config`); 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 + # `output_config`. + return self._chat_perform_args(stream, turns, tools, data_model, kwargs) + + @staticmethod + def _carries_native_format(args: "AnthropicSubmitInputArgs") -> bool: + # `output_config` also carries adaptive-thinking effort (from the + # `reasoning` param), which proves nothing about `format` support. + output_config = args.get("output_config") + return isinstance(output_config, dict) and "format" in output_config + + @staticmethod + def _is_native_rejection(error: "BadRequestError") -> bool: + # The specific 400 returned by mantle models that lack `output_config` + # support ("output_config.format: Extra inputs are not permitted"). + # Other errors mentioning `output_config` must propagate rather than + # disable native mode: schema-validation 400s (which imply the model + # *does* support native output), and rejections of nested (`...format.schema`) + # or unrelated (`...effort`) fields. Match the complete diagnostic as + # observed live: if mantle ever phrases the top-level rejection + # differently, that fails loudly instead of silently disabling native. + return "output_config.format: Extra inputs are not permitted" in str(error) + + def _structured_output_model( + self, kwargs: Optional["AnthropicSubmitInputArgs"] + ) -> Optional[str]: + # A per-request `model` override changes which model's native + # support verdict applies (the caches are keyed on the serving + # model). When this makes the strategy unstreamable while + # `can_stream()` allowed a stream, `chat_perform`'s stream branch + # raises rather than silently streaming tool-call input. + return cast("Optional[str]", (kwargs or {}).get("model")) + + def _use_native_structured_output(self, model: Optional[str] = None) -> bool: + # The unsupported verdict is keyed on the model that actually + # rejected `output_config` (see `chat_perform`), so strategy + # selection must consult the effective request model too: after a + # `kwargs={"model": ...}` override is marked, its retry and later + # requests must not attempt native output again. (The read side + # that can't see request kwargs -- `can_stream()` -- keeps the + # `self.model` default, erring toward probing.) + if (model or self.model) in self._native_unsupported_models: + return False + return super()._use_native_structured_output(model) + + def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool: + # Native structured outputs (`output_config`) 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 + if self._structured_output_mode == "native": + return True + if not self._use_native_structured_output(): + return False + # Mantle's `output_config` 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 bedrock_client_kwargs( *, diff --git a/tests/test_provider_anthropic.py b/tests/test_provider_anthropic.py index 2a44d3e0..3ccd4868 100644 --- a/tests/test_provider_anthropic.py +++ b/tests/test_provider_anthropic.py @@ -1380,6 +1380,28 @@ def test_anthropic_reasoning_effort_string(): } +def test_anthropic_strategy_ignores_per_request_model_override(): + # The structured-output strategy is a property of the configured model, + # not a per-request `model` override: `can_stream()` (which Chat consults + # before allowing a stream) can't see request kwargs, so honoring an + # override here could silently stream tool-call input where JSON was + # promised. (Bedrock's mantle endpoint overrides this via + # `_structured_output_model`, paired with a loud stream-time guard.) + class Person(BaseModel): + name: str + + provider = AnthropicProvider(model="claude-sonnet-4-6", api_key="x") + args = provider._chat_perform_args( + stream=False, + turns=[], + tools={}, + data_model=Person, + kwargs={"model": "claude-sonnet-4"}, + ) + assert args["model"] == "claude-sonnet-4" + assert args["output_config"]["format"]["type"] == "json_schema" + + def test_anthropic_adaptive_effort_merges_with_structured_output(): """When extracting data, adaptive effort merges into the native output_config.""" diff --git a/tests/test_provider_bedrock_converse.py b/tests/test_provider_bedrock_converse.py index bdab5314..a35b28ef 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -2226,14 +2226,15 @@ class Person(BaseModel): ) 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", - ) + def test_structured_output_mode_rejected_for_responses_api(self): + # "messages" also accepts `structured_output_mode` (covered in + # test_provider_bedrock_mantle.py); "responses" does not. + with pytest.raises(ValueError, match="structured_output_mode"): + ChatBedrock( + api="responses", + aws_region="us-east-1", + structured_output_mode="native", + ) def test_data_model_request_advertises_registered_tools(self): # At the provider level, tools are advertised so multi-step diff --git a/tests/test_provider_bedrock_mantle.py b/tests/test_provider_bedrock_mantle.py index 2d15f350..b7167282 100644 --- a/tests/test_provider_bedrock_mantle.py +++ b/tests/test_provider_bedrock_mantle.py @@ -2,6 +2,8 @@ import json from datetime import date from importlib import resources +from typing import Literal +from unittest.mock import patch import httpx import httpx2 @@ -324,6 +326,606 @@ def test_list_models_returns_the_combined_listing(self, monkeypatch): ] +class TestMessagesStructuredOutputMode: + """`structured_output_mode` on the mantle Messages API: native + `output_config` vs forced tool call, with "auto" probing per model. + + Mantle's `output_config` support can't be derived from the model ID (and + differs from both the Anthropic API and Converse), so "auto" mirrors the + Converse provider's probe semantics: an optimistic first native attempt, + then a remembered fallback to the forced tool call on the specific 400. + """ + + @staticmethod + def provider( + model: str = "anthropic.claude-haiku-4-5", + mode: Literal["auto", "native", "tool"] = "auto", + ): + from chatlas._provider_bedrock import BedrockMessagesProvider + + return BedrockMessagesProvider( + model=model, + aws_profile=None, + aws_region="us-east-1", + base_url=None, + structured_output_mode=mode, + ) + + @staticmethod + def _person(): + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + return Person + + @staticmethod + def _fake_message(): + from anthropic.types import Message, TextBlock, Usage + + return Message.construct( + id="msg_1", + type="message", + role="assistant", + model="anthropic.claude-haiku-4-5", + stop_reason="end_turn", + stop_sequence=None, + content=[TextBlock(type="text", text='{"name": "John", "age": 15}')], + usage=Usage.construct(input_tokens=1, output_tokens=1), + ) + + @staticmethod + def _bad_request(message: str): + from anthropic import BadRequestError + + request = httpx2.Request( + "POST", "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages" + ) + return BadRequestError( + message, + response=httpx2.Response(400, request=request), + body=None, + ) + + @classmethod + def _native_rejection(cls): + # The specific 400 mantle returns for models without `output_config` + # support (verified live: haiku-4-5, opus-4-8). + return cls._bad_request( + "Error code: 400 - {'type': 'error', 'error': " + "{'type': 'invalid_request_error', 'message': " + "'output_config.format: Extra inputs are not permitted'}}" + ) + + def test_chat_bedrock_threads_the_mode_to_the_messages_provider(self): + chat = ChatBedrock( + model="anthropic.claude-haiku-4-5", + api="messages", + structured_output_mode="tool", + aws_region="us-east-1", + ) + assert chat.provider._structured_output_mode == "tool" + + def test_non_auto_mode_is_still_rejected_for_the_responses_api(self): + with pytest.raises(ValueError, match="structured_output_mode"): + ChatBedrock( + model="openai.gpt-5.6-sol", + structured_output_mode="native", + aws_region="us-east-1", + ) + + def test_can_stream_matrix(self): + Person = self._person() + + # No data_model always streams. + assert self.provider().can_stream(None) is True + # "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="anthropic.claude-sonnet-4").can_stream(Person) is False + ) + # ... nor do models that already rejected `output_config`. + 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="anthropic.claude-sonnet-4", 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 _perform_with_fake_create(self, provider, data_model, kwargs=None): + """Call `chat_perform` with a mocked client; return the captured calls.""" + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + return self._fake_message() + + with patch.object(provider._client.messages, "create", side_effect=fake_create): + provider.chat_perform( + stream=False, + turns=[], + tools={}, + data_model=data_model, + kwargs=kwargs, + ) + return calls + + def test_auto_mode_probes_with_output_config(self): + (request,) = self._perform_with_fake_create(self.provider(), self._person()) + output_config = request["output_config"] + assert output_config["format"]["type"] == "json_schema" + assert "tool_choice" not in request + + def test_tool_mode_forces_the_structured_tool_call(self): + (request,) = self._perform_with_fake_create( + self.provider(mode="tool"), self._person() + ) + assert "output_config" not in request + assert request["tool_choice"] == { + "type": "tool", + "name": "_structured_tool_call", + } + + def test_auto_mode_on_unmatched_model_uses_the_tool_call(self): + (request,) = self._perform_with_fake_create( + self.provider(model="anthropic.claude-sonnet-4"), self._person() + ) + assert "output_config" not in request + assert request["tool_choice"]["name"] == "_structured_tool_call" + + def test_successful_native_request_marks_the_model_verified(self): + provider = self.provider() + self._perform_with_fake_create(provider, self._person()) + assert provider.model in provider._native_verified_models + + def test_requests_without_native_format_dont_mark_verified(self): + provider = self.provider() + # No data_model: no `output_config.format`, nothing proven. + self._perform_with_fake_create(provider, None) + assert provider.model not in provider._native_verified_models + # An effort-only `output_config` (from `reasoning`) proves nothing + # about `format` support either. + self._perform_with_fake_create( + provider, + None, + kwargs={ + "thinking": {"type": "adaptive"}, + "output_config": {"effort": "high"}, + }, + ) + assert provider.model not in provider._native_verified_models + + def test_native_rejection_retries_with_the_forced_tool_call(self): + provider = self.provider() + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + if len(calls) == 1: + raise self._native_rejection() + return self._fake_message() + + with ( + patch.object(provider._client.messages, "create", side_effect=fake_create), + pytest.warns(UserWarning, match="rejected native structured outputs"), + ): + provider.chat_perform( + stream=False, turns=[], tools={}, data_model=self._person() + ) + + assert len(calls) == 2 + # The retry carries the forced tool call, not `output_config.format`. + retry = calls[1] + assert "format" not in retry.get("output_config", {}) + assert retry["tool_choice"] == { + "type": "tool", + "name": "_structured_tool_call", + } + # The model is remembered as unsupported. + assert provider.model in provider._native_unsupported_models + assert provider.model not in provider._native_verified_models + + def test_explicit_native_mode_propagates_the_rejection(self): + from anthropic import BadRequestError + + provider = self.provider(mode="native") + with ( + patch.object( + provider._client.messages, + "create", + side_effect=self._native_rejection(), + ), + pytest.raises(BadRequestError), + ): + provider.chat_perform( + stream=False, turns=[], tools={}, data_model=self._person() + ) + assert provider.model not in provider._native_unsupported_models + + def test_other_output_config_errors_propagate(self): + # A schema-validation 400 implies the model *does* support native + # output: it must surface, not disable native mode. + from anthropic import BadRequestError + + provider = self.provider() + error = self._bad_request( + "Error code: 400 - {'type': 'error', 'error': " + "{'type': 'invalid_request_error', 'message': " + "'output_config.format.schema: invalid JSON schema'}}" + ) + with ( + patch.object(provider._client.messages, "create", side_effect=error), + pytest.raises(BadRequestError), + ): + provider.chat_perform( + stream=False, turns=[], tools={}, data_model=self._person() + ) + assert provider.model not in provider._native_unsupported_models + + def test_retry_strips_a_caller_supplied_output_config_format(self): + # A caller's own `output_config.format` contradicts extraction (the + # schema comes from `data_model`); left in place it would 400 the + # tool-call retry -- and every subsequent tool-mode request. + provider = self.provider() + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + if len(calls) == 1: + raise self._native_rejection() + return self._fake_message() + + kwargs = { + "output_config": { + "effort": "high", + "format": {"type": "json_schema", "schema": {}}, + } + } + with ( + patch.object(provider._client.messages, "create", side_effect=fake_create), + pytest.warns(UserWarning, match="rejected native structured outputs"), + ): + provider.chat_perform( + stream=False, + turns=[], + tools={}, + data_model=self._person(), + kwargs=kwargs, + ) + + assert len(calls) == 2 + # The retry carries the forced tool call and keeps the effort, but + # the contradictory format is gone ... + retry = calls[1] + assert retry["tool_choice"]["name"] == "_structured_tool_call" + assert retry.get("output_config") == {"effort": "high"} + # ... and so is any later tool-mode request with the same kwargs. + (later,) = self._perform_with_fake_create(provider, self._person(), kwargs) + assert later["tool_choice"]["name"] == "_structured_tool_call" + assert later.get("output_config") == {"effort": "high"} + # The caller's kwargs mapping is unchanged. + assert "format" in kwargs["output_config"] + + def test_caller_tools_kwarg_does_not_break_tool_mode_extraction(self): + # A raw caller `tools` list must not replace the generated schemas + # during extraction: tool mode forces `_structured_tool_call`, so + # dropping its declaration would invalidate the request (and the + # post-rejection retry). + provider = self.provider() + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + if len(calls) == 1: + raise self._native_rejection() + return self._fake_message() + + kwargs = {"tools": []} + with ( + patch.object(provider._client.messages, "create", side_effect=fake_create), + pytest.warns(UserWarning, match="rejected native structured outputs"), + ): + provider.chat_perform( + stream=False, + turns=[], + tools={}, + data_model=self._person(), + kwargs=kwargs, + ) + + assert len(calls) == 2 + retry = calls[1] + assert retry["tool_choice"]["name"] == "_structured_tool_call" + assert [t["name"] for t in retry["tools"]] == ["_structured_tool_call"] + # Later tool-mode requests with the same kwargs declare it too ... + (later,) = self._perform_with_fake_create(provider, self._person(), kwargs) + assert [t["name"] for t in later["tools"]] == ["_structured_tool_call"] + # ... and the caller's mapping is unchanged. + assert kwargs == {"tools": []} + + def test_caller_tool_choice_is_dropped_during_extraction(self): + # A caller `tool_choice` forcing an ordinary tool contradicts + # extraction (native mode needs JSON; tool mode forces its own + # choice) -- and once a caller `tools` list is dropped, it can + # dangle. It must not reach the request. + provider = self.provider() + (request,) = self._perform_with_fake_create( + provider, + self._person(), + kwargs={ + "tools": [], + "tool_choice": {"type": "tool", "name": "get_weather"}, + }, + ) + assert "tool_choice" not in request + assert "format" in request["output_config"] + + def test_effort_rejection_is_not_a_native_format_rejection(self): + # A model rejecting `output_config.effort` says nothing about + # `format` support: the error must propagate, unmarked, unretried. + provider = self.provider() + error = self._bad_request( + "Error code: 400 - {'type': 'error', 'error': " + "{'type': 'invalid_request_error', 'message': " + "'output_config.effort: Extra inputs are not permitted'}}" + ) + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + raise error + + from anthropic import BadRequestError + + with ( + patch.object(provider._client.messages, "create", side_effect=fake_create), + pytest.raises(BadRequestError), + ): + provider.chat_perform( + stream=False, turns=[], tools={}, data_model=self._person() + ) + assert len(calls) == 1 + assert provider.model not in provider._native_unsupported_models + + def test_verdicts_are_recorded_for_the_effective_request_model(self): + # `kwargs={"model": ...}` overrides the request model, so a verdict + # must not be recorded against `self.model`: a successful override + # that verified `self.model` would let a later stream bypass the + # probe and hit a native rejection with no fallback. + provider = self.provider(model="anthropic.claude-haiku-4-5") + override = {"model": "anthropic.claude-opus-5"} + + self._perform_with_fake_create(provider, self._person(), kwargs=override) + assert "anthropic.claude-opus-5" in provider._native_verified_models + assert provider.model not in provider._native_verified_models + + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + if len(calls) == 1: + raise self._native_rejection() + return self._fake_message() + + with ( + patch.object(provider._client.messages, "create", side_effect=fake_create), + pytest.warns(UserWarning, match="rejected native structured outputs"), + ): + provider.chat_perform( + stream=False, + turns=[], + tools={}, + data_model=self._person(), + kwargs={"model": "anthropic.claude-opus-4-8"}, + ) + assert "anthropic.claude-opus-4-8" in provider._native_unsupported_models + assert provider.model not in provider._native_unsupported_models + # The retry serves the overridden model, which is now known to reject + # native output: it must carry the forced tool call, not a second + # native attempt. + retry = calls[1] + assert retry["model"] == "anthropic.claude-opus-4-8" + assert "format" not in retry.get("output_config", {}) + assert retry["tool_choice"]["name"] == "_structured_tool_call" + # Subsequent requests with the same override go straight to the tool + # call (no second probe, no second warning). + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error") + (later,) = self._perform_with_fake_create( + provider, self._person(), kwargs={"model": "anthropic.claude-opus-4-8"} + ) + assert "format" not in later.get("output_config", {}) + assert later["tool_choice"]["name"] == "_structured_tool_call" + + def test_stream_with_tool_mode_model_override_errors_loudly(self): + # `can_stream()` (a kwargs-less hook) allowed streaming based on the + # verified constructor model; a per-request override to a model whose + # strategy is the forced tool call can't stream. That must be a + # clear error, not a silently broken stream of tool-call input. + provider = self.provider(model="anthropic.claude-opus-5") + provider._native_verified_models.add(provider.model) + provider._native_unsupported_models.add("anthropic.claude-haiku-4-5") + + with pytest.raises(ValueError, match="can't stream"): + provider.chat_perform( + stream=True, + turns=[], + tools={}, + data_model=self._person(), + kwargs={"model": "anthropic.claude-haiku-4-5"}, + ) + + @pytest.mark.asyncio + async def test_stream_with_tool_mode_model_override_errors_loudly_async(self): + provider = self.provider(model="anthropic.claude-opus-5") + provider._native_verified_models.add(provider.model) + provider._native_unsupported_models.add("anthropic.claude-haiku-4-5") + + with pytest.raises(ValueError, match="can't stream"): + await provider.chat_perform_async( + stream=True, + turns=[], + tools={}, + data_model=self._person(), + kwargs={"model": "anthropic.claude-haiku-4-5"}, + ) + + def test_stream_with_unverified_model_override_errors_loudly(self): + # In "auto" mode a model must complete the (non-streaming) probe + # before streaming natively; a per-request override must not bypass + # that, or the stream would fail mid-flight with no fallback. + provider = self.provider(model="anthropic.claude-opus-5") + provider._native_verified_models.add(provider.model) + + with pytest.raises(ValueError, match="can't stream"): + provider.chat_perform( + stream=True, + turns=[], + tools={}, + data_model=self._person(), + kwargs={"model": "anthropic.claude-haiku-5-5"}, + ) + + @pytest.mark.asyncio + async def test_stream_with_unverified_model_override_errors_loudly_async(self): + provider = self.provider(model="anthropic.claude-opus-5") + provider._native_verified_models.add(provider.model) + + with pytest.raises(ValueError, match="can't stream"): + await provider.chat_perform_async( + stream=True, + turns=[], + tools={}, + data_model=self._person(), + kwargs={"model": "anthropic.claude-haiku-5-5"}, + ) + + def test_stream_with_verified_model_override_streams(self): + # Overrides to models that have completed the probe stream fine. + provider = self.provider(model="anthropic.claude-opus-5") + provider._native_verified_models.add(provider.model) + provider._native_verified_models.add("anthropic.claude-sonnet-4-6") + requests: list[dict] = [] + + def fake_create(**kw): + requests.append(kw) + return object() + + with patch.object(provider._client.messages, "create", side_effect=fake_create): + provider.chat_perform( + stream=True, + turns=[], + tools={}, + data_model=self._person(), + kwargs={"model": "anthropic.claude-sonnet-4-6"}, + ) + assert "format" in requests[0]["output_config"] + + def test_nested_format_field_rejection_is_not_a_native_rejection(self): + # `output_config.format.schema` (or any nested field) rejected as + # extra says the model speaks `output_config` but not this shape -- + # it must propagate, not disable native mode. + provider = self.provider() + error = self._bad_request( + "Error code: 400 - {'type': 'error', 'error': " + "{'type': 'invalid_request_error', 'message': " + "'output_config.format.schema: Extra inputs are not permitted'}}" + ) + calls: list[dict] = [] + + def fake_create(**kw): + calls.append(kw) + raise error + + from anthropic import BadRequestError + + with ( + patch.object(provider._client.messages, "create", side_effect=fake_create), + pytest.raises(BadRequestError), + ): + provider.chat_perform( + stream=False, turns=[], tools={}, data_model=self._person() + ) + assert len(calls) == 1 + 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 + # native request is in flight; that request's own 400 must still + # fall back (eligibility comes from its args, not the cache). + from chatlas import UserTurn + + provider = self.provider() + Person = self._person() + turns = [UserTurn("John, age 15")] + args = provider._chat_perform_args( + stream=False, turns=turns, tools={}, data_model=Person + ) + assert "format" in args["output_config"] + + 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 "format" not in retry.get("output_config", {}) + assert retry["tool_choice"] == { + "type": "tool", + "name": "_structured_tool_call", + } + + @pytest.mark.asyncio + async def test_native_rejection_retries_async(self): + provider = self.provider() + calls: list[dict] = [] + + async def fake_create(**kw): + calls.append(kw) + if len(calls) == 1: + raise self._native_rejection() + return self._fake_message() + + with pytest.warns(UserWarning, match="rejected native structured outputs"): + with patch.object( + provider._async_client.messages, "create", side_effect=fake_create + ): + await provider.chat_perform_async( + stream=False, turns=[], tools={}, data_model=self._person() + ) + + assert len(calls) == 2 + assert "format" not in calls[1].get("output_config", {}) + assert calls[1]["tool_choice"]["name"] == "_structured_tool_call" + + def test_chat_structured_end_to_end(self): + provider = self.provider() + chat = Chat(provider=provider) + with patch.object( + provider._client.messages, + "create", + side_effect=lambda **kw: self._fake_message(), + ): + person = chat.chat_structured("John, age 15", data_model=self._person()) + assert person.name == "John" + assert person.age == 15 + + class TestUrlContentFallsBackToBytes: """Mantle can't fetch URLs, so PDF/document content built with a URL must be sent as bytes instead (https://github.com/posit-dev/chatlas/issues/410). @@ -671,6 +1273,84 @@ def test_tool_variations(self): def test_data_extraction(self): assert_data_extraction(chat_messages) + def test_data_extraction_native(self): + # claude-opus-5 accepts `output_config` on mantle (verified + # 2026-10-16); haiku-4-5 and opus-4-8 reject it. + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + chat = ChatBedrock( + model="anthropic.claude-opus-5", + api="messages", + structured_output_mode="native", + ) + person = chat.chat_structured("John is 15 years old.", data_model=Person) + assert person.name == "John" + assert person.age == 15 + + def test_stream_data_extraction_native(self): + # Native mode streams the JSON incrementally (no non-streaming + # fallback). + import warnings + + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + chat = ChatBedrock( + model="anthropic.claude-opus-5", + api="messages", + structured_output_mode="native", + ) + with warnings.catch_warnings(): + warnings.simplefilter("error") + chunks = list(chat.stream("John is 15 years old.", data_model=Person)) + assert len(chunks) > 1 + person = Person.model_validate_json("".join(chunks)) + assert person.name == "John" + assert person.age == 15 + + def test_data_extraction_auto_falls_back_to_the_tool_call(self): + # haiku-4-5 rejects `output_config` on mantle, so "auto" warns, + # remembers, and falls back to the forced tool call. + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + chat = chat_messages() + with pytest.warns(UserWarning, match="rejected native structured outputs"): + person = chat.chat_structured("John is 15 years old.", data_model=Person) + assert person.name == "John" + assert person.age == 15 + provider = chat.provider + assert provider.model in provider._native_unsupported_models + # The next request goes straight to the tool call: no second warning. + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("error") + person2 = chat.chat_structured("Jane is 16 years old.", data_model=Person) + assert person2.name == "Jane" + + def test_data_extraction_tool_mode(self): + from pydantic import BaseModel + + class Person(BaseModel): + name: str + age: int + + chat = chat_messages(structured_output_mode="tool") + person = chat.chat_structured("John is 15 years old.", data_model=Person) + assert person.name == "John" + assert person.age == 15 + @requires_mantle def test_openai_v1_path_rejects_gpt_oss_with_a_clear_error():