Skip to content

Commit b2c2f1b

Browse files
seanzhougooglecopybara-github
authored andcommitted
chore: Add an a2a sample agent to demo running the a2a server via unvicorn command and run remote agent as root_agent
PiperOrigin-RevId: 785629271
1 parent a77d689 commit b2c2f1b

4 files changed

Lines changed: 273 additions & 0 deletions

File tree

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
# A2A Root Sample Agent
2+
3+
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.
4+
5+
## Overview
6+
7+
The A2A Root sample consists of:
8+
9+
- **Root Agent** (`agent.py`): A remote A2A agent proxy as root agent that talks to a remote a2a agent running on a separate server
10+
- **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
11+
12+
## Architecture
13+
14+
```
15+
┌─────────────────┐ ┌────────────────────┐
16+
│ Root Agent │───▶│ Remote Hello │
17+
│ (RemoteA2aAgent)│ │ World Agent │
18+
│ (localhost:8000)│ │ (localhost:8001) │
19+
└─────────────────┘ └────────────────────┘
20+
```
21+
22+
## Key Features
23+
24+
### 1. **Remote A2A as Root Agent**
25+
- The `root_agent` is a `RemoteA2aAgent` that connects to a remote A2A service
26+
- Demonstrates how to use remote agents as the primary agent instead of local agents
27+
- Shows the flexibility of the A2A architecture for distributed agent deployment
28+
29+
### 2. **Uvicorn Server Deployment**
30+
- The remote agent is served using uvicorn, a lightweight ASGI server
31+
- Demonstrates a simple way to deploy A2A agents without using the ADK CLI
32+
- Shows how to expose A2A agents as standalone web services
33+
34+
### 3. **Agent Functionality**
35+
- **Dice Rolling**: Can roll dice with configurable number of sides
36+
- **Prime Number Checking**: Can check if numbers are prime
37+
- **State Management**: Maintains roll history in tool context
38+
- **Parallel Tool Execution**: Can use multiple tools in parallel
39+
40+
### 4. **Simple Deployment Pattern**
41+
- Uses the `to_a2a()` utility to convert a standard ADK agent to an A2A service
42+
- Minimal configuration required for remote agent deployment
43+
44+
## Setup and Usage
45+
46+
### Prerequisites
47+
48+
1. **Start the Remote A2A Agent server**:
49+
```bash
50+
# Start the remote agent using uvicorn
51+
uvicorn contributing.samples.a2a_root.remote_a2a.hello_world.agent:a2a_app --host localhost --port 8001
52+
```
53+
54+
2. **Run the Main Agent**:
55+
```bash
56+
# In a separate terminal, run the adk web server
57+
adk web contributing/samples/
58+
```
59+
60+
### Example Interactions
61+
62+
Once both services are running, you can interact with the root agent:
63+
64+
**Simple Dice Rolling:**
65+
```
66+
User: Roll a 6-sided die
67+
Bot: I rolled a 4 for you.
68+
```
69+
70+
**Prime Number Checking:**
71+
```
72+
User: Is 7 a prime number?
73+
Bot: Yes, 7 is a prime number.
74+
```
75+
76+
**Combined Operations:**
77+
```
78+
User: Roll a 10-sided die and check if it's prime
79+
Bot: I rolled an 8 for you.
80+
Bot: 8 is not a prime number.
81+
```
82+
83+
**Multiple Rolls with Prime Checking:**
84+
```
85+
User: Roll a die 3 times and check which results are prime
86+
Bot: I rolled a 3 for you.
87+
Bot: I rolled a 7 for you.
88+
Bot: I rolled a 4 for you.
89+
Bot: 3, 7 are prime numbers.
90+
```
91+
92+
## Code Structure
93+
94+
### Root Agent (`agent.py`)
95+
96+
- **`root_agent`**: A `RemoteA2aAgent` that connects to the remote A2A service
97+
- **Agent Card URL**: Points to the well-known agent card endpoint on the remote server
98+
99+
### Remote Hello World Agent (`remote_a2a/hello_world/agent.py`)
100+
101+
- **`roll_die(sides: int)`**: Function tool for rolling dice with state management
102+
- **`check_prime(nums: list[int])`**: Async function for prime number checking
103+
- **`root_agent`**: The main agent with comprehensive instructions
104+
- **`a2a_app`**: The A2A application created using `to_a2a()` utility
105+
106+
107+
108+
## Troubleshooting
109+
110+
**Connection Issues:**
111+
- Ensure the uvicorn server is running on port 8001
112+
- Check that no firewall is blocking localhost connections
113+
- Verify the agent card URL in the root agent configuration
114+
- Check uvicorn logs for any startup errors
115+
116+
**Agent Not Responding:**
117+
- Check the uvicorn server logs for errors
118+
- Verify the agent instructions are clear and unambiguous
119+
- Ensure the A2A app is properly configured with the correct port
120+
121+
**Uvicorn Issues:**
122+
- Make sure the module path is correct: `contributing.samples.a2a_root.remote_a2a.hello_world.agent:a2a_app`
123+
- Check that all dependencies are installed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Copyright 2025 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 a2a.utils.constants import AGENT_CARD_WELL_KNOWN_PATH
16+
from google.adk.agents.remote_a2a_agent import RemoteA2aAgent
17+
18+
root_agent = RemoteA2aAgent(
19+
name="hello_world_agent",
20+
description=(
21+
"Helpful assistant that can roll dice and check if numbers are prime."
22+
),
23+
agent_card=f"http://localhost:8001/{AGENT_CARD_WELL_KNOWN_PATH}",
24+
)
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Copyright 2025 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: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Copyright 2025 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 random
16+
17+
from google.adk import Agent
18+
from google.adk.a2a.utils.agent_to_a2a import to_a2a
19+
from google.adk.tools.tool_context import ToolContext
20+
from google.genai import types
21+
22+
23+
def roll_die(sides: int, tool_context: ToolContext) -> int:
24+
"""Roll a die and return the rolled result.
25+
26+
Args:
27+
sides: The integer number of sides the die has.
28+
tool_context: the tool context
29+
Returns:
30+
An integer of the result of rolling the die.
31+
"""
32+
result = random.randint(1, sides)
33+
if not 'rolls' in tool_context.state:
34+
tool_context.state['rolls'] = []
35+
36+
tool_context.state['rolls'] = tool_context.state['rolls'] + [result]
37+
return result
38+
39+
40+
async def check_prime(nums: list[int]) -> str:
41+
"""Check if a given list of numbers are prime.
42+
43+
Args:
44+
nums: The list of numbers to check.
45+
46+
Returns:
47+
A str indicating which number is prime.
48+
"""
49+
primes = set()
50+
for number in nums:
51+
number = int(number)
52+
if number <= 1:
53+
continue
54+
is_prime = True
55+
for i in range(2, int(number**0.5) + 1):
56+
if number % i == 0:
57+
is_prime = False
58+
break
59+
if is_prime:
60+
primes.add(number)
61+
return (
62+
'No prime numbers found.'
63+
if not primes
64+
else f"{', '.join(str(num) for num in primes)} are prime numbers."
65+
)
66+
67+
68+
root_agent = Agent(
69+
model='gemini-2.0-flash',
70+
name='hello_world_agent',
71+
description=(
72+
'hello world agent that can roll a dice of 8 sides and check prime'
73+
' numbers.'
74+
),
75+
instruction="""
76+
You roll dice and answer questions about the outcome of the dice rolls.
77+
You can roll dice of different sizes.
78+
You can use multiple tools in parallel by calling functions in parallel(in one request and in one round).
79+
It is ok to discuss previous dice roles, and comment on the dice rolls.
80+
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.
81+
You should never roll a die on your own.
82+
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.
83+
You should not check prime numbers before calling the tool.
84+
When you are asked to roll a die and check prime numbers, you should always make the following two function calls:
85+
1. You should first call the roll_die tool to get a roll. Wait for the function response before calling the check_prime tool.
86+
2. After you get the function response from roll_die tool, you should call the check_prime tool with the roll_die result.
87+
2.1 If user asks you to check primes based on previous rolls, make sure you include the previous rolls in the list.
88+
3. When you respond, you must include the roll_die result from step 1.
89+
You should always perform the previous 3 steps when asking for a roll and checking prime numbers.
90+
You should not rely on the previous history on prime results.
91+
""",
92+
tools=[
93+
roll_die,
94+
check_prime,
95+
],
96+
# planner=BuiltInPlanner(
97+
# thinking_config=types.ThinkingConfig(
98+
# include_thoughts=True,
99+
# ),
100+
# ),
101+
generate_content_config=types.GenerateContentConfig(
102+
safety_settings=[
103+
types.SafetySetting( # avoid false alarm about rolling dice.
104+
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
105+
threshold=types.HarmBlockThreshold.OFF,
106+
),
107+
]
108+
),
109+
)
110+
111+
a2a_app = to_a2a(root_agent, port=8001)

0 commit comments

Comments
 (0)