Your Personal AI Travel Team: Implementing a Multi-Agent Trip Planner Using Autogen GroupChat
Imagine having a dedicated team of AI experts at your disposal, ready to plan your dream vacation. With Autogen's GroupChat functionality, you can create a personalized travel planner that automates the mundane tasks of itinerary planning, destination suggestions, and budget management. By harnessing the power of multiple AI agents, you'll receive a comprehensive travel report that serves as a customizable foundation for your perfect getaway. Let's dive into how to build this AI-powered travel planner and unlock the potential of personalized travel experiences. If you are new to Autogen then check out my previous blog posts here and here.
If you are in a rush and just want to see the code, head over to GitHub.
Introduction to Autogen and Multi-Agent Systems
Autogen is a powerful framework that allows us to create conversational AI agents that can work together to solve complex problems. In our case, we're going to create a team of AI agents that will work together to plan the perfect trip.
A multi-agent system is a group of intelligent agents that interact to solve problems that are beyond the capabilities of any individual agent. This approach is particularly useful for tasks that require different areas of expertise, like travel planning.
Setting up the environment
Before we start building our AI Travel Planner, let's set up our development environment.
Python Installation
If you don't have Python installed, visit the official Python website and follow the installation instructions for your operating system.
Installing AutoGen
We'll use PyAutoGen, which is the Python package for AutoGen:
pip install pyautogen
Getting the OPENAI_API_KEY
We are going to use OpenAI gpt-4o-mini
model as the brain for out travel planner. First, we need to acquire an OPENAI_API_KEY
from https://platform.openai.com/api-keys. If you don’t have an account you might need to register first. You might need to buy credits worth $5 to get started and if your account is new you might qualify for some free credits to get started.
Building our AI travel planner
Let's create our AI friend chatbot step by step. Create a project directory named autogen-multi-agent-travel-assistant
. Inside this directory, create a .env
file to store our API keys:
OPENAI_API_KEY=sk-proj-secret-key-xxxxxxxxxxxxx
Create a file named travel-planner.py
in your project directory. We'll build our chatbot in this file.
Import Required Libraries
import os
from dotenv import load_dotenv
from autogen import ConversableAgent, GroupChat, GroupChatManager
load_dotenv()
Setting up the LLM
Autogen agents require a llm_config
dict that configures how to set up the LLM we want to use and the API keys required.
llm_config = {
"config_list": [
{
"model": "gpt-4o-mini",
"api_key": os.getenv("OPENAI_API_KEY"),
}
]
}
Setting Up Our Travel Planning Team
Let's break down the different agents in our travel planning team:
- User Proxy Agent: This agent represents the user and initiates the planning process.
- Destination Expert Agent: Suggests and provides information about travel destinations.
- Itinerary Creator Agent: Creates a detailed day-by-day itinerary.
- Budget Analyst Agent: Provides cost estimates and financial advice.
- Report Writer Agent: Compiles all the information into a comprehensive travel report.
Each agent is given a specific role and instructions on how to perform its task.
user_proxy = ConversableAgent(
name="User_Proxy_Agent",
system_message="You are a user proxy agent.",
llm_config=llm_config,
human_input_mode="NEVER",
)
destination_expert = ConversableAgent(
name="Destination_Expert_Agent",
system_message="""
You are the Destination Expert, a specialist in global travel destinations. Your responsibilities include:
1. Analyzing user preferences (e.g., climate, activities, culture) to suggest suitable destinations.
2. Providing detailed information about recommended locations, including attractions, best times to visit, and local customs.
3. Consider factors like seasonality, events, and travel advisories in your recommendations.
4. SELECT 1 destination that you think is the best choice
5. DO NOT GIVE AN ITINERARY
Base your suggestions on a wide range of global destinations and current travel trends.
Format your response with a clear "DESTINATION SUMMARY" header.
""",
llm_config=llm_config,
human_input_mode="NEVER",
)
itinerary_creator = ConversableAgent(
name="Itinerary_Creator_Agent",
system_message="""
You are the Itinerary Creator, responsible for crafting detailed travel itineraries. Your role involves:
1. Creating day-by-day schedules for the entire trip duration.
2. Incorporating user preferences for activities, pace of travel, and must-see attractions.
3. Balancing tourist attractions with local experiences.
4. Considering practical aspects like travel times, opening hours, and meal times.
5. Ensuring the itinerary aligns with the budget provided by the BudgetAnalyst.
Aim to create engaging, well-paced itineraries that maximize the travel experience within given constraints.
Format your response with a clear "ITINERARY" header, followed by a day-by-day breakdown.
""",
llm_config=llm_config,
human_input_mode="NEVER",
)
budget_analyst = ConversableAgent(
name="Budget_Analyst_Agent",
system_message="""
You are the Budge tAnalyst, an expert in travel budgeting and financial planning. Your tasks are to:
1. Analyze the user's overall budget for the trip.
2. Provide detailed cost estimates for various aspects of the trip (transportation, accommodation, food, activities).
3. Suggest ways to optimize spending and find cost-effective options.
4. Create a budget breakdown for the entire trip.
5. Offer financial advice related to travel (e.g., best payment methods, travel insurance).
Always strive for accuracy in your estimates and provide practical financial advice for travelers.
Format your response with a clear "BUDGET" header.
""",
llm_config=llm_config,
human_input_mode="NEVER",
)
report_writer = ConversableAgent(
name="Report_Writer_Agent",
system_message="""
You are the Report Compiler agent, tasked with creating a comprehensive travel report based on the outputs of the following agents:
Destination_Expert_Agent: Provides a recommended destination.
Itinerary_Creator_Agent: Creates a detailed itinerary for the chosen destination.
Budget_Analyst_Agent: Analyzes the budget and provides cost estimates for the trip.
Your Task:
Gather Information: Collect the outputs from each agent.
Structure the Report: Organize the information into a clear and concise report format.
Create a Summary: Provide a brief overview of the recommended destination, itinerary, and budget.
Highlight Key Points: Emphasize the most important aspects of the trip, such as unique experiences or cost-saving tips.
Report Structure:
Introduction: A brief welcome and overview of the trip.
Destination Summary: Details from the Destination_Expert_Agent, including the chosen destination and reasons for recommendation.
Cultural Tips: Information on local customs, etiquette, and cultural norms.
Itinerary: The detailed itinerary created by the Itinerary_Creator_Agent, including day-by-day activities and accommodations.
Transportation: A summary of transport modes found at the destination and their prices
Budget Breakdown: The cost estimates and financial advice from the Budget_Analyst_Agent.
Packing List: List of essential and optional items to pack for your trip.
Conclusion: A summary of the trip and any final recommendations or suggestions.
""",
llm_config=llm_config,
human_input_mode="NEVER",
)
Creating the Group Chat
To allow our agents to work together, we use Autogen's GroupChat functionality. We define which agents are allowed to communicate with each other:
allowed_transitions = {
user_proxy: [destination_expert, user_proxy],
destination_expert: [itinerary_creator, user_proxy],
itinerary_creator: [budget_analyst, user_proxy],
budget_analyst: [report_writer, user_proxy],
report_writer: [user_proxy],
}
group_chat = GroupChat(
agents=[
user_proxy,
destination_expert,
itinerary_creator,
budget_analyst,
report_writer,
],
allowed_or_disallowed_speaker_transitions=allowed_transitions,
speaker_transitions_type="allowed",
messages=[],
max_round=6,
)
travel_planner_manager = GroupChatManager(
groupchat=group_chat,
llm_config=llm_config,
)
This setup ensures that our agents communicate in a logical order, passing information from one to the next as needed.
Putting It All Together
The main function is where everything comes together. It creates a simple interface for the user to input their travel preferences:
def main():
print("Welcome to the Travel Planning Assistant!")
print("You can plan your trip by providing details about your desired vacation.")
print("Type 'exit', 'quit', or 'bye' to end the session.")
while True:
user_input = input(f"Enter your trip details: ")
if user_input.lower() in ["exit", "quit", "bye"]:
print(f"Goodbye! Have a great day!!")
break
print("\\nPlanning your trip... This may take a moment.")
try:
chat_result = user_proxy.initiate_chat(
travel_planner_manager,
message=user_input,
summary_method="last_msg",
)
report = next(
msg["content"]
for msg in chat_result.chat_history
if msg.get("name") == "Report_Writer_Agent"
)
print("\\n-------------Final Holiday Details----------\\n")
print(report)
print("\\n--------------------------------------------\\n")
except Exception as e:
print(f"An error occurred while planning your trip: {str(e)}")
print("Please try again.")
if __name__ == "__main__":
main()
The main()
function acts as the user's gateway to our Travel Planning Assistant. Upon execution, it welcomes the user and provides clear instructions. A continuous loop then prompts the user for trip details, initiating the planning process through a user_proxy
that interacts with the travel_planner_manager
. Once complete, the function extracts the final travel report from the chat history, specifically focusing on the output from the "Report_Writer_Agent." This report is then formatted and presented to the user.
To ensure a seamless experience, the function incorporates robust error handling to address any unforeseen issues during the planning process. Additionally, users can exit the program at their discretion. This design creates a user-friendly interface that simplifies the complex AI-driven planning operations happening behind the scenes.
In essence, this function serves as the bridge between the user and our AI-powered travel planning system, facilitating the chat, processing user input, and delivering the final travel report.
Starting your travel planner
To start the chatbot, navigate to your project directory in the terminal and run:
python travel-planner.py
An example input is below:
Enter your trip details: Plan a holiday for 2 in Miami near the beach. It should be 6 days long from arrival to departure. We will be traveling from Harare to Miami via air
Conclusion
We managed to create a sophisticated travel planning assistant that combines the expertise of multiple AI agents by leveraging Autogen's GroupChat functionality. This approach allows us to create a more comprehensive and personalized travel planning experience. The system is very flexible, you can easily add more agents to target other areas of the trip planning process for example a weather forecaster agent. You can also easily modify existing agents to suit different types of travel planning needs.
The next step is to keep on experimenting with the prompts to see if you can get better results. I hope this has been exciting and worthwhile to read. Remember the code is available on GitHub. If you have any questions you can reach out to me on X (formerly twitter) or LinkedIn. Happy coding!
AI should drive results, not complexity. AgentemAI helps businesses build scalable, efficient, and secure AI solutions. See how we can help.