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

MongoDB 와 LLPhant 통합

이 가이드 에서는 PHP 생성형 인공지능 프레임워크 인 LLPhantMongoDB 벡터 저장 로 사용하는 애플리케이션 만드는 방법을 학습 수 있습니다. LLPhant는 범위 기능을 제공하는 포괄적인 오픈 소스 프레임워크 , 여러 LLM 제공자를 지원 하는 AI 기반 애플리케이션을 빌드 할 수 있는 도구를 제공합니다.

LLPhant는 MongoDB 벡터 임베딩 저장 로 사용할 수 있도록 지원하므로 시맨틱 검색 및 벡터 연산이 필요한 강력한 AI 애플리케이션을 빌드 할 수 있습니다. LLPhant는 정확한 AI 검색 에 최적화된 MongoDB의 Voyage AI 임베딩 모델도 지원합니다. LLPhant의 AI 프레임워크 와 결합된 MongoDB의 네이티브 벡터 검색 기능은 다음과 같은 기능을 제공합니다.

  • 임베딩 저장 및 검색: MongoDB Vector Search와 함께 Voyage AI 임베딩을 사용하여 대규모 문서 컬렉션에서 빠르고 정확한 시맨틱 검색 쿼리를 수행합니다.

  • 유연한 문서 저장: 구조화된 메타데이터 와 벡터 임베딩을 모두 동일한 문서 에 저장합니다.

  • 확장 가능한 AI 애플리케이션: 대량의 문서와 복잡한 쿼리를 처리하다 할 수 있는 애플리케이션을 빌드합니다.

  • 멀티모달 검색: 텍스트, 이미지, 동영상이 혼합된 데이터를 벡터화하고 단일 검색 쿼리 로 이 데이터를 쿼리 . 자세한 학습 은 Voyage AI 문서에서 멀티모달 임베딩 을 참조하세요.

이 조합은 지능형 문서 관리 시스템, 시맨틱 제품 검색, 지식 기반, AI 기반 콘텐츠 추천 엔진과 같은 실제 애플리케이션을 지원합니다.

이 튜토리얼에서는 LLPhant와 MongoDB 사용하여 지능형 문서 검색 시스템을 빌드 방법을 보여줍니다. 이 애플리케이션 레스토랑 데이터를 저장 문서를 처리하고, Voyage AI 벡터 임베딩을 생성하여 MongoDB 에 저장하고, 시맨틱 검색 기능을 제공합니다. 이 튜토리얼에는 MongoDB Atlas cluster 에 연결하고 벡터 검색 기능을 구현하기 위한 지침이 포함되어 있습니다.

이 섹션의 단계에 따라 프로젝트 종속성을 설치하고, Atlas 클러스터를 만들고, 애플리케이션 구조를 설정하세요.

1

빠른 시작 애플리케이션 만들려면 개발 환경에 다음 소프트웨어를 설치하세요.

전제 조건
참고 사항

버전 8.1 이상을 사용하세요.

MongoDB PHP 확장인 mongodb을 설치합니다. 운영 체제에 해당하는 확장 문서의 지침을 따르세요.

PHP 종속성 관리 에 필요합니다.

임베딩을 생성하는 데 필요합니다. 계정을 만들고 API 키를 생성합니다.

코드 편집기

원하는 코드 편집기를 사용하세요.

터미널 앱 및 shell

macOS 사용자의 경우 터미널 또는 유사한 앱 사용하세요. Windows 사용자의 경우 PowerShell 또는 명령 shell 사용합니다.

2

MongoDB Atlas 는 MongoDB 배포를 호스팅하는 완전 관리형 클라우드 데이터베이스 서비스입니다. MongoDB 배포서버 없는 경우, MongoDB 시작하기 튜토리얼을 완료하여 MongoDB 클러스터 무료로 만들 수 있습니다.

MongoDB cluster 에 연결하려면 연결 문자열 사용해야 합니다. 연결 문자열 조회 방법을 학습 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/"
}
},
...
}

이 코드는 컴포저가 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 / Linux 또는 Windows 탭 선택하여 운영 체제에 해당하는 명령을 확인합니다.

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 통합

이 페이지의 내용