Tuesday, June 9, 2026

Constructing a Multi-Agent System in Python


are the discuss of the city. We see them all over the place, even getting used for the only of duties on our telephones. They’re handy, quick, and just about dependable, and assist us navigate day-to-day life. If you would like a straightforward clarification of a scientific idea, you ask ChatGPT. You need a information in your choosy toddler’s weight-reduction plan plan, so that you ask AI. Even the duty of planning your full journey tour could be delegated to AI. And, that is precisely what we’re going to do on this tutorial (keep tuned!).

We learn about AI Brokers, however what if we will construct and use completely different AI Brokers for various roles in an even bigger undertaking? That is the place the multi-agent system idea comes into play. As AI functions turn into extra superior, we’re shifting from single AI fashions that reply easy questions and do easy duties to techniques the place a number of AI brokers work collectively to resolve advanced issues. A Multi-Agent System (MAS) is an idea the place a number of AI brokers collaborate with one another to satisfy an even bigger objective. Every of those has a particular position resulting in the last word objective, they usually accomplish it with mutual collaboration.

A Multi-Agent Journey Planning System

On this undertaking, we can be constructing a Multi-Agent Journey Planning System. So mainly, what we can have is that as a substitute of only one AI Agent who will plan our travels, we can have a staff of AI brokers, every with one particular position, and they’re going to work with each other to make the right journey plan for us!

We are able to consider a Multi-Agent Journey Planning System like an actual journey company. As an alternative of a single particular person dealing with every part, completely different consultants can be dealing with completely different duties as per their experience and work collectively. For our AI Journey Planner, we can have the next brokers:

AI Brokers in our Undertaking (Picture by Creator)
  1. Journey Analysis Agent: This agent will carry out the analysis duties. It is going to discover the vacation spot the place the consumer desires to go and discover sights, hidden locations, native experiences, journey suggestions, and so on. It is going to acquire the fundamental data wanted to plan the journey.
  2. Exercise Planning Agent: This agent will plan actions primarily based on the analysis of the Analysis Agent. It will likely be the one to resolve which place to go to, when to go to, what actions to do, and the way to arrange the entire journey!
  3. Price range Agent: This agent is liable for correct budgeting. It is going to analyze the plan shared by the Exercise Planning Agent and share the anticipated prices, inexpensive choices, money-saving suggestions, and assist customise the journey to the consumer’s funds.
  4. Remaining Journey Assistant: Lastly, the ultimate journey assistant will mix the output from all three brokers: the analysis, actions plan, and funds, and create a easy personalised journey itinerary!

That is what the overall workflow of the entire undertaking will appear to be:

Undertaking Workflow (Picture by Creator)

We’ll construct this undertaking in Python, utilizing PyCharm IDE. That is an intermediate-level Python undertaking that requires a primary understanding of AI Brokers in Python, in addition to a preliminary information of Object-Oriented Programming, as we can be creating lessons. If you’re new to Python and Agentic AI, you may entry my beginner-friendly AI Agent tutorial from the next hyperlink:

The Final Newcomers’ Information to Constructing an AI Agent in Python

If you wish to study Python OOP, you may learn the next articles the place I’ve created a Espresso Machine in Python, after which, within the subsequent tutorial, used the idea of OOP to optimize the code:

Implementing the Espresso Machine in Python

Implementing the Espresso Machine Undertaking in Python Utilizing Object-Oriented Programming

All these articles will provide you with a primary understanding of Python code, and can in flip provide help to perceive the code that comes underneath this attention-grabbing undertaking. Allow us to begin coding the undertaking!

Creating the Undertaking

The very first thing is creating the undertaking folder in PyCharm (or IDE of your selection) and naming the undertaking “Multi Agent System” (or something of your selection).

Creating the Undertaking (Picture by Creator)

Putting in and Importing the Python Packages

As soon as the undertaking folder is created, go on and create a “fundamental.py” file the place we’ll do our coding. Within the terminal, set up OpenAI after which import it into your coding file.

pip set up openai
Creating Folder, Python file, Putting in and Importing OpenAI (Picture by Creator)
from openai import OpenAI

Connecting Python With the AI Mannequin

To ensure that our program to speak with OpenAI and course of the code, we have to join it to the AI platform. In our case, we’ll use OpenRouter.ai and add its URL. We may even add the API Key to our code, saving it within the api_key variable. This API key will give our program the required permission to make use of AI fashions. We’ll create a consumer that can talk with the AI mannequin utilizing the API key we created:

consumer = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key="YOUR API KEY"
)

When you create an API key in OpenRouter.ai, don’t share the important thing with anybody. Simply add it within the place of “YOUR API KEY”.

Creating the Agent Class

Now comes the a part of coding the AI brokers. Since we aren’t creating only one or two brokers, we won’t be straight coding. Fairly, we’ll use the idea of OOP, and create a category (or a blueprint in straightforward phrases) of the agent class, after which use this blueprint to create every particular person agent forward. The agent will retailer the title which identifies the agent, and the position, that tells AI how the agent ought to behave. Moreover, we may even create a perform run that can give our AI brokers the power to work, that’s, to ship duties to the AI mannequin.


class Agent:

    def __init__(self, title, position):

        self.title = title
        self.position = position


    def run(self, activity):

        print(f"{self.title} is working...")


        response = consumer.chat.completions.create(

            mannequin="gpt-4.1-mini",

            messages=[

                {
                    "role": "system",
                    "content": self.role
                },

                {
                    "role": "user",
                    "content": task
                }

            ],
            max_tokens=1200

        )


        return response.decisions[0].message.content material

The code above will ship the next two issues to the AI mannequin (which we’ve got additionally specified):

  • The respective agent’s job/position
  • The Person message taken as enter from the consumer (as you will note later)

We’ll get the AI Response returned from this code block with the next code return response.decisions[0].message.content material. This return assertion will extract the reply generated by the agent (if you happen to discover it obscure this code, consult with my AI Agent newbie information article linked at first of this text).

Creating Agent Objects

Now that our agent class is created, we’ll use this blueprint to create our particular person AI brokers. The next code makes use of the OOP idea to create agent objects, specifically:

  1. Analysis Agent
  2. Exercise Agent
  3. Price range Agent
  4. Remaining Agent

research_agent = Agent(
    "Analysis Agent",
    """
    You're an professional journey researcher.
    Your job:
    - Discover in style sights
    - Discover hidden gems
    - Counsel native experiences
    - Advocate finest locations
    """
)

activity_agent = Agent(
    "Exercise Planner Agent",
    """
    You're a skilled journey planner.
    Your job:
    - Create day by day actions
    - Plan sightseeing
    - Advocate meals experiences
    - Manage actions logically
    """
)

budget_agent = Agent(
    "Price range Agent",
    """
    You're a journey funds professional.
    Calculate:
    - Estimated flight price
    - Visa necessities
    - Visa charges if wanted
    - Resort price
    - Meals bills
    - Transport price
    - Exercise prices
    Create an approximate whole journey funds.
    Preserve response brief.
    """
)

final_agent = Agent(
    "Remaining Journey Assistant",
    """
    You're a skilled journey planner.
    Create the ultimate itinerary.
    Embody:
    1. Brief journey overview
    2. Visa data
    3. Estimated flight price
    4. Day-wise plan
    5. Meals recommendations
    6. Complete estimated funds
    Preserve every part underneath 700 phrases.
    """
)

This code will create particular person AI brokers with particular roles as talked about within the code. The position tells the AI mannequin the way it ought to behave and what activity it ought to deal with.

Person Enter

The subsequent activity is to get the enter from the consumer. We’ll ask the consumer the next questions:

  • The place are they flying from
  • There they’re flying to
  • Variety of days of the journey
  • Variety of vacationers
  • Pursuits
#Get Person Journey Particulars

starting_location = enter(
    "The place are you flying from? "
)

vacation spot = enter(
    "The place do you need to journey? "
)

days = enter(
    "What number of days is your journey? "
)

vacationers = enter(
    "What number of vacationers? "
)

funds = enter(
    "What's your funds? (low/medium/excessive) "
)


pursuits = enter(
    "What are your pursuits? "
)

Creating the Person Request

After amassing data from the consumer via the enter statements, we mix every part right into a single immediate and move it over to the AI brokers.

# Create request for AI brokers

user_request = f"""

Create a journey plan with these particulars:

Flying From:
{starting_location}

Vacation spot:
{vacation spot}

Journey Period:
{days} days

Variety of Vacationers:
{vacationers}

Price range Degree:
{funds}

Pursuits:
{pursuits}

Embody:
- Visa necessities
- Estimated flight price
- Locations to go to
- Actions
- Meals suggestions
- Complete estimated funds

"""

print("nCreating your AI journey plan...n")

Whereas the AI is working within the backend, we’ll print the assertion “Creating your AI journey plan”, so the consumer is aware of that the method is working and the brokers have began working.

Multi-Agent Workflow

Now that we’ve got created the consumer request, by giving all of it the main points we’ve got taken from the consumer, allow us to now get the multi-agent system working. Every agent completes one activity and passes its outcome to the following agent.

The consumer’s journey particulars are first despatched to the Analysis Agent. This agent asks the AI mannequin to seek out one of the best locations to go to, native experiences, and journey data. The result’s saved in analysis. The analysis output turns into the enter for the Exercise Agent. It converts journey data into day by day actions, sightseeing plans, and meals concepts. The result’s saved in actions. Then comes the Price range Agent who receives the deliberate actions and estimates the prices of flights, visas, inns, transport, and so on. The result’s saved in funds. The Remaining Journey Agent receives data from the entire earlier brokers and combines every part into one full journey itinerary, which is then output to the consumer.

#Multi-Agent Workflow

#Agent 1 researches vacation spot
analysis = research_agent.run(
    user_request
)
print("n--- Analysis Accomplished ---")

#Agent 2 creates actions
actions = activity_agent.run(
    analysis
)
print("n--- Actions Deliberate ---")

#Agent 3 calculates funds
funds = budget_agent.run(
    actions
)
print("n--- Price range Created ---")

#Agent 4 creates closing itinerary
final_plan = final_agent.run(
    f"""
    Analysis:
    {analysis}

    Actions:
    {actions}

    Price range:
    {funds}

    Create closing journey plan.
    """
)

print("n==========================")
print(" FINAL TRAVEL PLAN")
print("==========================n")

print(final_plan)

Operating the Code

By working the code, you may see this system asking for consumer enter. You may add your particular particulars, answering the questions. It’s primarily based on these solutions that the AI brokers staff will make your journey itinerary.

Operating the Code (Picture by Creator)
"C:UsersMahnoor JavedPycharmProjectsMulti Agent System.venvScriptspython.exe" "C:UsersMahnoor JavedPycharmProjectsMulti Agent Systemmain.py" 
The place are you flying from? islamabad
The place do you need to journey? istanbul
What number of days is your journey? 3
What number of vacationers? 4
What's your funds? (low/medium/excessive) $4k
What are your pursuits? child frinedly

Creating your AI journey plan...

Analysis Agent is working...

--- Analysis Accomplished ---
Exercise Planner Agent is working...

--- Actions Deliberate ---
Price range Agent is working...

--- Price range Created ---
Remaining Journey Assistant is working...

==========================
 FINAL TRAVEL PLAN
==========================

### 3-Day Household-Pleasant Itinerary: Islamabad to Istanbul

---

#### Journey Overview
Uncover Istanbul’s fascinating mix of historical past, tradition, and family-friendly enjoyable on this 3-day journey from Islamabad. Discover iconic landmarks like Hagia Sophia and Topkapi Palace, dive into interactive experiences at Istanbul Aquarium and KidZania, and unwind in lovely parks and bustling bazaars. This itinerary balances cultural discovery with partaking actions excellent for teenagers, making certain recollections for your complete household.

---

#### Visa Info
- **For Pakistani Residents:** Turkish e-Visa required  
- **Software:** Apply on-line earlier than journey at [e-Visa Turkey official website]  
- **Price:** Approx. $50 per particular person  
- **Processing time:** Normally 24-48 hours  
- **Tip:** Carry a printout or e-copy of the e-Visa throughout journey.

---

#### Estimated Flight Price  
- **Route:** Islamabad (ISB) – Istanbul (IST) round-trip  
- **Price:** $350 - $450 per particular person in economic system class  
- **For 4 vacationers:** Approx. $1,400 - $1,800 whole  
- **Tip:** Guide 2-3 months upfront to safe higher offers.

---

### Day-wise Itinerary

**Day 1: Historic and Iconic Sights**  
- **Morning:**  
  - Arrive Istanbul, switch and check-in at a family-friendly resort close to Sultanahmet.  
  - Go to **Hagia Sophia**, immersing within the grandeur of this iconic monument.  
  - Stroll to **Topkapi Palace**, exploring expansive gardens and kid-friendly areas.  
- **Afternoon:**  
  - Chill out and play at **Sultanahmet Sq.**; children take pleasure in ample open house.  
  - Hop on the nostalgic **Sultanahmet tram** for a captivating experience across the historic district.  
- **Night:**  
  - Take pleasure in a **Bosphorus dinner cruise** that includes household leisure and child actions alongside scrumptious Turkish delicacies.

---

**Day 2: Interactive Enjoyable and Exploration**  
- **Morning:**  
  - Go to **Istanbul Aquarium (Florya)** to see numerous marine life, contact swimming pools, and themed zones.  
  - Lunch at aquarium’s family-friendly café or close by **Discussion board Istanbul Mall**.  
- **Afternoon:**  
  - Work together and play at **KidZania Istanbul** contained in the mall the place kids role-play professions and study via enjoyable.  
  - Take pleasure in mall playgrounds and snack breaks.  
- **Night:**  
  - Attempt well-known **Maraş dondurma** (Turkish ice cream) with entertaining vendor reveals.  
  - Leisurely mall or park stroll earlier than returning to resort.

---

**Day 3: Parks, Museums, Markets & Native Flavors**  
- **Morning:**  
  - Picnic and playtime at **Gülhane Park** with pony rides for kids.  
  - Discover the **Rahmi M. Koç Museum** that includes interactive reveals together with autos, toys, and a submarine.  
- **Afternoon:**  
  - Brief go to to the **Grand Bazaar** specializing in kid-friendly memento outlets.  
  - Pattern native avenue meals: **simit** (sesame bagels) and **gözleme** (savory crepes).  
- **Night:**  
  - Dinner at **Çiya Sofrası** for delicate conventional dishes or strive **Saray Muhallebicisi** for genuine Turkish desserts like sütlaç (rice pudding).

---

### Meals Strategies  
- **Çiya Sofrası (Kadıköy):** Genuine Turkish with kid-friendly choices  
- **Saray Muhallebicisi:** Conventional desserts excellent for household treats  
- **Midpoint/Cookshop:** Informal eating with worldwide and native menus appropriate for kids  
- **Avenue Meals:** Attempt simit, lahmacun (Turkish pizza), and borek pastries at native distributors  

---

### Estimated Price range (4 Individuals)

| Class                  | Estimated Price (USD)          |
|---------------------------|-------------------------------|
| Flights (Spherical-trip)      | $1,400 - $1,800               |
| Visa Charges                 | $200                          |
| Lodging (3 nights) | $600 - $800                   |
| Meals                      | $300 - $400                   |
| Transport (Istanbulkart, taxis) | $100                  |
| Entrance Charges & Actions| $300                          |
| Miscellaneous             | $200                          |
| **Complete Estimate**        | **~$3,100 - $3,800**          |

*Word: Price range can differ relying on resort selection and eating preferences.*

---

### Extra Suggestions  
- Guide tickets on-line upfront for in style sights to skip queues.  
- Buy an **Istanbulkart** for handy and discounted journey on public transport.  
- Pack comfy sneakers and solar safety for kids.  
- Go for lodging with household facilities and shut proximity to tram or metro stations in Sultanahmet or Beyoğlu districts.  
- Many eating places present children’ menus and excessive chairs—ask beforehand.

---

Would you want personalised resort suggestions and assist with reserving flights? Additionally, I can help you with native transport particulars or restaurant reservations. Simply let me know!

Course of completed with exit code 0

The above is the output of the code. You may see how personalised the journey itinerary is!

Conclusion

On this undertaking, we’ve got efficiently used our information of constructing AI brokers in Python to construct one thing that’s sensible and has real-life functions. That is how real-world issues are: we have already got a system working, however we have to optimize it and make it extra environment friendly, and these could be simply executed by implementing some primary ideas.

We might have constructed this journey planner utilizing a single AI agent and requested it to deal with every part. Nevertheless, by making a multi-agent system, we divided the work amongst specialised brokers, every specializing in one particular activity. This strategy makes the system extra organized, environment friendly, and nearer to how real-world groups clear up issues. As an alternative of 1 AI attempting to do every part, a number of AI brokers collaborate to create a greater and extra personalised outcome for the consumer.

By including reminiscence, exterior instruments, APIs, and real-time information, these brokers can turn into much more highly effective and clear up advanced real-world issues; a undertaking for subsequent time!

Related Articles

Latest Articles