Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* `ChatCloudflare()` no longer errors when a response (or a streamed chunk of one) consists only of a number, which Cloudflare sends as a JSON number instead of a string (e.g. `"content": 2`). The content is now coerced to a string instead of breaking text display, chunk merging, and final-turn assembly.
* `.stream()` and `.stream_async()` with `data_model` no longer crash when the provider can't stream structured output — notably `ChatAnthropic()` with `structured_output_mode="tool"`, and older Claude models under the default `"auto"` mode. chatlas now warns and transparently falls back to a single non-streaming request, yielding the complete JSON as one chunk, so `data_model.model_validate_json("".join(chunks))` keeps working unchanged. (#317)
* `echo="all"` no longer displays structured-output JSON twice (once as the response text and again as a fenced code block). (#317)
* `ChatBedrock()` with the default Converse API previously yielded zero chunks from `.stream()`/`.stream_async()` with `data_model` (its structured output is extracted through a tool call, which can't stream). It now gets the same non-streaming fallback as `ChatAnthropic(structured_output_mode="tool")`: a warning, then the complete JSON as a single chunk. (#451)
* Structured-output requests to most OpenAI-compatible providers no longer include OpenAI's `strict` flag, which causes some backends to reject the request. Requests to OpenAI, `ChatGroq()`, `ChatAzureOpenAICompletions()`, and `ChatPosit()` models with an `openai/` prefix are unchanged. If structured output becomes less reliable for your provider (for example, OpenAI models behind a proxy), pass the new `strict=True` argument to `ChatOpenAICompletions()`, `ChatOpenRouter()`, `ChatPortkey()`, or `ChatHuggingFace()`.
* `Chat.get_tokens()` no longer errors when the conversation ends with a user turn that has no completed assistant response yet (e.g. after a failed request or `add_turn()`), when assistant turns don't strictly alternate with user turns, or when the history holds a single user turn (which now returns an empty list). Token accounting is now driven off complete assistant turns instead of assuming strict user/assistant alternation.
* `ChatBedrockAnthropic(reasoning=)` now accepts an effort level (`"low"`, `"medium"`, `"high"`, `"xhigh"` or `"max"`) to enable adaptive thinking, as `ChatAnthropic()` already did. It previously only took a token budget, which its default model (Claude Sonnet 5) rejects, so there was no way to turn on thinking with that model.
Expand Down
8 changes: 8 additions & 0 deletions chatlas/_provider_bedrock_converse.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,14 @@ async def chat_perform_async(
return self._converse_stream_async(args)
return await self._converse_async(args)

def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool:
# Structured data extraction is tool-based (a forced `toolChoice` on a
# tool whose input is `{"data": ...}`-wrapped), and Converse streams
# tool input in its own event type rather than as text, so a streamed
# response can't honor the extracted-JSON contract (`"".join(chunks)`
# would be empty). Fall back to a single non-streaming request.
return data_model is None

def stream_content(
self,
chunk: dict,
Expand Down
110 changes: 110 additions & 0 deletions tests/test_provider_bedrock_converse.py
Original file line number Diff line number Diff line change
Expand Up @@ -1817,6 +1817,116 @@ def assert_cache_point(self, args, *, expected: bool):
assert (cache_point in system) is expected


def _fake_data_model_converse_response():
return cast(
"ConverseResponseTypeDef",
{
"output": {
"message": {
"role": "assistant",
"content": [
{
"toolUse": {
"toolUseId": "toolu_x",
"name": "_structured_tool_call",
"input": {"data": {"name": "John", "age": 15}},
}
}
],
}
},
"stopReason": "tool_use",
"usage": {
"inputTokens": 1,
"outputTokens": 1,
"totalTokens": 2,
},
},
)


class TestStreamWithDataModel:
"""
Converse structured output is tool-based, so it can't stream incrementally;
`Chat` should downgrade to a non-streaming request that yields the full
JSON as a single chunk (see `Provider.can_stream`).
"""

def provider(self) -> BedrockConverseProvider:
return BedrockConverseProvider(
model="us.anthropic.claude-sonnet-4-6",
aws_profile=None,
aws_region="us-east-1",
base_url=None,
)

def test_stream_with_data_model_downgrades_gracefully(self):
from unittest.mock import patch

from chatlas import Chat
from chatlas._content import ContentJson
from pydantic import BaseModel

class Person(BaseModel):
name: str
age: int

provider = self.provider()
chat = Chat(provider=provider)

with patch.object(
provider, "_converse", return_value=_fake_data_model_converse_response()
):
with pytest.warns(UserWarning, match="streaming"):
chunks = list(chat.stream("John, age 15", data_model=Person))

person = Person.model_validate_json("".join(chunks))
assert person == Person(name="John", age=15)

turn = chat.get_last_turn()
assert turn is not None
assert len(turn.contents) == 1
assert isinstance(turn.contents[0], ContentJson)
assert turn.contents[0].value == {"name": "John", "age": 15}

@pytest.mark.asyncio
async def test_stream_async_with_data_model_downgrades_gracefully(self):
from unittest.mock import AsyncMock, patch

from chatlas import Chat
from chatlas._content import ContentJson
from pydantic import BaseModel

class Person(BaseModel):
name: str
age: int

provider = self.provider()
chat = Chat(provider=provider)

with patch.object(
provider,
"_converse_async",
new=AsyncMock(return_value=_fake_data_model_converse_response()),
):
with pytest.warns(UserWarning, match="streaming"):
chunks = [
chunk
async for chunk in await chat.stream_async(
"John, age 15", data_model=Person
)
]

person = Person.model_validate_json("".join(chunks))
assert person == Person(name="John", age=15)

turn = chat.get_last_turn()
assert turn is not None
assert len(turn.contents) == 1
assert isinstance(turn.contents[0], ContentJson)
assert turn.contents[0].value == {"name": "John", "age": 15}


def test_blocked_network_skips_live_converse_before_credential_probe(monkeypatch):
class BlockedConfig:
def getoption(self, option: str) -> bool:
Expand Down
Loading