Listen to this Post

Introduction
The convergence of artificial intelligence, workflow automation, and real-time API integration has fundamentally transformed how we approach complex multi-step processes. Manisha Rani’s AI-Powered Trip Planner represents a cutting-edge example of this transformation, demonstrating how AI agents can orchestrate travel planning across multiple data sources to deliver personalized, real-time recommendations. This project showcases the practical application of AI agents in solving real-world problems by combining conversational AI with live data aggregation from travel APIs, weather services, and event databases.
Learning Objectives
- Understand how to design and implement an AI-powered workflow automation system using n8n and OpenAI
- Learn to integrate multiple external APIs (SerpAPI, Google Sheets, Gmail, Telegram) into a cohesive automated workflow
- Master prompt engineering techniques for generating personalized travel recommendations based on real-time data
- Develop skills in building conversational AI agents with context memory for multi-turn interactions
You Should Know
- Designing the n8n Workflow Architecture for Multi-Step Automation
The foundation of this AI trip planner begins with n8n, an open-source workflow automation tool that serves as the orchestration layer connecting all components. The workflow starts with a Telegram trigger, which captures user messages containing travel requests. The first step involves parsing the user’s natural language input and extracting key parameters such as destination, dates, budget, and preferences using OpenAI’s API.
To set up n8n for this project, you’ll need to install it either locally or on a cloud instance. For local installation on Ubuntu/Debian:
Install Node.js and npm sudo apt update sudo apt install nodejs npm Install n8n globally npm install n8n -g Start n8n n8n start
For Windows, use the following in PowerShell:
Install n8n using npm npm install n8n -g Start n8n n8n start
The workflow nodes should be configured in this sequence: Telegram Trigger → OpenAI Node (for intent parsing) → Switch Node (to route based on intent) → SerpAPI Node (for flight/hotel/train searches) → HTTP Request Nodes (for weather and event APIs) → Google Sheets Node (for storing trip data) → Gmail Node (for sending itineraries). Each node must be carefully configured with authentication credentials stored as environment variables for security.
2. Implementing Conversational Memory with OpenAI’s API
Maintaining conversation context is critical for creating a natural travel planning experience. The AI agent must remember previous interactions, user preferences, and previously confirmed details. This is achieved by storing conversation history in a database or in-memory cache and passing it to OpenAI’s API with each request.
Here’s a Python example of how to maintain conversation memory using a Redis cache:
import redis
import openai
import json
Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
def get_conversation_history(user_id):
history = r.get(f"conversation:{user_id}")
if history:
return json.loads(history)
return []
def update_conversation(user_id, message, response):
history = get_conversation_history(user_id)
history.append({"role": "user", "content": message})
history.append({"role": "assistant", "content": response})
Keep last 10 exchanges for context
if len(history) > 20:
history = history[-20:]
r.set(f"conversation:{user_id}", json.dumps(history))
r.expire(f"conversation:{user_id}", 3600) Expire after 1 hour
def generate_response(user_id, user_message):
history = get_conversation_history(user_id)
system_prompt = """
You are an AI travel assistant. Help users plan their trips by asking for destination,
dates, budget, and preferences. Use the provided search results to make personalized
recommendations for flights, hotels, trains, weather, and local events.
"""
messages = [{"role": "system", "content": system_prompt}] + history
messages.append({"role": "user", "content": user_message})
response = openai.ChatCompletion.create(
model="gpt-4",
messages=messages,
temperature=0.7,
max_tokens=500
)
return response.choices[bash].message.content
This memory mechanism ensures the AI agent can reference previous discussions, making the conversation flow naturally rather than requiring the user to repeat information.
3. API Integration Strategy for Multi-Source Data Aggregation
The core value proposition of this trip planner lies in its ability to aggregate data from multiple sources into a unified experience. SerpAPI serves as the primary search engine API, enabling the agent to fetch flight, hotel, and train details. Weather data can be sourced from OpenWeatherMap or WeatherAPI, while local events can be pulled from Eventbrite or Ticketmaster APIs.
Here’s a practical example of using SerpAPI to fetch flight information:
import requests
def search_flights(origin, destination, departure_date, return_date=None):
params = {
"engine": "google_flights",
"departure_id": origin,
"arrival_id": destination,
"outbound_date": departure_date,
"api_key": "YOUR_SERPAPI_KEY"
}
if return_date:
params["return_date"] = return_date
response = requests.get("https://serpapi.com/search", params=params)
data = response.json()
flights = []
for flight in data.get("best_flights", []):
flights.append({
"airline": flight["airline"],
"departure_time": flight["departure_time"],
"arrival_time": flight["arrival_time"],
"price": flight["price"],
"duration": flight["duration"]
})
return flights
For hotel searches using SerpAPI:
def search_hotels(destination, check_in, check_out, guests=2):
params = {
"engine": "google_hotels",
"q": destination,
"check_in_date": check_in,
"check_out_date": check_out,
"adults": guests,
"api_key": "YOUR_SERPAPI_KEY"
}
response = requests.get("https://serpapi.com/search", params=params)
data = response.json()
hotels = []
for hotel in data.get("hotels", [])[:5]: Top 5 results
hotels.append({
"name": hotel["name"],
"rating": hotel.get("rating", "N/A"),
"price": hotel.get("price", "N/A"),
"address": hotel.get("address", "N/A")
})
return hotels
To maintain security, all API keys should be stored in environment variables rather than hardcoded in the workflow:
.env file SERPAPI_KEY=your_serpapi_key_here OPENAI_API_KEY=your_openai_key_here GOOGLE_SHEETS_CREDENTIALS=path_to_credentials.json GMAIL_CLIENT_ID=your_gmail_client_id GMAIL_CLIENT_SECRET=your_gmail_client_secret
In n8n, these environment variables can be accessed using `{{ $env.VARIABLE_NAME }}` syntax within the workflow nodes.
4. Data Processing and Personalization Logic
The raw data from APIs must be processed, filtered, and personalized before presenting it to the user. This involves applying user preferences (budget constraints, preferred airlines, star ratings, etc.) and generating personalized recommendations.
Here’s a Python function that processes flight data and filters based on user preferences:
def process_flight_recommendations(flights, max_price=None, preferred_airlines=None):
processed = []
for flight in flights:
Parse price (remove currency symbols and convert to float)
price_clean = float(flight['price'].replace('$', '').replace(',', ''))
Apply filters
if max_price and price_clean > max_price:
continue
if preferred_airlines and flight['airline'] not in preferred_airlines:
continue
processed.append({
"airline": flight['airline'],
"departure": flight['departure_time'],
"arrival": flight['arrival_time'],
"price": f"${price_clean:.2f}",
"duration": flight['duration']
})
Sort by price
return sorted(processed, key=lambda x: float(x['price'].replace('$', '')))
The prompt engineering for generating personalized recommendations requires carefully crafting the system message to incorporate all gathered data:
def generate_itinerary_prompt(user_preferences, flights, hotels, weather, events):
return f"""
Based on the user's preferences: {user_preferences}
Available Flights:
{flights}
Available Hotels:
{hotels}
Weather Forecast:
{weather}
Local Events:
{events}
Generate a personalized travel itinerary that includes:
1. Recommended flight options with best value and timing
2. Hotel recommendations matching budget and preferences
3. Daily activity suggestions based on weather and events
4. Packing recommendations based on weather conditions
5. Estimated total cost breakdown
Format the response as a structured day-by-day itinerary with clear sections.
"""
5. Google Sheets Integration for Trip Data Storage
Storing trip information in Google Sheets provides a structured data repository that enables data analysis, reporting, and future trip planning enhancements. The n8n Google Sheets node requires OAuth authentication or service account credentials.
To set up Google Sheets API access, follow these steps:
- Go to the Google Cloud Console and create a new project
2. Enable the Google Sheets API
- Create credentials (service account key) and download the JSON file
- Share your Google Sheet with the service account email address
Here’s a Python script to append trip data to Google Sheets:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def save_trip_to_sheets(trip_data, sheet_name="Trip Planner"):
scope = ["https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name(
'credentials.json', scope)
client = gspread.authorize(creds)
Open the sheet
sheet = client.open(sheet_name).sheet1
Define headers if empty
if not sheet.get_all_values():
headers = ["User ID", "Destination", "Start Date", "End Date",
"Flights", "Hotel", "Total Budget", "Generated Itinerary",
"Timestamp"]
sheet.append_row(headers)
Append trip data
row = [
trip_data.get("user_id"),
trip_data.get("destination"),
trip_data.get("start_date"),
trip_data.get("end_date"),
json.dumps(trip_data.get("flights")),
trip_data.get("hotel"),
trip_data.get("budget"),
trip_data.get("itinerary"),
datetime.now().isoformat()
]
sheet.append_row(row)
return True
6. Email Automation with Gmail API Integration
The final step in the workflow is sending the complete itinerary via email. The Gmail API integration in n8n handles authentication and email composition. For custom implementations, here’s a Python script using the Gmail API:
import base64
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
def send_itinerary_email(recipient, subject, body_html):
creds = Credentials.from_authorized_user_file('token.json')
service = build('gmail', 'v1', credentials=creds)
message = {
'to': recipient,
'subject': subject,
'body': body_html
}
Create the email message
raw_message = f"To: {message['to']}\r\n"
raw_message += f"Subject: {message['subject']}\r\n"
raw_message += "Content-Type: text/html; charset=utf-8\r\n"
raw_message += "\r\n"
raw_message += message['body']
encoded_message = base64.urlsafe_b64encode(
raw_message.encode('utf-8')).decode('utf-8')
try:
service.users().messages().send(
userId='me',
body={'raw': encoded_message}
).execute()
return True
except Exception as e:
print(f"Error sending email: {e}")
return False
What Undercode Say:
- Key Takeaway 1: The integration of multiple APIs (SerpAPI for travel data, OpenAI for conversational AI, Google Sheets for data persistence, and Gmail for email delivery) demonstrates how AI agents can seamlessly orchestrate complex workflows without requiring extensive custom coding, making AI automation accessible to a broader audience.
-
Key Takeaway 2: The project’s architecture showcases the importance of maintaining conversation memory for creating engaging, context-aware AI experiences, elevating the user experience from simple query-response to a meaningful conversational interaction that adapts to user preferences over multiple turns.
Analysis: This AI-powered trip planner represents a significant shift in how we approach automation, moving from traditional rule-based workflows to intelligent agents that can understand natural language, make decisions, and adapt to dynamic data conditions. The use of n8n as the orchestration layer exemplifies the growing trend of no-code/low-code automation platforms that democratize AI development. The project’s success lies in its practical problem-solving approach—addressing the real-world friction of planning travel across multiple websites by consolidating the experience into a single conversational interface. As AI agents become more sophisticated with improved reasoning capabilities and more extensive API ecosystems, we can expect these automated systems to handle increasingly complex tasks with minimal human intervention.
Expected Output:
Prediction:
- +1 The proliferation of AI-powered automation platforms like n8n will accelerate the development of industry-specific AI agents, with travel being just the beginning as similar architectures are adapted for healthcare scheduling, financial planning, and e-commerce personalization
- +1 The combination of conversational AI with real-time data APIs will create new opportunities for personalized services, reducing the cognitive load on users and potentially disrupting traditional travel agency business models
- -1 The reliance on multiple third-party APIs introduces significant operational risks, including rate limiting, API changes, and service disruptions that could impact the reliability of AI agents
- +1 As prompt engineering techniques improve and AI models become more contextually aware, the quality of personalized recommendations will surpass human-generated itineraries in terms of optimization and discovery
- -1 Security and privacy concerns surrounding the aggregation of personal data across multiple services will require robust encryption, consent management, and compliance with regulations like GDPR, potentially adding complexity to deployment
▶️ Related Video (80% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
Join Undercode Academy for Verified Certifications
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[email protected]
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: Manisha Rani – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


