pythonbeginner
Anthropic Streaming with Python
Stream Claude responses token by token using the Anthropic Python SDK with context manager.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
typescriptbeginner
Claude Messages API (Anthropic SDK)
Send messages to Claude using the official Anthropic SDK with system prompt and user turn.
Best for: AI assistant
#anthropic#claude
typescriptadvanced
Anthropic Claude Tool Use Pattern
Implement tool/function calling with Claude using the Anthropic SDK for agentic workflows.
Best for: agentic workflows
#ai#anthropic
pythonbeginner
Local LLM with Ollama Python Client
Run local open-source models with Ollama and stream responses using the Python API.
Best for: local AI
#ollama#local-llm
pythonintermediate
Python Streaming Data Processing
Process streaming data with generators, windowed aggregation, and memory-efficient line-by-line reading.
Best for: Processing large event log files efficiently
#streaming#python