AI / Google Antigravity Gemini Fundamentals Interview Questions
How do you implement streaming responses in the Gemini API?
Streaming delivers model output token by token as it generates, rather than waiting for the complete response. This dramatically improves perceived performance in interactive applications and is essential for long responses.
from google import genai client = genai.Client() # Method 1: generateContent with stream=True for chunk in client.models.generate_content_stream( model="gemini-3.5-flash", contents="Write a comprehensive guide to Python async programming.", ): print(chunk.text, end="", flush=True) # prints each chunk as it arrives print() # final newline # Method 2: Interactions API with stream=True for chunk in client.interactions.create( model="gemini-3.5-flash", input="Explain the history of computer science.", stream=True, ): if chunk.output_text: print(chunk.output_text, end="", flush=True) # Async streaming (for FastAPI, async web apps): async def stream_async(): async for chunk in await client.aio.models.generate_content_stream( model="gemini-3.5-flash", contents="Async streaming example.", ): print(chunk.text, end="", flush=True) yield chunk.text # yield to web framework (SSE, WebSocket)
Server-Sent Events (SSE) integration: streaming output can be forwarded to browsers via SSE or WebSockets. FastAPI, Flask-SSE, or any async web framework can yield streaming chunks directly to the client, enabling a ChatGPT-like typing effect in web applications.
More Related questions...