Reference · Snippet · python

Anthropic Messages — streaming

Last updated

anthropicstreamingpython

import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=512,
    messages=[{"role": "user", "content": "Explain RAG in three sentences."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)