diff --git a/CHANGELOG.md b/CHANGELOG.md index 52062f31d..c70e3ffb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/chatlas/_chat.py b/chatlas/_chat.py index 321b727da..a1b523555 100644 --- a/chatlas/_chat.py +++ b/chatlas/_chat.py @@ -27,6 +27,7 @@ overload, ) +import orjson from pydantic import BaseModel from ._callbacks import CallbackManager @@ -81,6 +82,7 @@ SystemTurn, Turn, UserTurn, + caller_stacklevel, check_finish_reason, normalize_turns_for_provider, user_turn, @@ -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( @@ -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) + display = self._markdown_display(echo=echo) response = ChatResponseAsync( @@ -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 @@ -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 @@ -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": @@ -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": @@ -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], @@ -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] = [] @@ -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): @@ -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): diff --git a/chatlas/_provider.py b/chatlas/_provider.py index eac98e856..e4ca4cc8e 100644 --- a/chatlas/_provider.py +++ b/chatlas/_provider.py @@ -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 + @abstractmethod def stream_content( self, diff --git a/chatlas/_provider_anthropic.py b/chatlas/_provider_anthropic.py index 295957436..b66a4f711 100644 --- a/chatlas/_provider_anthropic.py +++ b/chatlas/_provider_anthropic.py @@ -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, @@ -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 @@ -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, diff --git a/docs/get-started/structured-data.qmd b/docs/get-started/structured-data.qmd index 0e2e6f769..251010af9 100644 --- a/docs/get-started/structured-data.qmd +++ b/docs/get-started/structured-data.qmd @@ -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. -::: \ No newline at end of file +::: + + +## 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: + +```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()`. diff --git a/tests/test_chat.py b/tests/test_chat.py index 07ecf3a27..f5033fac9 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -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") @@ -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) diff --git a/tests/test_echo_display.py b/tests/test_echo_display.py index ba25aca3c..2d951e5df 100644 --- a/tests/test_echo_display.py +++ b/tests/test_echo_display.py @@ -23,6 +23,7 @@ ContentCitation, ContentImageInline, ContentImageRemote, + ContentJson, ContentText, ContentThinking, ContentThinkingDelta, @@ -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) diff --git a/tests/test_provider_anthropic.py b/tests/test_provider_anthropic.py index ff012bb35..2a44d3e0b 100644 --- a/tests/test_provider_anthropic.py +++ b/tests/test_provider_anthropic.py @@ -955,6 +955,150 @@ class Person(BaseModel): assert turn.contents[0].value == {"name": "John", "age": 15} +def _fake_tool_mode_message(model: str): + from anthropic.types import Message, ToolUseBlock, Usage + + return Message( + id="msg_x", + content=[ + ToolUseBlock( + id="toolu_x", + name="_structured_tool_call", + input={"data": {"name": "John", "age": 15}}, + type="tool_use", + ) + ], + model=model, + role="assistant", + stop_reason="tool_use", + stop_sequence=None, + type="message", + usage=Usage(input_tokens=1, output_tokens=1), + ) + + +def test_stream_with_data_model_tool_mode_downgrades_gracefully(): + from unittest.mock import patch + + from chatlas._content import ContentJson + + model = "claude-3-5-sonnet-20241022" + chat = ChatAnthropic(model=model, structured_output_mode="tool", api_key="x") + + class Person(BaseModel): + name: str + age: int + + fake = _fake_tool_mode_message(model) + provider = cast(AnthropicProvider, chat.provider) + + with patch.object(provider._client.messages, "create", return_value=fake): + 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_tool_mode_downgrades_gracefully(): + from unittest.mock import AsyncMock, patch + + from chatlas._content import ContentJson + + model = "claude-3-5-sonnet-20241022" + chat = ChatAnthropic(model=model, structured_output_mode="tool", api_key="x") + + class Person(BaseModel): + name: str + age: int + + fake = _fake_tool_mode_message(model) + provider = cast(AnthropicProvider, chat.provider) + + with patch.object( + provider._async_client.messages, + "create", + new=AsyncMock(return_value=fake), + ): + 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_chat_structured_stream_true_tool_mode_downgrades_gracefully(): + # chat_structured() bypasses _chat_impl, but must still take the + # non-streaming fallback when stream=True (gh-317). + from unittest.mock import patch + + model = "claude-3-5-sonnet-20241022" + chat = ChatAnthropic(model=model, structured_output_mode="tool", api_key="x") + + class Person(BaseModel): + name: str + age: int + + fake = _fake_tool_mode_message(model) + provider = cast(AnthropicProvider, chat.provider) + + with patch.object(provider._client.messages, "create", return_value=fake): + with pytest.warns(UserWarning, match="streaming"): + person = chat.chat_structured( + "John, age 15", data_model=Person, stream=True + ) + + assert person == Person(name="John", age=15) + + +@pytest.mark.asyncio +async def test_chat_structured_async_stream_true_tool_mode_downgrades_gracefully(): + # chat_structured_async() takes a separate async path + # (_submit_and_extract_data_async); cover it so the async fallback can't + # regress independently (gh-317). + from unittest.mock import AsyncMock, patch + + model = "claude-3-5-sonnet-20241022" + chat = ChatAnthropic(model=model, structured_output_mode="tool", api_key="x") + + class Person(BaseModel): + name: str + age: int + + fake = _fake_tool_mode_message(model) + provider = cast(AnthropicProvider, chat.provider) + + with patch.object( + provider._async_client.messages, + "create", + new=AsyncMock(return_value=fake), + ): + with pytest.warns(UserWarning, match="streaming"): + person = await chat.chat_structured_async( + "John, age 15", data_model=Person, stream=True + ) + + assert person == Person(name="John", age=15) + + @pytest.mark.vcr @retry_api_call def test_anthropic_images():