{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "Tce3stUlHN0L"
},
"source": [
"##### Copyright 2026 Google LLC."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"cellView": "form",
"id": "tuOe1ymfHZPu"
},
"outputs": [],
"source": [
"# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yeadDkMiISin"
},
"source": [
"# Gemini API: Streaming Quickstart"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3f5bc95b9107"
},
"source": [
"<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/quickstarts/Streaming.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "df1767a3d1cc"
},
"source": [
"This notebook demonstrates streaming in the Python SDK. By default, the Python SDK returns a response after the model completes the entire generation process. You can also stream the response as it is being generated, and the model will return chunks of the response as soon as they are generated."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bc76744e3544"
},
"source": [
"> **Note:** This notebook uses the [Interactions API](https://ai.google.dev/gemini-api/docs/interactions), the latest way to interact with Gemini models. Looking for the `generateContent` version? Check the [archive branch](https://github.com/google-gemini/cookbook/blob/archive/generate-content-api/quickstarts/Streaming.ipynb)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "xuiLSV7amy3P"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Note: you may need to restart the kernel to use updated packages.\n"
]
}
],
"source": [
"%pip install -U -q \"google-genai>=2.9.0\" # 2.0 for Interactions API"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"id": "79EWm0DAmy-g"
},
"outputs": [],
"source": [
"from google import genai"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "DkeZNMrw6kPD"
},
"source": [
"You'll need an API key stored in an environment variable to run this notebook. See the the [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) quickstart for a walkthrough."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"id": "t9O-OzeAKC_m"
},
"outputs": [],
"source": [
"from google.colab import userdata\n",
"\n",
"GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')\n",
"client = genai.Client(api_key=GEMINI_API_KEY)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"id": "92c0cb888dff"
},
"outputs": [],
"source": [
"MODEL_ID = \"gemini-3.7-flash\" # @param [\"gemini-3.7-flash\", \"gemini-2.5-pro\", \"gemini-3.1-pro-preview\"] {\"allow-input\":true, isTemplate: true}"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BUoa5q0iUuE1"
},
"source": [
"## Handle streaming responses\n",
"\n",
"To stream responses, use `stream=True` when calling `interactions.create`. The response will be an iterator that yields chunks as they are generated."
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"id": "nVWWGBsBok3m"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" his tracks squeaking in a rhythmic, mournful cadence. His task was eternal: sort the copper from the steel, the precious from the spent. He was a relic of a forgotten era, his chassis pitted by acid rain and his processors slowed by decades of isolation. He lived in a world of gray, where the only music was the groan of settling metal.\n",
"\n",
"One Tuesday, beneath the rusted skeleton of a fallen freighter, Unit 7 found a glitch in the scenery. A splash of defiant, impossible green pushed through the toxic, oily soil. It was a sapling, no taller than his smallest bolt, its two leaves trembling in the sulfurous wind.\n",
"\n",
"His logic core screamed *Anomaly.* His primary directive whispered *Clear the debris.*\n",
"\n",
"But Unit 7 paused. He felt a strange, flickering heat in his cooling vents that had nothing to do with his battery. He didn't see a weed; he saw a miracle. Instead of crushing it, he used his heavy pincers to gently stack a wall of discarded lead plates around the sprout, shielding it from the biting gales.\n",
"\n",
"Days turned into months. Unit 7 became a gardener of the wasteland. He rationed the moisture from his internal condensers, dripping precious droplets onto the thirsty roots each dawn. He began to talk to it—not in words, but in the low, rhythmic hum of his cooling fans. He told the plant about the stars he used to see before the smog grew thick.\n",
"\n",
"The sapling grew into a stubborn, twisted shrub, its roots eventually entwining with Unit 7’s stationary treads during his nightly power-downs. He was no longer just a machine in a graveyard. He was a guardian. In the middle of a dead world, the robot and the greenery found a shared language: the silent, beautiful persistence of staying alive. He wasn't alone; he was home.\n"
]
}
],
"source": [
"response = client.interactions.create(\n",
" model=MODEL_ID,\n",
" input='Tell me a story in 300 words about a lonely robot who finds friendship in a most unexpected place.',\n",
" stream=True,\n",
")\n",
"\n",
"for event in response:\n",
" # ContentDelta events contain the streamed text\n",
" if hasattr(event, 'delta') and hasattr(event.delta, 'text') and event.delta.text:\n",
" print(event.delta.text, end=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "KswwVyHCKC_n"
},
"source": [
"## Handle streaming responses asynchronously\n",
"\n",
"To stream responses asynchronously, use `stream=True` with the asynchronous client `client.aio`. \n",
"\n",
"The `client.aio` object provides the exact same API structure as the standard synchronous `client` (e.g., `client.aio.interactions.create` instead of `client.interactions.create`), but uses `async`/`await` to perform non-blocking network requests. This is especially useful in web servers or concurrent applications where you want to process chunks as they arrive without blocking the main execution thread."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"id": "DHbwhXi2nvnS"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" professional nap-taker. To the neighbors, they were classic rivals. Barnaby barked at the fence, and Mittens watched him from the porch with a disdainful flick of her tail.\n",
"\n",
"But once the humans left for work, the act crumbled.\n",
"\n",
"Barnaby would flop onto the sun-drenched living room rug with a heavy sigh. Mittens, after a brief, dignified stretch, would trot over. She’d give his floppy ear a gentle, affectionate bat before kneading his soft golden fur into a perfect pillow.\n",
"\n",
"One afternoon, a summer thunderstorm rolled in. Barnaby hated the \"sky-drums.\" He whimpered, tucking his nose under a sofa cushion. Usually, Mittens stayed in her high tower on the bookshelf, but not today. She jumped down, purring like a tiny, rhythmic motor, and curled herself right against Barnaby’s shaking chest.\n",
"\n",
"The thunder roared, but Barnaby stopped trembling. He rested his heavy chin on her small back, comforted by her warmth. When their owner finally walked through the door, Barnaby gave a half-hearted bark and Mittens darted away with a mock hiss. They had a reputation to uphold, after all. But that night, they slept as one big, happy cloud of fur.\n"
]
}
],
"source": [
"response = await client.aio.interactions.create(\n",
" model=MODEL_ID,\n",
" input=\"Write a cute story about cats and dogs in 200 words\",\n",
" stream=True,\n",
")\n",
"\n",
"async for event in response:\n",
" if hasattr(event, 'delta') and hasattr(event.delta, 'text') and event.delta.text:\n",
" print(event.delta.text, end=\"\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "jpK3p1B4KC_o"
},
"source": [
"Here's a simple example of using the async streaming API:\n"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"id": "1n5qFwvBpyQ1"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
" late 1960s with **ARPANET**, a U.S. Department of Defense project designed to share data between research institutions. In 1969, the first message was sent between UCLA and Stanford using packet-switching technology.\n",
"\n",
"The 1980s proved pivotal as **TCP/IP** protocols were standardized in 1983, allowing diverse networks to interconnect. This established the foundation for the \"network of networks.\" However, the internet remained text-heavy and difficult for the public until 1989, when **Tim Berners-Lee** invented the World Wide Web. By introducing HTML, HTTP, and the first web browser, he transformed the internet into a navigable, graphical space.\n",
"\n",
"The 1990s triggered a commercial explosion. Browsers like Mosaic and Netscape made the web accessible, leading to the dot-com boom and the rise of giants like Amazon and Google. In the 2000s, slow dial-up gave way to high-speed broadband, facilitating the birth of social media and video streaming. The 2007 launch of the iPhone shifted the internet into the mobile era, making connectivity constant. Today, the internet is an omnipresent utility, evolving through the Internet of Things (IoT) and AI, fundamentally reshaping how humanity communicates, works, and lives.\n"
]
}
],
"source": [
"import asyncio\n",
"\n",
"\n",
"async def get_response():\n",
" response = await client.aio.interactions.create(\n",
" model=MODEL_ID,\n",
" input=\"Tell me about the history of the internet in 200 words.\",\n",
" stream=True,\n",
" )\n",
" async for event in response:\n",
" if hasattr(event, 'delta') and hasattr(event.delta, 'text') and event.delta.text:\n",
" print(event.delta.text, end=\"\")\n",
"\n",
"await get_response()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3358e61a4665"
},
"source": [
"## What's next\n",
"\n",
"* [Asynchronous requests](./Asynchronous_requests.ipynb) — learn how to make multiple requests concurrently using `client.aio`.\n",
"* [Counting tokens](./Counting_Tokens.ipynb) — see how to check token usage for your prompts and files.\n",
"* [Interactions API documentation](https://ai.google.dev/gemini-api/docs/interactions) — explore the full capabilities of multi-turn interactions."
]
}
],
"metadata": {
"colab": {
"name": "Streaming.ipynb",
"toc_visible": true
},
"google": {
"image_path": "/site-assets/images/share.png",
"keywords": [
"examples",
"googleai",
"samplecode",
"python",
"embed",
"function"
]
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}