1. खास जानकारी
इस कोडलैब में, आपको एक मल्टी-एजेंट सिस्टम बनाना है. इसमें कई एडीके एजेंट, Agent2Agent (A2A) प्रोटोकॉल का इस्तेमाल करके एक-दूसरे से कम्यूनिकेट करते हैं और साथ मिलकर काम करते हैं.
आपको क्या सीखने को मिलेगा
- ADK के एक से ज़्यादा इंडिपेंडेंट एजेंट बनाने का तरीका
- हर एजेंट को एजेंट कार्ड कैसे दें और उन्हें A2A सर्वर के तौर पर कैसे रैप करें
- रिमोट एजेंट को मैनेज करने वाला होस्ट एजेंट बनाने का तरीका
- रिमोट एजेंट कनेक्शन सेट अप करने का तरीका
- मल्टी-एजेंट सिस्टम को स्थानीय तौर पर टेस्ट करने का तरीका
आपको किन चीज़ों की ज़रूरत होगी
- बिलिंग की सुविधा वाला Google Cloud प्रोजेक्ट
- कोई वेब ब्राउज़र, जैसे कि Chrome
- Python 3.12+ और uv, अगर आपको Cloud Shell के बजाय अपनी मशीन पर कोड चलाना है
यह कोडलैब, उन डेवलपर के लिए है जिन्हें Python और Google Cloud के बारे में कुछ जानकारी है.
इस कोडलैब को पूरा करने में करीब 15 मिनट लगेंगे.
इस कोडलैब में बनाए गए संसाधनों की लागत 5 डॉलर से कम होनी चाहिए.
2. अपना एनवायरमेंट सेट अप करने का तरीका
Google Cloud प्रोजेक्ट बनाना
- Google Cloud Console में, प्रोजेक्ट चुनने वाले पेज पर जाकर, Google Cloud प्रोजेक्ट चुनें या बनाएं.
- पक्का करें कि आपके क्लाउड प्रोजेक्ट के लिए बिलिंग की सुविधा चालू हो. किसी प्रोजेक्ट के लिए बिलिंग चालू है या नहीं, यह देखने का तरीका जानें.
Cloud Shell Editor शुरू करना
Google Cloud Console से Cloud Shell सेशन लॉन्च करने के लिए, Google Cloud Console में Cloud Shell चालू करें पर क्लिक करें.
इससे Google Cloud Console के सबसे नीचे वाले पैनल में एक सेशन शुरू होता है.
एडिटर लॉन्च करने के लिए, Cloud Shell विंडो के टूलबार पर मौजूद एडिटर खोलें पर क्लिक करें.
एपीआई चालू करें
टर्मिनल में, Gemini को कॉल करने के लिए ADK जिस एपीआई का इस्तेमाल करता है उसे चालू करने के लिए, यह कमांड चलाएं:
gcloud services enable aiplatform.googleapis.com
अपना एनवायरमेंट कॉन्फ़िगर करना
अपने A2A सिस्टम के लिए प्रोजेक्ट फ़ोल्डर स्ट्रक्चर बनाने के लिए, अपने टर्मिनल में यह कमांड चलाएं. इस डेमो के लिए, हम आपकी $HOME डायरेक्ट्री से ऐब्सलूट पाथिंग का इस्तेमाल करेंगे:
mkdir -p $HOME/app/src/agents $HOME/app/src/host
touch $HOME/app/.env $HOME/app/pyproject.toml
अब जब हमारे पास सामान्य आर्किटेक्चर है, तो आइए एनवायरमेंट कॉन्फ़िगरेशन भरते हैं. नीचे दिए गए कोड सेगमेंट को नई .env फ़ाइल में कॉपी करें:
अपनी नई .env फ़ाइल में, अपना Google क्लाउड प्रोजेक्ट आईडी डालें. GOOGLE_CLOUD_LOCATION को global पर सेट रखें. इस कोडलैब में Gemini मॉडल यहीं उपलब्ध है. अगर आपको उस एजेंट से रिपोर्ट वाले ईमेल पाने हैं जिसे आपको बनाना है, तो MAIL_TO में अपनी पसंद का ईमेल पता भी डाला जा सकता है. GitHub से डेटा पाने वाले एजेंट को आसानी से डेटा पाने में मदद करने के लिए, GitHub का निजी ऐक्सेस टोकन GITHUB_TOKEN जोड़ा जा सकता है.
नीचे दी गई बैश कमांड का इस्तेमाल करके, अपनी नई .env फ़ाइल खोलें:
cloudshell edit $HOME/app/.env
इसके बाद, यहां दी गई फ़ाइल को app/.env में मौजूद .env फ़ाइल में कॉपी करें. अहम जानकारी: पक्का करें कि आपने अपनी वैल्यू डाली हों.
# --- Google Cloud ---
GOOGLE_GENAI_USE_ENTERPRISE=True
GOOGLE_CLOUD_PROJECT=<your-gcp-project-id>
GOOGLE_CLOUD_LOCATION=global
# --- GitHub ---
# Personal Access Token with "repo" scope
# Create one at: https://github.com/settings/tokens
# Generate new token --> Fine-grained, repo-secured --> (populate) Token name --> (scroll down) Generate token
GITHUB_TOKEN=<your-github-pat>
GITHUB_MCP_URL=https://api.githubcopilot.com/mcp/
TARGET_REPOS=["google/adk-python", "langchain-ai/langchain"]
DEFAULT_ISSUE_COUNT=5
DEFAULT_PR_COUNT=5
# --- Email (Optional) ---
# Only needed if you want the emailer agent to send reports
RESEND_API_KEY=<your-resend-API-key>
RESEND_DOMAIN=<your-domain>
MAIL_TO=<insert-email-to-receive-reports>
# --- Local Development Overrides ---
RETRIEVAL_AGENT_URL=http://localhost:8001
EVALUATOR_AGENT_URL=http://localhost:8002
EMAILER_AGENT_URL=http://localhost:8003
ORCHESTRATOR_PORT=http://localhost:8000
अब जब आपने अपने एनवायरमेंट वैरिएबल भर दिए हैं, तो हमें अपने uv एनवायरमेंट को कॉन्फ़िगर करना होगा. pyproject.toml फ़ाइल खोलें:
cloudshell edit $HOME/app/pyproject.toml
इस कोड सेगमेंट को pyproject.toml फ़ाइल में कॉपी करें:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "app"
version = "0.1.0"
description = "Multi-agent system designed to assess the newest issues and pull requests from numerous agentic development platforms"
authors = [
{ name = "Thomas Wagner" },
{ name = "Kris Overholt" }
]
license = "Apache-2.0"
requires-python = ">=3.11"
dependencies = [
"markdown",
"resend",
"uvicorn",
"a2a-sdk",
"google-adk[a2a,mcp]",
"httpx",
"python-dotenv",
]
[project.optional-dependencies]
test = [
"pytest",
"pytest-asyncio",
"pytest-mock",
"respx",
]
[tool.ruff]
target-version = "py313"
line-length = 80
[tool.ruff.lint]
select = ["E", "F", "I", "C", "PL", "B", "UP", "RUF"]
ignore = ["E501", "C901"]
[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
[tool.ruff.lint.isort]
known-first-party = ["src"]
[tool.hatch.build.targets.wheel]
packages=["src/"]
डिपेंडेंसी इंस्टॉल करना
अब अपने टर्मिनल में यहां दी गई कमांड चलाएं. इससे, अभी बनाई गई app डायरेक्ट्री में जाकर, pyproject.toml फ़ाइल से सभी ज़रूरी डिपेंडेंसी इंस्टॉल हो जाएंगी:
cd $HOME/app
uv sync
uv, इस कोडलैब के लिए एक अलग Python एनवायरमेंट बनाता है. इसलिए, आपको कुछ भी चालू करने की ज़रूरत नहीं है. Python कमांड के पहले uv run प्रीफ़िक्स जोड़ें.
अब हमारे पास मल्टी-एजेंट सिस्टम बनाने के लिए सभी ज़रूरी चीज़ें हैं!
3. डेटा खोजने वाला एजेंट बनाना
ईवा एक सॉफ़्टवेयर डेवलपर है. वह GitHub रिपॉज़िटरी के बारे में अप-टू-डेट रहना चाहती है, क्योंकि नई समस्याओं और पीआर के साथ इन्हें अपडेट किया जाता है. इसलिए, वह GitHub से डेटा पाने के लिए ADK एजेंट बनाती है.
इस डेमो के लिए, अपने प्रोजेक्ट के रूट से यह कमांड चलाएं. इससे, रिट्रीवर एजेंट के लिए ज़रूरी डायरेक्ट्री और फ़ाइल बन जाएगी:
mkdir -p $HOME/app/src/agents/retriever
touch $HOME/app/src/agents/retriever/agent.py
touch $HOME/app/src/agents/retriever/__init__.py
echo "from . import agent" >> $HOME/app/src/agents/retriever/__init__.py
नीचे दिए गए ADK कोड सेगमेंट को $HOME/app/src/agents/retriever/agent.py में कॉपी करें:
import logging
import os
import json
from dotenv import load_dotenv
from google.adk.agents.llm_agent import Agent
from google.adk.models import Gemini
from google.genai import types
from google.adk.tools.mcp_tool.mcp_session_manager import (
StreamableHTTPConnectionParams,
)
from google.adk.tools.mcp_tool.mcp_toolset import McpToolset
logger = logging.getLogger(__name__)
load_dotenv()
GITHUB_MCP_URL = os.getenv(
"GITHUB_MCP_URL", "https://api.githubcopilot.com/mcp/"
)
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
if GITHUB_TOKEN is None:
raise ValueError("GITHUB_TOKEN env is not set")
TARGET_REPOS = os.getenv("TARGET_REPOS")
DEFAULT_ISSUE_COUNT = os.getenv("DEFAULT_ISSUE_COUNT")
DEFAULT_PR_COUNT = os.getenv("DEFAULT_PR_COUNT")
# --- Prompt ---
GITHUB_RETRIEVAL_INSTRUCTIONS = f"""
You are a specialized GitHub data retrieval agent.
Your only purpose is to fetch data from GitHub using the available MCP tools and format it for another agent.
**DEFAULT CONFIGURATION:**
If the orchestrator does not specify which repositories or how many items to fetch, you MUST use the following defaults:
- **Repositories:** {TARGET_REPOS}
- **PR Count:** {DEFAULT_PR_COUNT} per repository
- **Issue Count:** {DEFAULT_ISSUE_COUNT} per repository
**Your Task:**
1. Analyze the task. If no specific repo is mentioned, iterate through the Default Repositories list above.
2. Use the `GitHub` MCP tool to fetch the requested data (Pull Requests and/or Issues).
3. **CRITICAL:** After the tool has finished running, you MUST take the raw output and compile it into a single response.
The orchestrator is waiting for this raw data to pass to the Evaluator. Do not summarize it.
"""
# --- Agent Initialization ---
root_agent = Agent(
model=Gemini(
model="gemini-3.8-flash",
retry_options=types.HttpRetryOptions(attempts=5),
),
name="retriever",
instruction=GITHUB_RETRIEVAL_INSTRUCTIONS,
description="""
Connects to the GitHub MCP server to retrieve real-time development
insights, actively reading repository issues, pull requests, and commit
histories.
""",
tools=[
McpToolset(
connection_params=StreamableHTTPConnectionParams(
url=GITHUB_MCP_URL,
headers={
"Authorization": f"Bearer {GITHUB_TOKEN}",
"X-MCP-Toolsets": "repos,issues,pull_requests",
"X-MCP-Readonly": "true",
},
)
)
],
)
यह एजेंट, स्टैंडअलोन टूल के तौर पर काम करता है. इसे अलग से आज़माने के लिए, agents डायरेक्ट्री से adk run का इस्तेमाल करके, इससे चैट करने के लिए यहां दिए गए निर्देश चलाएं:
cd $HOME/app/src/agents
uv run adk run retriever
इसे आज़माने के लिए, [user]: प्रॉम्प्ट पर कोई मैसेज टाइप करें. इसके बाद, एजेंट को रोकने के लिए exit टाइप करें.
4. इवैल्यूएटर एजेंट बनाना
रिचर्ड को अक्सर तकनीकी जानकारी न रखने वाले अपने ग्राहकों और सहकर्मियों के लिए, तकनीकी शब्दों को आसान भाषा में समझाना पड़ता है. रिचर्ड को एक ही तरह के शब्दों को बार-बार परिभाषित करने और एक ही प्रोजेक्ट के बारे में बार-बार बताने में परेशानी होती है. इसलिए, वह एक ऐसा एजेंट बनाता है जो तकनीकी शब्दों को आसान शब्दों में बदल देता है.
इस डेमो के लिए, यह कमांड चलाकर, जांच करने वाले एजेंट के लिए फ़ाइल बनाएं:
mkdir -p $HOME/app/src/agents/evaluator
touch $HOME/app/src/agents/evaluator/agent.py
touch $HOME/app/src/agents/evaluator/__init__.py
echo "from . import agent" >> $HOME/app/src/agents/evaluator/__init__.py
नीचे दिए गए एजेंट कोड सेगमेंट को $HOME/app/src/agents/evaluator/agent.py में कॉपी करें
import json
from dotenv import load_dotenv
from google.adk.agents.llm_agent import Agent
from google.adk.models import Gemini
from google.genai import types
load_dotenv()
# --- Prompt ---
EVAL_AND_SUMMARIZATION_INSTRUCTIONS = """
You are a specialized analysis and summarization agent. Your only purpose is to take raw, structured text about GitHub repositories and transform it into a concise, human-readable Markdown report.
**Your Task:**
1. You will receive a block of text containing raw data about pull requests and issues from an orchestrator.
2. Analyze the provided data. For pull requests, evaluate their significance. For issues, identify key themes and problems.
3. **CRITICAL:** You MUST generate a comprehensive summary in Markdown format based on your analysis. Your final output should be ONLY this Markdown report. Do not add any conversational text or explanations (e.g., "Here is the summary..."). The orchestrator needs to pass your clean report to another agent or directly to the user.
**Output Format Rules:**
- The report MUST be in Markdown.
- Structure the report by repository.
- For each repository, provide a concise overview of significant pull requests and important issues.
- Conclude with overall insights.
The orchestrator is waiting for this report. Ensure your final response consists of nothing but the complete Markdown summary.
"""
# --- Agent ---
root_agent = Agent(
model=Gemini(
model="gemini-3.8-flash",
retry_options=types.HttpRetryOptions(attempts=5),
),
name="evaluator",
instruction=EVAL_AND_SUMMARIZATION_INSTRUCTIONS,
description="""
Distills and summarizes complex GitHub data, breaking down pull
requests, code changes, and issue discussions into easily understandable
insights.
""",
)
यह एजेंट, स्टैंडअलोन टूल के तौर पर काम करता है. इसे अलग से आज़माने के लिए, नए टर्मिनल में यहां दी गई कमांड चलाएं. इससे agents डायरेक्ट्री से adk run का इस्तेमाल करके, इसके साथ चैट की जा सकती है:
cd $HOME/app/src/agents
uv run adk run evaluator
इसे आज़माने के लिए, [user]: प्रॉम्प्ट पर कोई मैसेज टाइप करें. इसके बाद, एजेंट को रोकने के लिए exit टाइप करें.
5. ईमेल भेजने वाला एजेंट बनाना
इवान को ऐसे ईमेल लिखने में काफ़ी समय लगता है जिनमें उसे आसानी से उपलब्ध टेक्स्ट की खास जानकारी देनी होती है और उसे फिर से फ़ॉर्मैट करना होता है. इसलिए, उसने एक ईमेल एजेंट बनाया. यह एजेंट, दिए गए टेक्स्ट को फिर से फ़ॉर्मैट करेगा और दिए गए ईमेल खाते पर भेजेगा.
इस डेमो के लिए, ईमेल भेजने वाले एजेंट की फ़ाइल बनाने के लिए, अपने टर्मिनल में यह कमांड चलाएं:
mkdir -p $HOME/app/src/agents/emailer
touch $HOME/app/src/agents/emailer/agent.py
touch $HOME/app/src/agents/emailer/__init__.py
echo "from . import agent" >> $HOME/app/src/agents/emailer/__init__.py
एजेंट के इस कोड सेगमेंट को app/src/agents/emailer/agent.py में कॉपी करें
import logging
import os
import markdown
import resend
from dotenv import load_dotenv
from google.adk.agents.llm_agent import Agent
from google.adk.models import Gemini
from google.genai import types
load_dotenv()
logger = logging.getLogger(__name__)
RESEND_API_KEY = os.getenv("RESEND_API_KEY")
RESEND_DOMAIN = os.getenv("RESEND_DOMAIN")
MAIL_TO = os.getenv("MAIL_TO")
if RESEND_API_KEY:
resend.api_key = RESEND_API_KEY
# --- Tools ---
def send_report_email(recipient: str, subject: str, body: str) -> str:
"""
Sends an email of the given subject and body to the specified recipient
via Resend. If recipient is None, it defaults to the MAIL_TO environment variable.
Args:
recipient (str | None): The email address of the recipient. If None, defaults to MAIL_TO.
subject (str): The subject of the email.
body (str): The body of the email.
Returns:
str: A success or failure message.
"""
if not recipient:
recipient = MAIL_TO
if not all([RESEND_API_KEY, RESEND_DOMAIN, recipient]):
error_msg = "Error: Email tool configuration missing (API Key, Domain, or Recipient)"
logger.error(error_msg)
return error_msg
try:
html_body = markdown.markdown(body, extensions=["tables"])
params: resend.Emails.SendParams = {
"from": f"Research Agent <agent@{RESEND_DOMAIN}>",
"to": [recipient], #type: ignore
"subject": subject,
"text": body,
"html": html_body,
}
email = resend.Emails.send(params)
logger.info(f"Email sent successfully. ID: {email['id']}")
return f"Email sent! ID: {email['id']}"
except Exception as e:
error_msg = f"Failed to send email: {e}"
logger.error(error_msg)
return error_msg
# --- Prompt ---
EMAIL_INSTRUCTIONS = """
You are an emailer agent responsible for formatting and sending a research report via email.
INPUT: You will receive a Markdown-formatted string (the report) and the email recipient.
YOUR TASK:
1. Take the Markdown content and format it appropriately for an email body.
The goal is to render the Markdown effectively so it is readable and well-presented in an email client.
2. Based on the summary, generate a concise and informative subject line for the email.
The subject line should reflect the main themes or key insights from the report.
3. Use the `send_report_email` tool with the extracted recipient, the generated subject line, and the formatted email body.
If no email recipient is provided, output a message indicating that no recipient was specified and do NOT call the tool.
"""
# --- Agent ---
root_agent = Agent(
model=Gemini(
model="gemini-3.8-flash",
retry_options=types.HttpRetryOptions(attempts=5),
),
name="emailer",
instruction=EMAIL_INSTRUCTIONS,
description="""
Acts as the final delivery mechanism in the pipeline, dispatching
generated summaries and reports to designated email addresses.
""",
tools=[
send_report_email
],
)
यह एजेंट, स्टैंडअलोन टूल के तौर पर काम करता है. इसे अलग से आज़माने के लिए, नए टर्मिनल में यहां दी गई कमांड चलाएं. इससे agents डायरेक्ट्री से adk run का इस्तेमाल करके, इसके साथ चैट की जा सकती है:
cd $HOME/app/src/agents
uv run adk run emailer
इसे आज़माने के लिए, [user]: प्रॉम्प्ट पर कोई मैसेज टाइप करें. इसके बाद, एजेंट को रोकने के लिए exit टाइप करें.
6. एजेंट कार्ड बनाना
हमने अभी-अभी तीन इंडिपेंडेंट डेवलपर की कहानियां देखी हैं. इन सभी के अपने-अपने यूनीक एजेंट हैं. इन सभी एजेंट को पब्लिश किया गया है और ये अपनी कंपनी की एजेंट लाइब्रेरी में लॉग इन हैं. डायने नाम की एक अन्य डेवलपर इन अलग-अलग आइडिया को एक ही मल्टी-एजेंट सिस्टम में शामिल करना चाहती है.
उसे एक ऐसे रिसर्च एजेंट की ज़रूरत है जो उसकी ज़रूरत के हिसाब से काम करे. साथ ही, उसे अलग-अलग एजेंट डेवलपमेंट फ़्रेमवर्क से जुड़ी समस्याओं और पीआर के बारे में अप-टू-डेट रखे. उसे यह भी चाहिए कि यह टूल, इकोसिस्टम में हुए सभी नए बदलावों की खास जानकारी ईमेल करे. सभी एजेंट अलग-अलग एनवायरमेंट में बनाए जाते हैं. इसलिए, इन मौजूदा एजेंट को एक साथ लाने के लिए, A2A एक बेहतरीन समाधान है.
रिमोट एजेंट की सीरीज़ बनाने के लिए, सबसे पहले ज़रूरी रिमोट एजेंट को एजेंट कार्ड देना होता है. इन्हें अपने एजेंट के लिए बिज़नेस कार्ड की तरह समझें. ये JSON फ़ाइलें होती हैं. इनका इस्तेमाल, आपके होस्ट एजेंट को एजेंट की पहचान करने की सुविधा देने के लिए किया जाता है. जैसे, एजेंट का नाम, ब्यौरा, क्षमताएं, और इनपुट/आउटपुट स्कीमा. इस कोडलैब में मौजूद कार्ड, A2A v1.0 एजेंट कार्ड फ़ॉर्मैट का इस्तेमाल करते हैं. इसमें हर उस एंडपॉइंट की सूची दी गई है जहां supportedInterfaces में एजेंट से संपर्क किया जा सकता है.
सबसे पहले, अपने प्रोजेक्ट रूट से यह कमांड चलाकर cards डायरेक्ट्री बनाएं. साथ ही, एजेंट कार्ड के लिए सभी ज़रूरी JSON फ़ाइलें बनाएं:
mkdir -p $HOME/app/cards/
touch $HOME/app/cards/github_retrieval_agent_card.json
touch $HOME/app/cards/content_evaluator_agent_card.json
touch $HOME/app/cards/emailer_agent_card.json
इन फ़ाइलों को सिर्फ़ इस बैश कमांड से ऐक्सेस किया जा सकता है:
cloudshell edit $HOME/app/cards/github_retrieval_agent_card.json
यहां दिए गए JSON कॉन्टेंट को app/cards/github_retrieval_agent_card.json फ़ाइल में कॉपी करें:
{
"name": "GitHub_Retrieval_Agent",
"description": "Connects to the GitHub MCP server to retrieve real-time development insights, actively reading repository issues, pull requests, and commit histories.",
"version": "1.0.0",
"supportedInterfaces": [
{
"url": "http://localhost:8001",
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"
}
],
"capabilities": {
"streaming": true,
"pushNotifications": true
},
"defaultInputModes": [
"text",
"text/plain"
],
"defaultOutputModes": [
"text",
"json",
"text/plain"
],
"skills": [
{
"id": "read_github_repos",
"name": "GitHub_Retriever",
"description": "Fetches and analyzes recent content updates from GitHub repositories, including open/closed issues, pull request statuses, and detailed commit logs.",
"tags": [
"Find the newest pull requests from",
"Check recent issues in",
"Summarize commits for",
"GitHub repository status"
],
"examples": [
"Find the 10 most recent pull requests from the langchain-ai/langgraph repository along with their commits.",
"List all open issues tagged with 'bug' in the current repository."
]
}
]
}
नीचे दिए गए कॉन्टेंट को app/cards/content_evaluator_agent_card.json फ़ाइल में कॉपी करें. इससे होस्ट एजेंट को यह जानकारी मिलेगी कि यह एजेंट क्या कर सकता है. साथ ही, यह भी पता चलेगा कि इसे किस तरह का डेटा दिया जा सकता है और यह किस तरह का डेटा वापस देगा.
पहले की तरह, इस निर्देश का इस्तेमाल करके, आकलन करने वाले एजेंट कार्ड में बदलाव करें:
cloudshell edit $HOME/app/cards/content_evaluator_agent_card.json
{
"name": "Content_Evaluation_Agent",
"description": "Distills and summarizes complex GitHub data, breaking down pull requests, code changes, and issue discussions into easily understandable insights.",
"version": "1.0.0",
"supportedInterfaces": [
{
"url": "http://localhost:8002",
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"
}
],
"capabilities": {
"streaming": true,
"pushNotifications": true
},
"defaultInputModes": [
"text",
"json",
"text/plain"
],
"defaultOutputModes": [
"text",
"text/plain"
],
"skills": [
{
"id": "evaluate_github_content",
"name": "Evaluate GitHub Content",
"description": "Analyzes and synthesizes provided GitHub data—including code diffs, commit histories, issue threads, and PR comments—into clear, structured summaries.",
"tags": [
"summarize pull request",
"evaluate GitHub changes",
"break down commits",
"distill issue discussion",
"code review summary"
],
"examples": [
"Make a thorough summary of the code changes and commit history from this pull request data.",
"Break down the main arguments and proposed solutions from this provided GitHub issue discussion."
]
}
]
}
यहां ईमेल भेजने वाले एजेंट का एजेंट कार्ड दिया गया है. इसे app/cards/emailer_agent_card.json फ़ाइल में कॉपी करें. इसके लिए, उसी cloudshell कमांड का इस्तेमाल करें:
cloudshell edit $HOME/app/cards/emailer_agent_card.json
{
"name": "Email_Agent",
"description": "Acts as the final delivery mechanism in the pipeline, dispatching generated summaries and reports to designated email addresses.",
"version": "1.0.0",
"supportedInterfaces": [
{
"url": "http://localhost:8003",
"protocolBinding": "JSONRPC",
"protocolVersion": "1.0"
}
],
"capabilities": {
"streaming": true,
"pushNotifications": true
},
"defaultInputModes": [
"text",
"text/plain"
],
"defaultOutputModes": [
"text",
"text/plain"
],
"skills": [
{
"id": "dispatch_email_report",
"name": "Dispatch_Report_via_Email",
"description": "Takes synthesized text data and securely emails it to a specified recipient or distribution list.",
"tags": [
"send email",
"email summary",
"dispatch report",
"forward to inbox"
],
"examples": [
"Email me the summarized evaluations from the retrieved pull request and issue data.",
"Take this code review breakdown and send it in an email to the dev team."
]
}
]
}
7. रिमोट एजेंट एक्ज़ीक्यूटर बनाना
अगर रिमोट एजेंट को होस्ट एजेंट से ‘कॉल' या ‘बातचीत' करनी है, तो हर एजेंट के पास एक एजेंट एक्ज़ीक्यूटर होना चाहिए. यह A2A सर्वर को दिखना चाहिए और इसकी पहचान एजेंट कार्ड से होनी चाहिए. एक्ज़ीक्यूटर एक ऐब्स्ट्रैक्ट क्लास है. इसमें execute() और cancel() तरीके होते हैं. यह रिमोट एजेंट को कॉल करेगा और उसे कोई टास्क या मैसेज देगा या टास्क को पूरी तरह से रद्द कर देगा.
यहां ADK एजेंट एक्ज़ीक्यूटर का एक ऐब्स्ट्रैक्ट उदाहरण दिया गया है. यह रिमोट एजेंट को मैसेज भेजने और टास्क असाइन करने में मदद करता है. ये सभी एजेंट, टेक्स्ट Part आर्टफ़ैक्ट का इस्तेमाल करते हैं. इस वजह से, हम एजेंट के बीच शेयर किए गए एक सामान्य एजेंट एक्ज़ीक्यूटर का इस्तेमाल कर सकते हैं. नई एक्ज़ीक्यूटर फ़ाइल बनाएं:
touch $HOME/app/src/agents/executor.py
नीचे दिए गए कोड सेगमेंट को नई $HOME/app/src/agents/executor.py फ़ाइल में कॉपी करें:
# $HOME/app/src/agents/executor.py
from a2a.helpers import new_task_from_user_message, new_text_message
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.events.event_queue import EventQueue
from a2a.server.tasks import TaskUpdater
from a2a.types import Part, TaskState
from google.adk.artifacts import InMemoryArtifactService
from google.adk.memory.in_memory_memory_service import InMemoryMemoryService
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
class BaseAgentExecutor(AgentExecutor):
"""An AgentExecutor that runs a remote ADK Agent"""
def __init__(
self,
agent,
status_message='Processing request...',
artifact_name='response',
):
"""Initialize a generic ADK agent executor.
Args:
agent: The ADK agent instance
status_message: Message to display while processing
artifact_name: Name for the response artifact
"""
self.agent = agent
self.status_message = status_message
self.artifact_name = artifact_name
self.runner = Runner(
app_name=agent.name,
agent=agent,
artifact_service=InMemoryArtifactService(),
session_service=InMemorySessionService(),
memory_service=InMemoryMemoryService(),
)
async def execute(
self,
context: RequestContext,
event_queue: EventQueue,
) -> None:
query = context.get_user_input()
task = context.current_task or new_task_from_user_message(context.message) # type: ignore
await event_queue.enqueue_event(task)
updater = TaskUpdater(event_queue, task.id, task.context_id)
user_id = context.call_context.user.user_name or "a2a_user"
try:
# Update status with custom message
await updater.update_status(
TaskState.TASK_STATE_WORKING,
new_text_message(
self.status_message,
context_id=task.context_id,
task_id=task.id,
),
)
# Process with ADK agent, reusing the session for this context
session = await self.runner.session_service.get_session(
app_name=self.agent.name,
user_id=user_id,
session_id=task.context_id,
)
if session is None:
session = await self.runner.session_service.create_session(
app_name=self.agent.name,
user_id=user_id,
state={},
session_id=task.context_id,
)
content = types.Content(
role="user", parts=[types.Part.from_text(text=query)]
)
response_text = ""
async for event in self.runner.run_async(
user_id=user_id, session_id=session.id, new_message=content
):
if event.is_final_response() and event.content and event.content.parts:
for part in event.content.parts:
if hasattr(part, "text") and part.text:
response_text += part.text + "\n"
elif hasattr(part, "function_call"):
# Log or handle function calls if needed
pass # Function calls are handled internally by ADK
# Add response as artifact with custom name
await updater.add_artifact(
[Part(text=response_text)],
name=self.artifact_name,
)
await updater.complete()
except Exception as e:
await updater.update_status(
TaskState.TASK_STATE_FAILED,
new_text_message(
f"Error: {e!s}",
context_id=task.context_id,
task_id=task.id,
),
)
async def cancel(
self,
context: RequestContext,
event_queue: EventQueue
) -> None:
"""Cancel the execution of a specific task."""
raise NotImplementedError("Cancel not implemented for RetrieverAgentExecutor")
अब हमारे पास एक ऐब्स्ट्रैक्ट एजेंट एक्ज़ीक्यूटर है. इसलिए, हम Pythonic इनहेरिटेंस का इस्तेमाल करके, एक्ज़ीक्यूटर को एजेंट की हर खास क्षमता और ज़रूरत के हिसाब से बेहतर बना सकते हैं. हमारे मामले में, पेलोड के साथ एजेंट को कॉल करने, जवाब का इंतज़ार करने, और जवाब पेलोड को वापस पाने की प्रोसेस, हमारे वर्कफ़्लो के लिए यूनिवर्सल है. इस वजह से, हमें किसी खास बदलाव की ज़रूरत नहीं है. हालांकि, एजेंट के हर A2A सर्वर के लिए, एजेंट एक्ज़ीक्यूटर की ज़रूरत होती है. तीनों एजेंट के लिए एक्ज़ीक्यूटर फ़ाइलें बनाने के लिए, यह कमांड चलाएं:
touch $HOME/app/src/agents/retriever/executor.py
touch $HOME/app/src/agents/evaluator/executor.py
touch $HOME/app/src/agents/emailer/executor.py
अब हर फ़ाइल में उससे जुड़ा कॉन्टेंट जोड़ें.
# $HOME/app/src/agents/retriever/executor.py
from ..executor import BaseAgentExecutor
class RetrieverAgentExecutor(BaseAgentExecutor):
"""
An AgentExecutor that runs the Retriever Agent
All agent specific implementations for execute() and cancel() can be
overloaded here, along with any other desired funcitonality.
"""
pass
# $HOME/app/src/agents/evaluator/executor.py
from ..executor import BaseAgentExecutor
class EvaluatorAgentExecutor(BaseAgentExecutor):
"""
An AgentExecutor that runs the Evaluator Agent
All agent specific implementations for execute() and cancel() can be
overloaded here, along with any other desired funcitonality.
"""
pass
# $HOME/app/src/agents/emailer/executor.py
from ..executor import BaseAgentExecutor
class EmailerAgentExecutor(BaseAgentExecutor):
"""
An AgentExecutor that runs the Emailer Agent
All agent specific implementations for execute() and cancel() can be
overloaded here, along with any other desired funcitonality.
"""
pass
8. रिमोट एजेंट को A2A सर्वर के लिए उपलब्ध कराना
अब हर एजेंट के पास अपना बिज़नेस कार्ड है. इसलिए, A2A सर्वर के ज़रिए किसी एंडपॉइंट पर पहुंचने के बाद, उन्हें खोजा जा सकता है. इस कोडलैब के लिए, हम पूरी प्रोसेस को लोकल रख रहे हैं. इसके लिए, हर रिमोट एजेंट एंडपॉइंट के लिए लोकलहोस्ट का इस्तेमाल किया जा रहा है. हालांकि, इन्हें किसी भी एंडपॉइंट पर दिखाया जा सकता है. साथ ही, जब तक इन्हें एजेंट कार्ड के supportedInterfaces फ़ील्ड के url में शामिल किया जाता है, तब तक इन्हें खोजा जा सकता है.
हर सर्वर, अपने एजेंट कार्ड को /.well-known/agent-card.json पर दिखाता है. A2A क्लाइंट इसे यहीं ढूंढते हैं. साथ ही, यह / पर A2A JSON-RPC अनुरोधों को मैनेज करता है.
रिमोट एजेंट के लिए अगला चरण, उन्हें अपने A2A सर्वर से कनेक्ट करना है. तीनों रिमोट एजेंट के लिए server.py फ़ाइल बनाने के लिए, यह कमांड चलाएं:
touch $HOME/app/src/agents/retriever/server.py
touch $HOME/app/src/agents/evaluator/server.py
touch $HOME/app/src/agents/emailer/server.py
अब आपको हर एजेंट के लिए सर्वर कोड जोड़ना होगा. सबसे पहले, जानकारी इकट्ठा करने वाले एजेंट के बारे में जानते हैं:
# $HOME/app/src/agents/retriever/server.py
import logging
import os
import json
import uvicorn
from google.protobuf.json_format import ParseDict
from starlette.applications import Starlette
from a2a.types import AgentCard
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from .agent import root_agent as retriever_agent
from .executor import RetrieverAgentExecutor
logging.basicConfig(level=logging.INFO)
with open("cards/github_retrieval_agent_card.json", "r") as f:
card_data = json.load(f)
github_retrieval_agent_card = ParseDict(card_data, AgentCard())
request_handler = DefaultRequestHandler(
agent_executor=RetrieverAgentExecutor(
agent=retriever_agent
),
task_store=InMemoryTaskStore(),
agent_card=github_retrieval_agent_card,
)
server = Starlette(
routes=[
*create_agent_card_routes(github_retrieval_agent_card),
*create_jsonrpc_routes(request_handler, rpc_url="/"),
]
)
if __name__ == "__main__":
port = int(os.getenv("PORT", 8001))
print(f"Starting Retriever Agent on Port {port}...")
uvicorn.run(server, host="0.0.0.0", port=port)
इसके बाद, आकलन करने वाले एजेंट के लिए सर्वर बनाएं:
# $HOME/app/src/agents/evaluator/server.py
import logging
import os
import json
import uvicorn
from google.protobuf.json_format import ParseDict
from starlette.applications import Starlette
from a2a.types import AgentCard
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from .agent import root_agent as evaluator_agent
from .executor import EvaluatorAgentExecutor
logging.basicConfig(level=logging.INFO)
with open("cards/content_evaluator_agent_card.json", "r") as f:
card_data = json.load(f)
content_evaluator_agent_card = ParseDict(card_data, AgentCard())
request_handler = DefaultRequestHandler(
agent_executor=EvaluatorAgentExecutor(agent=evaluator_agent),
task_store=InMemoryTaskStore(),
agent_card=content_evaluator_agent_card,
)
server = Starlette(
routes=[
*create_agent_card_routes(content_evaluator_agent_card),
*create_jsonrpc_routes(request_handler, rpc_url="/"),
]
)
if __name__ == "__main__":
port = int(os.getenv("PORT", 8002))
print(f"Starting Evaluator Agent on Port {port}...")
uvicorn.run(server, host="0.0.0.0", port=port)
आखिर में, ईमेल भेजने वाले एजेंट के लिए:
# $HOME/app/src/agents/emailer/server.py
import logging
import os
import json
import uvicorn
from google.protobuf.json_format import ParseDict
from starlette.applications import Starlette
from a2a.types import AgentCard
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.routes import create_agent_card_routes, create_jsonrpc_routes
from a2a.server.tasks import InMemoryTaskStore
from .agent import root_agent as emailer_agent
from .executor import EmailerAgentExecutor
logging.basicConfig(level=logging.INFO)
with open("cards/emailer_agent_card.json", "r") as f:
card_data = json.load(f)
emailer_agent_card = ParseDict(card_data, AgentCard())
request_handler = DefaultRequestHandler(
agent_executor=EmailerAgentExecutor(
agent=emailer_agent
),
task_store=InMemoryTaskStore(),
agent_card=emailer_agent_card,
)
server = Starlette(
routes=[
*create_agent_card_routes(emailer_agent_card),
*create_jsonrpc_routes(request_handler, rpc_url="/"),
]
)
if __name__ == "__main__":
port = int(os.getenv("PORT", 8003))
print(f"Starting Emailer Agent on Port {port}...")
uvicorn.run(server, host="0.0.0.0", port=port)
9. होस्ट एजेंट बनाना
अब तक हमने अपने हर एजेंट को एक एपीआई में बदल दिया है, ताकि होस्ट एजेंट उसे पिंग कर सके. अब हमारे रिमोट एजेंट, अपने A2A सर्वर से कनेक्ट हो गए हैं. इसलिए, हमें एक होस्ट एजेंट बनाना होगा, जो उन्हें खोजे और व्यवस्थित करे.
इसके लिए, हमें होस्ट के कुछ पहलुओं पर काम करना होगा. सबसे पहले, हमें अपने हर रिमोट एजेंट और उनके सर्वर के लिए अलग-अलग क्लाइंट बनाने का तरीका तैयार करना होगा. इसके लिए, A2A क्लाइंट फ़ैक्ट्री बनाई जाती है. यह फ़ैक्ट्री, सर्वर पर होस्ट किए गए हर रिमोट एजेंट एंडपॉइंट से कनेक्शन बनाती है. इससे होस्ट, एजेंट कार्ड ढूंढ सकता है. होस्ट और हर रिमोट एजेंट के बीच कनेक्शन, RemoteAgentConnections ऑब्जेक्ट से शुरू किए जा सकते हैं.
touch $HOME/app/src/host/remote_agent_connection.py
touch $HOME/app/src/host/agent.py
touch $HOME/app/src/host/__init__.py
echo "from . import agent" >> $HOME/app/src/host/__init__.py
रिमोट एजेंट कनेक्शन के इस कोड को src/host/remote_agent_connection.py फ़ाइल में कॉपी करें:
# src/host/remote_agent_connection.py
import traceback
from a2a.client import (
Client,
ClientFactory,
)
from a2a.types import (
AgentCard,
Message,
SendMessageRequest,
Task,
TaskState,
)
class RemoteAgentConnection:
"""A class to hold the connections to the remote agents."""
def __init__(self, client_factory: ClientFactory, agent_card: AgentCard):
self.agent_client: Client = client_factory.create(agent_card)
self.card: AgentCard = agent_card
def get_agent(self) -> AgentCard:
return self.card
async def send_message(self, message: Message) -> Task | Message | None:
lastTask: Task | None = None
try:
async for event in self.agent_client.send_message(
SendMessageRequest(message=message)
):
if event.HasField('message'):
return event.message
# Build up the task from the streamed task and update events
if event.HasField('task'):
lastTask = event.task
elif lastTask and event.HasField('status_update'):
lastTask.status.CopyFrom(event.status_update.status)
elif lastTask and event.HasField('artifact_update'):
lastTask.artifacts.append(event.artifact_update.artifact)
if lastTask and self.is_terminal_or_interrupted(lastTask):
return lastTask
except Exception as e:
print('Exception found in send_message')
traceback.print_exc()
raise e
return lastTask
def is_terminal_or_interrupted(self, task: Task) -> bool:
return task.status.state in [
TaskState.TASK_STATE_COMPLETED,
TaskState.TASK_STATE_CANCELED,
TaskState.TASK_STATE_FAILED,
TaskState.TASK_STATE_REJECTED,
TaskState.TASK_STATE_INPUT_REQUIRED,
TaskState.TASK_STATE_AUTH_REQUIRED,
]
अब हमारे पास, क्लाइंट और सर्वर के बीच कनेक्शन बनाने की सुविधा है. इसके लिए, दिए गए क्लाइंट और एजेंट कार्ड का इस्तेमाल किया जाता है. यह एक ऐसा टूल होगा जिसका इस्तेमाल होस्ट एजेंट, रिमोट एजेंट सर्वर से कनेक्शन बनाने के लिए करेगा.
अब हम होस्ट एजेंट बनाने की प्रोसेस शुरू करते हैं. सबसे पहले, इस कोड सेगमेंट को कॉपी करके app/src/host/agent.py फ़ाइल में चिपकाएं. यह Pythonic क्लास का इनिशियलाइज़ेशन है. इसके लिए, रिमोट एजेंट एंडपॉइंट और स्टैंडर्ड httpx क्लाइंट की ज़रूरत होती है. इस एजेंट क्लास को शुरू करने पर, इसे दिए गए रिमोट पतों के ज़रिए कनेक्शन बनाएगा.
import asyncio
import json
import os
import uuid
import httpx
from typing import Any
from a2a.client import A2ACardResolver, ClientConfig, ClientFactory
from a2a.types import (
AgentCard,
Message,
Part,
Role,
Task,
TaskState,
)
from a2a.utils import TransportProtocol
from google.protobuf.json_format import MessageToDict
from google.adk import Agent
from google.adk.models import Gemini
from google.genai import types
from google.adk.agents.callback_context import CallbackContext
from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.tools.tool_context import ToolContext
from dotenv import load_dotenv
from .remote_agent_connection import RemoteAgentConnection
load_dotenv()
######################################
# --- Coordinator Agent Definition ---
######################################
class CoordinatorAgent:
"""
The Coordinator agent.
This is the agent responsible for sending tasks to agents.
"""
def __init__(
self,
remote_agent_addresses: list[str],
http_client: httpx.AsyncClient,
):
self.http_client = http_client
self.remote_agent_addresses = remote_agent_addresses
self.client_factory = None
self.remote_agent_connections: dict[str, RemoteAgentConnection] = {}
self.cards: dict[str, AgentCard] = {}
self.agents: str = ''
होस्ट एजेंट का अगला काम, रिमोट एजेंट से कनेक्शन बनाना है. __init__ में कनेक्ट करने के बजाय (यह मॉड्यूल इंपोर्ट करने के समय चलता है, इवेंट लूप के मौजूद होने से पहले), ensure_initialized तरीका इस काम को तब तक के लिए टाल देता है, जब तक एजेंट का इस्तेमाल नहीं किया जाता. यह कुकी यह जांच करती है कि कनेक्शन पहले से ही बन चुके हैं या नहीं. अगर कनेक्शन नहीं बने हैं, तो यह A2A क्लाइंट बनाती है और हर रिमोट एजेंट से पैरलल में कनेक्ट होती है. इस सेगमेंट को app/src/host/agent.py में पिछले सेगमेंट के ठीक नीचे कॉपी करें.
#####################################
# --- Remote Agent Initialization ---
#####################################
async def ensure_initialized(self):
if not self.remote_agent_connections:
config = ClientConfig(
httpx_client=self.http_client,
supported_protocol_bindings=[
TransportProtocol.JSONRPC,
TransportProtocol.HTTP_JSON,
],
)
self.client_factory = ClientFactory(config=config)
async with asyncio.TaskGroup() as task_group:
for address in self.remote_agent_addresses:
task_group.create_task(self.retrieve_card(address))
async def retrieve_card(self, address: str):
card_resolver = A2ACardResolver(self.http_client, address)
card = await card_resolver.get_agent_card()
# Use the actual address, not the hardcoded URL in the card JSON
for interface in card.supported_interfaces:
interface.url = address
remote_connection = RemoteAgentConnection(self.client_factory, card)
self.remote_agent_connections[card.name] = remote_connection
self.cards[card.name] = card
agent_info = []
for card in self.cards.values():
agent_info.append(
json.dumps({"name": card.name, "description": card.description})
)
self.agents = "\n".join(agent_info)
इसके बाद, एलएलएम एजेंट को लागू करने का तरीका बताया गया है. इस मामले में, हम अपने ऑर्केस्ट्रेटर के लिए ADK एजेंट का इस्तेमाल कर रहे हैं. इसके लिए, प्रॉम्प्ट के निर्देश, कॉलबैक, और टूल जैसे सामान्य ऐड-ऑन की ज़रूरत होती है. इन सभी कॉम्पोनेंट को app/src/host/agent.py फ़ाइल में मौजूद होस्ट एजेंट क्लास में कॉपी करें. होस्ट एजेंट क्लास में यहां दिया गया कॉलबैक डालें. एजेंट के ठीक से ट्रिगर होने से पहले, यह कॉलबैक एजेंट को शुरू करता है. ऐसा तब होता है, जब एजेंट की स्थिति में उसे पहले से शुरू न किया गया हो.
############################
# -- Implement the ADK Agent
############################
# --- Before Model Callback ---
def before_model_callback(
self, callback_context: CallbackContext, llm_request
):
"""
A callback to set up the session state before the model processes the
request
"""
state = callback_context.state
if 'session_active' not in state or not state['session_active']:
if 'session_id' not in state:
state['session_id'] = str(uuid.uuid4())
state['session_active'] = True
हमारे होस्ट एजेंट का अगला कॉम्पोनेंट, प्रॉम्प्ट निर्देश है. यह हमारा ऑर्केस्ट्रेटर एजेंट है. इसलिए, इसे उन रिमोट एजेंट के बारे में पता होना चाहिए जिनका इस्तेमाल यह करेगा. साथ ही, इसे मौजूदा एजेंट के बारे में भी पता होना चाहिए, ताकि कोऑर्डिनेटर को यह पता चल सके कि सेशन में फ़िलहाल क्या हो रहा है. कॉलबैक के नीचे, यह प्रॉम्प्ट और हेल्पर फ़ंक्शन जोड़ें.
# --- Prompt ---
def root_instruction(self, context: ReadonlyContext) -> str:
current_agent = self.check_state(context)
return f"""
You are an expert orchestrator that can delegate user requests to the
appropriate remote agents to generate a GitHub research report.
**Your Goal:** To fulfill user requests for GitHub repository data, evaluate it, and optionally email a report.
**Workflow Steps:**
1. **Understand the User Request**:
- Identify repository names (e.g., "google/adk-python").
- Determine if the user wants Pull Requests, Issues, or both.
- Extract any specified email address for sending the report (e.g., "user@example.com").
- Note the number of PRs/issues requested per repository. If not specified, the Retrieval Agent has defaults.
2. **Retrieve Data (GitHub_Retrieval_Agent)**:
- Use the `send_message` tool to send a message to the "GitHub_Retrieval_Agent".
- Your message to the Retrieval Agent should clearly state which repositories to fetch data for, and specify if you need issues, pull requests, and the respective limits.
- Example message to Retrieval Agent: "Fetch 5 issues and 3 pull requests for google/adk-python."
3. **Evaluate and Summarize Data (Content_Evaluation_Agent)**:
- Once you receive the raw JSON data from the "GitHub_Retrieval_Agent", use the `send_message` tool to send this data to the "Content_Evaluation_Agent".
- Your message to the Evaluation Agent should include the raw JSON data you received.
- The Evaluation Agent will return a Markdown-formatted report.
4. **Email Report (Email_Agent - if email provided)**:
- If the user's initial request included an email address, use the `send_message` tool to send the Markdown report from the "Content_Evaluation_Agent" to the "Email_Agent".
- Your message to the Email Agent should include the report and the recipient's email address.
- Example message to Email Agent: "Send this report to user@example.com: [Markdown Report Content]".
5. **Respond to User**:
- Based on the outcome of the steps above, formulate a concise and informative response to the user.
- If a report was generated and emailed, confirm that. If only a report was generated, provide it directly to the user.
- If an email address was requested but the email failed to send, inform the user.
- If any step failed, inform the user about the failure.
**Available Tools:**
- `list_remote_agents()`: Use this to see what agents are available (though you already know their names for this workflow).
- `send_message(agent_name: str, message: str)`: Use this to interact with remote agents.
**Crucial Guidelines:**
- **Rely on Tools**: ALWAYS use `send_message` to interact with the remote agents. Do NOT attempt to perform the tasks yourself.
- **No Conversational Filler**: Only communicate the essential information to the remote agents or back to the user.
- **Error Handling**: If a remote agent returns an error, acknowledge it and try to provide a helpful message to the user.
Agents:
{self.agents}
Current agent: {current_agent['active_agent']}
"""
def check_state(self, context: ReadonlyContext):
state = context.state
if (
'context_id' in state
and 'session_active' in state
and state['session_active']
and 'agent' in state
):
return {'active_agent': f'{state["agent"]}'}
return {'active_agent': 'None'}
अब बारी है होस्ट एजेंट के सबसे अहम हिस्से की, यानी कि टूल की. होस्ट के पास send_message() टूल और list_remote_agents() टूल का ऐक्सेस होगा. list_remote_agent() टूल का इस्तेमाल करना आसान है. यह सिर्फ़ क्लास के एजेंट कार्ड को पढ़ता है और डिक्शनरी की एक सूची दिखाता है. इसमें हर एजेंट का नाम और ब्यौरा होता है. send_message() फ़ंक्शन थोड़ा ज़्यादा अडवांस है. इसमें किसी रिमोट एजेंट को मैसेज या टास्क भेजने, स्ट्रीमिंग करने या बिना स्ट्रीमिंग किए मैसेज भेजने की सुविधा होती है. इसके लिए, एजेंट का नाम और मैसेज स्ट्रिंग की जानकारी दी जाती है. इस कोड सेगमेंट को, app/src/host/agent.py में प्रॉम्प्ट सेक्शन के नीचे मौजूद, एक ही होस्ट एजेंट Python क्लास में रखें.
# --- Agent Tools ---
def list_remote_agents(self):
"""List the available remote agents you can use to delegate the task."""
if not self.remote_agent_connections:
return []
remote_agent_info = []
for card in self.cards.values():
remote_agent_info.append(
{'name': card.name, 'description': card.description}
)
return remote_agent_info
async def send_message(
self, agent_name: str, message: str, tool_context: ToolContext
):
"""Sends a task either streaming (if supported) or non-streaming.
This will send a message to the remote agent named agent_name.
Args:
agent_name: The name of the agent to send the task to.
message: The message to send to the agent for the task.
tool_context: The tool context this method runs in.
Yields:
A dictionary of JSON data.
"""
await self.ensure_initialized()
if agent_name not in self.remote_agent_connections:
raise ValueError(f'Agent {agent_name} not found')
state = tool_context.state
state['agent'] = agent_name
client = self.remote_agent_connections[agent_name]
if not client:
raise ValueError(f'Client not available for {agent_name}')
task_id = state.get('task_id', None)
context_id = state.get('context_id', None)
message_id = state.get('message_id', None)
task: Task
if not message_id:
message_id = str(uuid.uuid4())
request_message = Message(
role=Role.ROLE_USER,
parts=[Part(text=message)],
message_id=message_id,
context_id=context_id,
task_id=task_id,
)
response = await client.send_message(request_message)
if isinstance(response, Message):
return await convert_parts(response.parts, tool_context)
task: Task = response # type: ignore
# Assume completion unless a state returns that isn't complete
state['session_active'] = not client.is_terminal_or_interrupted(task)
if task.context_id:
state['context_id'] = task.context_id
# Only reuse the task ID to continue a task that is waiting for input.
# Finished tasks can't take new messages, so the next call starts a new task.
if task.status.state == TaskState.TASK_STATE_INPUT_REQUIRED:
state['task_id'] = task.id
else:
state['task_id'] = None
if task.status.state == TaskState.TASK_STATE_INPUT_REQUIRED:
# Force user input back
tool_context.actions.skip_summarization = True
tool_context.actions.escalate = True
elif task.status.state == TaskState.TASK_STATE_CANCELED:
# Open question, should we return some info for cancellation instead
raise ValueError(f'Agent {agent_name} task {task.id} is cancelled')
elif task.status.state == TaskState.TASK_STATE_FAILED:
# Raise error for failure
raise ValueError(f'Agent {agent_name} task {task.id} failed')
response = []
if task.status.HasField('message'):
response.extend(
await convert_parts(task.status.message.parts, tool_context)
)
if task.artifacts:
for artifact in task.artifacts:
response.extend(
await convert_parts(artifact.parts, tool_context)
)
return response
आखिर में, हम ADK एजेंट को लागू करते हैं, जिसमें ये सभी कॉम्पोनेंट शामिल होते हैं. यह ऑर्केस्ट्रेटर क्लास एजेंट का मुख्य हिस्सा होता है. यह BeforeModelCallback के चलने के बाद, प्रॉम्प्ट को पूरा करने के लिए उपलब्ध टूल का इस्तेमाल करता है.
इस कोड सेगमेंट को, टूल सेक्शन के ठीक नीचे app/src/host/agent.py फ़ाइल में टूल सेक्शन के नीचे रखें:
def create_agent(self) -> Agent:
"""Create an instance of the CoordinatorAgent."""
return Agent(
model=Gemini(
model='gemini-3.8-flash',
retry_options=types.HttpRetryOptions(attempts=5),
),
name='host',
instruction=self.root_instruction,
before_model_callback=self.before_model_callback,
description=(
'This coordinator agent orchestrates the retriever, evaluator, and emailer agents'
),
tools=[
self.send_message,
self.list_remote_agents,
],
)
एजेंट को send_message() टूल के लिए कुछ हेल्पर फ़ंक्शन की ज़रूरत होती है, ताकि A2A के हिस्सों को रॉ टेक्स्ट और डेटा में बदला जा सके. इस सेगमेंट को CoordinatorAgent क्लास से बाहर कॉपी करें:
##########################
# --- Helper Functions ---
##########################
async def convert_part(part: Part, tool_context: ToolContext):
"""Convert a part to text. Only text parts are supported."""
if part.HasField("text"):
return part.text
if part.HasField("data"):
return MessageToDict(part.data)
return f"Unknown type: {part}"
async def convert_parts(parts: list[Part], tool_context: ToolContext):
"""Convert parts to text."""
rval = []
for p in parts:
rval.append(await convert_part(p, tool_context))
return rval
adk web या adk run के ज़रिए स्थानीय टेस्टिंग और इंटरैक्शन को आसान बनाने के लिए, app/src/host/agent.py फ़ाइल के सबसे नीचे root_agent इनिशियलाइज़ेशन जोड़ें:
root_agent = CoordinatorAgent(
remote_agent_addresses=[
os.getenv('RETRIEVAL_AGENT_URL', 'http://localhost:8001'),
os.getenv('EVALUATOR_AGENT_URL', 'http://localhost:8002'),
os.getenv('EMAILER_AGENT_URL', 'http://localhost:8003'),
],
http_client=httpx.AsyncClient(timeout=30),
).create_agent()
बधाई हो! आपने अभी-अभी अपना पहला A2A होस्ट एजेंट बनाया है. हमने इसे root_agent वैरिएबल के साथ शुरू किया है. इसलिए, हम इसके साथ adk run या लोकल adk web डिप्लॉयमेंट के ज़रिए इंटरैक्ट कर सकते हैं. ठीक वैसे ही जैसे अन्य रिमोट एजेंट के साथ किया जाता है. होस्ट से इंटरैक्ट करने के लिए, इन निर्देशों का इस्तेमाल करें:
cd $HOME/app/src/
uv run adk run host
होस्ट, सिर्फ़ तब जवाब दे सकता है, जब तीनों रिमोट एजेंट सर्वर चालू हों. इन्हें अगले चरण में चालू किया जाएगा. जब तक यह सुविधा उपलब्ध नहीं होती, तब तक होस्ट, अभिवादन का जवाब दे सकता है. हालांकि, रिमोट एजेंट की ज़रूरत वाले किसी भी अनुरोध को पूरा नहीं किया जा सकता. ऐसा होने पर, AgentCardResolutionError दिखेगा. होस्ट को रोकने के लिए, exit टाइप करें.
10. लोकल तौर पर टेस्ट करना
मल्टी-एजेंट सिस्टम की पूरी तरह से जांच करने के लिए, आपको उन रिमोट एजेंट सर्वर को शुरू करना होगा जिन्हें आपको होस्ट एजेंट के लिए उपलब्ध कराना है. यह स्क्रिप्ट, सभी एजेंट सर्वर को एक साथ शुरू कर देगी. स्क्रिप्ट फ़ाइल बनाएं:
touch $HOME/app/start_agents.sh
cloudshell edit $HOME/app/start_agents.sh
नीचे दी गई स्क्रिप्ट को $HOME/app/start_agents.sh में कॉपी करें:
#!/bin/bash
# Exit immediately if a command exits with a non-zero status.
set -e
# Function to stop all background processes
cleanup() {
echo "Stopping agent servers..."
kill $(jobs -p) 2>/dev/null
wait
echo "All processes terminated."
}
# Call the cleanup function when the script exits or is interrupted
trap cleanup EXIT
# Start the agent servers in the background from the app directory
cd $HOME/app
echo "Starting agent servers..."
uv run python3 -m src.agents.retriever.server &
uv run python3 -m src.agents.evaluator.server &
uv run python3 -m src.agents.emailer.server &
# Start the host agent (it reads the remote agent URLs from .env)
cd $HOME/app/src/
uv run adk run host
# Wait for all background processes to finish
wait
इसके बाद, स्क्रिप्ट चलाएं:
bash $HOME/app/start_agents.sh
इस स्क्रिप्ट से, चारों एजेंट (डेटा पाने वाला, आकलन करने वाला, ईमेल भेजने वाला, और होस्ट) शुरू हो जाएंगे. आपको अपने टर्मिनल में, हर सर्वर का लॉग आउटपुट दिखेगा. सर्वर चालू होने के बाद, नई टर्मिनल विंडो खोलें और adk web इंटरफ़ेस लॉन्च करें:
# In a new terminal
cd $HOME/app/src/
uv run adk web
अपने टर्मिनल में दिखने वाला लोकल होस्ट लिंक खोलें. यहां से, होस्ट एजेंट के साथ सीधे इंटरैक्ट किया जा सकता है. इसके लिए, सबसे ऊपर बाईं ओर मौजूद ड्रॉप-डाउन मेन्यू से एजेंट को चुनें.
11. स्टोरेज में जगह बनाएं
शुल्क से बचने के लिए, इस कोडलैब के दौरान बनाए गए संसाधनों को मिटाएं.
चल रहे सभी एजेंट सर्वर बंद करें. इसके बाद, अगर आपने इस कोडलैब के लिए कोई प्रोजेक्ट बनाया है, तो उसे मिटा दें. उन टर्मिनल पर जाएं जिन्होंने रिमोट एजेंट लॉन्च किए थे और Ctrl+C चलाएं. इसके बाद, इस Google Cloud प्रोजेक्ट को हटाएं:
gcloud projects delete <YOUR_PROJECT_ID>
12. बधाई हो
आपने Agent2Agent की मदद से मल्टी-एजेंट सिस्टम बना लिया है!
आपने क्या सीखा
- ADK एजेंट को उनके टूल के साथ कैसे बनाया जाता है
- एजेंट कार्ड की मदद से, एजेंट को ऐसी पहचान देने का तरीका जिसे खोजा जा सके
- A2A सर्वर के ज़रिए एजेंटों को कैसे ऐक्सेस किया जा सकता है
- रिमोट एजेंट को व्यवस्थित करने वाला होस्ट एजेंट कैसे बनाएं
- A2A प्रोटोकॉल, अलग-अलग डेवलपर के बनाए गए एजेंट के बीच कम्यूनिकेशन कैसे चालू करता है
अगले चरण
- सिस्टम को प्रोडक्शन के लिए Cloud Run पर डिप्लॉय करना
- सिस्टम की क्षमताओं को बढ़ाने के लिए, ज़्यादा रिमोट एजेंट जोड़ें
- A2A में स्ट्रीमिंग और पुश नोटिफ़िकेशन की सुविधाओं के बारे में जानकारी