diff --git a/CHANGELOG.md b/CHANGELOG.md index dbe1e6a8..944c4d9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,6 +47,8 @@ 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), 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. * `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/_chat.py b/chatlas/_chat.py index a1b52355..0deda46f 100644 --- a/chatlas/_chat.py +++ b/chatlas/_chat.py @@ -1661,6 +1661,7 @@ def _submit_and_extract_data( stream=stream, kwargs=kwargs, controller=StreamController(), + tools=self._tools_for_extraction(), ) ) @@ -1764,6 +1765,7 @@ async def _submit_and_extract_data_async( stream=stream, kwargs=kwargs, controller=StreamController(), + tools=self._tools_for_extraction(), ) ) @@ -2920,6 +2922,7 @@ def _submit_turns( *, controller: StreamController, _otel_parent: Optional[Span] = None, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> Generator[str, None, None]: ... @overload @@ -2934,6 +2937,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( @@ -2947,8 +2951,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] @@ -2994,7 +3000,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, ) @@ -3048,7 +3054,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, ) @@ -3091,6 +3097,7 @@ def _submit_turns_async( *, controller: StreamController, _otel_parent: Optional[Span] = None, + tools: Optional[dict[str, Tool | ToolBuiltIn]] = None, ) -> AsyncGenerator[str, None]: ... @overload @@ -3105,6 +3112,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( @@ -3118,7 +3126,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( @@ -3162,7 +3172,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, ) @@ -3218,7 +3228,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, ) @@ -3249,6 +3259,34 @@ 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 + 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 " + "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.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.py b/chatlas/_provider_bedrock.py index 52fdc07b..09fed7ae 100644 --- a/chatlas/_provider_bedrock.py +++ b/chatlas/_provider_bedrock.py @@ -12,7 +12,11 @@ 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, bedrock_anthropic_version +from ._provider_anthropic import ( + AnthropicProvider, + StructuredOutputMode, + bedrock_anthropic_version, +) 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 @@ -53,6 +57,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, @@ -134,6 +139,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 @@ -170,6 +186,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( @@ -217,6 +237,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/chatlas/_provider_bedrock_converse.py b/chatlas/_provider_bedrock_converse.py index c2776d34..274d3a05 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 ( @@ -45,7 +46,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, @@ -59,6 +64,7 @@ SystemTurn, Turn, UserTurn, + caller_stacklevel, check_finish_reason, ) from ._typing_extensions import NotRequired, TypedDict @@ -90,6 +96,7 @@ ConverseResponseTypeDef, InferenceConfigurationTypeDef, MessageUnionTypeDef, + OutputConfigTypeDef, SystemContentBlockTypeDef, TokenUsageTypeDef, ToolChoiceTypeDef, @@ -420,6 +427,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 +436,12 @@ 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 + # 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 @@ -523,7 +537,21 @@ def chat_perform( args = self._chat_perform_args(stream, turns, tools, data_model, kwargs) if stream: return self._converse_stream(args) - return self._converse(args) + try: + response = self._converse(args) + except ValueError as error: + retry = self._native_retry_args( + error, args, stream, turns, tools, data_model, kwargs + ) + 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( @@ -559,15 +587,112 @@ async def chat_perform_async( 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) + try: + response = await self._converse_async(args) + except ValueError as error: + retry = self._native_retry_args( + error, args, stream, turns, tools, data_model, kwargs + ) + 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, + error: ValueError, + args: ConverseRequestTypeDef, + 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. (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 + 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 "outputConfig" not in args + or not self._is_native_rejection(error) + ): + return None + 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 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: - # 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 + 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: + return False + mode = self._structured_output_mode + return mode == "native" or ( + mode == "auto" and supports_structured_outputs(self.model) + ) def stream_content( self, @@ -794,10 +919,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)) @@ -811,6 +939,18 @@ def _chat_perform_args( args["toolConfig"] = tool_config extra = dict(cast(dict, kwargs or {})) + if data_model is not None: + # 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) + 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) # Merge inferenceConfig rather than replacing it outright, so a # per-request override (e.g. from `set_model_params(temperature=...)`) # doesn't silently drop `maxTokens`. @@ -819,6 +959,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)) @@ -923,10 +1084,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" ): @@ -941,6 +1111,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 5e2f722a..bdab5314 100644 --- a/tests/test_provider_bedrock_converse.py +++ b/tests/test_provider_bedrock_converse.py @@ -1462,12 +1462,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): @@ -1853,11 +1857,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): @@ -1927,6 +1934,634 @@ 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" 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( + Person + ) + is True + ) + # ... 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 + + @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(mode="native") + 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} + + def test_auto_mode_first_request_probes_native_support(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) + + # 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) + + # 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 + + class Person(BaseModel): + name: str + age: int + + provider = self.provider() + chat = Chat(provider=provider) + + def fake_converse(args): + if "outputConfig" in args: + raise self._native_rejection() + return _fake_data_model_converse_response() + + 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_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", + ) + + 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 + + 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: tools advertised alongside `outputConfig`. + args = self.provider()._chat_perform_args( + stream=False, turns=turns, tools=tools, data_model=Person + ) + assert "outputConfig" in args + tool_names = [t["toolSpec"]["name"] for t in args["toolConfig"]["tools"]] + assert weather_tool.name in tool_names + + # 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 + ) + 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_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 + # 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 + + 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( + "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_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.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 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 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) + + @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(mode="native") + 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: def getoption(self, option: str) -> bool: @@ -2030,6 +2665,23 @@ 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", 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" + assert person.age == 15 + def test_images(self): assert_images_inline(ChatBedrock) assert_images_remote_error(ChatBedrock)