PHP code example of moneo / laravel-rag

1. Go to this page and download the library: Download moneo/laravel-rag library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

moneo / laravel-rag example snippets


use Moneo\LaravelRag\Concerns\HasVectorSearch;
use Moneo\LaravelRag\Concerns\AutoEmbeds;

class Document extends Model
{
    use HasVectorSearch, AutoEmbeds;

    protected string $embedSource = 'content';
    protected string $vectorColumn = 'embedding';
}

Schema::create('documents', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->text('content');
    $table->vector('embedding', 1536);
    $table->json('metadata')->nullable();
    $table->timestamps();

    $table->vectorIndex('embedding', method: 'hnsw', distance: 'cosine');
    $table->fulltextIndex('content');
});

use Moneo\LaravelRag\Facades\Ingest;

// From file
Ingest::file('docs/guide.pdf')
    ->chunk(strategy: 'markdown', size: 500)
    ->storeIn(Document::class)
    ->run();

// From text
Ingest::text($content)
    ->chunk(strategy: 'sentence')
    ->withMetadata(['category' => 'tech'])
    ->storeIn(Document::class)
    ->dispatch(); // async via queue

use Moneo\LaravelRag\Facades\Rag;

// Simple RAG
$result = Rag::from(Document::class)
    ->limit(5)
    ->threshold(0.8)
    ->ask('What is pgvector?');

echo $result->answer;
echo $result->totalTimeMs(); // timing

// With sources
$result = Rag::from(Document::class)
    ->askWithSources('How does indexing work?');

foreach ($result->sources() as $source) {
    echo "{$source['source']} (score: {$source['score']})";
}

// Dry run — retrieve only
$chunks = Rag::from(Document::class)
    ->dryRun('What is pgvector?');

// In a controller
return Rag::from(Document::class)
    ->stream($request->question)
    ->toStreamedResponse();

$result = Rag::from(Document::class)
    ->hybrid(semanticWeight: 0.7, fulltextWeight: 0.3)
    ->limit(10)
    ->ask('pgvector performance');

$result = Rag::from(Document::class)
    ->limit(20)       // retrieve 20 candidates
    ->rerank(topK: 5) // LLM scores and keeps top 5
    ->ask('question');

$result = Rag::from(Document::class)
    ->agentic(maxSteps: 3)
    ->ask('Complex multi-part question?');

echo $result->answer;
echo $result->stepCount();           // retrieval iterations
echo $result->totalChunksRetrieved;  // total chunks gathered

use Moneo\LaravelRag\Memory\RagThread;

$thread = RagThread::create(['model' => Document::class]);

$result1 = $thread->ask('What is Laravel?');
$result2 = $thread->ask('Compare it with Symfony.'); // context-aware

Ingest::text($content)
    ->chunk(strategy: 'character', size: 500, overlap: 50)
    ->chunk(strategy: 'sentence')
    ->chunk(strategy: 'markdown')
    ->chunk(strategy: 'semantic', threshold: 0.85)
    ->storeIn(Document::class)
    ->run();

use Moneo\LaravelRag\Facades\RagEval;

$report = RagEval::suite()
    ->using(Rag::from(Document::class))
    ->add(question: 'What is pgvector?', expected: 'A PostgreSQL extension for vector similarity search')
    ->add(question: 'How to install?', expected: 'Run composer 

// In AppServiceProvider::boot()
use Moneo\LaravelRag\Mcp\RagMcpServer;

app(RagMcpServer::class)
    ->register(Document::class)
    ->as('company-docs')
    ->description('Search internal company documentation')
    ->expose();

// In your PanelProvider
->plugins([
    \Moneo\LaravelRag\Filament\RagPlugin::make(),
])

use Moneo\LaravelRag\VectorStores\Contracts\VectorStoreContract;

class QdrantStore implements VectorStoreContract
{
    public function upsert(string $id, array $vector, array $metadata): void { /* ... */ }
    public function similaritySearch(array $vector, int $limit, float $threshold = 0.0): Collection { /* ... */ }
    public function hybridSearch(string $query, array $vector, float $semanticWeight, float $fulltextWeight, int $limit): Collection { /* ... */ }
    public function delete(string $id): void { /* ... */ }
    public function flush(string $collection): void { /* ... */ }
    public function table(string $table): static { /* ... */ }
    public function supportsFullTextSearch(): bool { return false; }
}

$this->app->singleton(VectorStoreContract::class, QdrantStore::class);
bash
php artisan vendor:publish --tag=rag-config
bash
php artisan vendor:publish --tag=rag-migrations
php artisan migrate
bash
# 1. Download sqlite-vec
wget https://github.com/asg017/sqlite-vec/releases/download/v0.1.7/sqlite-vec-0.1.7-loadable-linux-x86_64.tar.gz
tar xzf sqlite-vec-*.tar.gz
sudo mkdir -p /usr/lib/sqlite-vec && sudo cp vec0.so /usr/lib/sqlite-vec/

# 2. Add to php.ini
echo "sqlite3.extension_dir=/usr/lib/sqlite-vec" | sudo tee /etc/php/8.3/cli/conf.d/99-sqlite-vec.ini

# 3. Verify
php -r '$db = new SQLite3(":memory:"); $db->loadExtension("vec0.so"); echo "OK\n";'
bash
php artisan rag:eval --suite=tests/rag/evals.json --fail-below=0.8
bash
php artisan rag:mcp-serve --port=3000
bash
# Index all records
php artisan rag:index "App\Models\Document" --chunk=100

# Test a query
php artisan rag:test "What is pgvector?" --model="App\Models\Document" --rerank

# Estimate costs
php artisan rag:estimate --model="App\Models\Document"

# Run evals
php artisan rag:eval --suite=tests/rag/evals.json --fail-below=0.8

# Start MCP server
php artisan rag:mcp-serve --port=3000