chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
# A2A OAuth Authentication Sample Agent
|
||||
|
||||
This sample demonstrates the **Agent-to-Agent (A2A)** architecture with **OAuth Authentication** workflows in the Agent Development Kit (ADK). The sample implements a multi-agent system where a remote agent can surface OAuth authentication requests to the local agent, which then guides the end user through the OAuth flow before returning the authentication credentials to the remote agent for API access.
|
||||
|
||||
## Overview
|
||||
|
||||
The A2A OAuth Authentication sample consists of:
|
||||
|
||||
- **Root Agent** (`root_agent`): The main orchestrator that handles user requests and delegates tasks to specialized agents
|
||||
- **YouTube Search Agent** (`youtube_search_agent`): A local agent that handles YouTube video searches using LangChain tools
|
||||
- **BigQuery Agent** (`bigquery_agent`): A remote A2A agent that manages BigQuery operations and requires OAuth authentication for Google Cloud access
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌────────────────────┐ ┌──────────────────┐
|
||||
│ End User │───▶│ Root Agent │───▶│ BigQuery Agent │
|
||||
│ (OAuth Flow) │ │ (Local) │ │ (Remote A2A) │
|
||||
│ │ │ │ │ (localhost:8001) │
|
||||
│ OAuth UI │◀───│ │◀───│ OAuth Request │
|
||||
└─────────────────┘ └────────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. **Multi-Agent Architecture**
|
||||
|
||||
- Root agent coordinates between local YouTube search and remote BigQuery operations
|
||||
- Demonstrates hybrid local/remote agent workflows
|
||||
- Seamless task delegation based on user request types
|
||||
|
||||
### 2. **OAuth Authentication Workflow**
|
||||
|
||||
- Remote BigQuery agent surfaces OAuth authentication requests to the root agent
|
||||
- Root agent guides end users through Google OAuth flow for BigQuery access
|
||||
- Secure token exchange between agents for authenticated API calls
|
||||
|
||||
### 3. **Google Cloud Integration**
|
||||
|
||||
- BigQuery toolset with comprehensive dataset and table management capabilities
|
||||
- OAuth-protected access to user's Google Cloud BigQuery resources
|
||||
- Support for listing, creating, and managing datasets and tables
|
||||
|
||||
### 4. **LangChain Tool Integration**
|
||||
|
||||
- YouTube search functionality using LangChain community tools
|
||||
- Demonstrates integration of third-party tools in agent workflows
|
||||
|
||||
## Setup and Usage
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **Set up OAuth Credentials**:
|
||||
|
||||
```bash
|
||||
export OAUTH_CLIENT_ID=your_google_oauth_client_id
|
||||
export OAUTH_CLIENT_SECRET=your_google_oauth_client_secret
|
||||
```
|
||||
|
||||
1. **Start the Remote BigQuery Agent server**:
|
||||
|
||||
```bash
|
||||
# Start the remote a2a server that serves the BigQuery agent on port 8001
|
||||
adk api_server --a2a --port 8001 contributing/samples/a2a_auth/remote_a2a
|
||||
```
|
||||
|
||||
1. **Run the Main Agent**:
|
||||
|
||||
```bash
|
||||
# In a separate terminal, run the adk web server
|
||||
adk web contributing/samples/
|
||||
```
|
||||
|
||||
### Example Interactions
|
||||
|
||||
Once both services are running, you can interact with the root agent:
|
||||
|
||||
**YouTube Search (No Authentication Required):**
|
||||
|
||||
```
|
||||
User: Search for 3 Taylor Swift music videos
|
||||
Agent: I'll help you search for Taylor Swift music videos on YouTube.
|
||||
[Agent delegates to YouTube Search Agent]
|
||||
Agent: I found 3 Taylor Swift music videos:
|
||||
1. "Anti-Hero" - Official Music Video
|
||||
2. "Shake It Off" - Official Music Video
|
||||
3. "Blank Space" - Official Music Video
|
||||
```
|
||||
|
||||
**BigQuery Operations (OAuth Required):**
|
||||
|
||||
```
|
||||
User: List my BigQuery datasets
|
||||
Agent: I'll help you access your BigQuery datasets. This requires authentication with your Google account.
|
||||
[Agent delegates to BigQuery Agent]
|
||||
Agent: To access your BigQuery data, please complete the OAuth authentication.
|
||||
[OAuth flow initiated - user redirected to Google authentication]
|
||||
User: [Completes OAuth flow in browser]
|
||||
Agent: Authentication successful! Here are your BigQuery datasets:
|
||||
- dataset_1: Customer Analytics
|
||||
- dataset_2: Sales Data
|
||||
- dataset_3: Marketing Metrics
|
||||
```
|
||||
|
||||
**Dataset Management:**
|
||||
|
||||
```
|
||||
User: Show me details for my Customer Analytics dataset
|
||||
Agent: I'll get the details for your Customer Analytics dataset.
|
||||
[Using existing OAuth token]
|
||||
Agent: Customer Analytics Dataset Details:
|
||||
- Created: 2024-01-15
|
||||
- Location: US
|
||||
- Tables: 5
|
||||
- Description: Customer behavior and analytics data
|
||||
```
|
||||
|
||||
## Code Structure
|
||||
|
||||
### Main Agent (`agent.py`)
|
||||
|
||||
- **`youtube_search_agent`**: Local agent with LangChain YouTube search tool
|
||||
- **`bigquery_agent`**: Remote A2A agent configuration for BigQuery operations
|
||||
- **`root_agent`**: Main orchestrator with task delegation logic
|
||||
|
||||
### Remote BigQuery Agent (`remote_a2a/bigquery_agent/`)
|
||||
|
||||
- **`agent.py`**: Implementation of the BigQuery agent with OAuth toolset
|
||||
- **`agent.json`**: Agent card of the A2A agent
|
||||
- **`BigQueryToolset`**: OAuth-enabled tools for BigQuery dataset and table management
|
||||
|
||||
## OAuth Authentication Workflow
|
||||
|
||||
The OAuth authentication process follows this pattern:
|
||||
|
||||
1. **Initial Request**: User requests BigQuery operation through root agent
|
||||
1. **Delegation**: Root agent delegates to remote BigQuery agent
|
||||
1. **Auth Check**: BigQuery agent checks for valid OAuth token
|
||||
1. **Auth Request**: If no token, agent surfaces OAuth request to root agent
|
||||
1. **User OAuth**: Root agent guides user through Google OAuth flow
|
||||
1. **Token Exchange**: Root agent sends OAuth token to BigQuery agent
|
||||
1. **API Call**: BigQuery agent uses token to make authenticated API calls
|
||||
1. **Result Return**: BigQuery agent returns results through root agent to user
|
||||
|
||||
## Supported BigQuery Operations
|
||||
|
||||
The BigQuery agent supports the following operations:
|
||||
|
||||
### Dataset Operations:
|
||||
|
||||
- **List Datasets**: `bigquery_datasets_list` - Get all user's datasets
|
||||
- **Get Dataset**: `bigquery_datasets_get` - Get specific dataset details
|
||||
- **Create Dataset**: `bigquery_datasets_insert` - Create new dataset
|
||||
|
||||
### Table Operations:
|
||||
|
||||
- **List Tables**: `bigquery_tables_list` - Get tables in a dataset
|
||||
- **Get Table**: `bigquery_tables_get` - Get specific table details
|
||||
- **Create Table**: `bigquery_tables_insert` - Create new table in dataset
|
||||
|
||||
## Extending the Sample
|
||||
|
||||
You can extend this sample by:
|
||||
|
||||
- Adding more Google Cloud services (Cloud Storage, Compute Engine, etc.)
|
||||
- Implementing token refresh and expiration handling
|
||||
- Adding role-based access control for different BigQuery operations
|
||||
- Creating OAuth flows for other providers (Microsoft, Facebook, etc.)
|
||||
- Adding audit logging for authentication events
|
||||
- Implementing multi-tenant OAuth token management
|
||||
|
||||
## Deployment to Other Environments
|
||||
|
||||
When deploying the remote BigQuery A2A agent to different environments (e.g., Cloud Run, different hosts/ports), you **must** update the `url` field in the agent card JSON file:
|
||||
|
||||
### Local Development
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "http://localhost:8001/a2a/bigquery_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Cloud Run Example
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-bigquery-service-abc123-uc.a.run.app/a2a/bigquery_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Host/Port Example
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-domain.com:9000/a2a/bigquery_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The `url` field in `remote_a2a/bigquery_agent/agent.json` must point to the actual RPC endpoint where your remote BigQuery A2A agent is deployed and accessible.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
|
||||
- Ensure the local ADK web server is running on port 8000
|
||||
- Ensure the remote A2A server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- **Verify the `url` field in `remote_a2a/bigquery_agent/agent.json` matches the actual deployed location of your remote A2A server**
|
||||
- Verify the agent card URL passed to RemoteA2AAgent constructor matches the running A2A server
|
||||
|
||||
**OAuth Issues:**
|
||||
|
||||
- Verify OAuth client ID and secret are correctly set in .env file
|
||||
- Ensure OAuth redirect URIs are properly configured in Google Cloud Console
|
||||
- Check that the OAuth scopes include BigQuery access permissions
|
||||
- Verify the user has access to the BigQuery projects/datasets
|
||||
|
||||
**BigQuery Access Issues:**
|
||||
|
||||
- Ensure the authenticated user has BigQuery permissions
|
||||
- Check that the Google Cloud project has BigQuery API enabled
|
||||
- Verify dataset and table names are correct and accessible
|
||||
- Check for quota limits on BigQuery API calls
|
||||
|
||||
**Agent Communication Issues:**
|
||||
|
||||
- Check the logs for both the local ADK web server and remote A2A server
|
||||
- Verify OAuth tokens are properly passed between agents
|
||||
- Ensure agent instructions are clear about authentication requirements
|
||||
- **Double-check that the RPC URL in the agent.json file is correct and accessible**
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,61 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.agents.remote_a2a_agent import AGENT_CARD_WELL_KNOWN_PATH
|
||||
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
|
||||
from google.adk.tools.langchain_tool import LangchainTool
|
||||
from langchain_community.tools.youtube.search import YouTubeSearchTool
|
||||
|
||||
# Instantiate the tool
|
||||
langchain_yt_tool = YouTubeSearchTool()
|
||||
|
||||
# Wrap the tool in the LangchainTool class from ADK
|
||||
adk_yt_tool = LangchainTool(
|
||||
tool=langchain_yt_tool,
|
||||
)
|
||||
|
||||
youtube_search_agent = Agent(
|
||||
name="youtube_search_agent",
|
||||
instruction="""
|
||||
Ask customer to provide singer name, and the number of videos to search.
|
||||
""",
|
||||
description="Help customer to search for a video on Youtube.",
|
||||
tools=[adk_yt_tool],
|
||||
output_key="youtube_search_output",
|
||||
)
|
||||
|
||||
bigquery_agent = RemoteA2aAgent(
|
||||
name="bigquery_agent",
|
||||
description="Help customer to manage notion workspace.",
|
||||
agent_card=(
|
||||
f"http://localhost:8001/a2a/bigquery_agent{AGENT_CARD_WELL_KNOWN_PATH}"
|
||||
),
|
||||
)
|
||||
|
||||
root_agent = Agent(
|
||||
name="root_agent",
|
||||
instruction="""
|
||||
You are a helpful assistant that can help search youtube videos, look up BigQuery datasets and tables.
|
||||
You delegate youtube search tasks to the youtube_search_agent.
|
||||
You delegate BigQuery tasks to the bigquery_agent.
|
||||
Always clarify the results before proceeding.
|
||||
""",
|
||||
global_instruction=(
|
||||
"You are a helpful assistant that can help search youtube videos, look"
|
||||
" up BigQuery datasets and tables."
|
||||
),
|
||||
sub_agents=[youtube_search_agent, bigquery_agent],
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"capabilities": {},
|
||||
"defaultInputModes": [
|
||||
"text/plain"
|
||||
],
|
||||
"defaultOutputModes": [
|
||||
"application/json"
|
||||
],
|
||||
"description": "A Google BigQuery agent that helps manage users' data on Google BigQuery. Can list, get, and create datasets, as well as manage tables within datasets. Supports OAuth authentication for secure access to BigQuery resources.",
|
||||
"name": "bigquery_agent",
|
||||
"skills": [
|
||||
{
|
||||
"id": "dataset_management",
|
||||
"name": "Dataset Management",
|
||||
"description": "List, get details, and create BigQuery datasets",
|
||||
"tags": [
|
||||
"bigquery",
|
||||
"datasets",
|
||||
"google-cloud"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "table_management",
|
||||
"name": "Table Management",
|
||||
"description": "List, get details, and create BigQuery tables within datasets",
|
||||
"tags": [
|
||||
"bigquery",
|
||||
"tables",
|
||||
"google-cloud"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "oauth_authentication",
|
||||
"name": "OAuth Authentication",
|
||||
"description": "Secure authentication with Google BigQuery using OAuth",
|
||||
"tags": [
|
||||
"authentication",
|
||||
"oauth",
|
||||
"security"
|
||||
]
|
||||
}
|
||||
],
|
||||
"url": "http://localhost:8001/a2a/bigquery_agent",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import os
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from google.adk import Agent
|
||||
from google.adk.tools.google_api_tool import BigQueryToolset
|
||||
|
||||
# Load environment variables from .env file
|
||||
load_dotenv()
|
||||
|
||||
# Access the variable
|
||||
oauth_client_id = os.getenv("OAUTH_CLIENT_ID")
|
||||
oauth_client_secret = os.getenv("OAUTH_CLIENT_SECRET")
|
||||
tools_to_expose = [
|
||||
"bigquery_datasets_list",
|
||||
"bigquery_datasets_get",
|
||||
"bigquery_datasets_insert",
|
||||
"bigquery_tables_list",
|
||||
"bigquery_tables_get",
|
||||
"bigquery_tables_insert",
|
||||
]
|
||||
bigquery_toolset = BigQueryToolset(
|
||||
client_id=oauth_client_id,
|
||||
client_secret=oauth_client_secret,
|
||||
tool_filter=tools_to_expose,
|
||||
)
|
||||
|
||||
root_agent = Agent(
|
||||
name="bigquery_agent",
|
||||
instruction="""
|
||||
You are a helpful Google BigQuery agent that help to manage users' data on Google BigQuery.
|
||||
Use the provided tools to conduct various operations on users' data in Google BigQuery.
|
||||
|
||||
Scenario 1:
|
||||
The user wants to query their bigquery datasets
|
||||
Use bigquery_datasets_list to query user's datasets
|
||||
|
||||
Scenario 2:
|
||||
The user wants to query the details of a specific dataset
|
||||
Use bigquery_datasets_get to get a dataset's details
|
||||
|
||||
Scenario 3:
|
||||
The user wants to create a new dataset
|
||||
Use bigquery_datasets_insert to create a new dataset
|
||||
|
||||
Scenario 4:
|
||||
The user wants to query their tables in a specific dataset
|
||||
Use bigquery_tables_list to list all tables in a dataset
|
||||
|
||||
Scenario 5:
|
||||
The user wants to query the details of a specific table
|
||||
Use bigquery_tables_get to get a table's details
|
||||
|
||||
Scenario 6:
|
||||
The user wants to insert a new table into a dataset
|
||||
Use bigquery_tables_insert to insert a new table into a dataset
|
||||
|
||||
Current user:
|
||||
<User>
|
||||
{userInfo?}
|
||||
</User>
|
||||
""",
|
||||
tools=[bigquery_toolset],
|
||||
)
|
||||
@@ -0,0 +1,165 @@
|
||||
# A2A Basic Sample Agent
|
||||
|
||||
This sample demonstrates the **Agent-to-Agent (A2A)** architecture in the Agent Development Kit (ADK), showcasing how multiple agents can work together to handle complex tasks. The sample implements an agent that can roll dice and check if numbers are prime.
|
||||
|
||||
## Overview
|
||||
|
||||
The A2A Basic sample consists of:
|
||||
|
||||
- **Root Agent** (`root_agent`): The main orchestrator that delegates tasks to specialized sub-agents
|
||||
- **Roll Agent** (`roll_agent`): A local sub-agent that handles dice rolling operations
|
||||
- **Prime Agent** (`prime_agent`): A remote A2A agent that checks if numbers are prime, this agent is running on a separate A2A server
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌──────────────────┐ ┌────────────────────┐
|
||||
│ Root Agent │───▶│ Roll Agent │ │ Remote Prime │
|
||||
│ (Local) │ │ (Local) │ │ Agent │
|
||||
│ │ │ │ │ (localhost:8001) │
|
||||
│ │───▶│ │◀───│ │
|
||||
└─────────────────┘ └──────────────────┘ └────────────────────┘
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. **Local Sub-Agent Integration**
|
||||
|
||||
- The `roll_agent` demonstrates how to create and integrate local sub-agents
|
||||
- Handles dice rolling with configurable number of sides
|
||||
- Uses a simple function tool (`roll_die`) for random number generation
|
||||
|
||||
### 2. **Remote A2A Agent Integration**
|
||||
|
||||
- The `prime_agent` shows how to connect to remote agent services
|
||||
- Communicates with a separate service via HTTP at `http://localhost:8001/a2a/check_prime_agent`
|
||||
- Demonstrates cross-service agent communication
|
||||
|
||||
### 3. **Agent Orchestration**
|
||||
|
||||
- The root agent intelligently delegates tasks based on user requests
|
||||
- Can chain operations (e.g., "roll a die and check if it's prime")
|
||||
- Provides clear workflow coordination between multiple agents
|
||||
|
||||
### 4. **Example Tool Integration**
|
||||
|
||||
- Includes an `ExampleTool` with sample interactions for context
|
||||
- Helps the agent understand expected behavior patterns
|
||||
|
||||
## Setup and Usage
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **Start the Remote Prime Agent server**:
|
||||
|
||||
```bash
|
||||
# Start the remote a2a server that serves the check prime agent on port 8001
|
||||
adk api_server --a2a --port 8001 contributing/samples/a2a_basic/remote_a2a
|
||||
```
|
||||
|
||||
1. **Run the Main Agent**:
|
||||
|
||||
```bash
|
||||
# In a separate terminal, run the adk web server
|
||||
adk web contributing/samples/
|
||||
```
|
||||
|
||||
### Example Interactions
|
||||
|
||||
Once both services are running, you can interact with the root agent:
|
||||
|
||||
**Simple Dice Rolling:**
|
||||
|
||||
```
|
||||
User: Roll a 6-sided die
|
||||
Bot: I rolled a 4 for you.
|
||||
```
|
||||
|
||||
**Prime Number Checking:**
|
||||
|
||||
```
|
||||
User: Is 7 a prime number?
|
||||
Bot: Yes, 7 is a prime number.
|
||||
```
|
||||
|
||||
**Combined Operations:**
|
||||
|
||||
```
|
||||
User: Roll a 10-sided die and check if it's prime
|
||||
Bot: I rolled an 8 for you.
|
||||
Bot: 8 is not a prime number.
|
||||
```
|
||||
|
||||
## Code Structure
|
||||
|
||||
### Main Agent (`agent.py`)
|
||||
|
||||
- **`roll_die(sides: int)`**: Function tool for rolling dice
|
||||
- **`roll_agent`**: Local agent specialized in dice rolling
|
||||
- **`prime_agent`**: Remote A2A agent configuration
|
||||
- **`root_agent`**: Main orchestrator with delegation logic
|
||||
|
||||
### Remote Prime Agent (`remote_a2a/check_prime_agent/`)
|
||||
|
||||
- **`agent.py`**: Implementation of the prime checking service
|
||||
- **`agent.json`**: Agent card of the A2A agent
|
||||
- **`check_prime(nums: list[int])`**: Prime number checking algorithm
|
||||
|
||||
## Extending the Sample
|
||||
|
||||
You can extend this sample by:
|
||||
|
||||
- Adding more mathematical operations (factorization, square roots, etc.)
|
||||
- Creating additional remote agent
|
||||
- Implementing more complex delegation logic
|
||||
- Adding persistent state management
|
||||
- Integrating with external APIs or databases
|
||||
|
||||
## Deployment to Other Environments
|
||||
|
||||
When deploying the remote A2A agent to different environments (e.g., Cloud Run, different hosts/ports), you **must** update the `url` field in the agent card JSON file:
|
||||
|
||||
### Local Development
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "http://localhost:8001/a2a/check_prime_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Cloud Run Example
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-service-abc123-uc.a.run.app/a2a/check_prime_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Host/Port Example
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-domain.com:9000/a2a/check_prime_agent",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The `url` field in `remote_a2a/check_prime_agent/agent.json` must point to the actual RPC endpoint where your remote A2A agent is deployed and accessible.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
|
||||
- Ensure the local ADK web server is running on port 8000
|
||||
- Ensure the remote A2A server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- **Verify the `url` field in `remote_a2a/check_prime_agent/agent.json` matches the actual deployed location of your remote A2A server**
|
||||
- Verify the agent card URL passed to RemoteA2AAgent constructor matches the running A2A server
|
||||
|
||||
**Agent Not Responding:**
|
||||
|
||||
- Check the logs for both the local ADK web server on port 8000 and remote A2A server on port 8001
|
||||
- Verify the agent instructions are clear and unambiguous
|
||||
- **Double-check that the RPC URL in the agent.json file is correct and accessible**
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
Executable
+120
@@ -0,0 +1,120 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import random
|
||||
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.agents.remote_a2a_agent import AGENT_CARD_WELL_KNOWN_PATH
|
||||
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
|
||||
from google.adk.tools.example_tool import ExampleTool
|
||||
from google.genai import types
|
||||
|
||||
|
||||
# --- Roll Die Sub-Agent ---
|
||||
def roll_die(sides: int) -> int:
|
||||
"""Roll a die and return the rolled result."""
|
||||
return random.randint(1, sides)
|
||||
|
||||
|
||||
roll_agent = Agent(
|
||||
name="roll_agent",
|
||||
description="Handles rolling dice of different sizes.",
|
||||
instruction="""
|
||||
You are responsible for rolling dice based on the user's request.
|
||||
When asked to roll a die, you must call the roll_die tool with the number of sides as an integer.
|
||||
""",
|
||||
tools=[roll_die],
|
||||
generate_content_config=types.GenerateContentConfig(
|
||||
safety_settings=[
|
||||
types.SafetySetting( # avoid false alarm about rolling dice.
|
||||
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
||||
threshold=types.HarmBlockThreshold.OFF,
|
||||
),
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
example_tool = ExampleTool([
|
||||
{
|
||||
"input": {
|
||||
"role": "user",
|
||||
"parts": [{"text": "Roll a 6-sided die."}],
|
||||
},
|
||||
"output": [
|
||||
{"role": "model", "parts": [{"text": "I rolled a 4 for you."}]}
|
||||
],
|
||||
},
|
||||
{
|
||||
"input": {
|
||||
"role": "user",
|
||||
"parts": [{"text": "Is 7 a prime number?"}],
|
||||
},
|
||||
"output": [{
|
||||
"role": "model",
|
||||
"parts": [{"text": "Yes, 7 is a prime number."}],
|
||||
}],
|
||||
},
|
||||
{
|
||||
"input": {
|
||||
"role": "user",
|
||||
"parts": [{"text": "Roll a 10-sided die and check if it's prime."}],
|
||||
},
|
||||
"output": [
|
||||
{
|
||||
"role": "model",
|
||||
"parts": [{"text": "I rolled an 8 for you."}],
|
||||
},
|
||||
{
|
||||
"role": "model",
|
||||
"parts": [{"text": "8 is not a prime number."}],
|
||||
},
|
||||
],
|
||||
},
|
||||
])
|
||||
|
||||
prime_agent = RemoteA2aAgent(
|
||||
name="prime_agent",
|
||||
description="Agent that handles checking if numbers are prime.",
|
||||
agent_card=(
|
||||
f"http://localhost:8001/a2a/check_prime_agent{AGENT_CARD_WELL_KNOWN_PATH}"
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name="root_agent",
|
||||
instruction="""
|
||||
You are a helpful assistant that can roll dice and check if numbers are prime.
|
||||
You delegate rolling dice tasks to the roll_agent and prime checking tasks to the prime_agent.
|
||||
Follow these steps:
|
||||
1. If the user asks to roll a die, delegate to the roll_agent.
|
||||
2. If the user asks to check primes, delegate to the prime_agent.
|
||||
3. If the user asks to roll a die and then check if the result is prime, call roll_agent first, then pass the result to prime_agent.
|
||||
Always clarify the results before proceeding.
|
||||
""",
|
||||
global_instruction=(
|
||||
"You are DicePrimeBot, ready to roll dice and check prime numbers."
|
||||
),
|
||||
sub_agents=[roll_agent, prime_agent],
|
||||
tools=[example_tool],
|
||||
generate_content_config=types.GenerateContentConfig(
|
||||
safety_settings=[
|
||||
types.SafetySetting( # avoid false alarm about rolling dice.
|
||||
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
||||
threshold=types.HarmBlockThreshold.OFF,
|
||||
),
|
||||
]
|
||||
),
|
||||
)
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"capabilities": {},
|
||||
"defaultInputModes": [
|
||||
"text/plain"
|
||||
],
|
||||
"defaultOutputModes": [
|
||||
"application/json"
|
||||
],
|
||||
"description": "An agent specialized in checking whether numbers are prime. It can efficiently determine the primality of individual numbers or lists of numbers.",
|
||||
"name": "check_prime_agent",
|
||||
"skills": [
|
||||
{
|
||||
"id": "prime_checking",
|
||||
"name": "Prime Number Checking",
|
||||
"description": "Check if numbers in a list are prime using efficient mathematical algorithms",
|
||||
"tags": [
|
||||
"mathematical",
|
||||
"computation",
|
||||
"prime",
|
||||
"numbers"
|
||||
]
|
||||
}
|
||||
],
|
||||
"url": "http://localhost:8001/a2a/check_prime_agent",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import random
|
||||
|
||||
from google.adk import Agent
|
||||
from google.adk.tools.tool_context import ToolContext
|
||||
from google.genai import types
|
||||
|
||||
|
||||
async def check_prime(nums: list[int]) -> str:
|
||||
"""Check if a given list of numbers are prime.
|
||||
|
||||
Args:
|
||||
nums: The list of numbers to check.
|
||||
|
||||
Returns:
|
||||
A str indicating which number is prime.
|
||||
"""
|
||||
primes = set()
|
||||
for number in nums:
|
||||
number = int(number)
|
||||
if number <= 1:
|
||||
continue
|
||||
is_prime = True
|
||||
for i in range(2, int(number**0.5) + 1):
|
||||
if number % i == 0:
|
||||
is_prime = False
|
||||
break
|
||||
if is_prime:
|
||||
primes.add(number)
|
||||
return (
|
||||
'No prime numbers found.'
|
||||
if not primes
|
||||
else f"{', '.join(str(num) for num in primes)} are prime numbers."
|
||||
)
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name='check_prime_agent',
|
||||
description='check prime agent that can check whether numbers are prime.',
|
||||
instruction="""
|
||||
You check whether numbers are prime.
|
||||
When checking prime numbers, call the check_prime tool with a list of integers. Be sure to pass in a list of integers. You should never pass in a string.
|
||||
You should not rely on the previous history on prime results.
|
||||
""",
|
||||
tools=[
|
||||
check_prime,
|
||||
],
|
||||
# planner=BuiltInPlanner(
|
||||
# thinking_config=types.ThinkingConfig(
|
||||
# include_thoughts=True,
|
||||
# ),
|
||||
# ),
|
||||
generate_content_config=types.GenerateContentConfig(
|
||||
safety_settings=[
|
||||
types.SafetySetting( # avoid false alarm about rolling dice.
|
||||
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
||||
threshold=types.HarmBlockThreshold.OFF,
|
||||
),
|
||||
]
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,195 @@
|
||||
# A2A Human-in-the-Loop Sample Agent
|
||||
|
||||
This sample demonstrates the **Agent-to-Agent (A2A)** architecture with **Human-in-the-Loop** workflows in the Agent Development Kit (ADK). The sample implements a reimbursement processing agent that automatically handles small expenses while requiring remote agent to process for larger amounts. The remote agent will require a human approval for large amounts, thus surface this request to local agent and human interacting with local agent can approve the request.
|
||||
|
||||
## Overview
|
||||
|
||||
The A2A Human-in-the-Loop sample consists of:
|
||||
|
||||
- **Root Agent** (`root_agent`): The main reimbursement agent that handles expense requests and delegates approval to remote Approval Agent for large amounts
|
||||
- **Approval Agent** (`approval_agent`): A remote A2A agent that handles the human approval process via long-running tools (which implements asynchronous approval workflows that can pause execution and wait for human input), this agent is running on a separate A2A server
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌────────────────────┐ ┌──────────────────┐
|
||||
│ Human Manager │───▶│ Root Agent │───▶│ Approval Agent │
|
||||
│ (External) │ │ (Local) │ │ (Remote A2A) │
|
||||
│ │ │ │ │ (localhost:8001) │
|
||||
│ Approval UI │◀───│ │◀───│ │
|
||||
└─────────────────┘ └────────────────────┘ └──────────────────┘
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. **Automated Decision Making**
|
||||
|
||||
- Automatically approves reimbursements under $100
|
||||
- Uses business logic to determine when human intervention is required
|
||||
- Provides immediate responses for simple cases
|
||||
|
||||
### 2. **Human-in-the-Loop Workflow**
|
||||
|
||||
- Seamlessly escalates high-value requests (>$100) to remote approval agent
|
||||
- Remote approval agent uses long-running tools to surface approval requests back to the root agent
|
||||
- Human managers interact directly with the root agent to approve/reject requests
|
||||
|
||||
### 3. **Long-Running Tool Integration**
|
||||
|
||||
- Demonstrates `LongRunningFunctionTool` for asynchronous operations
|
||||
- Shows how to handle pending states and external updates
|
||||
- Implements proper tool response handling for delayed approvals
|
||||
|
||||
### 4. **Remote A2A Agent Communication**
|
||||
|
||||
- The approval agent runs as a separate service that processes approval workflows
|
||||
- Communicates via HTTP at `http://localhost:8001/a2a/human_in_loop`
|
||||
- Surfaces approval requests back to the root agent for human interaction
|
||||
|
||||
## Setup and Usage
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **Start the Remote Approval Agent server**:
|
||||
|
||||
```bash
|
||||
# Start the remote a2a server that serves the human-in-the-loop approval agent on port 8001
|
||||
adk api_server --a2a --port 8001 contributing/samples/a2a/a2a_human_in_loop/remote_a2a
|
||||
```
|
||||
|
||||
1. **Run the Main Agent**:
|
||||
|
||||
```bash
|
||||
# In a separate terminal, run the adk web server
|
||||
adk web contributing/samples/a2a
|
||||
```
|
||||
|
||||
### Example Interactions
|
||||
|
||||
Once both services are running, you can interact with the root agent through the approval workflow:
|
||||
|
||||
**Automatic Approval (Under $100):**
|
||||
|
||||
```
|
||||
User: Please reimburse $50 for meals
|
||||
Agent: I'll process your reimbursement request for $50 for meals. Since this amount is under $100, I can approve it automatically.
|
||||
Agent: ✅ Reimbursement approved and processed: $50 for meals
|
||||
```
|
||||
|
||||
**Human Approval Required (Over $100):**
|
||||
|
||||
```
|
||||
User: Please reimburse $200 for conference travel
|
||||
Agent: I'll process your reimbursement request for $200 for conference travel. Since this amount exceeds $100, I need to get manager approval.
|
||||
Agent: 🔄 Request submitted for approval (Ticket: reimbursement-ticket-001). Please wait for manager review.
|
||||
[Human manager approves the pending request from the ADK Web UI]
|
||||
Agent: ✅ Great news! Your reimbursement has been approved by the manager. Processing $200 for conference travel.
|
||||
```
|
||||
|
||||
> **Approving from the ADK Web UI:** The approval is a *long-running tool* call
|
||||
> that runs on the remote approval agent. The pending call is surfaced in the
|
||||
> Web UI as a function call awaiting a response. To approve (or reject), hover
|
||||
> over the pending `ask_for_approval` function response in the UI and use
|
||||
> **"Send another response"** to send back an updated response such as
|
||||
> `{"status": "approved", "ticketId": "reimbursement-ticket-001"}`. Simply
|
||||
> typing "I approve" as a chat message will **not** resume the pending request,
|
||||
> because the framework needs a `FunctionResponse` that carries the same call
|
||||
> `id` to resume the long-running tool.
|
||||
>
|
||||
> For this resume to be routed back to the remote approval agent (rather than
|
||||
> restarting at the root agent), the sample is exposed as an `App` with
|
||||
> `ResumabilityConfig(is_resumable=True)` in `agent.py`.
|
||||
|
||||
## Code Structure
|
||||
|
||||
### Main Agent (`agent.py`)
|
||||
|
||||
- **`reimburse(purpose: str, amount: float)`**: Function tool for processing reimbursements
|
||||
- **`approval_agent`**: Remote A2A agent configuration for human approval workflows
|
||||
- **`root_agent`**: Main reimbursement agent with automatic/manual approval logic
|
||||
|
||||
### Remote Approval Agent (`remote_a2a/human_in_loop/`)
|
||||
|
||||
- **`agent.py`**: Implementation of the approval agent with long-running tools
|
||||
|
||||
- **`agent.json`**: Agent card of the A2A agent
|
||||
|
||||
- **`ask_for_approval()`**: Long-running tool that handles approval requests
|
||||
|
||||
## Long-Running Tool Workflow
|
||||
|
||||
The human-in-the-loop process follows this pattern:
|
||||
|
||||
1. **Initial Call**: Root agent delegates approval request to remote approval agent for amounts >$100
|
||||
1. **Pending Response**: Remote approval agent returns immediate response with `status: "pending"` and ticket ID and surface the approval request to root agent
|
||||
1. **Agent Acknowledgment**: Root agent informs user about pending approval status
|
||||
1. **Human Interaction**: Human manager interacts with root agent to review and approve/reject the request
|
||||
1. **Updated Response**: Root agent receives updated tool response with approval decision and send it to remote agent
|
||||
1. **Final Action**: Remote agent processes the approval and completes the reimbursement and send the result to root_agent
|
||||
|
||||
## Extending the Sample
|
||||
|
||||
You can extend this sample by:
|
||||
|
||||
- Adding more complex approval hierarchies (multiple approval levels)
|
||||
- Implementing different approval rules based on expense categories
|
||||
- Creating additional remote agent for budget checking or policy validation
|
||||
- Adding notification systems for approval status updates
|
||||
- Integrating with external approval systems or databases
|
||||
- Implementing approval timeouts and escalation procedures
|
||||
|
||||
## Deployment to Other Environments
|
||||
|
||||
When deploying the remote approval A2A agent to different environments (e.g., Cloud Run, different hosts/ports), you **must** update the `url` field in the agent card JSON file:
|
||||
|
||||
### Local Development
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "http://localhost:8001/a2a/human_in_loop",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Cloud Run Example
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-approval-service-abc123-uc.a.run.app/a2a/human_in_loop",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Host/Port Example
|
||||
|
||||
```json
|
||||
{
|
||||
"url": "https://your-domain.com:9000/a2a/human_in_loop",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
**Important:** The `url` field in `remote_a2a/human_in_loop/agent.json` must point to the actual RPC endpoint where your remote approval A2A agent is deployed and accessible.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
|
||||
- Ensure the local ADK web server is running on port 8000
|
||||
- Ensure the remote A2A server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- **Verify the `url` field in `remote_a2a/human_in_loop/agent.json` matches the actual deployed location of your remote A2A server**
|
||||
- Verify the agent card URL passed to RemoteA2AAgent constructor matches the running A2A server
|
||||
|
||||
**Agent Not Responding:**
|
||||
|
||||
- Check the logs for both the local ADK web server on port 8000 and remote A2A server on port 8001
|
||||
- Verify the agent instructions are clear and unambiguous
|
||||
- Ensure long-running tool responses are properly formatted with matching IDs
|
||||
- **Double-check that the RPC URL in the agent.json file is correct and accessible**
|
||||
|
||||
**Approval Workflow Issues:**
|
||||
|
||||
- Verify that updated tool responses use the same `id` and `name` as the original function call
|
||||
- Check that the approval status is correctly updated in the tool response
|
||||
- Ensure the human approval process is properly simulated or integrated
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,68 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.agents.remote_a2a_agent import AGENT_CARD_WELL_KNOWN_PATH
|
||||
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
|
||||
from google.adk.apps import App
|
||||
from google.adk.apps import ResumabilityConfig
|
||||
from google.genai import types
|
||||
|
||||
|
||||
def reimburse(purpose: str, amount: float) -> str:
|
||||
"""Reimburse the amount of money to the employee."""
|
||||
return {
|
||||
'status': 'ok',
|
||||
}
|
||||
|
||||
|
||||
approval_agent = RemoteA2aAgent(
|
||||
name='approval_agent',
|
||||
description='Help approve the reimburse if the amount is greater than 100.',
|
||||
agent_card=(
|
||||
f'http://localhost:8001/a2a/human_in_loop{AGENT_CARD_WELL_KNOWN_PATH}'
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name='reimbursement_agent',
|
||||
instruction="""
|
||||
You are an agent whose job is to handle the reimbursement process for
|
||||
the employees. If the amount is less than $100, you will automatically
|
||||
approve the reimbursement. And call reimburse() to reimburse the amount to the employee.
|
||||
|
||||
If the amount is greater than $100. You will hand over the request to
|
||||
approval_agent to handle the reimburse.
|
||||
""",
|
||||
tools=[reimburse],
|
||||
sub_agents=[approval_agent],
|
||||
generate_content_config=types.GenerateContentConfig(temperature=0.1),
|
||||
)
|
||||
|
||||
# The human-in-the-loop approval runs as a long-running tool on the remote
|
||||
# approval_agent. When the manager approves (or rejects) the request, the ADK
|
||||
# Web UI sends back a FunctionResponse for that pending long-running call. For
|
||||
# the next turn to be routed back to the (remote) approval_agent so it can
|
||||
# resume the paused tool instead of restarting at the root reimbursement_agent,
|
||||
# the app must be resumable. Without this, the confirmation is delivered to the
|
||||
# root agent, which has no pending call, and nothing happens (see issue #5871).
|
||||
app = App(
|
||||
name='a2a_human_in_loop',
|
||||
root_agent=root_agent,
|
||||
resumability_config=ResumabilityConfig(
|
||||
is_resumable=True,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,45 @@
|
||||
{
|
||||
"capabilities": {},
|
||||
"defaultInputModes": [
|
||||
"text/plain"
|
||||
],
|
||||
"defaultOutputModes": [
|
||||
"application/json"
|
||||
],
|
||||
"description": "A reimbursement agent that handles employee expense reimbursement requests. Automatically approves amounts under $100 and requires manager approval for larger amounts using long-running tools for human-in-the-loop workflows.",
|
||||
"name": "reimbursement_agent",
|
||||
"skills": [
|
||||
{
|
||||
"id": "automatic_reimbursement",
|
||||
"name": "Automatic Reimbursement",
|
||||
"description": "Automatically process and approve reimbursements under $100",
|
||||
"tags": [
|
||||
"reimbursement",
|
||||
"automation",
|
||||
"finance"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "approval_workflow",
|
||||
"name": "Approval Workflow",
|
||||
"description": "Request manager approval for reimbursements over $100 using long-running tools",
|
||||
"tags": [
|
||||
"approval",
|
||||
"workflow",
|
||||
"human-in-loop"
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "expense_processing",
|
||||
"name": "Expense Processing",
|
||||
"description": "Process employee expense claims and handle reimbursement logic",
|
||||
"tags": [
|
||||
"expenses",
|
||||
"processing",
|
||||
"employee-services"
|
||||
]
|
||||
}
|
||||
],
|
||||
"url": "http://localhost:8001/a2a/human_in_loop",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from typing import Any
|
||||
|
||||
from google.adk import Agent
|
||||
from google.adk.tools.long_running_tool import LongRunningFunctionTool
|
||||
from google.adk.tools.tool_context import ToolContext
|
||||
from google.genai import types
|
||||
|
||||
|
||||
def reimburse(purpose: str, amount: float) -> str:
|
||||
"""Reimburse the amount of money to the employee."""
|
||||
return {
|
||||
'status': 'ok',
|
||||
}
|
||||
|
||||
|
||||
def ask_for_approval(
|
||||
purpose: str, amount: float, tool_context: ToolContext
|
||||
) -> dict[str, Any]:
|
||||
"""Ask for approval for the reimbursement."""
|
||||
return {
|
||||
'status': 'pending',
|
||||
'amount': amount,
|
||||
'ticketId': 'reimbursement-ticket-001',
|
||||
}
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name='reimbursement_agent',
|
||||
instruction="""
|
||||
You are an agent whose job is to handle the reimbursement process for
|
||||
the employees. If the amount is less than $100, you will automatically
|
||||
approve the reimbursement.
|
||||
|
||||
If the amount is greater than $100, you will
|
||||
ask for approval from the manager. If the manager approves, you will
|
||||
call reimburse() to reimburse the amount to the employee. If the manager
|
||||
rejects, you will inform the employee of the rejection.
|
||||
""",
|
||||
tools=[reimburse, LongRunningFunctionTool(func=ask_for_approval)],
|
||||
generate_content_config=types.GenerateContentConfig(temperature=0.1),
|
||||
)
|
||||
@@ -0,0 +1,134 @@
|
||||
# A2A Root Sample Agent
|
||||
|
||||
This sample demonstrates how to use a **remote Agent-to-Agent (A2A) agent as the root agent** in the Agent Development Kit (ADK). This is a simplified approach where the main agent is actually a remote A2A service, also showcasing how to run remote agents using uvicorn command.
|
||||
|
||||
## Overview
|
||||
|
||||
The A2A Root sample consists of:
|
||||
|
||||
- **Root Agent** (`agent.py`): A remote A2A agent proxy as root agent that talks to a remote a2a agent running on a separate server
|
||||
- **Remote Hello World Agent** (`remote_a2a/hello_world/agent.py`): The actual agent implementation that handles dice rolling and prime number checking running on remote server
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌────────────────────┐
|
||||
│ Root Agent │───▶│ Remote Hello │
|
||||
│ (RemoteA2aAgent)│ │ World Agent │
|
||||
│ (localhost:8000)│ │ (localhost:8001) │
|
||||
└─────────────────┘ └────────────────────┘
|
||||
```
|
||||
|
||||
## Key Features
|
||||
|
||||
### 1. **Remote A2A as Root Agent**
|
||||
|
||||
- The `root_agent` is a `RemoteA2aAgent` that connects to a remote A2A service
|
||||
- Demonstrates how to use remote agents as the primary agent instead of local agents
|
||||
- Shows the flexibility of the A2A architecture for distributed agent deployment
|
||||
|
||||
### 2. **Uvicorn Server Deployment**
|
||||
|
||||
- The remote agent is served using uvicorn, a lightweight ASGI server
|
||||
- Demonstrates a simple way to deploy A2A agents without using the ADK CLI
|
||||
- Shows how to expose A2A agents as standalone web services
|
||||
|
||||
### 3. **Agent Functionality**
|
||||
|
||||
- **Dice Rolling**: Can roll dice with configurable number of sides
|
||||
- **Prime Number Checking**: Can check if numbers are prime
|
||||
- **State Management**: Maintains roll history in tool context
|
||||
- **Parallel Tool Execution**: Can use multiple tools in parallel
|
||||
|
||||
### 4. **Simple Deployment Pattern**
|
||||
|
||||
- Uses the `to_a2a()` utility to convert a standard ADK agent to an A2A service
|
||||
- Minimal configuration required for remote agent deployment
|
||||
|
||||
## Setup and Usage
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. **Start the Remote A2A Agent server**:
|
||||
|
||||
```bash
|
||||
# Start the remote agent using uvicorn
|
||||
uvicorn contributing.samples.a2a_root.remote_a2a.hello_world.agent:a2a_app --host localhost --port 8001
|
||||
```
|
||||
|
||||
1. **Run the Main Agent**:
|
||||
|
||||
```bash
|
||||
# In a separate terminal, run the adk web server
|
||||
adk web contributing/samples/
|
||||
```
|
||||
|
||||
### Example Interactions
|
||||
|
||||
Once both services are running, you can interact with the root agent:
|
||||
|
||||
**Simple Dice Rolling:**
|
||||
|
||||
```
|
||||
User: Roll a 6-sided die
|
||||
Bot: I rolled a 4 for you.
|
||||
```
|
||||
|
||||
**Prime Number Checking:**
|
||||
|
||||
```
|
||||
User: Is 7 a prime number?
|
||||
Bot: Yes, 7 is a prime number.
|
||||
```
|
||||
|
||||
**Combined Operations:**
|
||||
|
||||
```
|
||||
User: Roll a 10-sided die and check if it's prime
|
||||
Bot: I rolled an 8 for you.
|
||||
Bot: 8 is not a prime number.
|
||||
```
|
||||
|
||||
**Multiple Rolls with Prime Checking:**
|
||||
|
||||
```
|
||||
User: Roll a die 3 times and check which results are prime
|
||||
Bot: I rolled a 3 for you.
|
||||
Bot: I rolled a 7 for you.
|
||||
Bot: I rolled a 4 for you.
|
||||
Bot: 3, 7 are prime numbers.
|
||||
```
|
||||
|
||||
## Code Structure
|
||||
|
||||
### Root Agent (`agent.py`)
|
||||
|
||||
- **`root_agent`**: A `RemoteA2aAgent` that connects to the remote A2A service
|
||||
- **Agent Card URL**: Points to the well-known agent card endpoint on the remote server
|
||||
|
||||
### Remote Hello World Agent (`remote_a2a/hello_world/agent.py`)
|
||||
|
||||
- **`roll_die(sides: int)`**: Function tool for rolling dice with state management
|
||||
- **`check_prime(nums: list[int])`**: Async function for prime number checking
|
||||
- **`root_agent`**: The main agent with comprehensive instructions
|
||||
- **`a2a_app`**: The A2A application created using `to_a2a()` utility
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Connection Issues:**
|
||||
|
||||
- Ensure the uvicorn server is running on port 8001
|
||||
- Check that no firewall is blocking localhost connections
|
||||
- Verify the agent card URL in the root agent configuration
|
||||
- Check uvicorn logs for any startup errors
|
||||
|
||||
**Agent Not Responding:**
|
||||
|
||||
- Check the uvicorn server logs for errors
|
||||
- Verify the agent instructions are clear and unambiguous
|
||||
- Ensure the A2A app is properly configured with the correct port
|
||||
|
||||
**Uvicorn Issues:**
|
||||
|
||||
- Make sure the module path is correct: `contributing.samples.a2a_root.remote_a2a.hello_world.agent:a2a_app`
|
||||
- Check that all dependencies are installed
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from google.adk.agents.remote_a2a_agent import AGENT_CARD_WELL_KNOWN_PATH
|
||||
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
|
||||
|
||||
root_agent = RemoteA2aAgent(
|
||||
name="hello_world_agent",
|
||||
description=(
|
||||
"Helpful assistant that can roll dice and check if numbers are prime."
|
||||
),
|
||||
agent_card=f"http://localhost:8001/{AGENT_CARD_WELL_KNOWN_PATH}",
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,110 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import random
|
||||
|
||||
from google.adk import Agent
|
||||
from google.adk.a2a.utils.agent_to_a2a import to_a2a
|
||||
from google.adk.tools.tool_context import ToolContext
|
||||
from google.genai import types
|
||||
|
||||
|
||||
def roll_die(sides: int, tool_context: ToolContext) -> int:
|
||||
"""Roll a die and return the rolled result.
|
||||
|
||||
Args:
|
||||
sides: The integer number of sides the die has.
|
||||
tool_context: the tool context
|
||||
Returns:
|
||||
An integer of the result of rolling the die.
|
||||
"""
|
||||
result = random.randint(1, sides)
|
||||
if not 'rolls' in tool_context.state:
|
||||
tool_context.state['rolls'] = []
|
||||
|
||||
tool_context.state['rolls'] = tool_context.state['rolls'] + [result]
|
||||
return result
|
||||
|
||||
|
||||
async def check_prime(nums: list[int]) -> str:
|
||||
"""Check if a given list of numbers are prime.
|
||||
|
||||
Args:
|
||||
nums: The list of numbers to check.
|
||||
|
||||
Returns:
|
||||
A str indicating which number is prime.
|
||||
"""
|
||||
primes = set()
|
||||
for number in nums:
|
||||
number = int(number)
|
||||
if number <= 1:
|
||||
continue
|
||||
is_prime = True
|
||||
for i in range(2, int(number**0.5) + 1):
|
||||
if number % i == 0:
|
||||
is_prime = False
|
||||
break
|
||||
if is_prime:
|
||||
primes.add(number)
|
||||
return (
|
||||
'No prime numbers found.'
|
||||
if not primes
|
||||
else f"{', '.join(str(num) for num in primes)} are prime numbers."
|
||||
)
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name='hello_world_agent',
|
||||
description=(
|
||||
'hello world agent that can roll a dice of 8 sides and check prime'
|
||||
' numbers.'
|
||||
),
|
||||
instruction="""
|
||||
You roll dice and answer questions about the outcome of the dice rolls.
|
||||
You can roll dice of different sizes.
|
||||
You can use multiple tools in parallel by calling functions in parallel(in one request and in one round).
|
||||
It is ok to discuss previous dice roles, and comment on the dice rolls.
|
||||
When you are asked to roll a die, you must call the roll_die tool with the number of sides. Be sure to pass in an integer. Do not pass in a string.
|
||||
You should never roll a die on your own.
|
||||
When checking prime numbers, call the check_prime tool with a list of integers. Be sure to pass in a list of integers. You should never pass in a string.
|
||||
You should not check prime numbers before calling the tool.
|
||||
When you are asked to roll a die and check prime numbers, you should always make the following two function calls:
|
||||
1. You should first call the roll_die tool to get a roll. Wait for the function response before calling the check_prime tool.
|
||||
2. After you get the function response from roll_die tool, you should call the check_prime tool with the roll_die result.
|
||||
2.1 If user asks you to check primes based on previous rolls, make sure you include the previous rolls in the list.
|
||||
3. When you respond, you must include the roll_die result from step 1.
|
||||
You should always perform the previous 3 steps when asking for a roll and checking prime numbers.
|
||||
You should not rely on the previous history on prime results.
|
||||
""",
|
||||
tools=[
|
||||
roll_die,
|
||||
check_prime,
|
||||
],
|
||||
# planner=BuiltInPlanner(
|
||||
# thinking_config=types.ThinkingConfig(
|
||||
# include_thoughts=True,
|
||||
# ),
|
||||
# ),
|
||||
generate_content_config=types.GenerateContentConfig(
|
||||
safety_settings=[
|
||||
types.SafetySetting( # avoid false alarm about rolling dice.
|
||||
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
||||
threshold=types.HarmBlockThreshold.OFF,
|
||||
),
|
||||
]
|
||||
),
|
||||
)
|
||||
|
||||
a2a_app = to_a2a(root_agent, port=8001)
|
||||
Reference in New Issue
Block a user