Skip to main content
Streaming allows the model to send responses back incrementally as they’re generated, rather than waiting for the complete response. This is ideal for better user experience in interactive applications.

Synchronous Streaming

Basic Text Streaming

The generate_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:
Stream responses for images stored in Google Cloud Storage:

Asynchronous Streaming

For async applications, use the aio 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:

Streaming with Configuration

You can apply all standard configuration options to streaming:

Buffering Strategies

Different strategies for handling streamed content:
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=True to print() 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

Error Handling