Overview
在本指南中,您可以学习;了解如何创建使用LLPhant(一种PHP生成式AI框架)和MongoDB作为向量存储的应用程序。LLPhant 是一个开源的综合框架,提供范围功能,提供工具来构建AI驱动的应用程序,并支持多个 LLM 提供商。
为何将MongoDB与 LLPhant 结合使用?
LLPhant 支持使用MongoDB作为向量嵌入存储,这允许您构建需要语义搜索和向量操作的功能强大的AI应用程序。LLPhant 还支持 MongoDB 的 Voyage AI嵌入模型,该模型针对准确的AI搜索和检索进行了优化。MongoDB 的原生向量搜索功能与 LLPhant 的AI框架相结合,可提供以下功能:
存储和搜索嵌入:将 Voyage AI embeddings with MongoDB Vector Search 结合使用,可在大型文档集合中快速、准确地执行语义搜索查询。
灵活的文档存储:将结构化元数据和向量嵌入存储在同一文档中。
可扩展的AI应用程序:构建可处理大量文档和复杂查询的应用程序。
多模态搜索:对混合文本、图像和视频数据进行矢量化,并在单个搜索查询中查询这些数据。要学习;了解详情,请参阅 Voyage AI文档中的 多模态嵌入。
这种组合支持实际应用程序,例如智能文档管理系统、语义产品搜索、知识库和AI驱动的内容推荐引擎。
快速入门教程
本教程向您展示如何使用 LLPhant 和MongoDB构建智能文档搜索系统。该应用程序程序处理存储餐厅数据的文档,生成 Voyage AI向量嵌入,将其存储在MongoDB中,并提供语义搜索功能。本教程包括有关连接到MongoDB Atlas 集群和实施向量搜索功能的说明。
设置您的项目
按照本节中的步骤安装项目依赖项,创建Atlas集群,并设立应用程序结构。
创建 MongoDB Atlas 集群。
MongoDB Atlas是一项完全托管云数据库服务,用于托管MongoDB部署。如果您没有MongoDB 部署,可以通过完成MongoDB入门教程来免费创建MongoDB 集群。
要连接到MongoDB 集群,必须使用连接字符串。要学习;了解如何检索连接字符串,请参阅MongoDB入门教程的添加连接字符串部分。
重要
将连接string保存在安全位置。
配置应用程序
设置项目依赖项后,请按照本节中的步骤创建搜索服务并实现搜索功能。
创建搜索服务。
从 llphant-quickstart目录运行以下命令,创建 src 子目录和 DocumentSearchService.php文件。选择 macOS / Linux 或 Windows标签页,查看与您的操作系统相对应的命令:
mkdir -p src touch src/DocumentSearchService.php
mkdir src type nul > src\DocumentSearchService.php
然后,将以下代码添加到 src/DocumentSearchService.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); } }
此服务类接收嵌入生成器和向量存储作为依赖项,并且包含处理文档存储和向量相似度搜索的方法。
创建主应用程序脚本。
选择与操作系统相对应的标签页,然后运行以下命令,在 llphant-quickstart目录中创建 index.php文件:
touch index.php
type nul > index.php
然后,将以下代码添加到 index.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"; }
此主应用程序脚本执行以下操作:
使用MongoDB作为向量存储,并指定要使用的数据库、集合和索引。
创建示例文档,用于存储有关纽约市餐馆的信息。每个文档都包含餐厅名称、说明和AI生成的嵌入内容。
执行语义搜索查询,以查找与
"High-end restaurant with unique options and a romantic atmosphere"查询短语类似的餐厅说明。显示按向量相似度排名的搜索结果。
运行应用程序
按照本节中的步骤运行文档搜索应用程序并测试语义搜索功能。
运行应用程序。
在 llphant-quickstart目录中运行以下命令以启动应用程序:
php index.php
如果应用程序成功运行,输出将类似于以下代码:
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. ...
测试不同的搜索查询。
您可以通过修改 index.php文件中的 $searchQuery 变量并再次运行应用程序来试验语义搜索。示例,使用以下搜索查询:
# Sample search queries $searchQuery = "Casual place for Middle Eastern food"; $searchQuery = "Modern Italian restaurant"; $searchQuery = "Affordable restaurants serving Asian cuisine";
提示
在运行其他查询之前,注释掉 index.php文件中添加示例文档的代码。
语义搜索根据含义而不是精确的关键字匹配返回相关文档,展示了向量嵌入在智能搜索应用程序中的强大功能。
恭喜您完成 LLPhant 快速入门教程!
完成这些步骤后,您就拥有了一个智能文档搜索系统,该系统使用 LLPhant 和MongoDB提供语义搜索功能。该应用程序演示了如何生成嵌入,将其存储在MongoDB中,以及为AI支持的文档检索执行向量相似度搜索。
其他资源
要学习;了解有关 LLPhant、 MongoDB和构建AI应用程序的更多信息,请参阅以下资源:
LLPhant 文档
MongoDB Vector Search documentation