এজেন্ট২এজেন্ট সহ মাল্টি-এজেন্ট সিস্টেম

১. সংক্ষিপ্ত বিবরণ

এই কোডল্যাবে, আপনি একটি মাল্টি-এজেন্ট সিস্টেম তৈরি করবেন যেখানে একাধিক ADK এজেন্ট Agent2Agent (A2A) প্রোটোকল ব্যবহার করে একে অপরের সাথে যোগাযোগ ও সহযোগিতা করবে।

আপনি যা শিখবেন

  • একাধিক স্বাধীন ADK এজেন্ট কীভাবে তৈরি করবেন
  • কীভাবে প্রতিটি এজেন্টকে একটি এজেন্ট কার্ড দেবেন এবং তাদেরকে A2A সার্ভার হিসেবে প্রস্তুত করবেন
  • কীভাবে একটি হোস্ট এজেন্ট তৈরি করবেন যা আপনার রিমোট এজেন্টগুলোকে সমন্বয় করে
  • রিমোট এজেন্ট সংযোগ কীভাবে স্থাপন করবেন
  • স্থানীয়ভাবে মাল্টি-এজেন্ট সিস্টেম কীভাবে পরীক্ষা করবেন

আপনার যা যা লাগবে

  • বিলিং সক্ষম একটি গুগল ক্লাউড প্রজেক্ট
  • ক্রোমের মতো একটি ওয়েব ব্রাউজার
  • পাইথন ৩.১২+

এই কোডল্যাবটি সেইসব মধ্যম স্তরের ডেভেলপারদের জন্য, যাদের পাইথন এবং গুগল ক্লাউড সম্পর্কে কিছুটা ধারণা আছে।

এই কোডল্যাবটি সম্পন্ন করতে প্রায় ১৫ মিনিট সময় লাগে।

এই কোডল্যাবে তৈরি রিসোর্সগুলোর খরচ ৫ ডলারের কম হওয়া উচিত।

২. আপনার পরিবেশ প্রস্তুত করুন

একটি গুগল ক্লাউড প্রজেক্ট তৈরি করুন

  1. গুগল ক্লাউড কনসোলের প্রজেক্ট সিলেক্টর পেজে, একটি গুগল ক্লাউড প্রজেক্ট নির্বাচন করুন বা তৈরি করুন
  2. আপনার ক্লাউড প্রোজেক্টের জন্য বিলিং চালু আছে কিনা তা নিশ্চিত করুন। কোনো প্রোজেক্টে বিলিং চালু আছে কিনা তা কীভাবে পরীক্ষা করবেন, তা জেনে নিন।

ক্লাউড শেল এডিটর শুরু করুন

Google Cloud কনসোল থেকে একটি Cloud Shell সেশন চালু করতে, আপনার Google Cloud কনসোলে থাকা ‘Activate Cloud Shell’ বোতামে ক্লিক করুন।

এটি আপনার গুগল ক্লাউড কনসোলের নিচের প্যানে একটি সেশন চালু করে।

এডিটর চালু করতে, ক্লাউড শেল উইন্ডোর টুলবারে থাকা ‘ওপেন এডিটর’-এ ক্লিক করুন।

আপনার পরিবেশ কনফিগার করুন

আপনার A2A সিস্টেমের জন্য প্রজেক্ট ফোল্ডার কাঠামো তৈরি করতে প্রথমে আপনার টার্মিনালে নিম্নলিখিত কমান্ডটি চালান। এই ডেমোর জন্য আমরা আপনার $HOME ডিরেক্টরি থেকে অ্যাবসোলিউট পাথিং ব্যবহার করব:

mkdir -p $HOME/app/src/agents $HOME/app/src/host
touch $HOME/app/.env $HOME/app/pyproject.toml

এখন যেহেতু আমাদের কাছে সাধারণ কাঠামোটি আছে, চলুন পরিবেশের কনফিগারেশনগুলো পূরণ করা যাক। নিচের কোড অংশটি নতুন .env ফাইলে কপি করুন:

আপনার নতুন .env ফাইলটিতে আপনার GCP প্রজেক্ট আইডি এবং GCP রিজিয়ন যোগ করুন। আপনি যে এজেন্টটি তৈরি করতে চলেছেন, সেটির রিপোর্ট ইমেল পেতে চাইলে MAIL_TO তে আপনার পছন্দের একটি ইমেলও ইনপুট করতে পারেন। এছাড়াও, গিটহাব রিট্রিভাল এজেন্টকে সহজতর করার জন্য আপনি একটি GitHub পার্সোনাল অ্যাক্সেস টোকেন GITHUB_TOKEN যোগ করতে পারেন।

নিম্নলিখিত ব্যাশ কমান্ডটি ব্যবহার করে আপনার নতুন .env ফাইলটি খুলুন:

cloudshell edit .env

এবং তারপর নিচের ফাইলটি app.env এর .env ফাইলে কপি করুন। গুরুত্বপূর্ণ দ্রষ্টব্য: নিশ্চিত করুন যে আপনি আপনার নিজের মানগুলি প্রবেশ করিয়েছেন।

# --- Google Cloud ---
GOOGLE_GENAI_USE_VERTEXAI=TRUE
GOOGLE_CLOUD_PROJECT=<your-gcp-project-id>
GOOGLE_CLOUD_LOCATION=<your-gcp-project-region>

# --- 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>
MCP_SERVER_HOST=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

এখন যেহেতু আপনি আপনার এনভায়রনমেন্ট ভেরিয়েবলগুলো পূরণ করেছেন, আমাদের ইউভি এনভায়রনমেন্ট কনফিগার করতে হবে। নিচের কোড অংশটি 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,<3.14"
dependencies = [
    "resend>=2.21.0",
    "uvicorn>=0.40.0",
    "a2a-sdk>=0.3.26,<0.4.0",
    "google-adk[a2a]>=1.27.0,<1.30.0",
    "google-generativeai>=0.8.4",
    "httpx>=0.28.1",
    "pydantic>=2.12.5, <3.0.0",
    "python-dotenv>=1.2.0",
    "nest-asyncio>=1.6.0",
]

[project.optional-dependencies]
test = [
    "pytest>=8.3.2",
    "pytest-asyncio>=0.23.8",
    "pytest-mock>=3.14.0",
    "respx>=0.21.0",
]

[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 ফাইল থেকে সমস্ত প্রয়োজনীয় ডিপেন্ডেন্সি ইনস্টল করবে।

# Ensure you are in the 'app' directory before running this

# Exit immediately if a command exits with a non-zero status.
set -e

# 1. Install uv, the Python package manager used for this project
echo "Installing uv..."
if ! command -v uv &> /dev/null
then
    pip install uv
else
    echo "uv is already installed."
fi

# 2. Create and activate virtual environment
echo "Setting up virtual environment..."
# --clear ensures you start with a fresh environment
uv venv --clear

# 3. Install dependencies
echo "Installing Python dependencies..."
uv sync

echo "Installation and setup complete."

এখন আমাদের মাল্টি-এজেন্ট সিস্টেমটি তৈরি করার জন্য সবকিছু প্রস্তুত!

৩. রিট্রিভার এজেন্ট তৈরি করুন

ইভা একজন সফটওয়্যার ডেভেলপার, যিনি নতুন ইস্যু এবং পিআর (PR) যুক্ত হওয়ার সাথে সাথে গিটহাব রিপোজিটরিগুলোর সর্বশেষ তথ্য সম্পর্কে অবগত থাকতে চান। তাই, তার অনুরোধ করা গিটহাব ডেটা সংগ্রহের জন্য তিনি একটি 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.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-2.5-flash",
    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/ ডিরেক্টরিতে uv run adk web কমান্ডগুলো চালান:

cd $HOME/app/src/agents

uv run adk run retriever

আপনার 'uv run adk web' টার্মিনালে লোকালহোস্ট লিঙ্কটি খুলুন এবং এজেন্টটি পরীক্ষা করার জন্য নির্বাচন করুন।

৪. মূল্যায়নকারী এজেন্ট তৈরি করুন

রিচার্ড প্রায়শই দেখেন যে, তাঁর অ-প্রযুক্তিগত গ্রাহক এবং সহকর্মীদের জন্য তাঁকে প্রচুর প্রযুক্তিগত পরিভাষা সহজ করে বোঝাতে হয়। একই পরিভাষার সংজ্ঞা দিতে এবং একই প্রকল্পকে সহজভাবে ব্যাখ্যা করতে করতে বিরক্ত হয়ে, রিচার্ড এমন একটি সহজীকরণকারী উপাদান তৈরি করেন যা প্রযুক্তিগত পরিভাষাকে সংক্ষিপ্ত করে সহজে বোধগম্য পাঠ্যে পরিণত করে।

এই ডেমোর জন্য, ইভ্যালুয়েটর এজেন্টের ফাইলটি তৈরি করতে নিম্নলিখিত কমান্ডটি চালান:

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 google.adk.agents.llm_agent import Agent

# --- 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-2.5-flash",
    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/ ডিরেক্টরিতে একটি নতুন টার্মিনালে uv run adk web কমান্ডগুলো চালান:

cd $HOME/app/src/agents

uv run adk run evaluator

আপনার টার্মিনালে লোকালহোস্ট লিঙ্কটি খুলুন এবং এটি পরীক্ষা করার জন্য ইভ্যালুয়েটর এজেন্টটি নির্বাচন করুন।

৫. ইমেইলার এজেন্ট তৈরি করুন

ইভান প্রচুর ইমেল লিখতে লিখতে বিরক্ত হয়ে গেছে, যেখানে তাকে শুধু হাতের কাছে থাকা কোনো লেখা সংক্ষিপ্ত করে নতুন বিন্যাসে সাজাতে হয়। তাই সে একটি ইমেইলার এজেন্ট তৈরি করেছে, যা একটি নির্দিষ্ট লেখাকে নতুন বিন্যাসে সাজিয়ে একটি প্রদত্ত ইমেল অ্যাকাউন্টে পাঠিয়ে দেবে।

এই ডেমোর জন্য, ইমেইলার এজেন্টের ফাইলটি তৈরি করতে আপনার টার্মিনালে নিম্নলিখিত কমান্ডটি চালান:

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 resend

from dotenv import load_dotenv
from google.adk.agents.llm_agent import Agent

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 = f"<div style='font-family: sans-serif; white-space: pre-wrap;'>{body}</div>"

        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-2.5-flash",
    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/ ডিরেক্টরিতে একটি নতুন টার্মিনালে uv run adk web কমান্ডগুলো চালান:

cd $HOME/app/src/agents

uv run adk run emailer

আপনার টার্মিনালে লোকালহোস্ট লিঙ্কটি খুলুন এবং এজেন্টটি নির্বাচন করে পরীক্ষা করে দেখুন।

৬. এজেন্ট কার্ড তৈরি করুন

আমরা এইমাত্র তিনজন স্বতন্ত্র ডেভেলপারের তিনটি স্টোরি নিয়ে আলোচনা করেছি, যাদের প্রত্যেকের নিজস্ব স্বতন্ত্র এজেন্ট রয়েছে। এই সমস্ত এজেন্ট তাদের নিজ নিজ কোম্পানির এজেন্ট লাইব্রেরিতে প্রকাশিত ও লগ করা আছে। আরেকজন ডেভেলপার, ডায়ান, এই স্বতন্ত্র ধারণাগুলোকে একত্রিত করে একটি একক মাল্টি-এজেন্ট সিস্টেম তৈরি করতে চান।

তার লক্ষ্য হলো এমন একটি অন-ডিমান্ড রিসার্চ এজেন্ট পাওয়া, যা তাকে বিভিন্ন এজেন্ট ডেভেলপমেন্ট ফ্রেমওয়ার্কের ইস্যু এবং পিআর (পুল রিকোয়েস্ট) সম্পর্কে আপ-টু-ডেট রাখবে। তিনি আরও চান যে, এটি ইকোসিস্টেমের সমস্ত নতুন উন্নয়নের একটি সংক্ষিপ্ত সারসংক্ষেপ ইমেইলের মাধ্যমে পাঠাক। যেহেতু সমস্ত এজেন্ট আলাদা আলাদা পরিবেশে স্বতন্ত্রভাবে তৈরি করা হয়েছে, তাই এই বিদ্যমান এজেন্টগুলোকে একত্রিত করার জন্য A2A একটি আদর্শ সমাধান।

একাধিক রিমোট এজেন্ট একত্রিত করার প্রথম ধাপ হলো প্রয়োজনীয় প্রতিটি রিমোট এজেন্টকে একটি করে এজেন্ট কার্ড দেওয়া। এগুলোকে আপনার এজেন্টের বিজনেস কার্ড হিসেবে ভাবুন। এগুলো হলো JSON ফাইল, যা আপনার হোস্ট এজেন্টকে এজেন্টদের নাম, বিবরণ, সক্ষমতা এবং ইনপুট/আউটপুট স্কিমার মাধ্যমে শনাক্ত করার ক্ষমতা দেয়।

প্রথমে, আপনার প্রজেক্ট রুট থেকে নিম্নলিখিত কমান্ডটি চালান, যা 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.",
  "url": "http://localhost:8001",
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "stateTransitionHistory": false
  },
  "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.",
  "url": "http://localhost:8002",
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "stateTransitionHistory": false
  },
  "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 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.",
  "url": "http://localhost:8003",
  "capabilities": {
    "streaming": true,
    "pushNotifications": true,
    "stateTransitionHistory": false
  },
  "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."
      ]
    }
  ]
}

৭. রিমোট এজেন্ট এক্সিকিউটর তৈরি করুন

হোস্ট এজেন্টের দ্বারা রিমোট এজেন্টদের 'কল' বা 'কথোপকথন' করার জন্য, প্রত্যেকটির একটি এজেন্ট এক্সিকিউটর প্রয়োজন যা A2A সার্ভারের কাছে দৃশ্যমান এবং এজেন্ট কার্ড দ্বারা চিহ্নিত। এক্সিকিউটর হলো একটি অ্যাবস্ট্রাক্ট ক্লাস, যাতে execute() এবং cancel() মেথড থাকে। এই মেথডগুলো রিমোট এজেন্টকে আহ্বান করে তাকে কোনো কাজ বা বার্তা প্রদান করে, অথবা কাজটি সরাসরি বাতিল করে দেয়।

এখানে একটি অ্যাবস্ট্রাক্ট ADK এজেন্ট এক্সিকিউটরের বাস্তবায়ন রয়েছে যা রিমোট এজেন্টদের কাছে বার্তা পাঠানো এবং টাস্ক অর্ডার করার সুবিধা দেয়, যেখানে সকলেই TextPart আর্টিফ্যাক্ট বিনিময় করে। এর ফলে, আমরা এজেন্টদের মধ্যে শেয়ার করা একটি সাধারণ এজেন্ট এক্সিকিউটর ব্যবহার করতে পারি। একটি নতুন এক্সিকিউটর ফাইল তৈরি করুন:

touch $HOME/app/src/agents/executor.py

নিম্নলিখিত কোড অংশটি নতুন $HOME/app/src/agents/executor.py ফাইলে কপি করুন:

# $HOME/app/src/agents/executor.py
from a2a.server.agent_execution import AgentExecutor, RequestContext
from a2a.server.agent_execution.context import RequestContext
from a2a.server.events.event_queue import EventQueue
from a2a.server.tasks import TaskUpdater
from a2a.types import TaskState, TextPart, Part
from a2a.utils import new_agent_text_message, new_task

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(context.message) # type: ignore
        await event_queue.enqueue_event(task)

        updater = TaskUpdater(event_queue, task.id, task.context_id)
        if context.call_context:
            user_id = context.call_context.user.user_name
        else:
            user_id = "a2a_user"

        try:
            # Update status with custom message
            await updater.update_status(
                TaskState.working,
                new_agent_text_message(
                    self.status_message,
                    task.context_id,
                    task.id
                ),
            )

            # Process with ADK agent
            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(root=TextPart(text=response_text))],
                name=self.artifact_name,
            )

            await updater.complete()

        except Exception as e:
            await updater.update_status(
                TaskState.failed,
                new_agent_text_message(f"Error: {e!s}", task.context_id, task.id),
                final=True,
            )

    async def cancel(
            self,
            context: RequestContext,
            event_queue: EventQueue
        ) -> None:
        """Cancel the execution of a specific task."""
        raise NotImplementedError("Cancel not implemented for RetrieverAgentExecutor")

এখন যেহেতু আমাদের কাছে সেই অ্যাবস্ট্রাক্ট এজেন্ট এক্সিকিউটরটি আছে, আমরা পাইথনিক ইনহেরিটেন্স ব্যবহার করে প্রতিটি এজেন্টের নির্দিষ্ট ক্ষমতা এবং প্রয়োজন অনুসারে এক্সিকিউটরটিকে সূক্ষ্মভাবে টিউন করতে পারি। আমাদের ক্ষেত্রে, একটি পেলোড দিয়ে এজেন্টকে কল করা, প্রতিক্রিয়ার জন্য অপেক্ষা করা এবং প্রতিক্রিয়া পেলোডটি পুনরুদ্ধার করার কাজটি আমাদের ওয়ার্কফ্লোর জন্য সার্বজনীন। এই কারণে আমাদের কোনো নির্দিষ্ট পরিবর্তনের প্রয়োজন নেই। তবে, প্রতিটি এজেন্ট 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

৮. রিমোট এজেন্টদের A2A সার্ভারের সংস্পর্শে আনুন

এখন যেহেতু প্রত্যেক এজেন্টের নিজস্ব বিজনেস কার্ড আছে, তাই একটি A2A সার্ভারের মাধ্যমে কোনো এন্ডপয়েন্টে উন্মুক্ত করা হলে তাদের খুঁজে পাওয়া যায়। এই কোডল্যাবের জন্য, আমরা প্রতিটি রিমোট এজেন্ট এন্ডপয়েন্টের জন্য লোকালহোস্ট ব্যবহার করে পুরো প্রক্রিয়াটি স্থানীয় রাখছি। কিন্তু বাস্তবে, এগুলোকে যেকোনো কাঙ্ক্ষিত এন্ডপয়েন্টে উন্মুক্ত করা যেতে পারে, এবং এজেন্ট কার্ডের url ফিল্ডে সেটির উল্লেখ থাকলেই তা খুঁজে পাওয়া যাবে।

প্রতিটি রিমোট এজেন্টের জন্য পরবর্তী পদক্ষেপ হলো সেগুলোকে তাদের নিজস্ব 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 a2a.types import AgentCard
from a2a.server.apps import A2AStarletteApplication
from a2a.server.request_handlers import DefaultRequestHandler
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 = AgentCard(**card_data)

request_handler = DefaultRequestHandler(
    agent_executor=RetrieverAgentExecutor(
        agent=retriever_agent
    ),
    task_store=InMemoryTaskStore(),
)

server = A2AStarletteApplication(
    http_handler=request_handler,
    agent_card=github_retrieval_agent_card,
)

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8001))
    print(f"Starting Retriever Agent on Port {port}...")
    uvicorn.run(server.build(), host="0.0.0.0", port=port)

এরপর ইভ্যাল এজেন্টের জন্য সার্ভারটি তৈরি করুন:

# $HOME/app/src/agents/evaluator/server.py
import logging
import os
import json
import uvicorn

from a2a.types import AgentCard
from a2a.server.apps import A2AStarletteApplication
from a2a.server.request_handlers import DefaultRequestHandler
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 = AgentCard(**card_data)

request_handler = DefaultRequestHandler(
    agent_executor=EvaluatorAgentExecutor(agent=evaluator_agent),
    task_store=InMemoryTaskStore(),
)

server = A2AStarletteApplication(
    http_handler=request_handler,
    agent_card=content_evaluator_agent_card,
)

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8002))
    print(f"Starting Evaluator Agent on Port {port}...")
    uvicorn.run(server.build(), host="0.0.0.0", port=port)

এবং পরিশেষে, ইমেইলার এজেন্টের জন্য:

# $HOME/app/src/agents/emailer/server.py
import logging
import os
import json
import uvicorn

from a2a.types import AgentCard
from a2a.server.apps import A2AStarletteApplication
from a2a.server.request_handlers import DefaultRequestHandler
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 = AgentCard(**card_data)

request_handler = DefaultRequestHandler(
    agent_executor=EmailerAgentExecutor(
        agent=emailer_agent
    ),
    task_store=InMemoryTaskStore(),
)

server = A2AStarletteApplication(
    http_handler=request_handler,
    agent_card=emailer_agent_card,
)

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8003))
    print(f"Starting Emailer Agent on Port {port}...")
    uvicorn.run(server.build(), host="0.0.0.0", port=port)

৯. হোস্ট এজেন্ট তৈরি করুন

এখন পর্যন্ত আমরা মূলত আমাদের প্রতিটি এজেন্টকে একটি এপিআই-তে পরিণত করেছি, যাতে হোস্ট এজেন্ট সেটিকে পিং করতে পারে। এখন যেহেতু আমাদের রিমোট এজেন্টগুলো তাদের নিজস্ব এ২এ সার্ভারের সংস্পর্শে এসেছে, তাই আমাদের এমন একটি হোস্ট এজেন্ট তৈরি করতে হবে যা সেগুলোকে খুঁজে বের করবে এবং সমন্বয় করবে।

এটি সম্পন্ন করার জন্য আমাদের হোস্টের কয়েকটি ভিন্ন দিক তৈরি করতে হবে। প্রথমত, আমাদের প্রতিটি রিমোট এজেন্ট এবং তাদের সার্ভারের জন্য স্বতন্ত্র ক্লায়েন্ট তৈরির একটি উপায় তৈরি করতে হবে। এটি করা হয় একটি 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,
    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(message):
                if isinstance(event, Message):
                    return event
                if self.is_terminal_or_interrupted(event[0]):
                    return event[0]
                lastTask = event[0]
        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.completed,
            TaskState.canceled,
            TaskState.failed,
            TaskState.input_required,
            TaskState.unknown,
        ]

এখন আমাদের একটি নির্দিষ্ট ক্লায়েন্ট এবং এজেন্ট কার্ডের মাধ্যমে ক্লায়েন্ট ও সার্ভারের মধ্যে সংযোগ স্থাপন করার ক্ষমতা রয়েছে। এটি এমন একটি টুল হবে যা হোস্ট এজেন্ট দূরবর্তী এজেন্ট সার্ভারগুলোর সাথে সংযোগ স্থাপনের জন্য ব্যবহার করবে।

এবার হোস্ট এজেন্টটি তৈরি করার দিকে এগোনো যাক। প্রথমে নিচের কোড অংশটি app/src/host/agent.py ফাইলে কপি করুন। এটি হলো পাইথনিক ক্লাসটির ইনিশিয়ালাইজেশন, যার জন্য রিমোট এজেন্ট এন্ডপয়েন্ট এবং একটি স্ট্যান্ডার্ড 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,
    TextPart,
    TransportProtocol,
)

from google.adk import Agent
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_transports=[
                    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()
        card.url = address  # Use the actual address, not the hardcoded URL in the card JSON

        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 ফাইলের একই Host Agent পাইথন ক্লাসের প্রম্পট সেকশনের নিচে রাখুন।

    # --- 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.user,
            parts=[Part(root=TextPart(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
        state['task_id'] = task.id

        if task.status.state == TaskState.input_required:
            # Force user input back
            tool_context.actions.skip_summarization = True
            tool_context.actions.escalate = True
        elif task.status.state == TaskState.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.failed:
            # Raise error for failure
            raise ValueError(f'Agent {agent_name} task {task.id} failed')

        response = []
        if task.status.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 ফাইলের tools সেকশনের ঠিক নিচে নিম্নলিখিত কোড অংশটি রাখুন:

    def create_agent(self) -> Agent:
        """Create an instance of the CoordinatorAgent."""
        return Agent(
            model='gemini-2.5-flash',
            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,
            ],
        )

A2A অংশগুলোকে মূল টেক্সট এবং ডেটাতে রূপান্তর করার জন্য এজেন্টের send_message() টুলের জন্য কয়েকটি সহায়ক ফাংশন প্রয়োজন। এই অংশটি CoordinatorAgent ক্লাসের বাইরে কপি করুন:

##########################
# --- Helper Functions ---
##########################
async def convert_part(part: Part, tool_context: ToolContext):
    """Convert a part to text. Only text parts are supported."""
    if isinstance(part.root, TextPart):
        return part.root.text
    if part.root.kind == "data":
        return part.root.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

uv run 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` ভেরিয়েবল দিয়ে ইনিশিয়ালাইজ করেছি, তাই অন্যান্য রিমোট এজেন্টের মতোই লোকাল `uv run adk web deployment`-এর মাধ্যমে এর সাথে ইন্টারঅ্যাক্ট করতে পারবেন। আপনার হোস্টের সাথে ইন্টারঅ্যাক্ট করার জন্য নিম্নলিখিত কমান্ডগুলো ব্যবহার করুন:

cd $HOME/app/src/

uv run adk run host

১০. স্থানীয়ভাবে পরীক্ষা করুন

সম্পূর্ণ মাল্টি-এজেন্ট সিস্টেমটি পরীক্ষা করার জন্য, আপনাকে সেই রিমোট এজেন্ট সার্ভারগুলো চালু করতে হবে যেগুলো আপনি আপনার হোস্ট এজেন্টের ব্যবহারের জন্য রাখতে চান। এটি একবারে সমস্ত এজেন্ট সার্ভার চালু করে দেবে।

# Make sure you have activated your virtual environment first!
# source .venv/bin/activate

#!/bin/bash

# Exit immediately if a command exits with a non-zero status.
set -e

# Function to kill all background processes
cleanup() {
    echo "Caught signal, terminating background processes..."
    # The negative PID kills the entire process group
    kill -TERM -$$
    wait
    echo "All processes terminated."
    exit
}

# Trap TERM, INT, and EXIT signals and call the cleanup function
trap cleanup TERM INT EXIT

# Activate virtual environment
uv sync

# Start the agent servers in the background
echo "Starting agent servers..."
uv run python3 -m src.agents.retriever.server --port 8001 &
uv run python3 -m src.agents.evaluator.server --port 8002 &
uv run python3 -m src.agents.emailer.server --port 8003 &

cd $HOME/app/src/
RETRIEVER_AGENT_URL=http://localhost:8001
EVALUATOR_AGENT_URL=http://localhost:8002
EMAILER_AGENT_URL=http://localhost:8003
uv run adk run host

# Wait for all background processes to finish
wait

এই ব্যাশ কমান্ডটি চারটি এজেন্ট সার্ভারই ​​(রিট্রিভার, ইভ্যালুয়েটর, ইমেইলার এবং হোস্ট) চালু করবে। আপনি আপনার টার্মিনালে প্রতিটি সার্ভারের লগ আউটপুট দেখতে পাবেন। সার্ভারগুলো চালু হয়ে গেলে, আপনি একটি নতুন টার্মিনাল উইন্ডো খুলতে পারেন (একই app ডিরেক্টরিতে আছেন এবং ভার্চুয়াল এনভায়রনমেন্ট সক্রিয় করা আছে তা নিশ্চিত করে) এবং uv run adk ওয়েব ইন্টারফেসটি চালু করতে পারেন:

# In a new terminal, from the 'app' directory
source .venv/bin/activate
cd $HOME/app/src/
uv run adk web

আপনার টার্মিনালে প্রদর্শিত লোকালহোস্ট লিঙ্কটি খুলুন। এখান থেকে আপনি উপরের বাম দিকের ড্রপ-ডাউন মেনু থেকে হোস্ট এজেন্ট নির্বাচন করে সরাসরি তার সাথে যোগাযোগ করতে পারবেন।

১১. পরিষ্কার করা

চলমান চার্জ এড়াতে, এই কোডল্যাব চলাকালীন তৈরি করা রিসোর্সগুলো মুছে ফেলুন।

চলমান সমস্ত এজেন্ট সার্ভার বন্ধ করুন, তারপর যদি এই কোডল্যাবের জন্য বিশেষভাবে কোনো প্রজেক্ট তৈরি করে থাকেন, তবে সেটি ডিলিট করে দিন। যে টার্মিনালগুলো রিমোট এজেন্টগুলো চালু করেছিল সেখানে যান এবং Ctrl+C চাপুন, এবং তারপর এই গুগল ক্লাউড প্রজেক্টটি রিমুভ করুন:

gcloud projects delete ${GOOGLE_CLOUD_PROJECT}

১২. অভিনন্দন

আপনি Agent2Agent ব্যবহার করে সফলভাবে একটি মাল্টি-এজেন্ট সিস্টেম তৈরি করেছেন!

আপনি যা শিখেছেন

  • কীভাবে তাদের নিজস্ব টুল ব্যবহার করে স্বাধীন ADK এজেন্ট তৈরি করবেন
  • এজেন্ট কার্ডের মাধ্যমে এজেন্টদেরকে কীভাবে শনাক্তযোগ্য পরিচয় দেওয়া যায়
  • A2A সার্ভারের মাধ্যমে এজেন্টদের কীভাবে প্রকাশ করা যায়
  • কীভাবে একটি হোস্ট এজেন্ট তৈরি করবেন যা রিমোট এজেন্টদের সমন্বয় করে
  • কীভাবে A2A প্রোটোকল স্বাধীনভাবে বিকশিত এজেন্টদের মধ্যে যোগাযোগ সক্ষম করে

পরবর্তী পদক্ষেপ

  • উৎপাদন ব্যবহারের জন্য সিস্টেমটি ক্লাউড রান-এ স্থাপন করুন।
  • সিস্টেমের কার্যক্ষমতা বাড়াতে আরও রিমোট এজেন্ট যোগ করুন।
  • A2A-তে স্ট্রিমিং এবং পুশ নোটিফিকেশন সুবিধাগুলো অন্বেষণ করুন

রেফারেন্স নথি