Skip to main content

Streaming Output

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://aisupermarket.work")

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

Get the Final Result

import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://aisupermarket.work")

with client.messages.stream(
model="claude-opus-4-7",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)

# Get the full message object after the stream ends
final_message = stream.get_final_message()
print(f"\nTotal token count: {final_message.usage.input_tokens + final_message.usage.output_tokens}")

Async Streaming

import asyncio
import anthropic

client = anthropic.AsyncAnthropic(api_key="your-api-key", base_url="https://aisupermarket.work")

async def main():
async with client.messages.stream(
model="claude-opus-4-7",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a poem"}],
) as stream:
async for text in stream.text_stream:
print(text, end="", flush=True)

asyncio.run(main())