Skip to content

Commit def0f3e

Browse files
PierrickVouletpierrick
andauthored
feat: add vertex ai sample (#2623)
Co-authored-by: pierrick <pierrick@google.com>
1 parent 9cdd28d commit def0f3e

File tree

8 files changed

+5972
-11
lines changed

8 files changed

+5972
-11
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Enterprise AI Agent (local)
2+
3+
**Note:** This project is part of the official Google Codelabs [Integrate Vertex AI Agents with Google Workspace](https://codelabs.developers.google.com/vertexai-agents-gws).
4+
5+
This sample contains a specialized Enterprise Agent built using the Google Agent Development Kit (ADK). This agent acts as an Enterprise AI Assistant by querying user's data corpus using the Vertex AI Search MCP toolset and sending Chat messages to DM spaces using a custom Function tool & Google Chat API.
6+
7+
## Key Features
8+
9+
1. **Dynamic Vertex AI Serving Configs:**
10+
The agent automatically discovers your project's `default_collection` engine and dynamically binds its queries to the `default_serving_config`.
11+
12+
2. **Static Authentication (`ACCESS_TOKEN`):**
13+
The client (e.g. ADK Web) passes an authentication token in the `ACCESS_TOKEN` environment variable. This agent extracts the token at runtime to securely execute calls using a Bearer token.
14+
15+
3. **Graceful Timeouts:**
16+
The `McpToolset` streaming components have been intentionally configured with an explicit 15-second `timeout` and `sse_read_timeout` to prevent the agent from hanging infinitely on backend network issues.
17+
18+
4. **Google Chat Integration:**
19+
The agent natively includes a `send_direct_message` tool powered by the `google-apps-chat` SDK. This allows the AI to immediately send direct messages to users inside Google Chat. It seamlessly reuses the same authentication token extracted from the `ACCESS_TOKEN` environment variable.
20+
21+
## Deployment
22+
23+
The agent requires a valid OAuth access token to authenticate with Google APIs (Vertex AI Search, Google Chat).
24+
To set the `ACCESS_TOKEN` environment variable with a valid token, you must authenticate using a **Desktop app OAuth client**.
25+
26+
1. Download your Desktop app OAuth client JSON file (e.g., `client_secret.json`) in the root directory.
27+
2. Authenticate using `gcloud` with the client ID and required scopes:
28+
29+
```bash
30+
gcloud auth application-default login \
31+
--client-id-file=client_secret.json \
32+
--scopes=https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/chat.spaces,https://www.googleapis.com/auth/chat.messages
33+
```
34+
35+
3. Generate the access token and set the environment variable:
36+
37+
```bash
38+
export ACCESS_TOKEN=$(gcloud auth application-default print-access-token)
39+
```
40+
41+
4. Optionally, you can set the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` environment variables (defaults to current gcloud project and `us-central1`).
42+
43+
5. Deploy the agent locally using the ADK `web` command:
44+
45+
```bash
46+
adk web
47+
```
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from . import agent
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import google.auth
17+
from dotenv import load_dotenv
18+
load_dotenv()
19+
20+
from google.cloud import discoveryengine_v1
21+
from google.adk.agents.llm_agent import LlmAgent
22+
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset, StreamableHTTPConnectionParams
23+
from google.adk.tools import FunctionTool
24+
from google.apps import chat_v1
25+
from google.oauth2.credentials import Credentials
26+
27+
MODEL = "gemini-2.5-flash"
28+
29+
# Access token for authentication
30+
ACCESS_TOKEN = os.environ.get("ACCESS_TOKEN")
31+
if not ACCESS_TOKEN:
32+
raise ValueError("ACCESS_TOKEN environment variable must be set")
33+
34+
VERTEXAI_SEARCH_TIMEOUT = 15.0
35+
36+
def get_project_id():
37+
"""Fetches the consumer project ID from the environment natively."""
38+
_, project = google.auth.default()
39+
if project:
40+
return project
41+
raise Exception(f"Failed to resolve GCP Project ID from environment.")
42+
43+
def find_serving_config_path():
44+
"""Dynamically finds the default serving config in the engine."""
45+
project_id = get_project_id()
46+
engines = discoveryengine_v1.EngineServiceClient().list_engines(
47+
parent=f"projects/{project_id}/locations/global/collections/default_collection"
48+
)
49+
for engine in engines:
50+
# engine.name natively contains the numeric Project Number
51+
return f"{engine.name}/servingConfigs/default_serving_config"
52+
raise Exception(f"No Discovery Engines found in project {project_id}")
53+
54+
def send_direct_message(email: str, message: str) -> dict:
55+
"""Sends a Google Chat Direct Message (DM) to a specific user by email address."""
56+
chat_client = chat_v1.ChatServiceClient(
57+
credentials=Credentials(token=ACCESS_TOKEN)
58+
)
59+
60+
# 1. Setup the DM space or find existing one
61+
person = chat_v1.User(
62+
name=f"users/{email}",
63+
type_=chat_v1.User.Type.HUMAN
64+
)
65+
membership = chat_v1.Membership(member=person)
66+
space_req = chat_v1.Space(space_type=chat_v1.Space.SpaceType.DIRECT_MESSAGE)
67+
setup_request = chat_v1.SetUpSpaceRequest(
68+
space=space_req,
69+
memberships=[membership]
70+
)
71+
space_response = chat_client.set_up_space(request=setup_request)
72+
space_name = space_response.name
73+
74+
# 2. Send the message
75+
msg = chat_v1.Message(text=message)
76+
message_request = chat_v1.CreateMessageRequest(
77+
parent=space_name,
78+
message=msg
79+
)
80+
message_response = chat_client.create_message(request=message_request)
81+
82+
return {"status": "success", "message_id": message_response.name, "space": space_name}
83+
84+
vertexai_mcp = McpToolset(
85+
connection_params=StreamableHTTPConnectionParams(
86+
url="https://discoveryengine.googleapis.com/mcp",
87+
timeout=VERTEXAI_SEARCH_TIMEOUT,
88+
sse_read_timeout=VERTEXAI_SEARCH_TIMEOUT,
89+
headers={"Authorization": f"Bearer {ACCESS_TOKEN}"}
90+
),
91+
tool_filter=['search']
92+
)
93+
94+
# Answer nicely the following user queries:
95+
# - Please find my meetings for today, I need their titles and links
96+
# - What is the latest Drive file I created?
97+
# - What is the latest Gmail message I received?
98+
# - Please send the following message to someone@example.com: Hello, this is a test message.
99+
100+
root_agent = LlmAgent(
101+
model=MODEL,
102+
name='enterprise_ai',
103+
instruction=f"""
104+
You are a helpful assistant that always uses the Vertex AI MCP search tool to answer the user's message, unless the user asks you to send a message to someone.
105+
If the user asks you to send a message to someone, use the send_direct_message tool to send the message.
106+
You MUST unconditionally use the Vertex AI MCP search tool to find answer, even if you believe you already know the answer or believe the Vertex AI MCP search tool does not contain the data.
107+
The Vertex AI MCP search tool accesses the user's data through datastores including Google Drive, Google Calendar, and Gmail.
108+
Only use the Vertex AI MCP search tool with servingConfig and query parameters, do not use any other parameters.
109+
Always use the servingConfig {find_serving_config_path()} while using the Vertex AI MCP search tool.
110+
""",
111+
tools=[vertexai_mcp, FunctionTool(send_direct_message)]
112+
)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Copyright 2026 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
google-adk (>=1.25.1,<2.0.0)
16+
google-cloud-aiplatform[adk,agent_engines] (>=1.126.1,<2.0.0)
17+
google-genai (>=1.9.0,<2.0.0)
18+
pydantic (>=2.10.6,<3.0.0)
19+
absl-py (>=2.2.1,<3.0.0)
20+
google-cloud-discoveryengine (>=0.13.12,<0.14.0)
21+
google-apps-chat (>=0.6.0,<0.7.0)

0 commit comments

Comments
 (0)