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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* MCP tools registered with a `namespace` (in `.register_mcp_tools_http_stream_async()` or `.register_mcp_tools_stdio_async()`) can be called successfully. `Tool.from_mcp()` gains a `name` argument for setting the tool's name independently of the MCP tool's name. (#458)
* The MCP client used by `.register_mcp_tools_http_stream_async()` and `.register_mcp_tools_stdio_async()` negotiates MCP protocol revision `2026-07-28` with servers that support it. (#456)
* `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)
* 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
72 changes: 65 additions & 7 deletions chatlas/_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
overload,
)

import orjson
from pydantic import BaseModel

from ._callbacks import CallbackManager
Expand Down Expand Up @@ -81,6 +82,7 @@
SystemTurn,
Turn,
UserTurn,
caller_stacklevel,
check_finish_reason,
normalize_turns_for_provider,
user_turn,
Expand Down Expand Up @@ -1647,6 +1649,8 @@ def _submit_and_extract_data(
stream: bool = False,
kwargs: Optional[SubmitInputArgsT] = None,
) -> dict[str, Any]:
stream = self._resolve_stream(stream, data_model, yields_chunks=False)

display = self._markdown_display(echo=echo)

response = ChatResponse(
Expand Down Expand Up @@ -1748,6 +1752,8 @@ async def _submit_and_extract_data_async(
stream: bool = False,
kwargs: Optional[SubmitInputArgsT] = None,
) -> dict[str, Any]:
stream = self._resolve_stream(stream, data_model, yields_chunks=False)
Comment thread
cpsievert marked this conversation as resolved.
Resolved

display = self._markdown_display(echo=echo)

response = ChatResponseAsync(
Expand Down Expand Up @@ -2755,6 +2761,8 @@ def _chat_impl(
*,
controller: StreamController,
) -> Generator[str | Content, None, None]:
stream = self._resolve_stream(stream, data_model)

agent_span = start_agent_span(self.provider, self._conversation_id)
try:
user_turn_result: UserTurn | None = user_turn
Expand Down Expand Up @@ -2842,6 +2850,8 @@ async def _chat_impl_async(
*,
controller: StreamController,
) -> AsyncGenerator[str | Content, None]:
stream = self._resolve_stream(stream, data_model)

agent_span = start_agent_span(self.provider, self._conversation_id)
try:
user_turn_result: UserTurn | None = user_turn
Expand Down Expand Up @@ -3051,9 +3061,10 @@ def emit(x: str | Content):
emit_thinking_contents(turn, emit)
emit_web_contents(turn, emit)

if turn.text:
emit(turn.text)
yield turn.text
text = nonstream_yield_text(turn, data_model)
if text:
emit(text)
yield text

emit_image_contents(turn, emit)
if echo == "all":
Expand Down Expand Up @@ -3220,9 +3231,10 @@ def emit(x: str | Content):
emit_thinking_contents(turn, emit)
emit_web_contents(turn, emit)

if turn.text:
emit(turn.text)
yield turn.text
text = nonstream_yield_text(turn, data_model)
if text:
emit(text)
yield text

emit_image_contents(turn, emit)
if echo == "all":
Expand All @@ -3237,6 +3249,30 @@ def emit(x: str | Content):
finally:
end_span(chat_span)

def _resolve_stream(
self,
stream: bool,
data_model: type[BaseModel] | None,
*,
yields_chunks: bool = True,
) -> bool:
"""Downgrade a streaming request when the provider can't stream it."""
if not stream or self.provider.can_stream(data_model):
return stream
outcome = (
"yielded (as a single chunk)"
if yields_chunks
# `chat_structured()` returns a validated model; nothing is yielded
else "produced"
)
warnings.warn(
"This provider does not support streaming structured data "
"extraction; falling back to a non-streaming request. The full "
f"result is still {outcome} and recorded in the conversation.",
stacklevel=caller_stacklevel(),
)
return False

def _collect_all_kwargs(
self,
kwargs: Optional[SubmitInputArgsT],
Expand Down Expand Up @@ -3752,7 +3788,8 @@ def emit_other_contents(

Reasoning and web activity are excluded: both are displayed as they arrive
(streaming) or explicitly before the text (non-streaming), so emitting them
from the turn's contents too would show them twice.
from the turn's contents too would show them twice. The same goes for an
assistant turn's structured-extraction JSON, which stands in for its text.
"""
# Gather other content to emit in _reverse_ order
to_emit: list[Content | str] = []
Expand All @@ -3765,6 +3802,11 @@ def emit_other_contents(
for content in reversed(x.contents):
if isinstance(content, ContentText):
has_text = True
elif isinstance(content, ContentJson) and isinstance(x, AssistantTurn):
# Structured-extraction JSON is the assistant turn's text: it was
# streamed live or emitted as the text, so emitting it here too
# would show it twice.
continue
elif isinstance(content, (ContentThinking, ContentThinkingDelta)):
continue
elif isinstance(content, PROVIDER_ANNOTATION_TYPES):
Expand Down Expand Up @@ -3845,6 +3887,22 @@ async def aclose_response(response: Any) -> None:
response.close()


def nonstream_yield_text(turn: Turn, data_model: type[BaseModel] | None) -> str:
"""
Text to yield for a turn produced by a non-streaming request.

A structured-extraction turn carries its result in `ContentJson`, which
`turn.text` ignores; serialize it so that `"".join(chunks)` still parses
(see [](`~chatlas.Chat.stream`)).
"""
if data_model is None:
return turn.text
for content in turn.contents:
if isinstance(content, ContentJson):
return orjson.dumps(content.value).decode("utf-8")
return turn.text


def finalize_assistant_turn(provider: Provider, turn: Turn) -> AssistantTurn:
"""Validate turn type, warn on incomplete responses, compute tokens and cost."""
if not isinstance(turn, AssistantTurn):
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 can_stream(self, data_model: Optional[type[BaseModel]]) -> bool:
"""
Whether a streaming request is supported for the given inputs.

Returning `False` causes [](`~chatlas.Chat`) to transparently fall back
to a non-streaming request (emitting the full response as a single
chunk). Providers override this when a particular feature—most notably
structured data extraction via certain `data_model` strategies—cannot be
streamed.
"""
return True
Comment thread
Copilot marked this conversation as resolved.
Resolved

@abstractmethod
def stream_content(
self,
Expand Down
26 changes: 16 additions & 10 deletions chatlas/_provider_anthropic.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,21 @@ async def chat_perform_async(
kwargs = self._chat_perform_args(stream, turns, tools, data_model, kwargs)
return await self._async_client.messages.create(**kwargs) # type: ignore

def can_stream(self, data_model: Optional[type[BaseModel]]) -> bool:
# The tool-based structured output strategy can't stream (Anthropic
# streams tool input as `{"data": ...}`-wrapped JSON, which doesn't
# match the extracted-object contract). The native `output_config`
# strategy streams JSON as ordinary text deltas, so it's fine.
if data_model is None:
return True
return self._use_native_structured_output()

def _use_native_structured_output(self) -> bool:
mode = self._structured_output_mode
return mode == "native" or (
mode == "auto" and supports_structured_outputs(self.model)
)

def _chat_perform_args(
self,
stream: bool,
Expand All @@ -521,10 +536,7 @@ def _chat_perform_args(
) -> "SubmitInputArgs":
tool_schemas = [self._anthropic_tool_schema(tool) for tool in tools.values()]

mode = self._structured_output_mode
use_native = mode == "native" or (
mode == "auto" and supports_structured_outputs(self.model)
)
use_native = self._use_native_structured_output()

if data_model is not None and use_native:
from anthropic import transform_schema
Expand All @@ -545,12 +557,6 @@ def _chat_perform_args(
elif data_model is not None:
data_model_tool = self.create_data_model_tool(data_model)
tool_schemas.append(self._anthropic_tool_schema(data_model_tool))
if stream:
stream = False
warnings.warn(
"Anthropic does not support structured data extraction in streaming mode.",
stacklevel=2,
)

kwargs_full: "SubmitInputArgs" = {
"stream": stream,
Expand Down
31 changes: 30 additions & 1 deletion docs/get-started/structured-data.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -218,4 +218,33 @@ height='tall' facial_hair='beard' scars='scar on left cheek' voice='deep voice'
This example only works with Claude, not GPT or Gemini, because only Claude supports adding arbitrary additional properties.

That said, you could prompt an LLM to suggest a `BaseModel` for you from the unstructured input, and then use that to extract the data. This is a bit more work, but it can be done.
:::
:::


## Streaming structured data

`.chat_structured()` waits for the full response before returning a validated model instance.
To instead consume the response as it's generated, pass `data_model` to [`.stream()`](../reference/Chat.qmd#stream) (or `.stream_async()`).
It yields the model's JSON one fragment at a time — only the *concatenation* of all the chunks is valid JSON, so accumulate them and parse once at the end:
Comment thread
cpsievert marked this conversation as resolved.
Resolved

```python
import chatlas as ctl
from pydantic import BaseModel

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

chat = ctl.ChatOpenAI()

chunks = []
for chunk in chat.stream("John, age 15, won first prize", data_model=Person):
chunks.append(chunk)

person = Person.model_validate_json("".join(chunks))
```

Incremental delivery depends on the provider: some providers can't stream structured output (for example, Anthropic models in `structured_output_mode="tool"`, or older Claude models).
In that case, chatlas warns, falls back to a single non-streaming request, and yields the complete JSON as one chunk — the accumulate-then-parse pattern above works unchanged either way.

The streamed `chat` also records the result as a `ContentJson` in conversation history, so `chat.get_last_turn()` reflects the extracted data just as it would after `.chat_structured()`.
12 changes: 11 additions & 1 deletion tests/test_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,8 @@ class Person(BaseModel):

@pytest.mark.vcr
def test_stream_with_data_model():
from unittest.mock import patch

from chatlas._content import ContentJson

chat = ChatOpenAI(model="gpt-5.4")
Expand All @@ -231,7 +233,15 @@ class Person(BaseModel):
name: str
age: int

chunks = list(chat.stream("John, age 15, won first prize", data_model=Person))
# Spy on the provider call to prove a genuinely streaming request is made.
# (Asserting on chunk boundaries would rely on where the API happens to
# split deltas, which isn't guaranteed.)
with patch.object(
chat.provider, "chat_perform", wraps=chat.provider.chat_perform
) as perform:
chunks = list(chat.stream("John, age 15, won first prize", data_model=Person))
assert perform.call_args.kwargs["stream"] is True

result = "".join(chunks)
person = Person.model_validate_json(result)
assert person == Person(name="John", age=15)
Expand Down
34 changes: 34 additions & 0 deletions tests/test_echo_display.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
ContentCitation,
ContentImageInline,
ContentImageRemote,
ContentJson,
ContentText,
ContentThinking,
ContentThinkingDelta,
Expand Down Expand Up @@ -508,6 +509,39 @@ def test_echo_all_still_shows_the_user_prompt():
assert "what is 2+2?" in res


def test_echo_all_shows_structured_json_exactly_once():
"""
For a structured-extraction turn, the `ContentJson` stands in for the
assistant's text: it's emitted as the (yielded) text, so
`emit_other_contents` must not repeat it as a fenced code block (gh-317).
"""
from pydantic import BaseModel

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

chat = make_chat([[ContentJson(value={"name": "John", "age": 15})]])
output = capture_echo(chat)
chat.chat_structured("John, age 15", data_model=Person, echo="all")
res = output()

assert res.count('"name"') == 1
assert "John" in res


def test_emit_other_contents_keeps_user_turn_json():
"""The `ContentJson` skip is scoped to assistant turns (extraction results)."""
from chatlas._chat import emit_other_contents
from chatlas._turn import UserTurn

emitted: list = []
emit_other_contents(
UserTurn([ContentJson(value={"name": "John", "age": 15})]), emitted.append
)
assert any(isinstance(x, ContentJson) for x in emitted)


def test_echo_does_not_truncate_a_short_tool_result():
chat = make_chat([[tool_request()], [text("It is 30°F.")]])
chat.register_tool(get_temperature)
Expand Down
Loading
Loading