How to use Python-A2A to create and connect financial agents with the agent agent protocol of Google (A2A)

by Brenden Burgess

When you buy through links on our site, we may earn a commission at no extra cost to you. However, this does not influence our evaluations.

Python A2A is an implementation of the Google agent (A2A) protocol (A2A), which allows AI agents to communicate with each other using a shared and standardized format – eliminating the need for personalized integration between services.

In this tutorial, we will use the approach based on the decorator provided by the Python-A2A library. With simple @agent And @skill Decorators, you can define the identity and behavior of your agent, while the library takes care of the management of the protocol and the flow of messages.

This method is perfect to quickly build useful agents and focused on tasks without worrying about the low -level communication logic.

Dependencies installation

To start, you will need to install the Python-A2A library, which provides clean abstraction to build and execute agents who follow the A2A protocol.

Open your terminal and run:

Create agents

For this tutorial, we will create two agents – one to calculate stock market yields according to investment, rate and time, and another to adjust an amount according to inflation over a period of years.

EMI Agent (EMI_AGENT.PY)

from python_a2a import A2AServer, skill, agent, run_server, TaskStatus, TaskState
import re

@agent(
    name="EMI Calculator Agent",
    description="Calculates EMI for a given principal, interest rate, and loan duration",
    version="1.0.0"
)
class EMIAgent(A2AServer):

    @skill(
        name="Calculate EMI",
        description="Calculates EMI given principal, annual interest rate, and duration in months",
        tags=("emi", "loan", "interest")
    )
    def calculate_emi(self, principal: float, annual_rate: float, months: int) -> str:
        monthly_rate = annual_rate / (12 * 100)
        emi = (principal * monthly_rate * ((1 + monthly_rate) ** months)) / (((1 + monthly_rate) ** months) - 1)
        return f"The EMI for a loan of ₹{principal:.0f} at {annual_rate:.2f}% interest for {months} months is ₹{emi:.2f}"

    def handle_task(self, task):
        input_text = task.message("content")("text")

        # Extract values from natural language
        principal_match = re.search(r"₹?(\d{4,10})", input_text)
        rate_match = re.search(r"(\d+(\.\d+)?)\s*%", input_text)
        months_match = re.search(r"(\d+)\s*(months|month)", input_text, re.IGNORECASE)

        try:
            principal = float(principal_match.group(1)) if principal_match else 100000
            rate = float(rate_match.group(1)) if rate_match else 10.0
            months = int(months_match.group(1)) if months_match else 12

            print(f"Inputs → Principal: {principal}, Rate: {rate}, Months: {months}")
            emi_text = self.calculate_emi(principal, rate, months)

        except Exception as e:
            emi_text = f"Sorry, I couldn't parse your input. Error: {e}"

        task.artifacts = ({
            "parts": ({"type": "text", "text": emi_text})
        })
        task.status = TaskStatus(state=TaskState.COMPLETED)

        return task

# Run the server
if __name__ == "__main__":
    agent = EMIAgent()
    run_server(agent, port=4737)

This EMI calculator agent is built using the Python-A2A library and follows the approach based on the decorator. Above, we use the @agent Decorator to define the name, description and version of the agent. This records the agent so that he can communicate using the A2A protocol.

Inside the class, we define a single skill using the @SkilThe Decorator. This competence, called calculatePerforms the real EMI calculation using the standard formula. The formula takes three parameters: the loan director, the annual interest rate and the duration of the loan in months. We convert the annual rate to a monthly rate and use it to calculate the monthly EMI.

THE handle_task The method is the heart of the agent. He receives the user's input message, extracts the relevant numbers using simple regular expressions and transmits them to the calculate_emi method.

Finally, at the bottom of the file, we launch the agent using the run_server () Port function 4737Preparing it to receive A2A protocol messages. This design maintains the agent simple, modular and easy to extend with more skills in the future.

Inflation agent (inflation_agent.py)

from python_a2a import A2AServer, skill, agent, run_server, TaskStatus, TaskState
import re

@agent(
    name="Inflation Adjusted Amount Agent",
    description="Calculates the future value adjusted for inflation",
    version="1.0.0"
)
class InflationAgent(A2AServer):

    @skill(
        name="Inflation Adjustment",
        description="Adjusts an amount for inflation over time",
        tags=("inflation", "adjustment", "future value")
    )
    def handle_input(self, text: str) -> str:
        try:
            # Extract amount
            amount_match = re.search(r"₹?(\d{3,10})", text)
            amount = float(amount_match.group(1)) if amount_match else None

            # Extract rate (e.g. 6%, 7.5 percent)
            rate_match = re.search(r"(\d+(\.\d+)?)\s*(%|percent)", text, re.IGNORECASE)
            rate = float(rate_match.group(1)) if rate_match else None

            # Extract years (e.g. 5 years)
            years_match = re.search(r"(\d+)\s*(years|year)", text, re.IGNORECASE)
            years = int(years_match.group(1)) if years_match else None

            if amount is not None and rate is not None and years is not None:
                adjusted = amount * ((1 + rate / 100) ** years)
                return f"₹{amount:.2f} adjusted for {rate:.2f}% inflation over {years} years is ₹{adjusted:.2f}"

            return (
                "Please provide amount, inflation rate (e.g. 6%) and duration (e.g. 5 years).\n"
                "Example: 'What is ₹10000 worth after 5 years at 6% inflation?'"
            )
        except Exception as e:
            return f"Sorry, I couldn't compute that. Error: {e}"

    def handle_task(self, task):
        text = task.message("content")("text")
        result = self.handle_input(text)

        task.artifacts = ({
            "parts": ({"type": "text", "text": result})
        })
        task.status = TaskStatus(state=TaskState.COMPLETED)
        return task

if __name__ == "__main__":
    agent = InflationAgent()
    run_server(agent, port=4747)

This agent helps to calculate the amount of a given amount in the future after adjusting inflation. It uses the same structure based on the decorator provided by the Python-A2A library. THE @agent The decorator defines the metadata of this agent and the @skill The decorator records the main logic under the name of “inflation adjustment”.

THE handle_input The method is the place where the main treatment occurs. It extracts the quantity, the inflation rate and the number of years of the user's input using simple regular expressions. If the three values ​​are present, it uses the standard standard value formula to calculate the adjusted amount as a function of inflation:

Adjusted value = amount × (1 + rate / 100) ^ years.

In case of value, the agent returns a useful prompt indicating to the user what to provide, including an example. THE handle_task The function connects while putting the user's message, by transmitting it to the skill function and by returning the formatted result to the user.

Finally, the agent is launched using run_server () on the port 4747Which prepares him to manage A2A requests.

Creation of the agent network

First run the two agents in two separate terminals

python inflation_agent.py

Each of these agents sets out a point of termination of the REST API (for example http: // Localhost: 4737 for EMI, http: // localhost: 4747 for inflation) using the A2A protocol. They listen to incoming tasks (like “calculate EMI for 2.00,000 ₹ …”) and respond with textual responses.

Now we will add these two agents to our network

from python_a2a import AgentNetwork, A2AClient, AIAgentRouter

# Create an agent network
network = AgentNetwork(name="Economics Calculator")

# Add agents to the network
network.add("EMI", "http://localhost:4737")
network.add("Inflation", "http://localhost:4747")

Then we will create a router to intelligently say requests to the best agent. This is a central utility of the A2A protocol – it defines a standard task format so that agents can be questioned uniformly, and routers can make smart routing decisions using LLMS.

router = AIAgentRouter(
    llm_client=A2AClient("http://localhost:5000/openai"),  # LLM for making routing decisions
    agent_network=network
)

Finally, we will question the agents

query = "Calculate EMI for ₹200000 at 5% interest over 18 months."
agent_name, confidence = router.route_query(query)
print(f"Routing to {agent_name} with {confidence:.2f} confidence")

# Get the selected agent and ask the question
agent = network.get_agent(agent_name)
response = agent.ask(query)
print(f"Response: {response}")
query = "What is ₹1500000 worth if inflation is 9% for 10 years?"
agent_name, confidence = router.route_query(query)
print(f"Routing to {agent_name} with {confidence:.2f} confidence")

# Get the selected agent and ask the question
agent = network.get_agent(agent_name)
response = agent.ask(query)
print(f"Response: {response}")

Discover the Notebooks inflation_agent.py,, network.ipynb And EMI_AGENT.PY. All the merit of this research goes to researchers in this project. Also, don't hesitate to follow us Twitter And don't forget to join our Subseubdredit 100k + ml and subscribe to Our newsletter.


I graduated in Civil Engineering (2022) by Jamia Millia Islamia, New Delhi, and I have a great interest in data science, in particular neural networks and their application in various fields.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.