{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "id": "ur8xi4C7S06n" }, "outputs": [], "source": [ "# Copyright 2024 Google LLC\n", "#\n", "# 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": "JAPoU8Sm5E6e" }, "source": [ "# Intro to Generating and Executing Python Code with Gemini 3\n", "\n", "\n", " \n", " \n", " \n", " \n", "
\n", " \n", " \"Google
Open in Colab\n", "
\n", "
\n", " \n", " \"Google
Open in Colab Enterprise\n", "
\n", "
\n", " \n", " \"Workbench
Open in Workbench\n", "
\n", "
\n", " \n", " \"GitHub
View on GitHub\n", "
\n", "
\n", "\n", "
\n", "\n", "

\n", "Share to:\n", "\n", "\n", " \"LinkedIn\n", "\n", "\n", "\n", " \"Bluesky\n", "\n", "\n", "\n", " \"X\n", "\n", "\n", "\n", " \"Reddit\n", "\n", "\n", "\n", " \"Facebook\n", "\n", "

" ] }, { "cell_type": "markdown", "metadata": { "id": "84f0f73a0f76" }, "source": [ "| Author |\n", "| --- |\n", "| [Kristopher Overholt](https://github.com/koverholt/) |" ] }, { "cell_type": "markdown", "metadata": { "id": "tvgnzT1CKxrO" }, "source": [ "## Overview\n", "\n", "This notebook introduces the code execution capabilities of the [Gemini 3 Flash model](https://cloud.google.com/vertex-ai/generative-ai/docs/gemini-v2), a new multimodal generative AI model from Google [DeepMind](https://deepmind.google/). Gemini 3 Flash offers improvements in speed, quality, and advanced reasoning capabilities including enhanced understanding, coding, and instruction following.\n", "\n", "## Code Execution\n", "\n", "A key feature of this model is [code execution](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/code-execution), which is the ability to generate and execute Python code directly within the API. If you want the API to generate and run Python code and return the results, you can use code execution as demonstrated in this notebook.\n", "\n", "This code execution capability enables the model to generate code, execute and observe the results, correct the code if needed, and learn iteratively from the results until it produces a final output. This is particularly useful for applications that involve code-based reasoning such as solving mathematical equations or processing text.\n", "\n", "## Objectives\n", "\n", "In this tutorial, you will learn how to generate and execute code using the Gemini API in Vertex AI and the Google Gen AI SDK for Python with the Gemini 3 Flash model.\n", "\n", "You will complete the following tasks:\n", "\n", "- Generating and running sample Python code from text prompts\n", "- Exploring data using code execution in multi-turn chats\n", "- Using code execution in streaming sessions" ] }, { "cell_type": "markdown", "metadata": { "id": "61RBz8LLbxCR" }, "source": [ "## Getting started" ] }, { "cell_type": "markdown", "metadata": { "id": "No17Cw5hgx12" }, "source": [ "### Install Google Gen AI SDK for Python\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "id": "tFy3H3aPgx12" }, "outputs": [], "source": [ "%pip install --upgrade --quiet google-genai" ] }, { "cell_type": "markdown", "metadata": { "id": "dmWOrTJ3gx13" }, "source": [ "### Authenticate your notebook environment (Colab only)\n", "\n", "If you're running this notebook on Google Colab, run the cell below to authenticate your environment." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "id": "NyKGtVQjgx13" }, "outputs": [], "source": [ "import sys\n", "\n", "if \"google.colab\" in sys.modules:\n", " from google.colab import auth\n", "\n", " auth.authenticate_user()" ] }, { "cell_type": "markdown", "metadata": { "id": "0fggiCx13zxX" }, "source": [ "### Import libraries" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "id": "JbrnA9yv3zMC" }, "outputs": [], "source": [ "import os\n", "\n", "from IPython.display import Markdown, display\n", "from google import genai\n", "from google.genai.types import GenerateContentConfig, Tool, ToolCodeExecution" ] }, { "cell_type": "markdown", "metadata": { "id": "vXiC1rOE3gSZ" }, "source": [ "### Connect to a generative AI API service\n", "\n", "Google Gen AI APIs and models including Gemini are available in the following two API services:\n", "\n", "- [Google AI for Developers](https://ai.google.dev/gemini-api/docs): Experiment, prototype, and deploy small projects.\n", "- [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs): Build enterprise-ready projects on Google Cloud.\n", "The Google Gen AI SDK provides a unified interface to these two API services.\n", "\n", "This notebook shows how to use the Google Gen AI SDK with the Gemini API in Vertex AI." ] }, { "cell_type": "markdown", "metadata": { "id": "DF4l8DTdWgPY" }, "source": [ "### Set Google Cloud project information and create client\n", "\n", "To get started using Vertex AI, you must have an existing Google Cloud project and [enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n", "\n", "Learn more about [setting up a project and a development environment](https://cloud.google.com/vertex-ai/docs/start/cloud-environment)." ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "id": "Nqwi-5ufWp_B" }, "outputs": [], "source": [ "# fmt: off\n", "PROJECT_ID = \"[your-project-id]\" # @param {type: \"string\", placeholder: \"[your-project-id]\", isTemplate: true}\n", "# fmt: on\n", "if not PROJECT_ID or PROJECT_ID == \"[your-project-id]\":\n", " PROJECT_ID = str(os.environ.get(\"GOOGLE_CLOUD_PROJECT\"))\n", "\n", "LOCATION = os.environ.get(\"GOOGLE_CLOUD_REGION\", \"global\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "id": "3Ab5NQwr4B8j" }, "outputs": [], "source": [ "client = genai.Client(enterprise=True, project=PROJECT_ID, location=LOCATION)" ] }, { "cell_type": "markdown", "metadata": { "id": "x1vpnyk-q-fz" }, "source": [ "## Working with code execution in Gemini 3\n", "\n", "### Load the Gemini model\n", "\n", "The following code loads the Gemini 3 Flash model. You can learn about all Gemini models on Vertex AI by visiting the [documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models):" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "id": "L8gLWcOFqqF2" }, "outputs": [], "source": [ "MODEL_ID = \"gemini-3.5-flash\" # @param {type: \"string\"}" ] }, { "cell_type": "markdown", "metadata": { "id": "q-jdBwXlM67j" }, "source": [ "### Define the code execution tool\n", "\n", "The following code initializes the code execution tool by passing `code_execution` in a `Tool` definition.\n", "\n", "Later we'll register this tool with the model that it can use to generate and run Python code:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "id": "BFxIcGkxbq3_" }, "outputs": [], "source": [ "code_execution_tool = Tool(code_execution=ToolCodeExecution())" ] }, { "cell_type": "markdown", "metadata": { "id": "mZgn5tm-NCfH" }, "source": [ "### Generate and execute code\n", "\n", "The following code sends a prompt to the Gemini model, asking it to generate and execute Python code to calculate the sum of the first 50 prime numbers. The code execution tool is passed in so the model can generate and run the code:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "id": "b52qMx0IGA0K" }, "outputs": [], "source": [ "PROMPT = \"\"\"What is the sum of the first 50 prime numbers?\n", "Generate and run code for the calculation.\"\"\"\n", "\n", "response = client.models.generate_content(\n", " model=MODEL_ID,\n", " contents=PROMPT,\n", " config=GenerateContentConfig(\n", " tools=[code_execution_tool],\n", " ),\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "l-mfiMNasgqH" }, "source": [ "### View the generated code\n", "\n", "The following code iterates through the response and displays any generated Python code by checking for `part.executable_code` in the response parts:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "id": "J5mcXw6ZraLS" }, "outputs": [ { "data": { "text/markdown": [ "\n", "```py\n", "def is_prime(n):\n", " if n < 2:\n", " return False\n", " for i in range(2, int(n**0.5) + 1):\n", " if n % i == 0:\n", " return False\n", " return True\n", "\n", "primes = []\n", "num = 2\n", "while len(primes) < 50:\n", " if is_prime(num):\n", " primes.append(num)\n", " num += 1\n", "\n", "sum_primes = sum(primes)\n", "print(f\"The first 50 prime numbers are: {primes}\")\n", "print(f\"The sum of the first 50 prime numbers is: {sum_primes}\")\n", "```\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "for part in response.candidates[0].content.parts:\n", " if part.executable_code:\n", " display(\n", " Markdown(\n", " f\"\"\"\n", "```py\n", "{part.executable_code.code}\n", "```\n", "\"\"\"\n", " )\n", " )" ] }, { "cell_type": "markdown", "metadata": { "id": "ppumif-94xTF" }, "source": [ "### View the code execution results\n", "\n", "The following code iterates through the response and displays the execution result and outcome by checking for `part.code_execution_result` in the response parts:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "id": "J891OBjc4xn9" }, "outputs": [ { "data": { "text/markdown": [ "`The first 50 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229]\n", "The sum of the first 50 prime numbers is: 5117\n", "`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Outcome: Outcome.OUTCOME_OK\n" ] } ], "source": [ "for part in response.candidates[0].content.parts:\n", " if part.code_execution_result:\n", " display(Markdown(f\"`{part.code_execution_result.output}`\"))\n", " print(\"\\nOutcome:\", part.code_execution_result.outcome)" ] }, { "cell_type": "markdown", "metadata": { "id": "5u_XuZlMnH9S" }, "source": [ "Great! Now you have the answer (`5117`) as well as the generated (and verified via execution!) Python code.\n", "\n", "At this point in your application, you would save the output code, result, or outcome and display it to the end-user or use it downstream in your application." ] }, { "cell_type": "markdown", "metadata": { "id": "8uJ-Fk1I_AH8" }, "source": [ "### Code execution in a chat session\n", "\n", "This section shows how to use code execution in an interactive chat with history using the Gemini API.\n", "\n", "You can use `client.chats.create` to create a chat session and passes in the code execution tool, enabling the model to generate and run code:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "id": "puL91bq7tirC" }, "outputs": [], "source": [ "chat = client.chats.create(\n", " model=MODEL_ID,\n", " config=GenerateContentConfig(\n", " tools=[code_execution_tool],\n", " ),\n", ")" ] }, { "cell_type": "markdown", "metadata": { "id": "Bmu4bSApoECT" }, "source": [ "You'll start the chat by asking the model to generate sample time series data with noise and then output a sample of 10 data points:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "id": "8iyq5sKCtstH" }, "outputs": [], "source": [ "PROMPT = \"\"\"Generate and run code to create sample time series data of temperature vs. time in a test furnace.\n", "Add noise to the data. Output a sample of 10 data points from the time series data.\"\"\"\n", "\n", "response = chat.send_message(PROMPT)" ] }, { "cell_type": "markdown", "metadata": { "id": "vVhCKKBioJga" }, "source": [ "Now you can iterate through the response to display any generated Python code and execution results by checking for `part.executable_code` and `part.code_execution_result` in the response parts:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "id": "8pjwEGzft29N" }, "outputs": [ { "data": { "text/markdown": [ "\n", "```py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "# Set seed for reproducibility\n", "np.random.seed(42)\n", "\n", "# Parameters\n", "time_minutes = np.arange(0, 121, 1) # 0 to 120 minutes\n", "ambient_temp = 25.0\n", "target_temp = 800.0\n", "k = 0.05 # Heating rate constant\n", "\n", "# Generate ideal temperature data (Newton's Law of Heating/Cooling approach)\n", "# T(t) = T_ambient + (T_target - T_ambient) * (1 - exp(-k * t))\n", "ideal_temp = ambient_temp + (target_temp - ambient_temp) * (1 - np.exp(-k * time_minutes))\n", "\n", "# Add Gaussian noise\n", "noise_std = 2.5\n", "noise = np.random.normal(0, noise_std, size=len(time_minutes))\n", "actual_temp = ideal_temp + noise\n", "\n", "# Create DataFrame\n", "df = pd.DataFrame({\n", " 'Time (min)': time_minutes,\n", " 'Temperature (C)': actual_temp\n", "})\n", "\n", "# Output a sample of 10 data points\n", "sample_data = df.head(10)\n", "print(sample_data)\n", "\n", "```\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "` Time (min) Temperature (C)\n", "0 0 26.241785\n", "1 1 62.451535\n", "2 2 100.370222\n", "3 3 136.758893\n", "4 4 164.898283\n", "5 5 195.844051\n", "6 6 229.813911\n", "7 7 255.785317\n", "8 8 279.328278\n", "9 9 307.194583\n", "`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Outcome: Outcome.OUTCOME_OK\n" ] } ], "source": [ "for part in response.candidates[0].content.parts:\n", " if part.executable_code:\n", " display(\n", " Markdown(\n", " f\"\"\"\n", "```py\n", "{part.executable_code.code}\n", "```\n", "\"\"\"\n", " )\n", " )\n", " if part.code_execution_result:\n", " display(Markdown(f\"`{part.code_execution_result.output}`\"))\n", " print(\"\\nOutcome:\", part.code_execution_result.outcome)" ] }, { "cell_type": "markdown", "metadata": { "id": "4AHoGmDBQuxn" }, "source": [ "Now you can ask the model to add a smoothed data series to the time series data:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "id": "alR_tq3pss7j" }, "outputs": [], "source": [ "PROMPT = \"Rewrite the code to add a data series that smooths the sample data.\"\n", "\n", "response = chat.send_message(PROMPT)" ] }, { "cell_type": "markdown", "metadata": { "id": "MnSlnA5FQ9UH" }, "source": [ "And then display the generated Python code and execution results:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "id": "uMXRpE0NtRYC" }, "outputs": [ { "data": { "text/markdown": [ "\n", "```py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "# Set seed for reproducibility\n", "np.random.seed(42)\n", "\n", "# 1. Generate Original Data (same as before)\n", "time_minutes = np.arange(0, 121, 1)\n", "ambient_temp = 25.0\n", "target_temp = 800.0\n", "k = 0.05\n", "ideal_temp = ambient_temp + (target_temp - ambient_temp) * (1 - np.exp(-k * time_minutes))\n", "noise = np.random.normal(0, 2.5, size=len(time_minutes))\n", "actual_temp = ideal_temp + noise\n", "\n", "# Create DataFrame\n", "df = pd.DataFrame({\n", " 'Time (min)': time_minutes,\n", " 'Temperature (C)': actual_temp\n", "})\n", "\n", "# 2. Add Smoothed Data Series\n", "# We use a Simple Moving Average (SMA) with a window of 5 minutes\n", "# min_periods=1 ensures we get values even at the start of the series\n", "df['Smoothed Temp (C)'] = df['Temperature (C)'].rolling(window=5, min_periods=1, center=True).mean()\n", "\n", "# Output a sample of the first 10 data points\n", "print(df.head(10))\n", "\n", "```\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "` Time (min) Temperature (C) Smoothed Temp (C)\n", "0 0 26.241785 63.021181\n", "1 1 62.451535 81.455609\n", "2 2 100.370222 98.144144\n", "3 3 136.758893 132.064597\n", "4 4 164.898283 165.537072\n", "5 5 195.844051 196.620091\n", "6 6 229.813911 225.133968\n", "7 7 255.785317 253.593228\n", "8 8 279.328278 280.180457\n", "9 9 307.194583 304.557589\n", "`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Outcome: Outcome.OUTCOME_OK\n" ] } ], "source": [ "for part in response.candidates[0].content.parts:\n", " if part.executable_code:\n", " display(\n", " Markdown(\n", " f\"\"\"\n", "```py\n", "{part.executable_code.code}\n", "```\n", "\"\"\"\n", " )\n", " )\n", " if part.code_execution_result:\n", " display(Markdown(f\"`{part.code_execution_result.output}`\"))\n", " print(\"\\nOutcome:\", part.code_execution_result.outcome)" ] }, { "cell_type": "markdown", "metadata": { "id": "I4VacTEyQ4lD" }, "source": [ "Finally, you can ask the model to generate descriptive statistics for the time series data:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "id": "dmhPzmP8tywL" }, "outputs": [], "source": [ "PROMPT = \"Rewrite the code to generate and output descriptive statistics on the time series data.\"\n", "\n", "response = chat.send_message(PROMPT)" ] }, { "cell_type": "markdown", "metadata": { "id": "I1t_zA5jRHsB" }, "source": [ "And then display the generated Python code and execution results:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "id": "hIsMH3fPuKr5" }, "outputs": [ { "data": { "text/markdown": [ "\n", "```py\n", "import numpy as np\n", "import pandas as pd\n", "\n", "# Set seed for reproducibility\n", "np.random.seed(42)\n", "\n", "# 1. Generate Data\n", "time_minutes = np.arange(0, 121, 1)\n", "ambient_temp = 25.0\n", "target_temp = 800.0\n", "k = 0.05\n", "ideal_temp = ambient_temp + (target_temp - ambient_temp) * (1 - np.exp(-k * time_minutes))\n", "noise = np.random.normal(0, 2.5, size=len(time_minutes))\n", "actual_temp = ideal_temp + noise\n", "\n", "# Create DataFrame\n", "df = pd.DataFrame({\n", " 'Time (min)': time_minutes,\n", " 'Temperature (C)': actual_temp\n", "})\n", "\n", "# 2. Add Smoothed Data Series\n", "df['Smoothed Temp (C)'] = df['Temperature (C)'].rolling(window=5, min_periods=1, center=True).mean()\n", "\n", "# 3. Generate Descriptive Statistics\n", "# We exclude 'Time' from the statistics as it is a linear index\n", "stats = df[['Temperature (C)', 'Smoothed Temp (C)']].describe()\n", "\n", "# Adding variance specifically as it's useful for noise analysis\n", "variance = df[['Temperature (C)', 'Smoothed Temp (C)']].var().to_frame(name='variance').T\n", "stats = pd.concat([stats, variance])\n", "\n", "print(\"Descriptive Statistics for Furnace Temperature Data:\")\n", "print(stats)\n", "\n", "```\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "`Descriptive Statistics for Furnace Temperature Data:\n", " Temperature (C) Smoothed Temp (C)\n", "count 121.000000 121.000000\n", "mean 668.801372 668.953269\n", "std 187.844672 186.708358\n", "min 26.241785 63.021181\n", "25% 625.569859 626.813876\n", "50% 761.875591 761.086311\n", "75% 791.239664 791.612873\n", "max 803.432030 800.216947\n", "variance 35285.620817 34860.010924\n", "`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Outcome: Outcome.OUTCOME_OK\n" ] } ], "source": [ "for part in response.candidates[0].content.parts:\n", " if part.executable_code:\n", " display(\n", " Markdown(\n", " f\"\"\"\n", "```py\n", "{part.executable_code.code}\n", "```\n", "\"\"\"\n", " )\n", " )\n", " if part.code_execution_result:\n", " display(Markdown(f\"`{part.code_execution_result.output}`\"))\n", " print(\"\\nOutcome:\", part.code_execution_result.outcome)" ] }, { "cell_type": "markdown", "metadata": { "id": "TBbNyWtDRZto" }, "source": [ "This chat example demonstrates how you can use the Gemini API with code execution as a powerful tool for exploratory data analysis and more. Go forth and adapt this approach to your own projects and use cases!" ] }, { "cell_type": "markdown", "metadata": { "id": "Bl6KG5Ufu5XQ" }, "source": [ "### Code execution in a streaming session\n", "\n", "You can also use the code execution functionality with streaming output from the Gemini API.\n", "\n", "The following code demonstrates how the Gemini API can generate and execute code while streaming the results:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "id": "gTNMMLkNu5JH" }, "outputs": [ { "data": { "text/markdown": [ "#### Code stream" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "\n", " ```py\n", " import random\n", "\n", "# A list of common names to sample from\n", "all_names = [\n", " \"James\", \"Mary\", \"Robert\", \"Patricia\", \"John\", \"Jennifer\", \"Michael\", \"Linda\",\n", " \"David\", \"Elizabeth\", \"William\", \"Barbara\", \"Richard\", \"Susan\", \"Joseph\", \"Jessica\",\n", " \"Thomas\", \"Sarah\", \"Christopher\", \"Karen\", \"Charles\", \"Lisa\", \"Daniel\", \"Nancy\",\n", " \"Matthew\", \"Betty\", \"Anthony\", \"Sandra\", \"Mark\", \"Margaret\", \"Donald\", \"Ashley\",\n", " \"Steven\", \"Kimberly\", \"Paul\", \"Emily\", \"Andrew\", \"Donna\", \"Joshua\", \"Michelle\",\n", " \"Kenneth\", \"Dorothy\", \"Kevin\", \"Carol\", \"Brian\", \"Amanda\", \"George\", \"Melissa\",\n", " \"Timothy\", \"Deborah\"\n", "]\n", "\n", "# 1. Create a list of 20 random names\n", "random_names = random.sample(all_names, 20)\n", "\n", "# 2. Create a new list with just the names containing the letter 'a' (case-insensitive)\n", "names_with_a = [name for name in random_names if 'a' in name.lower()]\n", "\n", "# 3. Output the number of names that contain 'a'\n", "count_a = len(names_with_a)\n", "\n", "print(f\"Randomly selected 20 names: {random_names}\")\n", "print(f\"\\nNumber of names containing 'a': {count_a}\")\n", "print(f\"Names containing 'a': {names_with_a}\")\n", "\n", " ```\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "---" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "#### Code result" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "\n", " ```\n", " Randomly selected 20 names: ['Nancy', 'Michael', 'Jennifer', 'James', 'Brian', 'Susan', 'Donna', 'George', 'Kenneth', 'Elizabeth', 'Michelle', 'Andrew', 'Kevin', 'Daniel', 'Matthew', 'Steven', 'Joshua', 'Lisa', 'Sarah', 'David']\n", "\n", "Number of names containing 'a': 14\n", "Names containing 'a': ['Nancy', 'Michael', 'James', 'Brian', 'Susan', 'Donna', 'Elizabeth', 'Andrew', 'Daniel', 'Matthew', 'Joshua', 'Lisa', 'Sarah', 'David']\n", "\n", " ```\n", " " ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "---" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "#### Natural language stream" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "I have generated a list of 20 random names and filtered them to find those containing the letter 'a'.\n", "\n", "**Number of names containing 'a':" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "---" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "#### Natural language stream" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "** 14\n", "\n", "**List of names containing 'a':**\n", "1. Nancy\n", "2. Michael\n", "3. James\n", "4. Brian\n", "5. Susan\n", "6. Donna\n", "7. Elizabeth\n", "8. Andrew\n", "9" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "---" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "#### Natural language stream" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ ". Daniel\n", "10. Matthew\n", "11. Joshua\n", "12. Lisa\n", "13. Sarah\n", "14. David\n", "\n", "**Full list of 20 random names generated:**\n", "`['Nancy', 'Michael', 'Jennifer', 'James', 'Brian', 'Susan', 'Donna', 'George'," ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "---" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "#### Natural language stream" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ " 'Kenneth', 'Elizabeth', 'Michelle', 'Andrew', 'Kevin', 'Daniel', 'Matthew', 'Steven', 'Joshua', 'Lisa', 'Sarah', 'David']`" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/markdown": [ "---" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "PROMPT = \"\"\"Generate and run code to create a list of 20 random names, then\n", "create a new list with just the names containing the letter 'a', then output the\n", "number of names that contain 'a', and finally show me that new list.\"\"\"\n", "\n", "for chunk in client.models.generate_content_stream(\n", " model=MODEL_ID,\n", " contents=PROMPT,\n", " config=GenerateContentConfig(\n", " tools=[code_execution_tool],\n", " ),\n", "):\n", " if chunk.candidates and chunk.candidates[0].content:\n", " if chunk.candidates[0].content.parts is not None:\n", " for part in chunk.candidates[0].content.parts:\n", " if part.text:\n", " display(Markdown(\"#### Natural language stream\"))\n", " display(Markdown(part.text))\n", " display(Markdown(\"---\"))\n", " if part.executable_code:\n", " display(Markdown(\"#### Code stream\"))\n", " display(\n", " Markdown(\n", " f\"\"\"\n", "```py\n", "{part.executable_code.code}\n", "```\n", "\"\"\"\n", " )\n", " )\n", " display(Markdown(\"---\"))\n", " if part.code_execution_result:\n", " display(Markdown(\"#### Code result\"))\n", " display(\n", " Markdown(\n", " f\"\"\"\n", " ```\n", " {part.code_execution_result.output}\n", " ```\n", " \"\"\"\n", " )\n", " )\n", " display(Markdown(\"---\"))" ] }, { "cell_type": "markdown", "metadata": { "id": "2a4e033321ad" }, "source": [ "This streaming example demonstrated how the Gemini API can generate, execute code, and provide results within a streaming session.\n", "\n", "## Summary\n", "\n", "Refer to the [documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/code-execution) for more details about code execution, and in particular, the [recommendations](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/code-execution#code-execution-vs-function-calling) regarding differences between code execution and [function calling](https://cloud.google.com/vertex-ai/generative-ai/docs/multimodal/function-calling).\n", "\n", "### Next steps\n", "\n", "- See the [Google Gen AI SDK reference docs](https://googleapis.github.io/python-genai/)\n", "- Explore other notebooks in the [Google Cloud Generative AI GitHub repository](https://github.com/GoogleCloudPlatform/generative-ai)\n", "- Explore AI models in [Model Garden](https://cloud.google.com/vertex-ai/generative-ai/docs/model-garden/explore-models)" ] } ], "metadata": { "colab": { "collapsed_sections": [ "YZNpgtKJDdPZ" ], "name": "intro_code_execution.ipynb", "toc_visible": true }, "kernelspec": { "display_name": "Python 3", "name": "python3" } }, "nbformat": 4, "nbformat_minor": 0 }