- Spec files
pypi-anthropic
Describes: pkg:pypi/anthropic@0.66.x
- Description
- The official Python library for the anthropic API
- Author
- tessl
- Last updated
streaming.md docs/
1# Streaming Interface23Real-time message streaming provides immediate access to Claude's responses as they're generated, enabling responsive user interfaces and real-time processing of partial responses, tool use events, and completion updates.45## Capabilities67### Message Stream Classes89```python { .api }10class MessageStream:11def __enter__(self) -> MessageStream: ...12def __exit__(self, exc_type, exc_val, exc_tb) -> None: ...13def __iter__(self) -> Iterator[MessageStreamEvent]: ...1415def on_text(self, handler: Callable[[TextEvent], None]) -> MessageStream: ...16def on_input_json(self, handler: Callable[[InputJsonEvent], None]) -> MessageStream: ...17def on_message_stop(self, handler: Callable[[MessageStopEvent], None]) -> MessageStream: ...18def on_content_block_start(self, handler: Callable[[ContentBlockStartEvent], None]) -> MessageStream: ...19def on_content_block_delta(self, handler: Callable[[ContentBlockDeltaEvent], None]) -> MessageStream: ...20def on_content_block_stop(self, handler: Callable[[ContentBlockStopEvent], None]) -> MessageStream: ...2122def get_final_message(self) -> Message: ...23def get_final_text(self) -> str: ...2425@property26def text_stream(self) -> Iterator[str]: ...27@property28def current_message_snapshot(self) -> Message: ...2930class AsyncMessageStream:31async def __aenter__(self) -> AsyncMessageStream: ...32async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: ...33def __aiter__(self) -> AsyncIterator[MessageStreamEvent]: ...3435def on_text(self, handler: Callable[[TextEvent], Awaitable[None]]) -> AsyncMessageStream: ...36def on_input_json(self, handler: Callable[[InputJsonEvent], Awaitable[None]]) -> AsyncMessageStream: ...37def on_message_stop(self, handler: Callable[[MessageStopEvent], Awaitable[None]]) -> AsyncMessageStream: ...38def on_content_block_start(self, handler: Callable[[ContentBlockStartEvent], Awaitable[None]]) -> AsyncMessageStream: ...39def on_content_block_delta(self, handler: Callable[[ContentBlockDeltaEvent], Awaitable[None]]) -> AsyncMessageStream: ...40def on_content_block_stop(self, handler: Callable[[ContentBlockStopEvent], Awaitable[None]]) -> AsyncMessageStream: ...4142async def get_final_message(self) -> Message: ...43async def get_final_text(self) -> str: ...4445@property46def text_stream(self) -> AsyncIterator[str]: ...47@property48def current_message_snapshot(self) -> Message: ...49```5051### Stream Managers5253```python { .api }54class MessageStreamManager:55def stream(56self,57max_tokens: int,58messages: List[MessageParam],59model: str,60*,61metadata: Optional[MetadataParam] = None,62stop_sequences: Optional[List[str]] = None,63system: Optional[str] = None,64temperature: Optional[float] = None,65tool_choice: Optional[ToolChoiceParam] = None,66tools: Optional[List[ToolParam]] = None,67top_k: Optional[int] = None,68top_p: Optional[float] = None,69**kwargs70) -> MessageStream: ...7172class AsyncMessageStreamManager:73def stream(74self,75max_tokens: int,76messages: List[MessageParam],77model: str,78*,79metadata: Optional[MetadataParam] = None,80stop_sequences: Optional[List[str]] = None,81system: Optional[str] = None,82temperature: Optional[float] = None,83tool_choice: Optional[ToolChoiceParam] = None,84tools: Optional[List[ToolParam]] = None,85top_k: Optional[int] = None,86top_p: Optional[float] = None,87**kwargs88) -> AsyncMessageStream: ...89```9091## Stream Event Types9293### Core Stream Events9495```python { .api }96class MessageStreamEvent(TypedDict):97type: str9899class MessageStartEvent(MessageStreamEvent):100type: Literal["message_start"]101message: Message102103class MessageDeltaEvent(MessageStreamEvent):104type: Literal["message_delta"]105delta: MessageDeltaUsage106usage: MessageDeltaUsage107108class MessageStopEvent(MessageStreamEvent):109type: Literal["message_stop"]110111class ContentBlockStartEvent(MessageStreamEvent):112type: Literal["content_block_start"]113index: int114content_block: ContentBlock115116class ContentBlockDeltaEvent(MessageStreamEvent):117type: Literal["content_block_delta"]118index: int119delta: Union[TextDelta, InputJSONDelta]120121class ContentBlockStopEvent(MessageStreamEvent):122type: Literal["content_block_stop"]123index: int124```125126### Specific Event Types127128```python { .api }129class TextEvent(TypedDict):130type: Literal["text"]131text: str132snapshot: str133134class InputJsonEvent(TypedDict):135type: Literal["input_json"]136partial_json: str137138class TextDelta(TypedDict):139type: Literal["text_delta"]140text: str141142class InputJSONDelta(TypedDict):143type: Literal["input_json_delta"]144partial_json: str145146class MessageDeltaUsage(TypedDict):147output_tokens: int148```149150### Raw Stream Events151152```python { .api }153class RawMessageStreamEvent(TypedDict):154type: str155156class RawMessageStartEvent(RawMessageStreamEvent):157type: Literal["message_start"]158message: Message159160class RawMessageDeltaEvent(RawMessageStreamEvent):161type: Literal["message_delta"]162delta: MessageDeltaUsage163usage: MessageDeltaUsage164165class RawMessageStopEvent(RawMessageStreamEvent):166type: Literal["message_stop"]167168class RawContentBlockStartEvent(RawMessageStreamEvent):169type: Literal["content_block_start"]170index: int171content_block: ContentBlock172173class RawContentBlockDeltaEvent(RawMessageStreamEvent):174type: Literal["content_block_delta"]175index: int176delta: RawContentBlockDelta177178class RawContentBlockStopEvent(RawMessageStreamEvent):179type: Literal["content_block_stop"]180index: int181182class RawContentBlockDelta(TypedDict):183type: str184text: Optional[str]185partial_json: Optional[str]186```187188## Usage Examples189190### Basic Text Streaming191192```python193from anthropic import Anthropic194195client = Anthropic()196197with client.messages.stream(198model="claude-sonnet-4-20250514",199max_tokens=1024,200messages=[201{"role": "user", "content": "Write a short story about a robot"}202]203) as stream:204for text in stream.text_stream:205print(text, end="", flush=True)206```207208### Event Handler Pattern209210```python211def handle_text(event):212print(f"Text: {event.text}")213214def handle_stop(event):215print("Message completed!")216217with client.messages.stream(218model="claude-sonnet-4-20250514",219max_tokens=1024,220messages=[221{"role": "user", "content": "Hello!"}222]223) as stream:224stream.on_text(handle_text)225stream.on_message_stop(handle_stop)226227# Process all events228for event in stream:229pass # Events are handled by registered handlers230231# Get final assembled message232final_message = stream.get_final_message()233print(final_message.content[0].text)234```235236### Tool Use Streaming237238```python239tools = [240{241"name": "get_weather",242"description": "Get current weather",243"input_schema": {244"type": "object",245"properties": {246"location": {"type": "string"}247},248"required": ["location"]249}250}251]252253def handle_tool_use(event):254print(f"Tool called: {event.name}")255print(f"Input: {event.input}")256257with client.messages.stream(258model="claude-sonnet-4-20250514",259max_tokens=1024,260tools=tools,261messages=[262{"role": "user", "content": "What's the weather in London?"}263]264) as stream:265stream.on_input_json(handle_tool_use)266267for event in stream:268if event.type == "content_block_start":269if event.content_block.type == "tool_use":270print(f"Starting tool use: {event.content_block.name}")271```272273### Async Streaming274275```python276import asyncio277from anthropic import AsyncAnthropic278279async def stream_chat():280client = AsyncAnthropic()281282async def handle_text(event):283print(f"Received: {event.text}")284285async with client.messages.stream(286model="claude-sonnet-4-20250514",287max_tokens=1024,288messages=[289{"role": "user", "content": "Count to 10"}290]291) as stream:292stream.on_text(handle_text)293294async for event in stream:295if event.type == "message_stop":296print("Finished!")297break298299asyncio.run(stream_chat())300```301302### Real-time Text Processing303304```python305accumulated_text = ""306307with client.messages.stream(308model="claude-sonnet-4-20250514",309max_tokens=1024,310messages=[311{"role": "user", "content": "Write a poem about the ocean"}312]313) as stream:314for text in stream.text_stream:315accumulated_text += text316317# Process text in real-time (e.g., update UI)318if "\n" in text: # New line completed319lines = accumulated_text.split("\n")320for line in lines[:-1]: # Process complete lines321print(f"Complete line: {line}")322accumulated_text = lines[-1] # Keep incomplete line323```324325### Streaming with Current Snapshot326327```python328with client.messages.stream(329model="claude-sonnet-4-20250514",330max_tokens=1024,331messages=[332{"role": "user", "content": "Explain quantum computing"}333]334) as stream:335for event in stream:336if event.type == "content_block_delta":337# Get current state of the message being built338current_snapshot = stream.current_message_snapshot339print(f"Current length: {len(current_snapshot.content[0].text)} chars")340341# Get final complete message342final_message = stream.get_final_message()343final_text = stream.get_final_text()344```345346### Error Handling in Streams347348```python349try:350with client.messages.stream(351model="claude-sonnet-4-20250514",352max_tokens=1024,353messages=[354{"role": "user", "content": "Hello!"}355]356) as stream:357for text in stream.text_stream:358print(text, end="")359360except Exception as e:361print(f"Streaming error: {e}")362# Handle connection issues, rate limits, etc.363```364365### Custom Stream Processing366367```python368class CustomStreamHandler:369def __init__(self):370self.word_count = 0371self.sentences = []372self.current_sentence = ""373374def handle_text(self, event):375text = event.text376self.current_sentence += text377self.word_count += len(text.split())378379if "." in text or "!" in text or "?" in text:380self.sentences.append(self.current_sentence.strip())381self.current_sentence = ""382383def handle_stop(self, event):384print(f"Final stats: {self.word_count} words, {len(self.sentences)} sentences")385386handler = CustomStreamHandler()387388with client.messages.stream(389model="claude-sonnet-4-20250514",390max_tokens=1024,391messages=[392{"role": "user", "content": "Tell me about machine learning"}393]394) as stream:395stream.on_text(handler.handle_text)396stream.on_message_stop(handler.handle_stop)397398for event in stream:399pass # Let handlers process events400```