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

将MongoDB与 LLPhant 集成

在本指南中,您可以学习;了解如何创建使用LLPhant(一种PHP生成式AI框架)和MongoDB作为向量存储的应用程序。LLPhant 是一个开源的综合框架,提供范围功能,提供工具来构建AI驱动的应用程序,并支持多个 LLM 提供商。

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集群,并设立应用程序结构。

1

要创建快速入门应用程序,请在开发环境中安装以下软件:

先决条件
注意

使用 8.1 或更高版本。

安装 mongodb,MongoDB PHP 扩展。请按照与您的操作系统相对应的扩展文档中的说明进行操作。

PHP依赖项管理必需的。

生成嵌入时必需的。创建帐户并生成API密钥。

代码编辑器

使用您选择的代码编辑器。

终端应用和shell

对于 macOS 用户,请使用终端或类似应用。对于Windows用户,请使用 PowerShell 或 Command Shell。

2

MongoDB Atlas是一项完全托管云数据库服务,用于托管MongoDB部署。如果您没有MongoDB 部署,可以通过完成MongoDB入门教程来免费创建MongoDB 集群。

要连接到MongoDB 集群,必须使用连接字符串。要学习;了解如何检索连接字符串,请参阅MongoDB入门教程的添加连接字符串部分。

重要

将连接string保存在安全位置。

3

从终端运行以下命令,为项目创建新目录并导航到该目录:

mkdir llphant-quickstart
cd llphant-quickstart
4

通过运行以下命令来安装所需的依赖项:

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

此命令会安装 LLPhant、 MongoDB PHP库和用于管理环境变量的 Symfony dotenv包。

5

llphant-quickstart目录中,导航到 composer.json文件。将突出显示的代码添加到此文件:

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

此代码指示 Composer 从 src目录自动加载 App命名空间中的类。

6

要存储环境变量,请在 llphant-quickstart目录中创建 .env文件。将以下代码粘贴到文件中:

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

将占位符值替换为前面步骤中的 Voyage AI API密钥和MongoDB连接字符串。

设置项目依赖项后,请按照本节中的步骤创建搜索服务并实现搜索功能。

1

llphant-quickstart目录运行以下命令,创建 src 子目录和 DocumentSearchService.php文件。选择 macOS / LinuxWindows标签页,查看与您的操作系统相对应的命令:

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

然后,将以下代码添加到 src/DocumentSearchService.php文件中:

<?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);
}
}

此服务类接收嵌入生成器和向量存储作为依赖项,并且包含处理文档存储和向量相似度搜索的方法。

2

选择与操作系统相对应的标签页,然后运行以下命令,在 llphant-quickstart目录中创建 index.php文件:

touch index.php
type nul > index.php

然后,将以下代码添加到 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";
}

此主应用程序脚本执行以下操作:

  • 使用MongoDB作为向量存储,并指定要使用的数据库、集合和索引。

  • 创建示例文档,用于存储有关纽约市餐馆的信息。每个文档都包含餐厅名称、说明和AI生成的嵌入内容。

  • 执行语义搜索查询,以查找与 "High-end restaurant with unique options and a romantic atmosphere"查询短语类似的餐厅说明。

  • 显示按向量相似度排名的搜索结果。

按照本节中的步骤运行文档搜索应用程序并测试语义搜索功能。

1

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. ...
2

您可以通过修改 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应用程序的更多信息,请参阅以下资源:

后退

Drupal 集成

在此页面上