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

438 lines
17 KiB
Plaintext

{
"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": [
"# Building and Deploying a LangGraph Agent with Agent Engine in Vertex AI\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/gemini/agent-engine/tutorial_langgraph.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/vertex-ai/colab/import/https:%2F%2Fraw.githubusercontent.com%2FGoogleCloudPlatform%2Fgenerative-ai%2Fmain%2Fgemini%2Fagent-engine%2Ftutorial_langgraph.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/vertex-ai/workbench/deploy-notebook?download_url=https://raw.githubusercontent.com/GoogleCloudPlatform/generative-ai/main/gemini/agent-engine/tutorial_langgraph.ipynb\">\n",
" <img src=\"https://lh3.googleusercontent.com/UiNooY4LUgW_oTvpsNhPpQzsstV5W8F7rYgxgGBD85cWJoLmrOzhVs_ksK_vgx40SHs7jCqkTkCk=e14-rj-sc0xffffff-h130-w32\" alt=\"Vertex AI 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/gemini/agent-engine/tutorial_langgraph.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",
"<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/gemini/agent-engine/tutorial_langgraph.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/gemini/agent-engine/tutorial_langgraph.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/gemini/agent-engine/tutorial_langgraph.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/gemini/agent-engine/tutorial_langgraph.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/gemini/agent-engine/tutorial_langgraph.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> "
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "84f0f73a0f76"
},
"source": [
"| | |\n",
"|-|-|\n",
"| Author(s) | [Kristopher Overholt](https://github.com/koverholt), [Shawn Yang](https://github.com/shawn-yang-google) |"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "tvgnzT1CKxrO"
},
"source": [
"## Overview\n",
"\n",
"[Agent Engine](https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview) is a managed service that helps you to build and deploy agent frameworks. [LangGraph](https://langchain-ai.github.io/langgraph/) is a library for building stateful, multi-actor applications with LLMs, used to create agent and multi-agent workflows.\n",
"\n",
"This notebook demonstrates how to build, deploy, and test a LangGraph agent using [Agent Engine](https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview) in Vertex AI. You'll learn how to use the [LanggraphAgent template](https://cloud.google.com/agent-builder/agent-engine/develop/langgraph) in Agent Engine to deploy a LangGraph agent with custom tools.\n",
"\n",
"This notebook covers the following steps:\n",
"\n",
"- **Define a tool**: Create a custom Python function to act as a tool your AI agent can use.\n",
"- **Define a LangGraph agent**: Create a LangGraph agent using the Gemini model and the tool that you define.\n",
"- **Local testing**: Test your LangGraph agent locally to ensure functionality.\n",
"- **Deploy to Agent Engine**: Deploy your LangGraph agent to Agent Engine for scalable execution.\n",
"- **Remote testing**: Interact with your deployed agent through Agent Engine, testing its functionality in a production-like environment.\n",
"- **Clean up resources**: Delete your deployed agent on Agent Engine to avoid incurring unnecessary charges.\n",
"\n",
"By the end of this notebook, you'll have the skills and knowledge to build and deploy your own LangGraph agents using Agent Engine in Vertex AI."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "61RBz8LLbxCR"
},
"source": [
"## Get started"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "No17Cw5hgx12"
},
"source": [
"### Install Vertex AI SDK and extra packages"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"id": "tFy3H3aPgx12"
},
"outputs": [],
"source": [
"%pip install --upgrade --quiet \"google-cloud-aiplatform[agent_engines,langchain]\""
]
},
{
"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": "DF4l8DTdWgPY"
},
"source": [
"### Set Google Cloud project information and initialize Vertex AI SDK\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": null,
"metadata": {
"id": "Nqwi-5ufWp_B"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" # @param {type:\"string\"}\n",
"LOCATION = \"us-central1\" # @param {type:\"string\"}\n",
"STAGING_BUCKET = f\"gs://{PROJECT_ID}-agent-engine-staging\" # @param {type:\"string\"}\n",
"\n",
"import vertexai\n",
"\n",
"vertexai.init(project=PROJECT_ID, location=LOCATION)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "EdvJRUWRNGHE"
},
"source": [
"## Building and deploying a LangGraph agent on Agent Engine\n",
"\n",
"In the following sections, we'll walk through the process of building and deploying a LangGraph application using Agent Engine in Vertex AI."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "3b3004f33544"
},
"source": [
"### Import libraries\n",
"\n",
"Import the Vertex AI SDK libraries for Agent Engine."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"id": "67acfba81563"
},
"outputs": [],
"source": [
"import vertexai\n",
"from vertexai import agent_engines"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "94db54ba756b"
},
"source": [
"### Define a tool\n",
"\n",
"Define a custom Python function that acts as a tool in your LangGraph agent.\n",
"\n",
"In this case, you'll define a simple tool that returns a product description based on the product that the user asks about. In practice, you can write functions to call APIs, query databases, or any other tasks that you might want your agent to be able to use."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"id": "22981b2e1c59"
},
"outputs": [],
"source": [
"def get_product_details(product_name: str):\n",
" \"\"\"Gathers basic details about a product.\"\"\"\n",
" details = {\n",
" \"smartphone\": \"A cutting-edge smartphone with advanced camera features and lightning-fast processing.\",\n",
" \"coffee\": \"A rich, aromatic blend of ethically sourced coffee beans.\",\n",
" \"shoes\": \"High-performance running shoes designed for comfort, support, and speed.\",\n",
" \"headphones\": \"Wireless headphones with advanced noise cancellation technology for immersive audio.\",\n",
" \"speaker\": \"A voice-controlled smart speaker that plays music, sets alarms, and controls smart home devices.\",\n",
" }\n",
" return details.get(product_name, \"Product details not found.\")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d32ce189d989"
},
"source": [
"### Define LangGraph agent\n",
"\n",
"Define a LangGraph agent using the `LanggraphAgent` template in Agent Engine with the Gemini model and the tool that you defined."
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"id": "6eeff14856cd"
},
"outputs": [],
"source": [
"agent = agent_engines.LanggraphAgent(\n",
" model=\"gemini-2.5-flash\",\n",
" tools=[get_product_details],\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "be06c89a87aa"
},
"source": [
"### Local test\n",
"\n",
"In this section, you'll test your LangGraph agent locally to ensure that it behaves as expected before deployment."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"id": "6e2cb6d16e34"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Wireless headphones with advanced noise cancellation technology for immersive audio.\n"
]
}
],
"source": [
"response = agent.query(\n",
" input={\"messages\": [(\"user\", \"Get product details for headphones\")]}\n",
")\n",
"\n",
"print(response[\"messages\"][-1][\"kwargs\"][\"content\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5ccd4227e8c8"
},
"source": [
"### Deploy your LangGraph agent\n",
"\n",
"Now that you verified that your LangGraph agent is working locally, it's time to deploy it to Agent Engine! This will make your agent accessible remotely and allow you to integrate it into larger systems or provide it as a service."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dced52d8c524"
},
"outputs": [],
"source": [
"client = vertexai.Client(project=PROJECT_ID, location=LOCATION)\n",
"\n",
"remote_agent = client.agent_engines.create(\n",
" agent=agent,\n",
" config={\n",
" \"staging_bucket\": STAGING_BUCKET,\n",
" \"requirements\": [\n",
" \"google-cloud-aiplatform[agent_engines,langchain]\",\n",
" ],\n",
" \"display_name\": \"Agent Engine with LangGraph\",\n",
" \"description\": \"This is a sample custom application in Agent Engine that uses LangGraph\",\n",
" },\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "b876ca670960"
},
"source": [
"### Remote test\n",
"\n",
"Now that your LangGraph agent is running on Agent Engine, let's test it out by querying it in the remote environment:"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"id": "8836a18a41f1"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"High-performance running shoes designed for comfort, support, and speed.\n"
]
}
],
"source": [
"response = remote_agent.query(\n",
" input={\"messages\": [(\"user\", \"Get product details for shoes\")]}\n",
")\n",
"\n",
"print(response[\"messages\"][-1][\"kwargs\"][\"content\"])"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "2a4e033321ad"
},
"source": [
"## Cleaning up\n",
"\n",
"After you've finished experimenting, it's a good practice to clean up your cloud resources. You can delete the deployed Agent Engine instance and optionally remove the staging bucket to avoid any unexpected charges on your Google Cloud account."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "eb5fbfa43866"
},
"outputs": [],
"source": [
"# Delete the deployed agent\n",
"client.agent_engines.delete(name=remote_agent.api_resource.name)\n",
"\n",
"# Optionally, delete the staging bucket\n",
"# from google.cloud import storage\n",
"# storage.Client().bucket(STAGING_BUCKET.replace(\"gs://\", \"\")).delete(force=True)"
]
}
],
"metadata": {
"colab": {
"name": "tutorial_langgraph.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 0
}