Generative AI

Creating Agent Agent for a Random number of A2A: Step Guide for the action to use a lower case pattern with Python

The Agent-to-agent Protocol (A2A) is a new standard for Google that empowered agents It works through appropriate classes, agent cards (explaining whether the agent can do), with work-based murder, allowing agents to participate in HTTP without a custom logic. A2A makes the scales easy, working with alent different systems by removing communication difficulties.

In this lesson, we will use a simple demo agent that returns random number, helping you understand the basic composition of A2A protocol through the code.

To set up the dependence

We will start to set up our environment and start by installing UV package manager. With Mac or Linux:

curl -LsSf  | sh 

Of Windows (PowerShip):

powershell -ExecutionPolicy ByPass -c "irm  | iex"

We will create a new project directory and start with UV

uv init a2a-demo
cd a2a-demo

We can now create and use physical environment. With Mac or Linux:

uv venv
source .venv/bin/activate

In Windows:

uv venv
.venvScriptsactivate

We will now include the leaning needed

uv add a2a-sdk python-a2a uvicorn

Using key building blocks

Agent Caxi (agent_execututor.py)

In this step, we use the basic logic of our agent by creating an agent assistant, which is responsible for managing requests and returning answers in A2A. This page MentrentnumbagentEcut Suggestion Mentrambambagent That produces a random number between 1 and 100. When an application is entered, the output method calls for an agent's concept and enforcing the result of the event line as an event message as an average A2A message. This setup creates a bacsend logic that A2A clients can contact. Look Full codes in Github

import random
from a2a.server.agent_execution import AgentExecutor
from a2a.server.agent_execution.context import RequestContext
from a2a.server.events.event_queue import EventQueue
from a2a.utils import new_agent_text_message
from pydantic import BaseModel


class RandomNumberAgent(BaseModel):
    """Generates a random number between 1 and 100"""

    async def invoke(self) -> str:
        number = random.randint(1, 100)
        return f"Random number generated: {number}"


class RandomNumberAgentExecutor(AgentExecutor):

    def __init__(self):
        self.agent = RandomNumberAgent()

    async def execute(self, context: RequestContext, event_queue: EventQueue):
        result = await self.agent.invoke()
        await event_queue.enqueue_event(new_agent_text_message(result))

    async def cancel(self, context: RequestContext, event_queue: EventQueue):
        raise Exception("Cancel not supported")

To set the A2A server and agent card (Main.py)

In this stage, it describes the metadata explaining what our agent can do – this is called Agent card. Think about it as an agent's business card, which contains details such as its name, description, skills available, types of installation, and type.

We also register the agent skills, explaining the type of activities I handle. In our case, including the ability to produce random number, mark according to the example in an agreement.

When Metadata is ready, we prepare for A2A server using A2astarleapplication. We provide a agent card and connect it with our agent agent using a DefauldtreeQuesHandleruse MentrentnumbagentEcut We have used it forward. Finally, we use the server using the Uvicorn so the agent can start listening to an A2A incoming messages in Durban 9999.

This is set up to make our agent for regular A2A messages, processing, and responds in an orderly way – following A2A Protocol. Look Full codes in Github

import uvicorn
from a2a.server.apps import A2AStarletteApplication
from a2a.server.request_handlers import DefaultRequestHandler
from a2a.server.tasks import InMemoryTaskStore
from a2a.types import AgentCapabilities, AgentCard, AgentSkill
from agent_executor import RandomNumberAgentExecutor


def main():
    # Define the skill metadata
    skill = AgentSkill(
        id="random_number",
        name="Random Number Generator",
        description="Generates a random number between 1 and 100",
        tags=["random", "number", "utility"],
        examples=["Give me a random number", "Roll a number", "Random"],
    )

    # Define the agent metadata
    agent_card = AgentCard(
        name="Random Number Agent",
        description="An agent that returns a random number between 1 and 100",
        url="
        defaultInputModes=["text"],
        defaultOutputModes=["text"],
        skills=[skill],
        version="1.0.0",
        capabilities=AgentCapabilities(),
    )

    # Configure the request handler with our custom agent executor
    request_handler = DefaultRequestHandler(
        agent_executor=RandomNumberAgentExecutor(),
        task_store=InMemoryTaskStore(),
    )

    # Create the A2A app server
    server = A2AStarletteApplication(
        http_handler=request_handler,
        agent_card=agent_card,
    )

    # Run the server
    uvicorn.run(server.build(), host="0.0.0.0", port=9999)


if __name__ == "__main__":
    main()

Contact with an agent using A2aclient (Client.py)

Next, we build a client that will contact our A2A AGENT. This client text performs three main activities:

  • Download the agent card: We begin by resolving the Agent's public metada using A2acardresolver. This is a File Agent.json File at the end of .jwell, which contain important information such as the Agent name, description, skills, and communication skills.
  • Start A2A client: Using the Find Center, we placed A2aclient, dealing with a contact protocol. This document will be responsible for sending messages organized into the agent and the answers they receive.

Send a message and get the answer: We create a message by text “Give me random number” using A2A message (message, part, text). The message is sent as part of the secondMesswageEquest, which is threatened with a unique application ID. As soon as the message is sent, the agent is considering and responding to a random number produced, published in JSON format. Look Full codes in Github

import uuid
import httpx
from a2a.client import A2ACardResolver, A2AClient
from a2a.types import (
    AgentCard,
    Message,
    MessageSendParams,
    Part,
    Role,
    SendMessageRequest,
    TextPart,
)

PUBLIC_AGENT_CARD_PATH = "/.well-known/agent.json"
BASE_URL = "


async def main() -> None:
    async with httpx.AsyncClient() as httpx_client:
        # Fetch the agent card
        resolver = A2ACardResolver(httpx_client=httpx_client, base_url=BASE_URL)
        try:
            print(f"Fetching public agent card from: {BASE_URL}{PUBLIC_AGENT_CARD_PATH}")
            agent_card: AgentCard = await resolver.get_agent_card()
            print("Agent card fetched successfully:")
            print(agent_card.model_dump_json(indent=2))
        except Exception as e:
            print(f"Error fetching public agent card: {e}")
            return

        # Initialize A2A client with the agent card
        client = A2AClient(httpx_client=httpx_client, agent_card=agent_card)

        # Build message
        message_payload = Message(
            role=Role.user,
            messageId=str(uuid.uuid4()),
            parts=[Part(root=TextPart(text="Give me a random number"))],
        )
        request = SendMessageRequest(
            id=str(uuid.uuid4()),
            params=MessageSendParams(message=message_payload),
        )

        # Send message
        print("Sending message...")
        response = await client.send_message(request)

        # Print response
        print("Response:")
        print(response.model_dump_json(indent=2))


if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Running the agent and asking the same

To check our A2A setup, we will start through the agent server. This is done by making the primary file.py, which starts the agent, display its agent card, and starts to listen to applications in Port 9999. Look Full codes in Github

When the agent has grown and running, we will move to the Customer Scripture. The client will download the agent's metadata, sending a structured question using A2A Protocol, and then receives an answer. In our position, the question is a simple message such as “give me a random number”, and the agent will return the number between 1 and 100.


Look Full codes in Github. All credit for this study goes to research for this project. Also, feel free to follow it Sane and don't forget to join ours 100K + ml subreddit Then sign up for Our newspaper.


I am the student of the community engineering (2022) from Jamia Millia Islamia, New Delhi, and I am very interested in data science, especially neural networks and their application at various locations.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button