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
3 changes: 3 additions & 0 deletions helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ Blocks until the stream has been read to completion and returns the accumulated

Blocks until the stream has been read to completion and returns all `text` content blocks concatenated together.

Both final-result methods raise `anthropic.AnthropicError` if the stream ends before `message_stop`.
If a message started, `stream.current_message_snapshot` holds the content received so far.

## Message Threads

A message thread (beta) keeps the conversation on the server, so each request sends only the new messages instead of the whole history. `client.beta.messages.thread(...)` takes what `create()` takes and sends nothing until the first turn.
Expand Down
17 changes: 9 additions & 8 deletions src/anthropic/lib/streaming/_beta_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from ..._utils import consume_sync_iterator, consume_async_iterator
from ..._models import build, construct_type, construct_type_unchecked
from .._tracing import share_message_snapshot, withhold_message_snapshot
from ._messages import require_message_stop
from ._beta_types import (
BetaCitationEvent,
BetaThinkingEvent,
Expand Down Expand Up @@ -100,19 +101,19 @@ def close(self) -> None:

def get_final_message(self) -> ParsedBetaMessage[ResponseFormatT]:
"""Waits until the stream has been read to completion and returns
the accumulated `Message` object.
the accumulated `Message` object. Raises `AnthropicError` if the stream ends before `message_stop`.
"""
self.until_done()
assert self.__final_message_snapshot is not None
return self.__final_message_snapshot
require_message_stop(self._message_complete)
return self.current_message_snapshot

def get_final_text(self) -> str:
"""Returns all `text` content blocks concatenated together.

> [!NOTE]
> Currently the API will only respond with a single content block.

Will raise an error if no `text` content blocks were returned.
Raises `AnthropicError` if the stream ends before `message_stop`, or `RuntimeError` if it has no text blocks.
"""
message = self.get_final_message()
text_blocks: list[str] = []
Expand Down Expand Up @@ -272,19 +273,19 @@ async def close(self) -> None:

async def get_final_message(self) -> ParsedBetaMessage[ResponseFormatT]:
"""Waits until the stream has been read to completion and returns
the accumulated `Message` object.
the accumulated `Message` object. Raises `AnthropicError` if the stream ends before `message_stop`.
"""
await self.until_done()
assert self.__final_message_snapshot is not None
return self.__final_message_snapshot
require_message_stop(self._message_complete)
return self.current_message_snapshot

async def get_final_text(self) -> str:
"""Returns all `text` content blocks concatenated together.

> [!NOTE]
> Currently the API will only respond with a single content block.

Will raise an error if no `text` content blocks were returned.
Raises `AnthropicError` if the stream ends before `message_stop`, or `RuntimeError` if it has no text blocks.
"""
message = await self.get_final_message()
text_blocks: list[str] = []
Expand Down
36 changes: 28 additions & 8 deletions src/anthropic/lib/streaming/_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,21 @@
from ..._models import build, construct_type, construct_type_unchecked
from .._tracing import share_message_snapshot, withhold_message_snapshot
from ..._streaming import Stream, AsyncStream
from ..._exceptions import AnthropicError
from ..._utils._utils import is_given
from .._parse._response import ResponseFormatT, parse_text
from ...types.parsed_message import ParsedMessage, ParsedContentBlock


def require_message_stop(complete: bool) -> None:
if not complete:
raise AnthropicError("The stream ended before the `message_stop` event.")


class MessageStream(Generic[ResponseFormatT]):
_message_complete: bool
"""Whether the stream received the final `message_stop` event."""

text_stream: Iterator[str]
"""Iterator over just the text deltas in the stream.

Expand All @@ -48,6 +57,7 @@ def __init__(
output_format: ResponseFormatT | NotGiven,
) -> None:
self._raw_stream = raw_stream
self._message_complete = False
self.text_stream = self.__stream_text__()
self._iterator = self.__stream__()
self.__final_message_snapshot: ParsedMessage[ResponseFormatT] | None = None
Expand Down Expand Up @@ -95,19 +105,19 @@ def close(self) -> None:

def get_final_message(self) -> ParsedMessage[ResponseFormatT]:
"""Waits until the stream has been read to completion and returns
the accumulated `Message` object.
the accumulated `Message` object. Raises `AnthropicError` if the stream ends before `message_stop`.
"""
self.until_done()
assert self.__final_message_snapshot is not None
return self.__final_message_snapshot
require_message_stop(self._message_complete)
return self.current_message_snapshot

def get_final_text(self) -> str:
"""Returns all `text` content blocks concatenated together.

> [!NOTE]
> Currently the API will only respond with a single content block.

Will raise an error if no `text` content blocks were returned.
Raises `AnthropicError` if the stream ends before `message_stop`, or `RuntimeError` if it has no text blocks.
"""
message = self.get_final_message()
text_blocks: list[str] = []
Expand Down Expand Up @@ -151,6 +161,9 @@ def __stream__(self) -> Iterator[ParsedMessageStreamEvent[ResponseFormatT]]:
withhold_message_snapshot(self._raw_stream)
raise

if sse_event.type == "message_stop":
self._message_complete = True

events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot)
for event in events_to_fire:
yield event
Expand Down Expand Up @@ -197,6 +210,9 @@ def __exit__(


class AsyncMessageStream(Generic[ResponseFormatT]):
_message_complete: bool
"""Whether the stream received the final `message_stop` event."""

text_stream: AsyncIterator[str]
"""Async iterator over just the text deltas in the stream.

Expand All @@ -213,6 +229,7 @@ def __init__(
output_format: ResponseFormatT | NotGiven,
) -> None:
self._raw_stream = raw_stream
self._message_complete = False
self.text_stream = self.__stream_text__()
self._iterator = self.__stream__()
self.__final_message_snapshot: ParsedMessage[ResponseFormatT] | None = None
Expand Down Expand Up @@ -260,19 +277,19 @@ async def close(self) -> None:

async def get_final_message(self) -> ParsedMessage[ResponseFormatT]:
"""Waits until the stream has been read to completion and returns
the accumulated `Message` object.
the accumulated `Message` object. Raises `AnthropicError` if the stream ends before `message_stop`.
"""
await self.until_done()
assert self.__final_message_snapshot is not None
return self.__final_message_snapshot
require_message_stop(self._message_complete)
return self.current_message_snapshot

async def get_final_text(self) -> str:
"""Returns all `text` content blocks concatenated together.

> [!NOTE]
> Currently the API will only respond with a single content block.

Will raise an error if no `text` content blocks were returned.
Raises `AnthropicError` if the stream ends before `message_stop`, or `RuntimeError` if it has no text blocks.
"""
message = await self.get_final_message()
text_blocks: list[str] = []
Expand Down Expand Up @@ -316,6 +333,9 @@ async def __stream__(self) -> AsyncIterator[ParsedMessageStreamEvent[ResponseFor
withhold_message_snapshot(self._raw_stream)
raise

if sse_event.type == "message_stop":
self._message_complete = True

events_to_fire = build_events(event=sse_event, message_snapshot=self.current_message_snapshot)
for event in events_to_fire:
yield event
Expand Down
5 changes: 3 additions & 2 deletions tests/lib/streaming/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ def load_fixture(fixture_name: str) -> str:


def get_response(fixture_name: str) -> Iterator[bytes]:
"""Convert a fixture file into a stream of bytes for testing."""
content = load_fixture(fixture_name)
"""Send the fixture as SSE, including the blank line that dispatches its last event."""
content = load_fixture(fixture_name).rstrip("\n")
for line in content.splitlines():
yield line.encode() + b"\n"
yield b"\n"


async def to_async_iter(iter: Iterator[_T]) -> AsyncIterator[_T]:
Expand Down
12 changes: 8 additions & 4 deletions tests/lib/streaming/test_beta_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def to_dict(self) -> BetaToolParam:
"text",
"content_block_stop",
"message_delta",
"message_stop",
]

EXPECTED_TOOL_USE_MESSAGE = {
Expand Down Expand Up @@ -114,6 +115,7 @@ def to_dict(self) -> BetaToolParam:
"input_json",
"content_block_stop",
"message_delta",
"message_stop",
]

EXPECTED_INCOMPLETE_MESSAGE = {
Expand Down Expand Up @@ -175,6 +177,7 @@ def to_dict(self) -> BetaToolParam:
"content_block_delta",
"input_json",
"message_delta",
"message_stop",
]

EXPECTED_COMPACTION_MESSAGE = {
Expand Down Expand Up @@ -205,6 +208,7 @@ def to_dict(self) -> BetaToolParam:
"text",
"content_block_stop",
"message_delta",
"message_stop",
]


Expand Down Expand Up @@ -299,6 +303,7 @@ def assert_refusal_response(message: BetaMessage) -> None:
"text",
"content_block_stop",
"message_delta",
"message_stop",
]


Expand Down Expand Up @@ -332,6 +337,7 @@ def assert_fallback_response(events: list[ParsedBetaMessageStreamEvent], message
"text",
"content_block_stop",
"message_delta",
"message_stop",
]


Expand Down Expand Up @@ -586,9 +592,8 @@ def test_refusal_stop_details_propagated(self, respx_mock: MockRouter) -> None:
@pytest.mark.respx(base_url=base_url)
@pytest.mark.filterwarnings("error")
def test_message_stop_event_serialization(self, respx_mock: MockRouter) -> None:
# trailing blank line terminates the final `message_stop` SSE so it is dispatched
respx_mock.post("/v1/messages").mock(
return_value=httpx2.Response(200, content=iter([*get_response("basic_response.txt"), b"\n"]))
return_value=httpx2.Response(200, content=get_response("basic_response.txt"))
)

with sync_client.beta.messages.stream(
Expand Down Expand Up @@ -905,9 +910,8 @@ async def test_refusal_stop_details_propagated(self, respx_mock: MockRouter) ->
@pytest.mark.respx(base_url=base_url)
@pytest.mark.filterwarnings("error")
async def test_message_stop_event_serialization(self, respx_mock: MockRouter) -> None:
# trailing blank line terminates the final `message_stop` SSE so it is dispatched
respx_mock.post("/v1/messages").mock(
return_value=httpx2.Response(200, content=to_async_iter(iter([*get_response("basic_response.txt"), b"\n"])))
return_value=httpx2.Response(200, content=to_async_iter(get_response("basic_response.txt")))
)

async with async_client.beta.messages.stream(
Expand Down
Loading