Explore Developer Center's New Chatbot! MongoDB AI Chatbot can be accessed at the top of your navigation to answer all your MongoDB questions.

MongoDB Developer
PHP
plus
Sign in to follow topics
MongoDB Developer Centerchevron-right
Developer Topicschevron-right
Languageschevron-right
PHPchevron-right

Introducing the Tour Planner With MongoDB Vector Search

Pavel Duchovny5 min read • Published Sep 24, 2024 • Updated Sep 24, 2024
AIAtlasVector SearchPHP
FULL APPLICATION
Facebook Icontwitter iconlinkedin icon
Rate this code example
star-empty
star-empty
star-empty
star-empty
star-empty
social-githubView Code
In today's fast-paced world, planning a trip can often feel like a daunting task. From selecting the perfect destinations to finding the most exciting activities, it can be overwhelming. But what if there was a smarter way to plan your travels? A way that combines leading technology like OpenAI and MongoDB to smarter applications? Welcome to the Tour Planner with MongoDB Vector Search!
A video with the application and solution overview!

The Essence of the Tour Planner

The Tour Planner project is an innovative travel planning application designed to simplify and enhance your travel experience. By leveraging the power of MongoDB Vector Search and integrating with OpenAI, the Tour Planner offers intelligent search and recommendation features with a few lines of code.
Main application page

Key features

Our advanced vector-based similarity search allows you to discover cities that match your interests. Whether you're looking for a city rich in history, a vibrant nightlife, or serene landscapes, our smart search feature will find the perfect destination for you.
Semantic Search with Vectors

2. Personalized points of interest

Gone are the days of generic travel recommendations. With the Tour Planner, you receive personalized points of interest based on your unique preferences. The document model allows developers to store and retrieve specific information crafted from different structures, while still being easily consumed by LLMs.
Planner customized

3. Intelligent trip planning

The integration of OpenAI into our platform takes trip planning to a whole new level. By analyzing your selected destinations and points of interest, our intelligent system generates a detailed itinerary that optimizes your time and enhances your travel experience. All you need to do is sit back and enjoy the journey. This in turn combines AI generated data with our real-time database to search for flights or other specific information for our personalized tour.
Plan built with AI

Why Laravel?

We chose Laravel for its robust and elegant framework that simplifies the development process. Laravel's built-in features, such as a powerful ORM, routing, and authentication, make it an ideal choice for building complex applications quickly and efficiently.

Ease of setup with MongoDB and Laravel OpenAI integrations

Integrating MongoDB and OpenAI with Laravel allows us to build retrieval-augmented generation (RAG) and AI-powered back ends seamlessly. MongoDB's flexible schema and powerful querying capabilities, combined with Laravel's expressive syntax, enable us to implement advanced search functionalities with ease. The integration with OpenAI further enhances our application by providing intelligent recommendations and dynamic trip planning features.
By using Laravel, MongoDB, and OpenAI together, we can create a scalable, efficient, and intelligent back end that leverages the best of modern web development technologies.
The OpenAI package for Laravel is not included by default in Laravel installations. You need to install it separately. Here's how you can add it to your project:
First, you need to install the package using Composer. Run this command in your project directory:
1composer require openai-php/laravel
After installation, you should publish the configuration file:
1php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
This will create a configuration file at config/openai.php. You'll need to set your OpenAI API key in this file or, preferably, in your .env file:
1OPENAI_API_KEY=your-api-key-here
Once installed and configured, you can use the OpenAI facade in your Laravel application as shown in the previous examples:
1use OpenAI\Laravel\Facades\OpenAI;
In our application, all those steps were performed and are part of the composer.json file.

How it works

The back end of the Tour Planner is powered by Laravel, under the app folder.
Points of interest and city information are stored in a MongoDB collection (points_of_interest) mapped to the following application model:
1<?php
2
3namespace App\Models;
4
5use MongoDB\Laravel\Eloquent\Model;
6
7class PointOfInterest extends Model
8{
9 protected $connection = 'mongodb';
10 protected $collection = 'points_of_interest';
11
12 protected $fillable = [
13 'name',
14 'description',
15 'type',
16 'rating',
17 'location',
18 'embedding',
19 ];
20
21 protected $casts = [
22 'location' => 'object',
23 'embedding' => 'array',
24 ];
25}
MongoDB Vector Search handles the complex search queries. When you search for a city or activity, the system generates embeddings based on your input and searches for the best matches within the database.
1$embedding = $this->generateEmbedding($search);
2$points = DB::collection('points_of_interest')
3 ->raw(function ($collection) use ($embedding) {
4 return $collection->aggregate([
5 [
6 '$vectorSearch' => [
7 'index' => 'vector_index',
8 'path' => 'embedding',
9 'queryVector' => $embedding,
10 'numCandidates' => 20,
11 'limit' => 5
12 ],
13 ],
14 [
15 '$project' => [
16 'name' => 1,
17 'description' => 1,
18 'rating' => 1,
19 'location' => 1,
20 'score' => ['$meta' => 'vectorSearchScore']
21 ]
22 ]
23 ]);
24 })
25 ->toArray();
The results are then augmented with relevant context using OpenAI to create a comprehensive trip plan. The system generates an itinerary that includes flight details, activities, and free time, ensuring every moment of your trip is well-planned.
1protected function generatePossibleTrip($cities, $context, $days) {
2 $result = OpenAI::chat()->create([
3 'model' => 'gpt-4o-mini',
4 'temperature' => 0,
5 'response_format' => ['type' => 'json_object'],
6 'messages' => [
7 [
8 'role' => 'system',
9 'content' => 'You are a travel agent helping a customer plan a trip to a city. If it will be hard to visit all in the number of days designated, return a one day plan stating the problem. The customer will provide you with points of interest to visit in json.'
10 ],
11 [
12 'role' => 'system',
13 'content' => 'Take this schema, for flights add orig_airport_code and dest_airport_code:
14 "tripPlan": {
15 "destination": [{
16 "city": "string",
17 "country": "string"
18 }],
19 "pointsOfInterest": [
20 {
21 "name": "string",
22 "description": "string",
23 "location": {
24 "coordinates": [number, number]
25 },
26 "rating": number
27 }
28 ],
29 "flights" : [ "src_airport_code": "string",
30 "dest_airport_code": "string"
31 ],
32 "itinerary": [
33 {
34 "day": number,
35 "destination": "string",
36 "activities": [
37 {
38 "time": "string",
39 "activity": "string",
40 "duration": "string",
41 // if flight
42 "src_airport_code": "string",
43 dest_airport_code: "string"
44 }
45 ...
46 ]
47 }
48 ...
49 ]
50 }'
51 ],
52 [
53 'role' => 'user',
54 'content' => 'For cities: ' . json_encode($cities) . '| Take this POIs: ' . $context . ' and build a plan for a trip of ' . $days . ' days.'
55 ]
56 ]
57 ]);
58 return $result->choices[0]->message->content;
59}
Since both the format expected and the system prompts specify a JSON output, the LLM returns a predictable flexible JSON that is being downstreamed easily to a frontend UI.

Getting started

To get started with the Tour Planner, you need a few prerequisites:
  • PHP 8.1+
  • MongoDB extension and prerequisites
  • Composer
  • Node.js and npm
  • MongoDB Atlas cluster
  • OpenAI API key
Clone the project on our GitHub repository.

Backend setup (Laravel):

Navigate to the cloned directory:
1cd laravel-openai-vector-search
Install PHP dependencies:
1composer install
Copy the .env.example file to .env and configure your environment variables:
1OPENAI_API_KEY=your_openai_api_key
2DB_URI=your_atlas_uri
Generate an application key:
1php artisan key:generate
Run database seeders:
1php artisan db:seed
This will create two collections under database trip_planner.
  • collection: points_of_interest. Sample document:
1{
2 "name": "Eiffel Tower",
3 "description": "Iconic iron lattice tower on the Champ de Mars in Paris.",
4 "type": "landmark",
5 "location": {
6 "city": "Paris",
7 "country": "France",
8 "coordinates": [
9 48.8584,
10 2.2945
11 ]
12 },
13 "rating": 4.7,
14 "embedding":[]
15}
  • Collection: air_routes. Sample document:
1{
2 "airline": {
3 "id": 410,
4 "name": "Aerocondor",
5 "alias": "2B",
6 "iata": "ARD"
7 },
8 "src_airport": "CEK",
9 "dst_airport": "KZN",
10 "codeshare": "",
11 "stops": 0,
12 "airplane": "CR2"
13}
Create an Atlas Vector Search index on the database: trip_planner collection: points_of_interest. See the guide for more details on how to index fields for vector search.
Index name: vector_index
1{
2 "fields": [
3 {
4 "type": "vector",
5 "path": "embedding",
6 "numDimensions": 1536,
7 "similarity": "cosine"
8 }
9 ]
10}
Start the Laravel development server:
1php artisan serve

Frontend setup (Vue.js)

Navigate to the frontend directory:
1cd frontend/trip-planner-frontend
2npm install
3npm run serve
The application should be visible at http://localhost:8080.

Conclusion

The Tour Planner utilizes MongoDB Vector Search to enhance travel planning capabilities. It combines user preferences with data analysis to suggest tailored trip options. This implementation demonstrates the integration of MongoDB, Laravel, and OpenAI technologies to create an advanced search application for travel recommendations.
Ready to start your journey? Dive into our documentation for detailed setup guides, try out MongoDB for yourself at MongoDB Atlas, and explore the project on GitHub. Unlock a new way of travel planning and make your next project with MongoDB.
Top Comments in Forums
There are no comments on this article yet.
Start the Conversation

Facebook Icontwitter iconlinkedin icon
Rate this code example
star-empty
star-empty
star-empty
star-empty
star-empty
Related
Tutorial

How To Build a Laravel + MongoDB Back End Service


Oct 01, 2024 | 15 min read
Quickstart

Complex Aggregation Pipelines with Vanilla PHP and MongoDB


Sep 05, 2024 | 10 min read
Code Example

Go-FIFA


Jul 07, 2022 | 2 min read
News & Announcements

Laravel Herd Adds Native MongoDB Support


Oct 07, 2024 | 0 min read
Technologies Used
Languages
Technologies
Table of Contents