Files
2026-07-13 13:30:30 +08:00

1142 lines
46 KiB
Plaintext

{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "a653d416",
"metadata": {},
"outputs": [],
"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."
]
},
{
"cell_type": "markdown",
"id": "4d6328f6",
"metadata": {},
"source": [
"# Intro to Managed Agents API on Agent Platform (cURL)\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_curl.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_curl.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_curl.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_curl.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_curl.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_curl.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_curl.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_curl.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_curl.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>"
]
},
{
"cell_type": "markdown",
"id": "7d76e1d9",
"metadata": {},
"source": [
"| Authors |\n",
"| --- |\n",
"| [Tianyang Zhan](github.com/tianyangzhan) |\n",
"| [Eric Schmidt](https://github.com/cloude-google) |\n",
"| [Polong Lin](https://github.com/polong-lin) |"
]
},
{
"cell_type": "markdown",
"id": "d22e226f",
"metadata": {},
"source": [
"### Overview\n",
"\n",
"This notebook demonstrates operations for **Managed Agents API on Gemini Enterprise Agent Platform** using `curl` commands to interact with the REST APIs.\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 Managed Agents API documentation please visit: https://docs.cloud.google.com/gemini-enterprise-agent-platform/build/managed-agents."
]
},
{
"cell_type": "markdown",
"id": "53811b67",
"metadata": {},
"source": [
"## Getting Started\n",
"\n",
"### Prerequisites\n",
"\n",
"To use the REST API with `curl`, you need:\n",
"1. A Google Cloud project with the Agent Platform API enabled.\n",
"2. An access token for authentication.\n",
"\n",
"### Set up Environment Variables\n",
"\n",
"Run the following cell to set your project ID and location."
]
},
{
"cell_type": "markdown",
"id": "e1d1ff8d",
"metadata": {},
"source": [
"### Import Libraries"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "b0185569",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"import requests\n",
"import json\n",
"from IPython.display import display, HTML, JSON as IPythonJSON"
]
},
{
"cell_type": "markdown",
"id": "4a2f25a0",
"metadata": {},
"source": [
"### Authenticate your Notebook Environment\n",
"\n",
"If you are running this notebook in **Google Colab**, execute the cell below to authenticate."
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "668314ea",
"metadata": {},
"outputs": [],
"source": [
"if \"google.colab\" in sys.modules:\n",
" from google.colab import auth\n",
" auth.authenticate_user()"
]
},
{
"cell_type": "markdown",
"id": "73546596",
"metadata": {},
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a1632a66",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"PROJECT_ID: polong-sandbox\n",
"LOCATION: global\n",
"Access token retrieved.\n"
]
}
],
"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",
"ENDPOINT = \"https://aiplatform.googleapis.com\"\n",
"\n",
"print(f\"PROJECT_ID: {PROJECT_ID}\")\n",
"print(f\"LOCATION: {LOCATION}\")\n",
"\n",
"# Get access token\n",
"import subprocess\n",
"try:\n",
" TOKEN = subprocess.check_output([\"gcloud\", \"auth\", \"print-access-token\"]).decode(\"utf-8\").strip()\n",
" print(\"Access token retrieved.\")\n",
"except Exception as e:\n",
" print(f\"Failed to get access token: {e}\")\n",
" print(\"You may need to authenticate.\")\n",
" TOKEN = \"\""
]
},
{
"cell_type": "markdown",
"id": "9fa8935d",
"metadata": {},
"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 commands validate:\n",
"* **Authentication**: Confirms active Application Default Credentials (ADC).\n",
"* **API Enablement**: Verifies **`aiplatform.googleapis.com`** is enabled.\n",
"* **User Access**: Confirms your identity is authorized."
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "7554e748",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Raw roles found: ['roles/owner']\n",
"✅ The user polong@google.com is a project Owner, which inherits all AI Platform permissions.\n"
]
}
],
"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)"
]
},
{
"cell_type": "markdown",
"id": "17749b65",
"metadata": {},
"source": [
"### Helper function to pretty print"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "19e2bf34",
"metadata": {},
"outputs": [],
"source": [
"def pretty_print(data, color=\"inherit\", label=None):\n",
" \"\"\"\n",
" Prints strings, dicts, lists, or objects with color and formatting.\n",
" \"\"\"\n",
" # 1. Print an optional bold label to identify the output\n",
" if label:\n",
" display(HTML(f\"<b style='color: {color}; font-size: 16px;'>{label}:</b>\"))\n",
"\n",
" # 2. Check if the data is a Dictionary or List (JSON-like)\n",
" if isinstance(data, (dict, list)):\n",
" pretty_json = json.dumps(data, indent=4)\n",
" display(HTML(f\"<pre style='color: {color}; font-weight: bold;'>{pretty_json}</pre>\"))\n",
"\n",
" # 3. Check if it's a String\n",
" elif isinstance(data, str):\n",
" display(HTML(f\"<div style='color: {color}; font-family: monospace; white-space: pre-wrap;'>{data}</div>\"))\n",
"\n",
" # 4. Handle everything else (integers, objects, etc.)\n",
" else:\n",
" display(HTML(f\"<span style='color: {color}; border-bottom: 1px solid {color};'>{repr(data)}</span>\"))\n"
]
},
{
"cell_type": "markdown",
"id": "1bb96b0b",
"metadata": {},
"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"
]
},
{
"cell_type": "markdown",
"id": "1febf58b",
"metadata": {},
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6b80fc88",
"metadata": {},
"outputs": [
{
"data": {
"text/html": [
"<pre style='color: inherit; font-weight: bold;'>{\n",
" \"name\": \"projects/835358766633/locations/global/agents/my-demo-agent/operations/8629567588134813696\",\n",
" \"metadata\": {\n",
" \"@type\": \"type.googleapis.com/google.cloud.aiplatform.v1beta1.CreateAgentOperationMetadata\",\n",
" \"genericMetadata\": {\n",
" \"createTime\": \"2026-05-19T19:25:41.652154Z\",\n",
" \"updateTime\": \"2026-05-19T19:25:41.652154Z\"\n",
" }\n",
" }\n",
"}</pre>"
],
"text/plain": [
"<IPython.core.display.HTML object>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"token = !gcloud auth application-default print-access-token\n",
"\n",
"AGENT_ID=\"my-demo-agent\" # @param {type:\"string\"}\n",
"AGENT_DESCRIPTION=\"A demo agent showcasing Environment and Skills use case.\" # @param {type:\"string\"}\n",
"INSTRUCTIONS=\"You are a helpful assistant to user.\" # @param {type:\"string\"}\n",
"GCS_BUCKET=\"gs://agents-api-sample-skills\" # @param {type:\"string\"}\n",
"\n",
"response = requests.post(\n",
" f\"{ENDPOINT}/v1beta1/projects/{PROJECT_ID}/locations/{LOCATION}/agents\",\n",
" headers = {\n",
" \"Content-Type\": \"application/json; charset=utf-8\",\n",
" \"Authorization\": f\"Bearer {token[0]}\"\n",
" },\n",
" data=json.dumps({\n",
" \"id\": AGENT_ID,\n",
" \"base_agent\": \"antigravity-preview-05-2026\",\n",
" \"description\": AGENT_DESCRIPTION,\n",
" \"system_instruction\": INSTRUCTIONS,\n",
" \"tools\": [\n",
" {\"type\": \"code_execution\"},\n",
" {\"type\": \"filesystem\"},\n",
" {\"type\": \"google_search\"},\n",
" {\"type\": \"url_context\"},\n",
" ],\n",
" \"base_environment\": {\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": GCS_BUCKET,\n",
" \"target\": \".agent/skills\"\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [\n",
" { \"domain\": \"*\" }\n",
" ]\n",
" }\n",
" },\n",
" })\n",
")\n",
"\n",
"pretty_print(json.loads(response.content))"
]
},
{
"cell_type": "markdown",
"id": "d0f86c09",
"metadata": {},
"source": [
"### 2. List Registered Agents\n",
"\n",
"List all agents in the project."
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "b491fc49",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Listing agents...\n",
"{\n",
" \"agents\": [\n",
" {\n",
" \"name\": \"projects/835358766633/locations/global/agents/my-demo-agent\",\n",
" \"id\": \"my-demo-agent\",\n",
" \"created\": \"2026-05-19T19:25:41.652Z\",\n",
" \"updated\": \"2026-05-19T19:25:44.171Z\",\n",
" \"system_instruction\": \"You are a helpful assistant to user.\",\n",
" \"tools\": [\n",
" {\n",
" \"type\": \"code_execution\"\n",
" },\n",
" {\n",
" \"type\": \"filesystem\"\n",
" },\n",
" {\n",
" \"type\": \"google_search\"\n",
" },\n",
" {\n",
" \"type\": \"url_context\"\n",
" }\n",
" ],\n",
" \"description\": \"A demo agent showcasing Environment and Skills use case.\",\n",
" \"base_environment\": {\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": \"gs://polong-sandbox-bucket\",\n",
" \"target\": \".agent/skills\"\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [\n",
" {\n",
" \"domain\": \"*\"\n",
" }\n",
" ]\n",
" }\n",
" },\n",
" \"base_agent\": \"antigravity-preview-05-2026\",\n",
" \"object\": \"agent\"\n",
" },\n",
" {\n",
" \"name\": \"projects/835358766633/locations/global/agents/my-demo-agent1\",\n",
" \"id\": \"my-demo-agent1\",\n",
" \"created\": \"2026-05-19T18:49:26.234Z\",\n",
" \"updated\": \"2026-05-19T18:49:28.442Z\",\n",
" \"system_instruction\": \"You are a helpful assistant to user.\",\n",
" \"tools\": [\n",
" {\n",
" \"type\": \"code_execution\"\n",
" },\n",
" {\n",
" \"type\": \"filesystem\"\n",
" },\n",
" {\n",
" \"type\": \"google_search\"\n",
" },\n",
" {\n",
" \"type\": \"url_context\"\n",
" }\n",
" ],\n",
" \"description\": \"A demo agent showcasing Environment and Skills use case.\",\n",
" \"base_environment\": {\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": \"gs://polong-sandbox-bucket\",\n",
" \"target\": \".agent/skills\"\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [\n",
" {\n",
" \"domain\": \"*\"\n",
" }\n",
" ]\n",
" }\n",
" },\n",
" \"base_agent\": \"antigravity-preview-05-2026\",\n",
" \"object\": \"agent\"\n",
" }\n",
" ]\n",
"}\n"
]
}
],
"source": [
"print(\"Listing agents...\")\n",
"!curl -X GET \\\n",
" \"https://aiplatform.googleapis.com/v1beta1/projects/$PROJECT_ID/locations/$LOCATION/agents\" \\\n",
" -H \"Authorization: Bearer $TOKEN\""
]
},
{
"cell_type": "markdown",
"id": "10b308d4",
"metadata": {},
"source": [
"### 3. Get Agent\n",
"\n",
"Retrieve details of a specific agent. You need to provide the `AGENT_ID`."
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "a2aa7229",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Getting agent my-demo-agent...\n",
"{\n",
" \"name\": \"projects/polong-sandbox/locations/global/agents/my-demo-agent\",\n",
" \"id\": \"my-demo-agent\",\n",
" \"created\": \"2026-05-19T19:25:41.652Z\",\n",
" \"updated\": \"2026-05-19T19:25:44.171Z\",\n",
" \"system_instruction\": \"You are a helpful assistant to user.\",\n",
" \"tools\": [\n",
" {\n",
" \"type\": \"code_execution\"\n",
" },\n",
" {\n",
" \"type\": \"filesystem\"\n",
" },\n",
" {\n",
" \"type\": \"google_search\"\n",
" },\n",
" {\n",
" \"type\": \"url_context\"\n",
" }\n",
" ],\n",
" \"description\": \"A demo agent showcasing Environment and Skills use case.\",\n",
" \"base_environment\": {\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": \"gs://polong-sandbox-bucket\",\n",
" \"target\": \".agent/skills\"\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [\n",
" {\n",
" \"domain\": \"*\"\n",
" }\n",
" ]\n",
" }\n",
" },\n",
" \"base_agent\": \"antigravity-preview-05-2026\",\n",
" \"object\": \"agent\"\n",
"}\n"
]
}
],
"source": [
"print(f\"Getting agent {AGENT_ID}...\")\n",
"!curl -X GET \\\n",
" \"https://aiplatform.googleapis.com/v1beta1/projects/$PROJECT_ID/locations/$LOCATION/agents/$AGENT_ID\" \\\n",
" -H \"Authorization: Bearer $TOKEN\""
]
},
{
"cell_type": "markdown",
"id": "765102fc",
"metadata": {},
"source": [
"### 4. Update Agent\n",
"\n",
"For fast interactions, you may do in-place updates to your created Agents. All fields other than the identifier `agent_id` are mutable.\n",
"\n",
"In this example, we will update the `system_instruction` field of the Agent."
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "4d77c34b",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Updating agent my-demo-agent...\n",
"{\n",
" \"name\": \"projects/polong-sandbox/locations/global/agents/my-demo-agent\",\n",
" \"id\": \"my-demo-agent\",\n",
" \"created\": \"2026-05-19T19:25:41.652Z\",\n",
" \"updated\": \"2026-05-19T19:34:47.236206Z\",\n",
" \"system_instruction\": \"You are a helpful coding assistant. You should always use available tools when relevant.\",\n",
" \"tools\": [\n",
" {\n",
" \"type\": \"code_execution\"\n",
" },\n",
" {\n",
" \"type\": \"filesystem\"\n",
" },\n",
" {\n",
" \"type\": \"google_search\"\n",
" },\n",
" {\n",
" \"type\": \"url_context\"\n",
" }\n",
" ],\n",
" \"description\": \"A demo agent showcasing Environment and Skills use case.\",\n",
" \"base_environment\": {\n",
" \"type\": \"remote\",\n",
" \"sources\": [\n",
" {\n",
" \"type\": \"gcs\",\n",
" \"source\": \"gs://polong-sandbox-bucket\",\n",
" \"target\": \".agent/skills\"\n",
" }\n",
" ],\n",
" \"network\": {\n",
" \"allowlist\": [\n",
" {\n",
" \"domain\": \"*\"\n",
" }\n",
" ]\n",
" }\n",
" },\n",
" \"base_agent\": \"antigravity-preview-05-2026\",\n",
" \"object\": \"agent\"\n",
"}\n"
]
}
],
"source": [
"update_payload = \"\"\"{\n",
" \"system_instruction\": \"You are a helpful coding assistant. You should always use available tools when relevant.\"\n",
"}\"\"\"\n",
"\n",
"with open(\"update_payload.json\", \"w\") as f:\n",
" f.write(update_payload)\n",
"\n",
"print(f\"Updating agent {AGENT_ID}...\")\n",
"!curl -X PATCH \\\n",
" \"https://aiplatform.googleapis.com/v1beta1/projects/$PROJECT_ID/locations/$LOCATION/agents/$AGENT_ID?update_mask=system_instruction\" \\\n",
" -H \"Authorization: Bearer $TOKEN\" \\\n",
" -H \"Content-Type: application/json\" \\\n",
" -d @update_payload.json"
]
},
{
"cell_type": "markdown",
"id": "a27b8d3a",
"metadata": {},
"source": [
"### 5. Delete Agent\n",
"\n",
"Delete the custom agent when you are done."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2a06dde1",
"metadata": {},
"outputs": [],
"source": [
"print(f\"Deleting agent {AGENT_ID}...\")\n",
"!curl -X DELETE \\\n",
" \"https://aiplatform.googleapis.com/v1beta1/projects/$PROJECT_ID/locations/$LOCATION/agents/$AGENT_ID\" \\\n",
" -H \"Authorization: Bearer $TOKEN\""
]
},
{
"cell_type": "markdown",
"id": "41e8ce3f",
"metadata": {},
"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"
]
},
{
"cell_type": "markdown",
"id": "7be3a5b6",
"metadata": {},
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7401fb2f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Interacting with agent...\n",
"event: interaction.created\n",
"data: {\"interaction\":{\"id\":\"ChAxZjE3NWZhZDIyNTRkZmVhEAgaAzI3NSoEbWFpbg\",\"status\":\"in_progress\",\"object\":\"interaction\"},\"event_type\":\"interaction.created\"}\n",
"\n",
"event: interaction.status_update\n",
"data: {\"interaction_id\":\"ChAxZjE3NWZhZDIyNTRkZmVhEAgaAzI3NSoEbWFpbg\",\"status\":\"in_progress\",\"event_type\":\"interaction.status_update\"}\n",
"\n",
"event: step.start\n",
"data: {\"index\":0,\"step\":{\"id\":\"d35bfe13-cfa5-40f4-9531-0a54fdfc57d9\",\"type\":\"function_call\",\"name\":\"run_command\",\"arguments\":{}},\"event_type\":\"step.start\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":0,\"delta\":{\"arguments\":\"{\\\"toolSummary\\\":\\\"Python execution demonstration\\\",\\\"toolAction\\\":\\\"Running Python command\\\",\\\"CommandLine\\\":\\\"python3 -c \\\\\\\"import sys; print(f'Hello from Python {sys.version}!')\\\\\\\"\\\",\\\"WaitMsBeforeAsync\\\":5000,\\\"Cwd\\\":\\\"/workspace\\\",\\\"explanation\\\":\\\"Executed a Python command to demonstrate the capability to run Python code.\\\"}\",\"type\":\"arguments_delta\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.stop\n",
"data: {\"index\":0,\"event_type\":\"step.stop\"}\n",
"\n",
"event: step.start\n",
"data: {\"index\":1,\"step\":{\"call_id\":\"d35bfe13-cfa5-40f4-9531-0a54fdfc57d9\",\"signature\":\"\",\"type\":\"function_result\",\"name\":\"run_command\"},\"event_type\":\"step.start\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":1,\"delta\":{\"name\":\"run_command\",\"is_error\":false,\"type\":\"function_result\",\"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}},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.stop\n",
"data: {\"index\":1,\"event_type\":\"step.stop\"}\n",
"\n",
"event: step.start\n",
"data: {\"index\":2,\"step\":{\"type\":\"model_output\"},\"event_type\":\"step.start\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\"I am Antigravity, an AI assistant built by Google. Yes\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\", I can run Python code directly in my environment. \\n\\nHere is an example of running a simple Python script:\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\"\\n\\n```bash\\n$ python3 -c \\\"import sys; print(f'Hello from Python {sys.version}!')\\\"\\nHello\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\" from Python 3.11.15 (main, Mar 3 2026, 0\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\"9:26:23) [GCC 11.4.0]!\\n```\\n\\n### Summary of work\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\"\\n- Introduced myself.\\n- Demonstrated Python execution capabilities.\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.stop\n",
"data: {\"index\":2,\"event_type\":\"step.stop\"}\n",
"\n",
"event: interaction.completed\n",
"data: {\"interaction\":{\"id\":\"ChAxZjE3NWZhZDIyNTRkZmVhEAgaAzI3NSoEbWFpbg\",\"status\":\"completed\",\"usage\":{\"total_tokens\":14330,\"total_input_tokens\":13216,\"input_tokens_by_modality\":[{\"modality\":\"text\",\"tokens\":13216}],\"total_output_tokens\":250,\"output_tokens_by_modality\":[{\"modality\":\"text\",\"tokens\":250}],\"total_thought_tokens\":864},\"created\":\"2026-05-19T19:13:20Z\",\"updated\":\"2026-05-19T19:13:20Z\",\"environment_id\":\"env_CAEQgICAgIDQyIcuGiA5ZGVmMGE0ZTc2ZTk0MjA1OTM1ZjM0OGNjYjgxMjQxNA\",\"object\":\"interaction\"},\"event_type\":\"interaction.completed\"}\n",
"\n",
"event: done\n",
"data: [DONE]\n",
"\n"
]
}
],
"source": [
"interaction_payload = \"\"\"{\n",
" \"stream\": true,\n",
" \"background\": true,\n",
" \"store\": true,\n",
" \"agent\": \"antigravity-preview-05-2026\",\n",
" \"environment\": {\"type\": \"remote\"},\n",
" \"input\": [\n",
" {\n",
" \"type\": \"user_input\",\n",
" \"content\": [\n",
" {\n",
" \"type\": \"text\",\n",
" \"text\": \"Who are you, can you execute python code? Show me an example.\"\n",
" }\n",
" ]\n",
" }\n",
" ]\n",
"}\"\"\"\n",
"\n",
"print(\"interaction_payload:\")\n",
"print(interaction_payload)\n",
"\n",
"with open(\"interaction_payload.json\", \"w\") as f:\n",
" f.write(interaction_payload)\n",
"\n",
"print(\"Interacting with agent...\")\n",
"!curl -X POST \\\n",
" \"https://aiplatform.googleapis.com/v1beta1/projects/$PROJECT_ID/locations/$LOCATION/interactions\" \\\n",
" -H \"Authorization: Bearer $TOKEN\" \\\n",
" -H \"Content-Type: application/json\" \\\n",
" -H \"Api-Revision: 2026-05-20\" \\\n",
" -d @interaction_payload.json"
]
},
{
"cell_type": "markdown",
"id": "22b0d540",
"metadata": {},
"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."
]
},
{
"cell_type": "code",
"execution_count": 30,
"id": "bc33b299",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"interaction_payload:\n",
"{\n",
" \"stream\": true,\n",
" \"background\": true,\n",
" \"store\": true,\n",
" \"agent\": \"my-demo-agent\",\n",
" \"environment\": {\"type\": \"remote\"},\n",
" \"input\": [\n",
" {\n",
" \"type\": \"user_input\",\n",
" \"content\": [\n",
" {\n",
" \"type\": \"text\",\n",
" \"text\": \"Who are you, can you execute python code? Show me an example.\"\n",
" }\n",
" ]\n",
" }\n",
" ]\n",
"}\n",
"Interacting with agent...\n",
"event: interaction.created\n",
"data: {\"interaction\":{\"id\":\"ChA2M2U5NjA2Y2E5YmFlMDJiEAgaAzBhYSoEbWFpbg\",\"status\":\"in_progress\",\"object\":\"interaction\"},\"event_type\":\"interaction.created\"}\n",
"\n",
"event: interaction.status_update\n",
"data: {\"interaction_id\":\"ChA2M2U5NjA2Y2E5YmFlMDJiEAgaAzBhYSoEbWFpbg\",\"status\":\"in_progress\",\"event_type\":\"interaction.status_update\"}\n",
"\n",
"event: step.start\n",
"data: {\"index\":0,\"step\":{\"id\":\"e9749919-988b-4ceb-9dd6-efc3cfa43444\",\"type\":\"function_call\",\"name\":\"run_command\",\"arguments\":{}},\"event_type\":\"step.start\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":0,\"delta\":{\"arguments\":\"{\\\"WaitMsBeforeAsync\\\":5000,\\\"Cwd\\\":\\\"/workspace\\\",\\\"toolSummary\\\":\\\"Run Python command\\\",\\\"toolAction\\\":\\\"Running python3 command\\\",\\\"CommandLine\\\":\\\"python3 -c \\\\\\\"import sys; print(f'Python version: {sys.version}'); print('Hello, I am Antigravity! I can run Python code.')\\\\\\\"\\\",\\\"explanation\\\":\\\"Executed a simple inline Python command to demonstrate capability and print the Python version.\\\"}\",\"type\":\"arguments_delta\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.stop\n",
"data: {\"index\":0,\"event_type\":\"step.stop\"}\n",
"\n",
"event: step.start\n",
"data: {\"index\":1,\"step\":{\"call_id\":\"e9749919-988b-4ceb-9dd6-efc3cfa43444\",\"signature\":\"\",\"type\":\"function_result\",\"name\":\"run_command\"},\"event_type\":\"step.start\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":1,\"delta\":{\"name\":\"run_command\",\"is_error\":false,\"type\":\"function_result\",\"result\":{\"ExitCode\":0,\"Output\":\"[STDOUT]\\nPython version: 3.11.15 (main, Mar 3 2026, 09:26:23) [GCC 11.4.0]\\nHello, I am Antigravity! I can run Python code.\\n\\n\\n[STDERR]\\n\"}},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.stop\n",
"data: {\"index\":1,\"event_type\":\"step.stop\"}\n",
"\n",
"event: step.start\n",
"data: {\"index\":2,\"step\":{\"type\":\"model_output\"},\"event_type\":\"step.start\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\"I am Antigravity, a powerful AI assistant designed by Google. \\n\\nYes, I can execute Python code!\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\" Here is an example of running a Python snippet directly in this environment:\\n\\n```python\\nimport sys\\n\\nprint(f\\\"Python version:\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\" {sys.version}\\\")\\nprint(\\\"Hello, I am Antigravity! I can run Python code.\\\")\\n\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\"```\\n\\n**Output:**\\n```\\nPython version: 3.11.15 (main, Mar 3\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\" 2026, 09:26:23)\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.delta\n",
"data: {\"index\":2,\"delta\":{\"text\":\" [GCC 11.4.0]\\nHello, I am Antigravity! I can run Python code.\\n```\",\"type\":\"text\"},\"event_type\":\"step.delta\"}\n",
"\n",
"event: step.stop\n",
"data: {\"index\":2,\"event_type\":\"step.stop\"}\n",
"\n",
"event: interaction.completed\n",
"data: {\"interaction\":{\"id\":\"ChA2M2U5NjA2Y2E5YmFlMDJiEAgaAzBhYSoEbWFpbg\",\"status\":\"completed\",\"usage\":{\"total_tokens\":15084,\"total_input_tokens\":14240,\"input_tokens_by_modality\":[{\"modality\":\"text\",\"tokens\":14240}],\"total_output_tokens\":281,\"output_tokens_by_modality\":[{\"modality\":\"text\",\"tokens\":281}],\"total_thought_tokens\":563},\"created\":\"2026-05-19T19:35:07Z\",\"updated\":\"2026-05-19T19:35:07Z\",\"environment_id\":\"env_CAEQgICAgIDQyIcuGiA1NmNmNmUwNTlmZGY0NjI0OTJhOWY4MGQzMGQ3Nzk2Yw\",\"object\":\"interaction\"},\"event_type\":\"interaction.completed\"}\n",
"\n",
"event: done\n",
"data: [DONE]\n",
"\n"
]
}
],
"source": [
"interaction_payload = f\"\"\"{{\n",
" \"stream\": true,\n",
" \"background\": true,\n",
" \"store\": true,\n",
" \"agent\": \"{AGENT_ID}\",\n",
" \"environment\": {{\"type\": \"remote\"}},\n",
" \"input\": [\n",
" {{\n",
" \"type\": \"user_input\",\n",
" \"content\": [\n",
" {{\n",
" \"type\": \"text\",\n",
" \"text\": \"Who are you, can you execute python code? Show me an example.\"\n",
" }}\n",
" ]\n",
" }}\n",
" ]\n",
"}}\"\"\"\n",
"\n",
"print(\"interaction_payload:\")\n",
"print(interaction_payload)\n",
"\n",
"with open(\"interaction_payload.json\", \"w\") as f:\n",
" f.write(interaction_payload)\n",
"\n",
"print(\"Interacting with agent...\")\n",
"!curl -X POST \\\n",
" \"https://aiplatform.googleapis.com/v1beta1/projects/$PROJECT_ID/locations/$LOCATION/interactions\" \\\n",
" -H \"Authorization: Bearer $TOKEN\" \\\n",
" -H \"Content-Type: application/json\" \\\n",
" -H \"Api-Revision: 2026-05-20\" \\\n",
" -d @interaction_payload.json"
]
},
{
"cell_type": "markdown",
"id": "715e5730",
"metadata": {},
"source": [
"---\n",
"## Cleanup\n",
"\n",
"Delete the test agents we created. Agent configurations persist until explicitly deleted.\n"
]
},
{
"cell_type": "markdown",
"id": "f781f152",
"metadata": {},
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "883b2ff4",
"metadata": {},
"outputs": [],
"source": [
"for agent_id_to_delete in [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'}\")"
]
},
{
"cell_type": "markdown",
"id": "32531dee",
"metadata": {},
"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": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}