Synchronous Streaming
Basic Text Streaming
Thegenerate_content_stream method returns an iterator that yields chunks as they arrive:
Notice the
end='' parameter in print() - this prevents adding newlines between chunks and creates a smooth streaming effect.Streaming with Images
You can stream responses for multimodal inputs:- Cloud Storage (GCS)
- Local Files
Stream responses for images stored in Google Cloud Storage:
Asynchronous Streaming
For async applications, use theaio client to stream responses asynchronously:
Basic Async Streaming
Async Non-Streaming
You can also use async without streaming:Processing Stream Chunks
Each chunk in the stream has the same structure as a complete response:Chat Streaming
Streaming works seamlessly with chat sessions:- Sync Chat Streaming
- Async Chat Streaming
Streaming with Configuration
You can apply all standard configuration options to streaming:Buffering Strategies
Different strategies for handling streamed content:- Immediate Display
- Accumulate and Display
- Sentence-by-Sentence
Display each chunk immediately (best for chatbots):
Use Cases
Chatbots
Real-time responses for better user engagement
Content Writing
Show progress for long-form content generation
Code Generation
Display code as it’s being generated
Summarization
Progressive summaries for long documents
Best Practices
- Use streaming for responses that take more than 2-3 seconds
- Add
flush=Truetoprint()for immediate display in terminals - Use async streaming in web applications for better concurrency
- Buffer content if you need to process the complete response
- Handle network interruptions gracefully with try-except blocks
- Consider user experience - streaming improves perceived latency