Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
e78c910
Add structured_output_mode state and mode-aware can_stream() to Bedro…
cpsievert Oct 16, 2026
6429a26
Send outputConfig for native structured outputs on Bedrock Converse
cpsievert Oct 16, 2026
07fcc95
Fall back to tool-based extraction when Converse rejects outputConfig
cpsievert Oct 16, 2026
40c68f9
Expose structured_output_mode on ChatBedrock for the Converse API
cpsievert Oct 16, 2026
82e8445
Add live streaming structured-output test and CHANGELOG entry
cpsievert Oct 16, 2026
9c4a410
Reference PR #463 in CHANGELOG
cpsievert Oct 16, 2026
ccbefd3
Address Copilot review: args-based retry eligibility, stricter reject…
cpsievert Oct 16, 2026
bc9572c
Address Copilot review round 2: non-stream service for tool-args in s…
cpsievert Oct 16, 2026
87ea81d
Simplify: probe semantics replace in-stream fallback machinery
cpsievert Oct 16, 2026
1a7e82b
Don't advertise ordinary tools during structured extraction
cpsievert Oct 16, 2026
4f26beb
Scope one-shot extraction policy to chat_structured() at the Chat layer
cpsievert Oct 16, 2026
b770087
Keep tool specs for extraction when history contains tool use
cpsievert Oct 16, 2026
debadf8
Merge remote-tracking branch 'origin/main' into HEAD
cpsievert Nov 9, 2026
829e30d
ci: retrigger workflows (synchronize event dropped)
cpsievert Nov 9, 2026
95dbc76
Merge branch 'main' into bedrock-converse-native-structured-output
cpsievert Nov 9, 2026
bd5b85a
Merge remote-tracking branch 'origin/bedrock-converse-stream-fallback…
cpsievert Nov 9, 2026
a2b9df4
Merge branch 'tmp451' into HEAD
cpsievert Nov 10, 2026
2a2c5ad
Merge branch 'bedrock-converse-stream-fallback' into bedrock-converse…
cpsievert Nov 10, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 43 additions & 5 deletions chatlas/_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1661,6 +1661,7 @@ def _submit_and_extract_data(
stream=stream,
kwargs=kwargs,
controller=StreamController(),
tools=self._tools_for_extraction(),
)
)

Expand Down Expand Up @@ -1764,6 +1765,7 @@ async def _submit_and_extract_data_async(
stream=stream,
kwargs=kwargs,
controller=StreamController(),
tools=self._tools_for_extraction(),
)
)

Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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]
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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
Expand All @@ -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(
Expand All @@ -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(
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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,
)
Expand Down Expand Up @@ -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 {}
Comment on lines +3281 to +3288

def _resolve_stream(
self,
stream: bool,
Expand Down
12 changes: 12 additions & 0 deletions chatlas/_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
23 changes: 22 additions & 1 deletion chatlas/_provider_bedrock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading