·6 min

AI Travel Planner with Microsoft AutoGen: Multi-Agent Collaboration

DK

Daniel Kliewer

Author, Sovereign AI

Microsoft AutogenMulti-Agent SystemsOpenAITravel PlanningAI Collaboration
Sovereign AI book cover

From the Book

This is from Sovereign AI: Building Local-First Intelligent Systems.

Get the Book — $88
AI Travel Planner with Microsoft AutoGen: Multi-Agent Collaboration

Image

Building an AI Travel Planner with AutoGen: A Step-by-Step Guide

This guide will help you create an AI-powered travel planner using Microsoft's AutoGen framework. The application will utilize multiple AI agents to collaborate and plan a personalized travel itinerary based on user preferences. We'll use Python and the AgentChat API of AutoGen to build this system.


Table of Contents

  1. Introduction
  2. Prerequisites
  3. Project Setup
  4. Installing Dependencies
  5. Creating the Agents
  6. Implementing the Main Program
  7. Running the Application
  8. Conclusion
  9. Additional Notes

Introduction

AutoGen is an open-source framework for building AI agent systems. It simplifies the creation of event-driven, distributed, scalable, and resilient agentic applications. In this guide, we'll build an AI Travel Planner where different AI agents collaborate to plan a travel itinerary based on user input.

Use Case: An AI Travel Planner that interacts with the user to gather preferences and coordinates multiple specialized agents (FlightAgent, HotelAgent, ActivityAgent) to plan flights, accommodations, and activities.


Prerequisites

  • Python 3.8+ installed on your machine.
  • OpenAI API Key: Obtain one from OpenAI.
  • Terminal Access: Ability to run commands in your operating system's terminal.
  • Git (optional): For version control.
  • Basic Knowledge of Python: Understanding of Python programming and asynchronous programming with asyncio.

Project Setup

1. Create a Project Directory

Open your terminal and create a new directory for the project:

bash
1mkdir ai_travel_planner
2cd ai_travel_planner

2. Initialize a Git Repository (Optional)

bash
1git init

3. Create a Virtual Environment

bash
1python3 -m venv venv

4. Activate the Virtual Environment

  • On Linux/macOS:

    bash
    1source venv/bin/activate
  • On Windows:

    bash
    1venv\Scripts\activate

Installing Dependencies

1. Upgrade pip

bash
1pip install --upgrade pip

2. Install AutoGen Packages

Install the required AutoGen packages and the OpenAI extension:

bash
1pip install 'autogen-agentchat==0.4.0.dev8' 'autogen-ext[openai]==0.4.0.dev8'

3. Install python-dotenv for Environment Variables

bash
1pip install python-dotenv

Creating the Agents

We'll create four agents:

  1. UserAgent: Interacts with the user to gather preferences.
  2. FlightAgent: Handles flight booking queries.
  3. HotelAgent: Handles accommodation booking.
  4. ActivityAgent: Suggests activities based on destination.

1. UserAgent

This agent will initiate the conversation with the user, gather preferences, and coordinate with other agents.

Code: user_agent.py

python
1# user_agent.py
2
3from autogen_agentchat.agents import UserProxyAgent
4from autogen_agentchat.message import AssistantMessage
5
6class UserAgent(UserProxyAgent):
7 pass # Inherits functionality from UserProxyAgent

2. FlightAgent

Handles flight-related queries and bookings.

Code: flight_agent.py

python
1# flight_agent.py
2
3import asyncio
4from autogen_agentchat.agents import AssistantAgent
5from autogen_ext.models import OpenAIChatCompletionClient
6
7async def search_flights(departure_city: str, destination_city: str, departure_date: str, return_date: str):
8 # Mock implementation of flight search
9 await asyncio.sleep(1) # Simulate network delay
10 return f"Found flights from {departure_city} to {destination_city} departing on {departure_date} and returning on {return_date}."
11
12flight_agent = AssistantAgent(
13 name="FlightAgent",
14 model_client=OpenAIChatCompletionClient(
15 model="gpt-4",
16 # api_key will be loaded from environment variable
17 ),
18 instructions="""
19You are an AI agent specialized in booking flights. Assist in finding flights based on user preferences.
20""",
21 tools=[search_flights],
22)

3. HotelAgent

Handles accommodation queries and bookings.

Code: hotel_agent.py

python
1# hotel_agent.py
2
3import asyncio
4from autogen_agentchat.agents import AssistantAgent
5from autogen_ext.models import OpenAIChatCompletionClient
6
7async def search_hotels(destination_city: str, check_in_date: str, check_out_date: str):
8 # Mock implementation of hotel search
9 await asyncio.sleep(1) # Simulate network delay
10 return f"Found hotels in {destination_city} from {check_in_date} to {check_out_date}."
11
12hotel_agent = AssistantAgent(
13 name="HotelAgent",
14 model_client=OpenAIChatCompletionClient(
15 model="gpt-4",
16 ),
17 instructions="""
18You are an AI agent specialized in booking accommodations. Assist in finding hotels based on user preferences.
19""",
20 tools=[search_hotels],
21)

4. ActivityAgent

Suggests activities at the destination.

Code: activity_agent.py

python
1# activity_agent.py
2
3import asyncio
4from autogen_agentchat.agents import AssistantAgent
5from autogen_ext.models import OpenAIChatCompletionClient
6
7async def suggest_activities(destination_city: str, interests: str):
8 # Mock implementation of activity suggestions
9 await asyncio.sleep(1) # Simulate processing time
10 return f"Suggested activities in {destination_city} based on your interests ({interests}): Visit the museum, explore downtown, enjoy local cuisine."
11
12activity_agent = AssistantAgent(
13 name="ActivityAgent",
14 model_client=OpenAIChatCompletionClient(
15 model="gpt-4",
16 ),
17 instructions="""
18You are an AI agent specialized in suggesting activities and attractions. Provide recommendations based on user interests.
19""",
20 tools=[suggest_activities],
21)

Implementing the Main Program

We'll now create the main script that ties everything together.

Code: main.py

python
1# main.py
2
3import asyncio
4import os
5from dotenv import load_dotenv
6from autogen_agentchat.agents import UserProxyAgent
7from autogen_agentchat.teams import SequentialTeam
8from autogen_agentchat.task import Console
9from autogen_ext.models import OpenAIChatCompletionClient
10
11# Import agents
12from flight_agent import flight_agent
13from hotel_agent import hotel_agent
14from activity_agent import activity_agent
15
16# Load environment variables
17load_dotenv()
18openai_api_key = os.getenv("OPENAI_API_KEY")
19
20# Ensure API key is set
21if not openai_api_key:
22 raise ValueError("OPENAI_API_KEY is not set in the environment variables.")
23
24# Set the API key for model clients
25flight_agent.model_client.api_key = openai_api_key
26hotel_agent.model_client.api_key = openai_api_key
27activity_agent.model_client.api_key = openai_api_key
28
29async def main():
30 # Create the user agent
31 user_agent = UserProxyAgent(
32 name="UserAgent",
33 )
34
35 # Define the travel planning team
36 travel_team = SequentialTeam(
37 agents=[
38 flight_agent,
39 hotel_agent,
40 activity_agent,
41 ],
42 user_agent=user_agent,
43 )
44
45 # Initial user message
46 user_message = input("You: ")
47
48 # Run the team
49 stream = travel_team.run_stream(task=user_message)
50 await Console(stream)
51
52if __name__ == "__main__":
53 asyncio.run(main())

Running the Application

1. Set Up Environment Variables

Create a .env file in your project directory:

bash
1touch .env

Add your OpenAI API key to the .env file:

ini
1# .env
2OPENAI_API_KEY=your_openai_api_key_here

Note: Replace your_openai_api_key_here with your actual API key.

2. Run the Application

bash
1python main.py

3. Interact with the Travel Planner

Example Interaction:

text
1You: I want to plan a trip to Paris from New York next month.
2
3FlightAgent: Found flights from New York to Paris departing on 2024-12-01 and returning on 2024-12-10.
4
5HotelAgent: Found hotels in Paris from 2024-12-01 to 2024-12-10.
6
7ActivityAgent: Suggested activities in Paris based on your interests (art, history): Visit the Louvre Museum, explore the Eiffel Tower, enjoy local French cuisine.

Conclusion

You've successfully built an AI Travel Planner using AutoGen! This application demonstrates how multiple AI agents can collaborate to perform complex tasks. Each agent specializes in a particular domain and communicates to provide a cohesive service to the user.


Additional Notes

  • Asynchronous Programming: The use of asyncio allows agents to perform tasks concurrently.
  • Mock Implementations: The functions search_flights, search_hotels, and suggest_activities are mock implementations. In a real-world application, you'd integrate with actual APIs.
  • Error Handling: For production use, add proper error handling and input validation.
  • Extensibility: You can extend this application by adding more agents, such as a CarRentalAgent or RestaurantAgent.

Happy Coding!

Sovereign AI book cover

Sovereign AI: Building Local-First Intelligent Systems

by Daniel Kliewer · Paperback · 72 pages

The hands-on guide to building AI that runs on your hardware, keeps your data private, and eliminates cloud dependence. Working code included.