pythonbeginner

Anthropic Streaming with Python

Stream Claude responses token by token using the Anthropic Python SDK with context manager.

python
import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model='claude-opus-4-5',
    max_tokens=1024,
    messages=[{'role':'user','content':'Write a short poem about data pipelines.'}],
) as stream:
    for text in stream.text_stream:
        print(text, end='', flush=True)
    print()

final = stream.get_final_message()
print(f'Input tokens: {final.usage.input_tokens}, Output: {final.usage.output_tokens}')

Use Cases

  • streaming responses
  • real-time AI output
  • token-by-token display

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.