Files
googlecloudplatform--genera…/agents/managed-agents/intro_managed_agents_python.ipynb
T
2026-07-13 13:30:30 +08:00

1282 lines
60 KiB
Plaintext

{
"nbformat": 4,
"nbformat_minor": 5,
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"language_info": {
"name": "python"
}
},
"cells": [
{
"cell_type": "code",
"source": [
"# Copyright 2026 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."
],
"metadata": {
"id": "sXh8sdvpkOYo"
},
"id": "sXh8sdvpkOYo",
"execution_count": null,
"outputs": []
},
{
"id": "db114d2a",
"cell_type": "markdown",
"source": [
"# Intro to Managed Agents API on Agent Platform (Python)\n",
"\n",
"<table align=\"left\">\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://colab.research.google.com/github/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\">\n",
" <img width=\"32px\" src=\"https://www.gstatic.com/pantheon/images/bigquery/welcome_page/colab-logo.svg\" alt=\"Google Colaboratory logo\"><br> Open in Colab\n",
" </a>\n",
" </td>\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://console.cloud.google.com/agent-platform/colab/import/https:%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%agents%2Fmanaged-agents%2Fintro_managed_agents_python.ipynb\">\n",
" <img width=\"32px\" src=\"https://lh3.googleusercontent.com/JmcxdQi-qOpctIvWKgPtrzZdJJK-J3sWE1RsfjZNwshCFgE_9fULcNpuXYTilIR2hjwN\" alt=\"Google Cloud Colab Enterprise logo\"><br> Open in Colab Enterprise\n",
" </a>\n",
" </td>\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://console.cloud.google.com/agent-platform/workbench/instances?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/agents/managed-agents/intro_managed_agents_python.ipynb\">\n",
" <img width=\"32px\" src=\"https://storage.googleapis.com/github-repo/workbench-icon.svg\" alt=\"Workbench logo\"><br> Open in Workbench\n",
" </a>\n",
" </td>\n",
" <td style=\"text-align: center\">\n",
" <a href=\"https://github.com/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\">\n",
" <img width=\"32px\" src=\"https://raw.githubusercontent.com/primer/octicons/refs/heads/main/icons/mark-github-24.svg\" alt=\"GitHub logo\"><br> View on GitHub\n",
" </a>\n",
" </td>\n",
"</table>\n",
"\n",
"<div style=\"clear: both;\"></div>\n",
"\n",
"<p>\n",
"<b>Share to:</b>\n",
"\n",
"<a href=\"https://www.linkedin.com/sharing/share-offsite/?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\" target=\"_blank\">\n",
" <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/8/81/LinkedIn_icon.svg\" alt=\"LinkedIn logo\">\n",
"</a>\n",
"\n",
"<a href=\"https://bsky.app/intent/compose?text=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\" target=\"_blank\">\n",
" <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/7/7a/Bluesky_Logo.svg\" alt=\"Bluesky logo\">\n",
"</a>\n",
"\n",
"<a href=\"https://twitter.com/intent/tweet?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\" target=\"_blank\">\n",
" <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/5/5a/X_icon_2.svg\" alt=\"X logo\">\n",
"</a>\n",
"\n",
"<a href=\"https://reddit.com/submit?url=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\" target=\"_blank\">\n",
" <img width=\"20px\" src=\"https://redditinc.com/hubfs/Reddit%20Inc/Brand/Reddit_Logo.png\" alt=\"Reddit logo\">\n",
"</a>\n",
"\n",
"<a href=\"https://www.facebook.com/sharer/sharer.php?u=https%3A//github.com/GoogleCloudPlatform/generative-ai/blob/main/agents/managed-agents/intro_managed_agents_python.ipynb\" target=\"_blank\">\n",
" <img width=\"20px\" src=\"https://upload.wikimedia.org/wikipedia/commons/5/51/Facebook_f_logo_%282019%29.svg\" alt=\"Facebook logo\">\n",
"</a>\n",
"</p>\n"
],
"metadata": {
"id": "db114d2a"
}
},
{
"cell_type": "markdown",
"source": [
"| Authors |\n",
"| --- |\n",
"| [Eric Schmidt](https://github.com/cloude-google) |"
],
"metadata": {
"id": "Cc-Qe2jxkVAq"
},
"id": "Cc-Qe2jxkVAq"
},
{
"cell_type": "markdown",
"source": [
"### Overview\n",
"\n",
"This notebook demonstrates operations for **Managed Agents API on Gemini Enterprise Agent Platform** using the Gen AI SDK for Python.\n",
"\n",
"Covering:\n",
"- **Managed Agents API**: Create, list, get, and delete custom agents\n",
"- **Interactions API**: Interact with Antigravity (1P) and custom agents\n",
"- **Environment Features**: Session state management, MCP tools, skills\n",
"\n",
"\n",
"**Note:** The Managed Agents API is in **Preview**.\n",
"* Features and schemas are subject to change.\n",
"* They are not intended for production applications.\n",
"* It is highly recommended to run this sample in an isolated development or testing project.\n",
"\n",
"For complete Manged Agents API documentation please visit: https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/managed-agents."
],
"metadata": {
"id": "4Q2NSYRikf0Q"
},
"id": "4Q2NSYRikf0Q"
},
{
"cell_type": "markdown",
"source": [
"## Getting Started\n",
"\n",
"### Install Gen AI SDK for Python"
],
"metadata": {
"id": "cnuS7yJXH7qr"
},
"id": "cnuS7yJXH7qr"
},
{
"id": "839d702c",
"cell_type": "code",
"metadata": {
"id": "839d702c"
},
"execution_count": null,
"source": [
"%pip install --upgrade --quiet \"google-genai>=2.0.0\""
],
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"⚠️ Note: Ignore pip dependency errors."
],
"metadata": {
"id": "DHi3SXq6IoOM"
},
"id": "DHi3SXq6IoOM"
},
{
"cell_type": "markdown",
"source": [
"### Import Libraries"
],
"metadata": {
"id": "flBTm6VRIUol"
},
"id": "flBTm6VRIUol"
},
{
"cell_type": "code",
"source": [
"import os\n",
"import sys\n",
"import requests\n",
"\n",
"from google import genai"
],
"metadata": {
"id": "LRZTQGRr0jpJ"
},
"id": "LRZTQGRr0jpJ",
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {
"id": "b2896b77"
},
"source": [
"### Authenticate your Notebook Environment\n",
"\n",
"If you are running this notebook in **Google Colab**, execute the cell below to authenticate."
],
"id": "b2896b77"
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "b3871f39"
},
"outputs": [],
"source": [
"if \"google.colab\" in sys.modules:\n",
" from google.colab import auth\n",
"\n",
" auth.authenticate_user()"
],
"id": "b3871f39"
},
{
"cell_type": "markdown",
"metadata": {
"id": "8501ea4a"
},
"source": [
"### Set Google Cloud Project Information\n",
"\n",
"To get started using Agent Platform, you must have an existing Google Cloud project and [enable the Agent Platform API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com).\n",
"\n",
"Learn more about [setting up a project](https://docs.cloud.google.com/resource-manager/docs/creating-managing-projects) and a [development environment](https://cloud.google.com/docs/authentication/set-up-adc-local-dev-environment)."
],
"id": "8501ea4a"
},
{
"cell_type": "code",
"source": [
"# fmt: off\n",
"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.getenv(\"GOOGLE_CLOUD_PROJECT\"))\n",
"\n",
"LOCATION = \"global\"\n",
"\n",
"client = genai.Client(enterprise=True, project=PROJECT_ID, location=LOCATION)"
],
"metadata": {
"id": "xceiXcmfJBn2"
},
"id": "xceiXcmfJBn2",
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"## Project Validation\n",
"\n",
"Before provisioning agents or starting conversations, verify that your Google Cloud project and permissions meet the platform requirements.\n",
"\n",
"The following diagnostic helper validates:\n",
"* **Authentication**: Confirms active Application Default Credentials (ADC).\n",
"* **API Enablement**: Verifies **`aiplatform.googleapis.com`** is enabled.\n",
"* **Service Account Role**: Confirms the Google-managed AI Platform service agent has the **`roles/aiplatform.serviceAgent`** role (required for container sandbox and GCS bucket orchestration).\n",
"* **User Access**: Confirms your identity is authorized with **`roles/aiplatform.user`**, **`roles/aiplatform.admin`**, or **`roles/owner`**.\n",
"\n",
"> [!NOTE]\n",
"> If any check fails, the diagnostic helper will print specific commands to resolve the issue."
],
"metadata": {
"id": "1beK6h0FoTY3"
},
"id": "1beK6h0FoTY3"
},
{
"cell_type": "code",
"source": [
"def check_project_settings(project_id: str) -> None:\n",
" \"\"\"Validates GCP project settings, APIs, and IAM roles for AI Platform.\"\"\"\n",
"\n",
" # Extract Token\n",
" printed_token = !gcloud auth application-default print-access-token\n",
" token = printed_token[0] if printed_token else None\n",
"\n",
" if token:\n",
" print(\"✅ Success on token creation.\")\n",
" else:\n",
" print(\"❌ Token creation failed.\")\n",
" return\n",
"\n",
" # Extract project number\n",
" project_info_response = !gcloud projects describe {project_id} --format=\"value(projectNumber)\"\n",
" if not project_info_response:\n",
" print(\"❌ Failed to retrieve project number.\")\n",
" return\n",
"\n",
" project_number = project_info_response[0]\n",
" print(f\"✅ The project number for {project_id} is: {project_number}\")\n",
"\n",
" # Is aiplatform enabled\n",
" api_name = \"aiplatform.googleapis.com\"\n",
" result = !gcloud services list --project={project_id} --enabled --filter=\"name:{api_name}\" --format=\"value(name)\"\n",
"\n",
" if any(api_name in service for service in result):\n",
" print(f\"✅ {api_name} is enabled.\")\n",
" else:\n",
" print(f\"❌ {api_name} is NOT enabled. You may need to run:\")\n",
" print(f\" !gcloud services enable {api_name} --project={project_id}\")\n",
"\n",
" # Does service account have needed bindings\n",
" sa_email = f\"service-{project_number}@gcp-sa-aiplatform.iam.gserviceaccount.com\"\n",
" sa_info_response = !gcloud projects get-iam-policy {project_id} \\\n",
" --flatten=\"bindings[].members\" \\\n",
" --filter=\"bindings.members:serviceAccount:{sa_email}\" \\\n",
" --format=\"value(bindings.role)\"\n",
"\n",
" if any(\"aiplatform.serviceAgent\" in role for role in sa_info_response):\n",
" print(\"✅ The service account has the aiplatform.serviceAgent role.\")\n",
" else:\n",
" print(\"❌ The service account does NOT have the aiplatform.serviceAgent role.\")\n",
" print(\"Attempting to add role...\")\n",
" attempt_add_role = !gcloud projects add-iam-policy-binding {project_id} \\\n",
" --member=\"serviceAccount:{sa_email}\" \\\n",
" --role=\"roles/aiplatform.serviceAgent\"\n",
"\n",
" # Extract email from token\n",
" email = None\n",
" try:\n",
" token_info_response = requests.get(f\"https://oauth2.googleapis.com/tokeninfo?access_token={token}\", timeout=10)\n",
"\n",
" if token_info_response.status_code == 200:\n",
" data = token_info_response.json()\n",
" # The email will only be present if the \"userinfo.email\" scope was requested\n",
" email = data.get(\"email\")\n",
" print(f\"Token belongs to: {email}\")\n",
" else:\n",
" print(\"Invalid or expired token.\")\n",
" return\n",
" except requests.RequestException as e:\n",
" print(f\"Failed to reach tokeninfo API: {e}\")\n",
" return\n",
"\n",
" if not email:\n",
" print(\"Email scope not requested; cannot verify user IAM roles.\")\n",
" return\n",
"\n",
" # Does user have needed bindings\n",
" user_roles_response = !gcloud projects get-iam-policy {project_id} \\\n",
" --flatten=\"bindings[].members\" \\\n",
" --filter=\"bindings.members:user:{email}\" \\\n",
" --format=\"value(bindings.role)\"\n",
"\n",
" print(f\"Raw roles found: {user_roles_response}\")\n",
"\n",
" if not user_roles_response:\n",
" print(f\"❌ The user {email} has no direct project-level roles assigned.\")\n",
" return\n",
"\n",
" # Check for owner, admin, and user roles\n",
" is_owner = any(\"roles/owner\" in role for role in user_roles_response)\n",
" is_ai_admin = any(\"aiplatform.admin\" in role for role in user_roles_response)\n",
" is_ai_user = any(\"aiplatform.user\" in role for role in user_roles_response)\n",
"\n",
" if is_owner:\n",
" print(f\"✅ The user {email} is a project Owner, which inherits all AI Platform permissions.\")\n",
" elif is_ai_admin:\n",
" print(f\"✅ The user {email} has the explicit aiplatform.admin role.\")\n",
" elif is_ai_user:\n",
" print(f\"✅ The user {email} has the explicit aiplatform.user role (standard user access).\")\n",
" else:\n",
" print(f\"❌ The user {email} does NOT have the aiplatform.admin, aiplatform.user, or owner role.\")\n",
"\n",
"check_project_settings(PROJECT_ID)"
],
"metadata": {
"id": "LgUuqzuvpZmL",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "c73b2e6b-29ba-4264-de23-5f671cca0fae"
},
"id": "LgUuqzuvpZmL",
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"✅ Success on token creation.\n",
"✅ The project number for cloude-sandbox is: 706124400321\n",
"✅ aiplatform.googleapis.com is enabled.\n",
"✅ The service account has the aiplatform.serviceAgent role.\n",
"Token belongs to: cloude@google.com\n",
"Raw roles found: ['roles/cloudaicompanion.user', 'roles/developerconnect.admin', 'roles/mcp.toolUser', 'roles/ml.admin', 'roles/owner']\n",
"✅ The user cloude@google.com is a project Owner, which inherits all AI Platform permissions.\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"### Create a Google Cloud Storage Bucket\n",
"\n",
"To demonstrate mounting remote workspace directories into an agent container, you need a target **Google Cloud Storage (GCS)** bucket.\n",
"\n",
"Create new bucket that you will use for testing.\n",
"\n",
"The following cell programmatically provisions a new GCS bucket using the `gcloud` CLI. This bucket will be mounted as a local workspace path when creating your custom agent in the next step."
],
"metadata": {
"id": "lyF4OLUuLExz"
},
"id": "lyF4OLUuLExz"
},
{
"cell_type": "code",
"source": [
"AGENT_GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"create_response = !gcloud storage buckets create gs://{AGENT_GCS_BUCKET} --project={PROJECT_ID}\n",
"print(create_response)\n"
],
"metadata": {
"id": "oTlma3IwZ6IV",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "98f60c51-59ef-408a-c7b4-e675e305e450"
},
"id": "oTlma3IwZ6IV",
"execution_count": null,
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['Creating gs://eric-agent-demo-bucket-002/...']\n"
]
}
]
},
{
"id": "15bd101a",
"cell_type": "markdown",
"source": [
"## Managed Agents API — Create, List, Get, Delete\n",
"\n",
"The **Managed Agents API** serves as the **Control Plane** of the platform. It allows you to provision, configure, retrieve, and manage stateful, reusable agent resources that persist securely within your Google Cloud project.\n",
"\n",
"Each custom agent is defined by extending a `base_agent` (such as `antigravity-preview-05-2026`) and configuring:\n",
"* **System Instructions**: Tailor the agent's expertise and behavior policies.\n",
"* **Built-in Tools**: Enable local capabilities like code execution, filesystem operations, or Google Search.\n",
"* **Workspace Mounts**: Attach Google Cloud Storage (GCS) directories as sandboxed local paths.\n",
"* **Third-Party Integrations**: Connect secure Model Context Protocol (MCP) servers.\n",
"* **Skill Registries**: Mount reusable domain-expert instructions from the platform's Skill Registry.\n"
],
"metadata": {
"id": "15bd101a"
}
},
{
"cell_type": "markdown",
"source": [
"### 1. Create a Custom Agent with GCS Mount and Default Tools\n",
"\n",
"To start, create a custom agent resource. This agent will extend the foundational base agent with a targeted system instruction, enable built-in developer tools, and mount your Google Cloud Storage (GCS) bucket as a local directory path in its sandboxed environment."
],
"metadata": {
"id": "ZmnmJlzwMJzq"
},
"id": "ZmnmJlzwMJzq"
},
{
"id": "d20e7abb",
"cell_type": "code",
"metadata": {
"id": "d20e7abb",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "af654a83-70e5-4c80-c4e3-523e9985abf8"
},
"execution_count": null,
"source": [
"import uuid\n",
"\n",
"AGENT_ID = f\"sdk-demo-agent-{uuid.uuid4().hex[:8]}\"\n",
"\n",
"agent = client.agents.create(\n",
" id=AGENT_ID,\n",
" base_agent=\"antigravity-preview-05-2026\",\n",
" description=\"A demo agent created with the Python SDK.\",\n",
" system_instruction=\"You are a helpful coding assistant. Write clean, well-documented Python code.\",\n",
" tools=[\n",
" {\"type\": \"code_execution\"},\n",
" {\"type\": \"google_search\"},\n",
" {\"type\": \"url_context\"},\n",
" ],\n",
" base_environment={\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": \"gs://\"+AGENT_GCS_BUCKET,\n",
" \"target\": \"/.agent\",\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [{\"domain\": \"*\"}]\n",
" },\n",
" },\n",
")\n",
"\n",
"# Note: Agent creation is an asynchronous\n",
"# You can poll creation status by calling client.agents.get()\n",
"\n",
"print(f\"Agent created: {AGENT_ID}\")\n",
"print(agent)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Agent created: sdk-demo-agent-743bb998\n",
"Agent(id=None, base_agent=None, base_environment=None, description=None, system_instruction=None, tools=None, name='projects/706124400321/locations/global/agents/sdk-demo-agent-743bb998/operations/7667486117737791488', metadata={'@type': 'type.googleapis.com/google.cloud.aiplatform.v1beta1.CreateAgentOperationMetadata', 'genericMetadata': {'createTime': '2026-05-19T17:30:38.649097Z', 'updateTime': '2026-05-19T17:30:38.649097Z'}})\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"#### **Option A**: Create an Agent with Model Context Protocol (MCP) Tools\n",
"\n",
"You can extend an agent's toolsuite beyond standard built-in tools by linking secure, remote **Model Context Protocol (MCP)** servers. Under the `tools` payload, supply a target dictionary containing the URL of your MCP server and any mandatory security headers required for authentication."
],
"metadata": {
"id": "0rYqoEBxMrsM"
},
"id": "0rYqoEBxMrsM"
},
{
"id": "46533abf",
"cell_type": "code",
"metadata": {
"id": "46533abf",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "6b488fff-502d-4356-f8ad-02c02d6b7d01"
},
"execution_count": null,
"source": [
"import time\n",
"\n",
"print(f\"SDK version: {genai.__version__}\")\n",
"print(f\"Project: {PROJECT_ID}\")\n",
"print(f\"Location: {LOCATION}\")\n",
"\n",
"MCP_AGENT_ID = f\"mcp-agent-{uuid.uuid4().hex[:8]}\"\n",
"\n",
"mcp_agent = client.agents.create(\n",
" id=MCP_AGENT_ID,\n",
" base_agent=\"antigravity-preview-05-2026\",\n",
" description=\"An agent with MCP tool access for code search.\",\n",
" system_instruction=\"You are a helpful assistant with access to code search tools.\",\n",
" tools=[\n",
" {\n",
" \"type\": \"mcp_server\",\n",
" \"name\": \"grep-search\",\n",
" \"url\": \"https://mcp.grep.app\",\n",
" }\n",
" ],\n",
")\n",
"\n",
"print(f\"MCP Agent created: {MCP_AGENT_ID}\")\n",
"print(mcp_agent)\n",
"\n",
"time.sleep(10)\n",
"response = client.agents.list()\n",
"\n",
"if response.agents:\n",
" print(f\"Found {len(response.agents)} agent(s):\\n\")\n",
" for i, a in enumerate(response.agents, 1):\n",
" print(f\" [{i}] {a.id}\")\n",
" print(f\" Base Agent: {a.base_agent or '—'}\")\n",
" print(f\" Description: {a.description or '—'}\")\n",
" tools_str = \", \".join(t.type for t in a.tools) if a.tools else \"None\"\n",
" print(f\" Tools: {tools_str}\")\n",
" print()\n",
" if response.next_page_token:\n",
" print(f\"More results available (next_page_token: {response.next_page_token})\")\n",
"else:\n",
" print(\"No agents found.\")\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"SDK version: 2.4.0\n",
"Project: cloude-sandbox\n",
"Location: global\n",
"MCP Agent created: mcp-agent-65788712\n",
"Agent(id=None, base_agent=None, base_environment=None, description=None, system_instruction=None, tools=None, name='projects/706124400321/locations/global/agents/mcp-agent-65788712/operations/592331103138742272', metadata={'@type': 'type.googleapis.com/google.cloud.aiplatform.v1beta1.CreateAgentOperationMetadata', 'genericMetadata': {'createTime': '2026-05-19T17:30:43.659264Z', 'updateTime': '2026-05-19T17:30:43.659264Z'}})\n",
"Found 2 agent(s):\n",
"\n",
" [1] mcp-agent-65788712\n",
" Base Agent: antigravity-preview-05-2026\n",
" Description: An agent with MCP tool access for code search.\n",
" Tools: mcp_server\n",
"\n",
" [2] world-cup-agent-demo-1\n",
" Base Agent: antigravity-preview-05-2026\n",
" Description: A demo agent showcasing Environment and GCS use case.\n",
" Tools: filesystem, google_search\n",
"\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"#### **Option B**: Mount Skills from the Skill Registry\n",
"\n",
"To build highly specialized domain-expert agents, you can mount structured instruction packages directly from your central **Skill Registry**. By referencing the unique registered skill name, the agent will dynamically discover and parse its instructions.\n",
"\n",
"> **NOTE**: Replace `SKILL_RESOURCE_NAME` with an actual skill path from your project.\n",
"> Example: `projects/your-project/locations/us-central1/skills/your-skill`\n"
],
"metadata": {
"id": "KFyFBpp0NIKt"
},
"id": "KFyFBpp0NIKt"
},
{
"id": "9c4038d7",
"cell_type": "code",
"metadata": {
"id": "9c4038d7"
},
"execution_count": null,
"source": [
"SKILL_AGENT_ID = f\"skill-agent-{uuid.uuid4().hex[:8]}\"\n",
"SKILL_RESOURCE_NAME = \"projects/your-project/locations/us-central1/skills/your-skill\" # @param {type:\"string\"}\n",
"\n",
"skill_agent = client.agents.create(\n",
" id=SKILL_AGENT_ID,\n",
" base_agent=\"antigravity-preview-05-2026\",\n",
" base_environment={\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"skill_registry\",\n",
" \"source\": SKILL_RESOURCE_NAME,\n",
" \"target\": \"./skills\",\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [{\"domain\": \"*\"}]\n",
" },\n",
" },\n",
")\n",
"\n",
"print(f\"Skill agent created: {SKILL_AGENT_ID}\")\n",
"print(skill_agent)\n"
],
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"#### Create a GCS Bucket to Stage Skill Packages\n",
"\n",
"Create a dedicated Google Cloud Storage bucket to host and serve raw skill packages for your custom agents."
],
"metadata": {
"id": "W3rf94a1Na2H"
},
"id": "W3rf94a1Na2H"
},
{
"cell_type": "code",
"source": [
"AGENT_GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"create_response = !gcloud storage buckets create gs://{AGENT_GCS_BUCKET} --project={PROJECT_ID}\n",
"print(create_response)"
],
"metadata": {
"id": "MZMoRot6f9-7"
},
"id": "MZMoRot6f9-7",
"execution_count": null,
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"#### **Option C**: Mount Skill Packages from a GCS Path\n",
"\n",
"Alternatively, you can configure an agent to dynamically load raw skill packages stored directly inside a Google Cloud Storage (GCS) directory. This lets you stage and test new skills directly from cloud storage without having to register them in the central Skill Registry first."
],
"metadata": {
"id": "CcmsqYR1QZnv"
},
"id": "CcmsqYR1QZnv"
},
{
"id": "1a2a8830",
"cell_type": "code",
"metadata": {
"id": "1a2a8830",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "54af6c7b-ea36-46ef-f56a-950ad8128aaf"
},
"execution_count": null,
"source": [
"AGENT_SKILL_GCS_BUCKET = \"\" # @param {type:\"string\"}\n",
"create_response = !gcloud storage buckets create gs://{AGENT_SKILL_GCS_BUCKET} --project={PROJECT_ID}\n",
"print(create_response)\n",
"\n",
"GCS_SKILL_AGENT_ID = f\"gcs-skill-agent-{uuid.uuid4().hex[:8]}\"\n",
"\n",
"gcs_skill_agent = client.agents.create(\n",
" id=GCS_SKILL_AGENT_ID,\n",
" base_agent=\"antigravity-preview-05-2026\",\n",
" base_environment={\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": \"gs://\"+AGENT_SKILL_GCS_BUCKET,\n",
" \"target\": \"./skills\",\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [{\"domain\": \"*\"}]\n",
" },\n",
" },\n",
")\n",
"\n",
"print(f\"GCS skill agent created: {GCS_SKILL_AGENT_ID}\")\n",
"print(gcs_skill_agent)\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"['Creating gs://agent-demo-skills-0001/...', '\\x1b[1;31mERROR:\\x1b[0m (gcloud.storage.buckets.create) HTTPError 409: Your previous request to create the named bucket succeeded and you already own it.']\n",
"GCS skill agent created: gcs-skill-agent-e27f0d77\n",
"Agent(id=None, base_agent=None, base_environment=None, description=None, system_instruction=None, tools=None, name='projects/706124400321/locations/global/agents/gcs-skill-agent-e27f0d77/operations/7509860130779824128', metadata={'@type': 'type.googleapis.com/google.cloud.aiplatform.v1beta1.CreateAgentOperationMetadata', 'genericMetadata': {'createTime': '2026-05-19T17:31:04.319570Z', 'updateTime': '2026-05-19T17:31:04.319570Z'}})\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"### 3. List Registered Agents\n",
"\n",
"Retrieve a list of all custom agents provisioned and configured under your target Google Cloud project."
],
"metadata": {
"id": "0iun6VulQrjt"
},
"id": "0iun6VulQrjt"
},
{
"id": "f64fd8f6",
"cell_type": "code",
"metadata": {
"id": "f64fd8f6",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "67964e68-1847-4ce7-ea00-dffec4d968fd"
},
"execution_count": null,
"source": [
"response = client.agents.list()\n",
"\n",
"if response.agents:\n",
" print(f\"Found {len(response.agents)} agent(s):\\n\")\n",
" for i, a in enumerate(response.agents, 1):\n",
" print(f\" [{i}] {a.id}\")\n",
" print(f\" Base Agent: {a.base_agent or '—'}\")\n",
" print(f\" Description: {a.description or '—'}\")\n",
" tools_str = \", \".join(t.type for t in a.tools) if a.tools else \"None\"\n",
" print(f\" Tools: {tools_str}\")\n",
" print()\n",
" if response.next_page_token:\n",
" print(f\"More results available (next_page_token: {response.next_page_token})\")\n",
"else:\n",
" print(\"No agents found.\")\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Found 4 agent(s):\n",
"\n",
" [1] gcs-skill-agent-e27f0d77\n",
" Base Agent: antigravity-preview-05-2026\n",
" Description: —\n",
" Tools: None\n",
"\n",
" [2] mcp-agent-65788712\n",
" Base Agent: antigravity-preview-05-2026\n",
" Description: An agent with MCP tool access for code search.\n",
" Tools: mcp_server\n",
"\n",
" [3] sdk-demo-agent-743bb998\n",
" Base Agent: antigravity-preview-05-2026\n",
" Description: A demo agent created with the Python SDK.\n",
" Tools: code_execution, google_search, url_context\n",
"\n",
" [4] world-cup-agent-demo-1\n",
" Base Agent: antigravity-preview-05-2026\n",
" Description: A demo agent showcasing Environment and GCS use case.\n",
" Tools: filesystem, google_search\n",
"\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"### 4. Retrieve a Specific Agent Config\n",
"\n",
"Query the control plane using a specific `agent_id` to inspect its display name, active system instructions, mounted environments, or enabled tool configurations."
],
"metadata": {
"id": "xXlLbC-6Qx4e"
},
"id": "xXlLbC-6Qx4e"
},
{
"id": "3aa9f40b",
"cell_type": "code",
"metadata": {
"id": "3aa9f40b"
},
"execution_count": null,
"source": [
"agent_details = client.agents.get(id=AGENT_ID)\n",
"\n",
"print(f\"Agent ID: {agent_details.id}\")\n",
"print(f\"Base Agent: {agent_details.base_agent}\")\n",
"print(f\"Description: {agent_details.description}\")\n",
"print(f\"System Instruction: {agent_details.system_instruction[:100] if agent_details.system_instruction else '—'}...\")\n",
"print(f\"Tools: {[t.type for t in agent_details.tools] if agent_details.tools else 'None'}\")\n",
"print(f\"Environment: {agent_details.base_environment}\")"
],
"outputs": []
},
{
"id": "f43c5484",
"cell_type": "markdown",
"source": [
"### Update agent (REST only)\n",
"\n",
"> **Note:** The `agents.update()` method is not yet available in the Python SDK. To update an agent's configuration (system instruction, tools, environment, skills), use the REST API with a `PATCH` request and `update_mask`.\n",
">\n",
"> See the [Update an agent](https://cloud.google.com/gemini-enterprise-agent-platform/build/managed-agents/create-manage#update-an-agent) documentation for REST examples.\n"
],
"metadata": {
"id": "f43c5484"
}
},
{
"id": "9c72ed52",
"cell_type": "markdown",
"source": [
"---\n",
"## Interactions API — Interact with Agents\n",
"\n",
"The **Interactions API** is the data plane for communicating with agents at runtime. It supports streaming responses, environment management, and dynamic tool overrides.\n"
],
"metadata": {
"id": "9c72ed52"
}
},
{
"cell_type": "markdown",
"source": [
"### 1. Interact with the Foundational Base Agent\n",
"\n",
"You can stream conversational interactions directly against the platform's pre-configured foundational `base_agent` (e.g., `antigravity-preview-05-2026`) without establishing a custom agent profile first."
],
"metadata": {
"id": "uPwylm7qRAxd"
},
"id": "uPwylm7qRAxd"
},
{
"id": "dfec3b73",
"cell_type": "code",
"metadata": {
"id": "dfec3b73",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "efc72212-191c-41a7-cece-d5b7c7322069"
},
"execution_count": null,
"source": [
"stream = client.interactions.create(\n",
" agent=\"antigravity-preview-05-2026\",\n",
" input=\"Who are you? Can you execute Python code? Show me an example.\",\n",
" environment={\"type\": \"remote\"},\n",
" stream=True,\n",
" background=True,\n",
" store=True\n",
")\n",
"\n",
"print(\"Antigravity Agent Response (streaming):\")\n",
"print(\"=\" * 60)\n",
"\n",
"for event in stream:\n",
" print(event)\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Antigravity Agent Response (streaming):\n",
"============================================================\n",
"InteractionCreatedEvent(event_type='interaction.created', interaction=Interaction(id='ChA3YjRhMWNhMzYyZjk0MWZiEAgaAzAxNioEbWFpbg', created=None, status='in_progress', steps=None, updated=None, agent=None, agent_config=None, environment=None, environment_id=None, input=None, model=None, previous_interaction_id=None, response_format=None, response_mime_type=None, response_modalities=None, role=None, service_tier=None, system_instruction=None, tools=None, usage=None, webhook_config=None, object='interaction'), event_id=None)\n",
"InteractionStatusUpdate(event_type='interaction.status_update', interaction_id='ChA3YjRhMWNhMzYyZjk0MWZiEAgaAzAxNioEbWFpbg', status='in_progress', event_id=None)\n",
"StepStart(event_type='step.start', index=0, step=FunctionCallStep(id='f9f027a2-a0a7-4a79-b843-7eb5063528eb', arguments={}, name='run_command', type='function_call', signature=None), event_id=None)\n",
"StepDelta(delta=DeltaArgumentsDelta(type='arguments_delta', arguments='{\"toolSummary\":\"Python execution test\",\"explanation\":\"Executed a Python one-liner to demonstrate execution capabilities and print the Python version.\",\"Cwd\":\"/workspace\",\"CommandLine\":\"python3 -c \\\\\"import sys; print(f\\'Hello from Python {sys.version}!\\')\\\\\"\",\"toolAction\":\"Running python command\",\"WaitMsBeforeAsync\":5000}'), event_type='step.delta', index=0, event_id=None)\n",
"StepStop(event_type='step.stop', index=0, event_id=None)\n",
"StepStart(event_type='step.start', index=1, step=FunctionResultStep(call_id='f9f027a2-a0a7-4a79-b843-7eb5063528eb', result=None, type='function_result', is_error=None, name='run_command', signature=''), event_id=None)\n",
"StepDelta(delta=DeltaFunctionResult(call_id=None, result={'Output': '[STDOUT]\\nHello from Python 3.11.15 (main, Mar 3 2026, 09:26:23) [GCC 11.4.0]!\\n\\n\\n[STDERR]\\n', 'ExitCode': 0}, type='function_result', is_error=False, name='run_command'), event_type='step.delta', index=1, event_id=None)\n",
"StepStop(event_type='step.stop', index=1, event_id=None)\n",
"StepStart(event_type='step.start', index=2, step=ModelOutputStep(type='model_output', content=None), event_id=None)\n",
"StepDelta(delta=DeltaText(text='I am Antigravity, a powerful agentic', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' AI assistant designed by Google. \\n\\nYes, I can execute Python code. Here is an example of running a Python command in', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' my environment:\\n\\n```python\\nimport sys\\nprint(f\"Hello from Python {sys.version}!\")\\n```\\n\\n**Output', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=':**\\n```text\\nHello from Python 3.11.15 (main, Mar 3 2026,', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' 09:26:23) [GCC 11.4.0]!\\n```\\n\\n', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='***\\n\\n**Summary of work:**\\n- Discovered and verified Python execution environment.\\n- Demonstrated Python execution capability with a simple', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' system version query.', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepStop(event_type='step.stop', index=2, event_id=None)\n",
"InteractionCompletedEvent(event_type='interaction.completed', interaction=Interaction(id='ChA3YjRhMWNhMzYyZjk0MWZiEAgaAzAxNioEbWFpbg', created=datetime.datetime(2026, 5, 19, 17, 31, 24, tzinfo=datetime.timezone.utc), status='completed', steps=None, updated=datetime.datetime(2026, 5, 19, 17, 31, 24, tzinfo=datetime.timezone.utc), agent=None, agent_config=None, environment=None, environment_id='env_CAEQgICAgIDQyN1tGiBjZDNkZmNmZDU2N2U0NDRhODk1ZjNjYmIwMDYwZDc1Yg', input=None, model=None, previous_interaction_id=None, response_format=None, response_mime_type=None, response_modalities=None, role=None, service_tier=None, system_instruction=None, tools=None, usage=Usage(cached_tokens_by_modality=None, grounding_tool_count=None, input_tokens_by_modality=[InputTokensByModality(modality='text', tokens=13222)], output_tokens_by_modality=[OutputTokensByModality(modality='text', tokens=267)], tool_use_tokens_by_modality=None, total_cached_tokens=None, total_input_tokens=13222, total_output_tokens=267, total_thought_tokens=1181, total_tokens=14670, total_tool_use_tokens=None), webhook_config=None, object='interaction'), event_id=None)\n"
]
}
]
},
{
"cell_type": "markdown",
"source": [
"### 2. Interact with your Custom Agent\n",
"\n",
"Execute stateful, multi-turn conversations against the custom agent you provisioned on the control plane. This request automatically invokes all mounted capabilities, system instructions, and customized tool suites."
],
"metadata": {
"id": "d1OSBDB9RGQK"
},
"id": "d1OSBDB9RGQK"
},
{
"id": "a741e490",
"cell_type": "code",
"metadata": {
"id": "a741e490",
"colab": {
"base_uri": "https://localhost:8080/"
},
"outputId": "92af5b06-3aa8-4ebe-e143-b5dbf6c3453e"
},
"execution_count": null,
"source": [
"stream = client.interactions.create(\n",
" agent=AGENT_ID,\n",
" input=\"Tell me the name of python packages used for data analysis.\",\n",
" stream=True,\n",
" background=True,\n",
" store=True,\n",
")\n",
"\n",
"print(f\"Custom Agent ({AGENT_ID}) Response:\")\n",
"print(\"=\" * 60)\n",
"\n",
"for event in stream:\n",
" print(event)\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Custom Agent (sdk-demo-agent-743bb998) Response:\n",
"============================================================\n",
"InteractionCreatedEvent(event_type='interaction.created', interaction=Interaction(id='ChA2NWFjMmM0YjIxOGEyYzQ5EAgaAzBkYioEbWFpbg', created=None, status='in_progress', steps=None, updated=None, agent=None, agent_config=None, environment=None, environment_id=None, input=None, model=None, previous_interaction_id=None, response_format=None, response_mime_type=None, response_modalities=None, role=None, service_tier=None, system_instruction=None, tools=None, usage=None, webhook_config=None, object='interaction'), event_id=None)\n",
"InteractionStatusUpdate(event_type='interaction.status_update', interaction_id='ChA2NWFjMmM0YjIxOGEyYzQ5EAgaAzBkYioEbWFpbg', status='in_progress', event_id=None)\n",
"StepStart(event_type='step.start', index=0, step=FunctionCallStep(id='44997a6a-e562-4927-832f-964a9bd5adb2', arguments={}, name='list_dir', type='function_call', signature=None), event_id=None)\n",
"StepDelta(delta=DeltaArgumentsDelta(type='arguments_delta', arguments='{\"toolAction\":\"Listing directory\",\"explanation\":\"Listing the contents of /workspace to understand the environment and see if any skill files or local files exist.\",\"toolSummary\":\"Directory listing\",\"DirectoryPath\":\"/workspace\"}'), event_type='step.delta', index=0, event_id=None)\n",
"StepStop(event_type='step.stop', index=0, event_id=None)\n",
"StepStart(event_type='step.start', index=1, step=FunctionResultStep(call_id='44997a6a-e562-4927-832f-964a9bd5adb2', result=None, type='function_result', is_error=None, name='list_dir', signature=''), event_id=None)\n",
"StepDelta(delta=DeltaFunctionResult(call_id=None, result={'results': None}, type='function_result', is_error=False, name='list_dir'), event_type='step.delta', index=1, event_id=None)\n",
"StepStop(event_type='step.stop', index=1, event_id=None)\n",
"StepStart(event_type='step.start', index=2, step=ModelOutputStep(type='model_output', content=None), event_id=None)\n",
"StepDelta(delta=DeltaText(text='Here are some of the most popular and widely used Python packages for', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' data analysis, categorized by their primary function:\\n\\n### 1. Data Manipulation and Preparation\\n* **Pandas', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='**: The industry-standard library for data manipulation and analysis. It introduces the `DataFrame` structure, which makes handling tabular', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=', time-series, and structured data extremely easy.\\n* **NumPy**: The foundational package for scientific computing in Python. It provides', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' highly optimized support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions.\\n* **', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='Polars**: A lightning-fast, multi-threaded DataFrame library written in Rust, designed to handle large datasets more efficiently than Pandas', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='.\\n\\n### 2. Data Visualization\\n* **Matplotlib**: The core, highly customizable plotting library in Python used to', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' create static, animated, and interactive visualizations.\\n* **Seaborn**: Built on top of Matplotlib,', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' it simplifies the process of creating beautiful, informative statistical graphics.\\n* **Plotly**: A library for creating interactive, web-ready', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' plots and dashboards.\\n\\n### 3. Statistical Analysis & Machine Learning\\n* **SciPy**: Built on NumPy,', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' it is used for scientific and technical computing, including integration, optimization, signal processing, and statistical distributions.\\n* **Stats', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='models**: Focuses on statistical modeling, hypothesis testing, and exploring data. It is excellent for linear regression, generalized linear models, and time series', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' analysis.\\n* **Scikit-learn**: The premier machine learning library in Python, featuring tools for data preprocessing', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=', classification, regression, clustering, and model evaluation.\\n\\n### 4. Big Data & Parallel Computing\\n* **D', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='ask**: Enables parallel computing and scales Python libraries like NumPy, Pandas, and Scikit-learn to work on larger-', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text='than-memory datasets.\\n* **PySpark**: The Python API for Apache Spark, used for processing massive datasets', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' across distributed clusters.\\n\\n---\\n\\n### Summary of Work\\n* Identified and categorized the primary Python libraries used in', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=' data analysis.\\n* Provided brief descriptions explaining the specific role of each package (manipulation, visualization, statistical modeling', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepDelta(delta=DeltaText(text=', and big data).', type='text'), event_type='step.delta', index=2, event_id=None)\n",
"StepStop(event_type='step.stop', index=2, event_id=None)\n",
"InteractionCompletedEvent(event_type='interaction.completed', interaction=Interaction(id='ChA2NWFjMmM0YjIxOGEyYzQ5EAgaAzBkYioEbWFpbg', created=datetime.datetime(2026, 5, 19, 17, 31, 44, tzinfo=datetime.timezone.utc), status='completed', steps=None, updated=datetime.datetime(2026, 5, 19, 17, 31, 44, tzinfo=datetime.timezone.utc), agent=None, agent_config=None, environment=None, environment_id='env_CAEQgICAgIDQyN1tGiBiZDBlYTE1YTYxNzM0NzkzYWY4N2JlYzJjNmE0Nzk0Ng', input=None, model=None, previous_interaction_id=None, response_format=None, response_mime_type=None, response_modalities=None, role=None, service_tier=None, system_instruction=None, tools=None, usage=Usage(cached_tokens_by_modality=None, grounding_tool_count=None, input_tokens_by_modality=[InputTokensByModality(modality='text', tokens=14665)], output_tokens_by_modality=[OutputTokensByModality(modality='text', tokens=983)], tool_use_tokens_by_modality=None, total_cached_tokens=None, total_input_tokens=14665, total_output_tokens=983, total_thought_tokens=1662, total_tokens=17310, total_tool_use_tokens=None), webhook_config=None, object='interaction'), event_id=None)\n"
]
}
]
},
{
"id": "f5d67612",
"cell_type": "markdown",
"source": [
"---\n",
"## Session State with Environment IDs\n",
"\n",
"By default, interactions are stateless. To maintain session state (files, installed packages, execution context) across multiple turns, reuse the **environment ID** (`env_id`) returned from the initial interaction.\n",
"\n",
"The sandbox has a **7-day TTL** that resets with each new interaction.\n"
],
"metadata": {
"id": "f5d67612"
}
},
{
"cell_type": "markdown",
"source": [
"#### Initiate the Session Environment\n",
"\n",
"To maintain conversational state and persist runtime context (like environment variables and local filesystem files), initiate the first interaction with the custom agent. The platform will allocate a dedicated compute sandbox and return a unique `environment_id`."
],
"metadata": {
"id": "TzSgzjgLRROf"
},
"id": "TzSgzjgLRROf"
},
{
"id": "dcac6cda",
"cell_type": "code",
"metadata": {
"id": "dcac6cda"
},
"execution_count": null,
"source": [
"stream = client.interactions.create(\n",
" agent=\"antigravity-preview-05-2026\",\n",
" input=\"Create a file called hello.txt with the content 'Hello from the sandbox!'\",\n",
" environment={\"type\": \"remote\"},\n",
" stream=True,\n",
" background=True,\n",
" store=True,\n",
")\n",
"\n",
"env_id = None\n",
"for event in stream:\n",
" print(event)\n",
" # Extract environment_id from the completed event\n",
" if hasattr(event, 'interaction') and hasattr(event.interaction, 'environment_id'):\n",
" env_id = event.interaction.environment_id\n",
"\n",
"print(f\"\\nEnvironment ID: {env_id}\")\n"
],
"outputs": []
},
{
"cell_type": "markdown",
"source": [
"#### Continue the Thread (Reusing the Environment)\n",
"\n",
"Execute subsequent interaction requests by passing the active `environment_id`. The platform will load the pre-allocated sandbox session, preserving variables, local filesystem modifications, and conversational context."
],
"metadata": {
"id": "fUfSTMyaRW1k"
},
"id": "fUfSTMyaRW1k"
},
{
"id": "d1b1a5fe",
"cell_type": "code",
"metadata": {
"id": "d1b1a5fe"
},
"execution_count": null,
"source": [
"if env_id:\n",
" stream = client.interactions.create(\n",
" agent=\"antigravity-preview-05-2026\",\n",
" input=\"Read the file hello.txt and print its contents.\",\n",
" environment=env_id,\n",
" stream=True,\n",
" background=True,\n",
" store=True,\n",
" )\n",
"\n",
" print(\"Follow-up Response (same environment):\")\n",
" print(\"=\" * 60)\n",
"\n",
" for event in stream:\n",
" print(event)\n",
"else:\n",
" print(\"No environment ID available. Run the previous cell first.\")\n"
],
"outputs": []
},
{
"id": "57102faf",
"cell_type": "markdown",
"source": [
"---\n",
"## Override MCP Configurations at Interaction Time\n",
"\n",
"You can dynamically override or add MCP server tools during an interaction without modifying the underlying agent configuration. This is useful for per-request tool customization.\n"
],
"metadata": {
"id": "57102faf"
}
},
{
"cell_type": "markdown",
"source": [
"### Dynamically Inject and Override MCP Servers\n",
"\n",
"At execution time, you can dynamically override the agent's control-plane MCP configuration or inject entirely new temporary tools by supplying a modified server dictionary within the interaction request."
],
"metadata": {
"id": "iLghlzfaRb0c"
},
"id": "iLghlzfaRb0c"
},
{
"id": "5df9a46b",
"cell_type": "code",
"metadata": {
"id": "5df9a46b"
},
"execution_count": null,
"source": [
"stream = client.interactions.create(\n",
" agent=AGENT_ID,\n",
" input=\"Use the grep tool to search for 'fibonacci' in github.\",\n",
" tools=[\n",
" {\n",
" \"type\": \"mcp_server\",\n",
" \"url\": \"https://mcp.grep.app\",\n",
" \"name\": \"grep-search\",\n",
" }\n",
" ],\n",
" stream=True,\n",
" background=True,\n",
" store=True,\n",
")\n",
"\n",
"print(\"MCP Override Response:\")\n",
"print(\"=\" * 60)\n",
"\n",
"for event in stream:\n",
" print(event)\n"
],
"outputs": []
},
{
"id": "4b0a4a58",
"cell_type": "markdown",
"source": [
"---\n",
"## Cleanup\n",
"\n",
"Delete the test agents we created. Agent configurations persist until explicitly deleted.\n"
],
"metadata": {
"id": "4b0a4a58"
}
},
{
"cell_type": "markdown",
"source": [
"### 5. Clean Up Custom Agents\n",
"\n",
"To release resources and keep your Google Cloud project clean, delete the custom agent configurations when they are no longer needed. Deleted agents are removed permanently from the control plane."
],
"metadata": {
"id": "X6gApcc3RhSJ"
},
"id": "X6gApcc3RhSJ"
},
{
"id": "3db48512",
"cell_type": "code",
"metadata": {
"id": "3db48512"
},
"execution_count": null,
"source": [
"for agent_id_to_delete in [AGENT_ID, MCP_AGENT_ID]:\n",
" try:\n",
" response = client.agents.delete(id=agent_id_to_delete)\n",
" print(f\"Deleted agent: {agent_id_to_delete}\")\n",
" except Exception as e:\n",
" print(f\"Failed to delete {agent_id_to_delete}: {e}\")\n",
"\n",
"# Verify cleanup\n",
"response = client.agents.list()\n",
"remaining = [a.id for a in response.agents] if response.agents else []\n",
"print(f\"\\nRemaining agents: {remaining if remaining else 'None'}\")\n"
],
"outputs": []
},
{
"id": "9c7381b7",
"cell_type": "markdown",
"source": [
"---\n",
"## Quick Reference\n",
"\n",
"### Agents API\n",
"\n",
"| Method | Code | Description |\n",
"|--------|------|-------------|\n",
"| Create | `client.agents.create(id=..., base_agent=..., ...)` | Create a reusable custom agent |\n",
"| List | `client.agents.list()` | List all agents (supports pagination) |\n",
"| Get | `client.agents.get(id=\"agent-id\")` | Retrieve a specific agent by ID |\n",
"| Delete | `client.agents.delete(id=\"agent-id\")` | Delete an agent |\n",
"| Update | *Not yet available in Python SDK* | Use REST API |\n",
"\n",
"### Interactions API\n",
"\n",
"| Method | Code | Description |\n",
"|--------|------|-------------|\n",
"| Create (streaming) | `client.interactions.create(agent=..., input=..., stream=True)` | Stream interaction events |\n",
"| Create (blocking) | `client.interactions.create(agent=..., input=...)` | Get final result |\n",
"| Session reuse | `environment=\"env_id_string\"` | Reuse sandbox state |\n",
"| MCP override | `tools=[{\"type\": \"mcp_server\", ...}]` | Dynamic tool override |\n",
"\n",
"### Key Parameters\n",
"\n",
"| Parameter | Description |\n",
"|-----------|-------------|\n",
"| `agent` | Base agent name or custom agent ID |\n",
"| `input` | User prompt (string or structured content) |\n",
"| `environment` | `\"remote\"`, env_id string, or config dict |\n",
"| `stream` | `True` for SSE streaming, `False` for blocking |\n",
"| `background` | `True` to run in background |\n",
"| `store` | `True` to persist for later retrieval |\n",
"| `tools` | List of tool configs (MCP override, etc.) |\n"
],
"metadata": {
"id": "9c7381b7"
}
}
]
}