PHPackages                             thaolaptrinh/laravel-rag - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. thaolaptrinh/laravel-rag

ActiveLibrary

thaolaptrinh/laravel-rag
========================

Production-grade RAG engine for Laravel — provider-agnostic, HTTP-based, extensible

v0.1.0(1mo ago)00MITPHPPHP ^8.4CI passing

Since Mar 29Pushed 1mo agoCompare

[ Source](https://github.com/thaolaptrinh/laravel-rag)[ Packagist](https://packagist.org/packages/thaolaptrinh/laravel-rag)[ Docs](https://github.com/thaolaptrinh/laravel-rag)[ GitHub Sponsors](https://github.com/:vendor_name)[ RSS](/packages/thaolaptrinh-laravel-rag/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (19)Versions (2)Used By (0)

Laravel RAG
===========

[](#laravel-rag)

[![Tests](https://camo.githubusercontent.com/c4251f9ec81659f49745317455ac85731501b72362923f079b01b6ae3a159178/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468616f6c61707472696e682f6c61726176656c2d7261672f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)](https://camo.githubusercontent.com/c4251f9ec81659f49745317455ac85731501b72362923f079b01b6ae3a159178/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468616f6c61707472696e682f6c61726176656c2d7261672f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473)[![PHPStan](https://camo.githubusercontent.com/62fe2139973af11afc584fa8caf33cdfd70a46a49a4beb29a30f6cc3b6d13feb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468616f6c61707472696e682f6c61726176656c2d7261672f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d5048505374616e)](https://camo.githubusercontent.com/62fe2139973af11afc584fa8caf33cdfd70a46a49a4beb29a30f6cc3b6d13feb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f7468616f6c61707472696e682f6c61726176656c2d7261672f7068707374616e2e796d6c3f6272616e63683d6d61696e266c6162656c3d5048505374616e)[![License](https://camo.githubusercontent.com/641bc228ab47b6a9ea5cf95fdca972c587fa8d0b80718ecbf4edaa6f5c58f0ac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c6963656e73652f7468616f6c61707472696e682f6c61726176656c2d726167)](https://camo.githubusercontent.com/641bc228ab47b6a9ea5cf95fdca972c587fa8d0b80718ecbf4edaa6f5c58f0ac/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c6963656e73652f7468616f6c61707472696e682f6c61726176656c2d726167)

Production-grade RAG (Retrieval-Augmented Generation) engine for Laravel — provider-agnostic, HTTP-based, extensible.

Features
--------

[](#features)

- **Document Ingestion**: Split documents into chunks, generate embeddings, store in pgvector
- **Semantic Search**: Cosine similarity search with metadata filtering
- **LLM Integration**: OpenAI-compatible API support (OpenAI, FPT Cloud, Ollama, vLLM, Supabase)
- **Idempotent Re-ingestion**: Skip unchanged documents using content hash
- **Queue Support**: Process large document sets asynchronously
- **Testing Helpers**: Fake mode for unit testing

Requirements
------------

[](#requirements)

- PHP 8.4+
- Laravel 11.0, 12.0, 13.0
- PostgreSQL 13+ with pgvector extension

Installation
------------

[](#installation)

```
composer require thaolaptrinh/laravel-rag
```

### Configuration

[](#configuration)

1. Add the RAG database connection to `config/database.php`:

```
'rag' => [
    'driver' => 'pgsql',
    'host' => env('RAG_DB_HOST', '127.0.0.1'),
    'port' => env('RAG_DB_PORT', '5432'),
    'database' => env('RAG_DB_DATABASE', 'laravel'),
    'username' => env('RAG_DB_USERNAME', 'postgres'),
    'password' => env('RAG_DB_PASSWORD', ''),
    'prefix' => '',
    'search_path' => env('RAG_DB_SCHEMA', 'public'),
],
```

2. Publish and run migrations:

```
php artisan rag:install
```

Or manually:

```
php artisan vendor:publish --provider="Thaolaptrinh\Rag\RagServiceProvider" --tag="rag-config"
php artisan vendor:publish --provider="Thaolaptrinh\Rag\RagServiceProvider" --tag="rag-migrations"
php artisan migrate
```

### Post-Installation: Create HNSW Index

[](#post-installation-create-hnsw-index)

After ingesting your first documents, create the HNSW vector index for optimal search performance:

```
php artisan rag:ingest "Your document content" --id="doc-1"
php artisan rag:index
```

> **Note**: The HNSW index cannot be created on an empty table. Run `rag:index` after your first ingestion.

### Environment Variables

[](#environment-variables)

```
# Database (separate from app DB)
RAG_DB_CONNECTION=rag
RAG_DB_HOST=127.0.0.1
RAG_DB_PORT=5432
RAG_DB_DATABASE=laravel
RAG_DB_USERNAME=postgres
RAG_DB_PASSWORD=

# Embedding (OpenAI-compatible HTTP)
RAG_EMBEDDING_API_URL=https://api.openai.com/v1/embeddings
RAG_EMBEDDING_API_KEY=sk-...
RAG_EMBEDDING_MODEL=text-embedding-3-small
RAG_EMBEDDING_DIMENSIONS=1536
RAG_EMBEDDING_BATCH_SIZE=100
RAG_EMBEDDING_TIMEOUT=120

# LLM (OpenAI-compatible HTTP)
RAG_LLM_API_URL=https://api.openai.com/v1/chat/completions
RAG_LLM_API_KEY=sk-...
RAG_LLM_MODEL=gpt-4o-mini
RAG_LLM_MAX_OUTPUT_TOKENS=4096
RAG_LLM_CONTEXT_WINDOW=128000
RAG_LLM_TEMPERATURE=0.7
RAG_LLM_TIMEOUT=120

# Chunking
RAG_CHUNK_SIZE=1000
RAG_CHUNK_OVERLAP=200

# Document
RAG_DOCUMENT_MAX_CONTENT_LENGTH=100000

# Ingestion
RAG_INGESTION_SUB_BATCH_SIZE=10
RAG_INGESTION_PIPELINE_TIMEOUT=600

# Retrieval
RAG_RETRIEVAL_TOP_K=20
RAG_RETRIEVAL_MIN_SCORE=0.0
RAG_HNSW_EF_SEARCH=100

# Prompt
RAG_PROMPT_SYSTEM=You are a helpful assistant...
RAG_PROMPT_TOKENS_PER_CHAR=0.25

# Contextual Retrieval (Optional)
RAG_CONTEXTUAL_ENABLED=false
```

Usage
-----

[](#usage)

### Ingest Documents

[](#ingest-documents)

```
use Thaolaptrinh\Rag\Data\Document;
use Thaolaptrinh\Rag\Rag;

// Single document
$result = Rag::ingest(Document::create('Your document content here', [
    'source' => 'manual',
    'file_id' => 123,
]));

// Multiple documents
$result = Rag::ingestMany([
    Document::create('Content 1', ['source' => 'pdf']),
    Document::create('Content 2', ['source' => 'pdf']),
]);
```

### Query

[](#query)

```
// Simple query
$answer = Rag::query('What is this document about?');

// With options
$answer = Rag::query('What is this about?', [
    'top_k' => 10,
    'filters' => ['source' => 'pdf'],
    'system' => 'Custom system prompt',
]);

echo $answer->text;
echo $answer->traceId;

// Access sources
foreach ($answer->sources as $source) {
    echo $source->content;
    echo $source->score;
}
```

### Streaming

[](#streaming)

```
Rag::queryStream('Tell me about...', function (string $token): void {
    echo $token;
});
```

### Delete

[](#delete)

```
// Delete single document
Rag::delete('document-id');

// Delete multiple
$count = Rag::deleteMany(['id-1', 'id-2']);

// Delete all
Rag::truncate();
```

### Queue Support

[](#queue-support)

For large document sets, use queued ingestion:

```
// Queue single document
Rag::ingestQueued($document);
Rag::ingestQueued($document, 'rag-embeddings');

// Queue multiple (one job per document)
Rag::ingestManyQueued($documents);
```

### Testing

[](#testing)

```
use Thaolaptrinh\Rag\Rag;
use Thaolaptrinh\Rag\Data\Document;

beforeEach(function () {
    Rag::fake();
});

it('ingests documents', function () {
    $result = Rag::ingest(Document::create('test content'));

    expect($result->ingested)->toBe(1);

    Rag::assertIngested('document-id');
});

it('queries the store', function () {
    $answer = Rag::query('What is Laravel?');

    expect($answer->text)->toBe('Fake response');

    Rag::assertQueried('What is Laravel?');
});
```

Artisan Commands
----------------

[](#artisan-commands)

```
# Ingest a document
php artisan rag:ingest "Document content" --id="doc-1" --metadata='{"source": "manual"}'

# Query
php artisan rag:query "What is this about?"

# Delete
php artisan rag:delete doc-1
php artisan rag:delete --all

# Install (publish config + run migrations)
php artisan rag:install
php artisan rag:install --without-migration

# Create HNSW index (after ingesting data)
php artisan rag:index
```

Architecture
------------

[](#architecture)

See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) for detailed architecture documentation.

### Key Design Decisions

[](#key-design-decisions)

- **Provider-agnostic**: Core never mentions specific providers (OpenAI, pgvector, etc.)
- **Batch operations**: Use `embedBatch()`, `storeMany()` for production performance
- **Idempotent ingestion**: Content hash check skips unchanged documents
- **Separate database**: Uses `RAG_DB_*` connection, not app's default
- **Hard delete**: No soft delete to avoid HNSW index bloat

Testing
-------

[](#testing-1)

```
# Run tests
composer test

# Run PHPStan
composer analyse
```

License
-------

[](#license)

MIT License. See [LICENSE.md](LICENSE.md).

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance90

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

46d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4d89d5461dd11a15263d2ade3e266eab5b950942919fc6a4cc7e2d7b322a3384?d=identicon)[thaolaptrinh](/maintainers/thaolaptrinh)

---

Top Contributors

[![thaolaptrinh](https://avatars.githubusercontent.com/u/105599110?v=4)](https://github.com/thaolaptrinh "thaolaptrinh (41 commits)")

---

Tags

laravelllmembeddingsragpgvectorretrieval-augmented-generationthaolaptrinh

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/thaolaptrinh-laravel-rag/health.svg)

```
[![Health](https://phpackages.com/badges/thaolaptrinh-laravel-rag/health.svg)](https://phpackages.com/packages/thaolaptrinh-laravel-rag)
```

###  Alternatives

[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k25.9M107](/packages/laravel-cashier)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k43.5M5.2k](/packages/larastan-larastan)[laravel/passport

Laravel Passport provides OAuth2 server support to Laravel.

3.4k85.0M532](/packages/laravel-passport)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k12.1M99](/packages/laravel-pulse)[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
