Learn the "why" behind slow queries and how to fix them in our 2-Part Webinar.
Register now >
Docs Menu
Docs Home
/ /

Integrate MongoDB with LLPhant

In this guide, you can learn how to create an application that uses LLPhant, a PHP generative AI framework, and MongoDB as a vector store. LLPhant is an open-source, comprehensive framework that offers a range of features, providing tools to build AI-powered applications with support for multiple LLM providers.

LLPhant supports the use of MongoDB as a vector embeddings store, which allows you to build powerful AI applications that require semantic search and vector operations. LLPhant also supports MongoDB's Voyage AI embedding models, which are optimized for accurate AI search and retrieval. MongoDB's native vector search capabilities, combined with LLPhant's AI framework, provide the following features:

  • Store and search embeddings: Use Voyage AI embeddings with MongoDB Vector Search to perform fast, accurate semantic search queries across large document collections.

  • Flexible document storage: Store both structured metadata and vector embeddings in the same document.

  • Scalable AI applications: Build applications that can handle large volumes of documents and complex queries.

  • Multimodal search: Vectorize mixed text, image, and video data, and query this data in a single search query. To learn more, see Multimodal Embeddings in the Voyage AI documentation.

This combination supports real-world applications such as intelligent document management systems, semantic product search, knowledge bases, and AI-powered content recommendation engines.

This tutorial shows you how to build an intelligent document search system by using LLPhant and MongoDB. The application processes documents that store restaurant data, generates Voyage AI vector embeddings, stores them in MongoDB, and provides semantic search capabilities. The tutorial includes instructions for connecting to a MongoDB Atlas cluster and implementing vector search functionality.

Follow the steps in this section to install the project dependencies, create an Atlas cluster, and set up the application structure.

1

To create the Quick Start application, install the following software in your development environment:

Prerequisite
Notes

Use version 8.1 or later.

Install mongodb, the MongoDB PHP extension. Follow the instructions in the extension documentation that correspond to your operating system.

Required for PHP dependency management.

Required for generating embeddings. Create an account and generate an API key.

Code editor

Use the code editor of your choice.

Terminal app and shell

For macOS users, use Terminal or a similar app. For Windows users, use PowerShell or the Command shell.

2

MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. If you do not have a MongoDB deployment, you can create a MongoDB cluster for free by completing the MongoDB Get Started tutorial.

To connect to your MongoDB cluster, you must use a connection string. To learn how to retrieve your connection string, see the Add your connection string section of the MongoDB Get Started tutorial.

Important

Save your connection string in a secure location.

3

From your terminal, run the following commands to create a new directory for your project and navigate to it:

mkdir llphant-quickstart
cd llphant-quickstart
4

Install the required dependencies by running the following command:

composer require theodo-group/llphant symfony/dotenv mongodb/mongodb

This command installs LLPhant, the MongoDB PHP Library, and the Symfony dotenv package for managing environment variables.

5

In your llphant-quickstart directory, navigate to your composer.json file. Add the highlighted code to this file:

{
"require": {
"theodo-group/llphant": "^0.11.15",
"symfony/dotenv": "^8.0"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
...
}

This code instructs Composer to autoload classes in the App namespace from the src directory.

6

To store your environment variables, create an .env file in your llphant-quickstart directory. Paste the following code into the file:

VOYAGE_AI_API_KEY=<Voyage AI key>
MONGODB_URI=<connection string>

Replace the placeholder values with your Voyage AI API key and MongoDB connection string from the previous steps.

After setting up the project dependencies, follow the steps in this section to create the search service and implement search functionality.

1

Run the following commands from your llphant-quickstart directory to create a src subdirectory and a DocumentSearchService.php file. Select the macOS / Linux or Windows tab to see the commands that correspond to your operating system:

mkdir -p src
touch src/DocumentSearchService.php
mkdir src
type nul > src\DocumentSearchService.php

Then, add the following code to your src/DocumentSearchService.php file:

<?php
namespace App;
use LLPhant\Embeddings\EmbeddingGenerator\EmbeddingGeneratorInterface;
use LLPhant\Embeddings\VectorStores\VectorStoreBase;
use LLPhant\Embeddings\Document;
class DocumentSearchService
{
public function __construct(
private EmbeddingGeneratorInterface $embeddingGenerator,
private VectorStoreBase $vectorStore
) {
}
public function addDocument(string $title, string $content): void
{
// Generates embedding for the content
$document = new Document();
$document->content = $content;
$document->formattedContent = $title;
$this->embeddingGenerator->embedDocument($document);
// Adds to vector store
$this->vectorStore->addDocument($document);
}
public function searchDocuments(string $query, int $limit = 5): array
{
// Generates embedding for the query
$queryDocument = new Document();
$queryDocument->content = $query;
$this->embeddingGenerator->embedDocument($queryDocument);
// Searches using the embedding
return $this->vectorStore->similaritySearch($queryDocument->embedding, $limit);
}
}

This service class receives an embeddings generator and vector store as dependencies, and it includes methods that handle document storage and vector similarity search.

2

Select the tab corresponding to your operating system and run the following command to create an index.php file in your llphant-quickstart directory:

touch index.php
type nul > index.php

Then, add the following code to index.php:

<?php
require_once 'vendor/autoload.php';
use App\DocumentSearchService;
use LLPhant\Embeddings\EmbeddingGenerator\VoyageAI\Voyage3EmbeddingGenerator;
use LLPhant\Embeddings\VectorStores\MongoDB\MongoDBVectorStore;
use LLPhant\VoyageAIConfig;
use MongoDB\Client;
use Symfony\Component\Dotenv\Dotenv;
$dotenv = new Dotenv();
$dotenv->load(__DIR__ . '/.env');
$client = new Client($_ENV['MONGODB_URI']);
// Creates the embedding generator
$config = new VoyageAIConfig(apiKey: $_ENV['VOYAGE_AI_API_KEY']);
$embeddingGenerator = new Voyage3EmbeddingGenerator($config);
// Creates the vector store
$vectorStore = new MongoDBVectorStore(
$client,
'test',
'searchable_restaurants',
'restaurant_vector_idx'
);
$searchService = new DocumentSearchService($embeddingGenerator, $vectorStore);
// Sample restaurant documents to add
$restaurantDocs = [
[
"name" => "Le Bernardin",
"description" => "Elite French restaurant offers chef Eric Ripert's refined seafood, expert service & luxurious decor. Fine dining establishment known for exceptional French cuisine with a focus on seafood. Upscale, formal atmosphere with premium pricing. Reservations required. Dress code enforced."
],
[
"name" => "Au Za'atar",
"description" => "Polished eatery offering shawarma, mezze, and Lebanese dishes, plus outdoor dining. Features authentic shawarma, falafel, hummus, and fresh mezze platters. Relaxed atmosphere with both indoor and outdoor seating. Moderate pricing, family-friendly."
],
[
"name" => "Bacaro",
"description" => "Candlelit basement eatery serving pastas & Venetian small plates alongside Italian wines. Intimate Italian restaurant featuring traditional Venetian cicchetti (small plates) and handmade pasta. Romantic ambiance with dim lighting. Extensive Italian wine selection. Cozy, casual-upscale atmosphere. Moderate to high pricing."
],
[
"name" => "Levant",
"description" => "Cozy eatery serving Middle Eastern comfort food, with healthy options, and coffee. Offers authentic Lebanese, Syrian, and Mediterranean dishes. Known for fresh, healthy options including vegetarian and vegan choices. Warm, welcoming atmosphere. Great for lunch or casual dinner. Affordable pricing. Popular items include falafel wraps, tabbouleh, and grilled kebabs."
],
[
"name" => "Hangawi",
"description" => "Upscale menu of creative, gourmet Korean fare in a tranquil space where shoes come off at the door. Fine dining Korean restaurant specializing in traditional temple cuisine. Entirely vegetarian menu featuring organic ingredients. Unique cultural experience with floor seating and traditional Korean decor. Peaceful, meditative atmosphere. Upscale pricing. Reservations recommended."
]
];
echo "Adding sample restaurant documents...\n";
foreach ($restaurantDocs as $restaurant) {
$searchService->addDocument($restaurant['name'], $restaurant['description']);
echo "Added: {$restaurant['name']}\n";
}
echo "\nPerforming semantic search...\n";
$searchQuery = "High-end restaurant with unique options and a romantic atmosphere";
echo "Query: $searchQuery\n\n";
$results = $searchService->searchDocuments($searchQuery, 3);
echo "Search Results:\n";
foreach ($results as $index => $result) {
echo ($index + 1) . ". {$result->formattedContent}\n";
echo " Description: " . substr($result->content, 0, 100) . "...\n\n";
}

This main application script performs the following actions:

  • Uses MongoDB as a vector store, specifying the database, collection, and index to use.

  • Creates sample documents that store information about restaurants in New York City. Each document contains a restaurant name, description, and AI-generated embeddings.

  • Performs a semantic search query to find restaurant descriptions that are similar to the "High-end restaurant with unique options and a romantic atmosphere" query phrase.

  • Displays the search results ranked by vector similarity.

Follow the steps in this section to run your document search application and test the semantic search functionality.

1

From your llphant-quickstart directory, run the following command to start the application:

php index.php

If the application runs successfully, your output resembles the following code:

Adding sample documents...
Added: Le Bernardin
Added: Au Za'atar
Added: Bacaro
Added: Levant
Added: Hangawi
Performing semantic search...
Query: High-end restaurant with unique options and a romantic atmosphere
Search Results:
1. Au Za'atar
Description: Polished eatery offering shawarma, mezze, and Lebanese dishes, plus outdoor dining. Features authent...
2. Bacaro
Description: Candlelit basement eatery serving pastas & Venetian small plates alongside Italian wines. Intimate I...
3. Hangawi
Description: Upscale menu of creative, gourmet Korean fare in a tranquil space where shoes come off at the door. ...
2

You can experiment with the semantic search by modifying the $searchQuery variable in your index.php file and running the application again. For example, use the following search queries:

# Sample search queries
$searchQuery = "Casual place for Middle Eastern food";
$searchQuery = "Modern Italian restaurant";
$searchQuery = "Affordable restaurants serving Asian cuisine";

Tip

Before running additional queries, comment out the code that adds sample documents in your index.php file.

The semantic search returns relevant documents based on meaning rather than exact keyword matches, demonstrating the power of vector embeddings for intelligent search applications.

Congratulations on completing the LLPhant Quick Start tutorial!

After you complete these steps, you have an intelligent document search system that uses LLPhant and MongoDB to provide semantic search capabilities. The application demonstrates how to generate embeddings, store them in MongoDB, and perform vector similarity searches for AI-powered document retrieval.

To learn more about LLPhant, MongoDB, and building AI applications, see the following resources:

Back

Drupal Integration

On this page