Overview
このガイドでは、TLPhant、 PHP生成系AIフレームワーク、およびMongoDB をベクトルストアとして使用するアプリケーションを作成する方法を学習できます。LLPhant は、幅広い機能を提供し、複数の LLM プロバイダーをサポートするAI強化アプリケーションを構築するためのツールを提供するオープンソースの包括的なフレームワークです。
LHPhant でMongoDB を使用する理由
LLVent はベクトル埋め込みストアとしてMongoDBの使用をサポートしており、セマンティック検索とベクトル操作を必要とする強力なAIアプリケーションを構築できます。LHPhant は、正確なAI検索と取得のために最適化された MongoDB の Voyage AI埋め込みモデルもサポートしています。MongoDB のネイティブベクトル検索機能と LDP のAIフレームワークを組み合わせると、次の機能が提供されます。
埋め込みを保存して検索する: MongoDB Vector Search で Voyage AI埋め込みを使用すると、大規模なドキュメントコレクション全体で高速で正確なセマンティック検索クエリを実行できます。
柔軟なドキュメントストレージ: 構造化メタデータとベクトル埋め込みの両方を 同じドキュメントに保存します。
スケーラブルなAIアプリケーション: 大量のドキュメントと複雑なクエリを取り扱えるアプリケーションをビルドします。
マルチモーダル検索: テキスト、画像、ビデオの混合データをベクトル化し、このデータを 1 つの検索クエリーでクエリします。詳細については、Vorage AIドキュメントの「マルチモーダル埋め込み」を参照してください。
この組み合わせは、インテリジェントドキュメントマネジメントシステム、セマンティック製品検索、知識ベース、 AI強化コンテンツ推奨エンジンなどの本番環境のアプリケーションをサポートします。
クイック スタート チュートリアル
このチュートリアルでは、 LDP とMongoDBを使用してインテリジェントなドキュメント検索システムをビルドする方法を説明します。このアプリケーションは、レストラン データを保存するドキュメントを処理し、Voyage AIベクトル埋め込みを生成し、それらをMongoDBに保存し、セマンティック検索機能を提供します。チュートリアルには、 MongoDB Atlasクラスターに接続し、ベクトル検索機能を実装するための手順が含まれています。
プロジェクトを設定する
このセクションの手順に従って、プロジェクトの依存関係のインストール、Atlas クラスターの作成、およびアプリケーション構造の設定を行います。
前提条件を確認します。
クイック スタートアプリケーションを作成するには、開発環境に次のソフトウェアをインストールします。
前提条件 | ノート |
|---|---|
バージョン 8.1 以降を使用します。 | |
MongoDB PHP拡張機能である | |
PHP依存関係マネジメントに必要です。 | |
埋め込みの生成に必要です。アカウントを作成し、 APIキーを生成します。 | |
コードエディター | お好みのコード エディターを使用してください。 |
ターミナルアプリとシェル | macOS ユーザーの場合は、 ターミナル または 類似アプリを使用します。Windowsユーザーの場合は、 PowerShell または コマンドシェルを使用します。 |
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";
Tip
追加のクエリを実行中前に、index.phpファイルにサンプルドキュメントを追加するコードをコメントアウトします。
セマンティック検索では、キーワードの完全一致ではなく、意味に基づいて関連ドキュメントが返されるため、インテリジェント検索アプリケーション向けのベクトル埋め込みの能力が示されます。
LLFhant クイック スタート チュートリアルが完了しました。
これらの手順を完了すると、LDAP とMongoDBを使用してセマンティック検索機能を提供するインテリジェントなドキュメント検索システムが作成されます。このアプリケーションでは、埋め込みの生成方法、 MongoDBへの保存方法、およびAIによるドキュメント検索のベクトル類似度検索を実行する方法を説明します。
追加リソース
LLFhant、 MongoDB、およびAIアプリケーションの構築の詳細については、次のリソースを参照してください。
LLFhant のドキュメント
MongoDB Vector Search documentation
MongoDB PHPライブラリのドキュメント
Voyage AI のドキュメント