PHPackages                             akira/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. [Database &amp; ORM](/categories/database)
4. /
5. akira/laravel-rag

ActiveLibrary[Database &amp; ORM](/categories/database)

akira/laravel-rag
=================

Akira RAG for Laravel 12 with PostgreSQL + pgvector

v0.2.0(4mo ago)5237↓50%MITPHPPHP ^8.4CI passing

Since Dec 19Pushed 3mo ago1 watchersCompare

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

READMEChangelog (2)Dependencies (19)Versions (4)Used By (0)

Akira RAG for Laravel
=====================

[](#akira-rag-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d9f84bfe42fa82dbda16dcb8f8152b4ba342aac66bf0c0202fba61a290a3387e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616b6972612f6c61726176656c2d7261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/akira/laravel-rag)[![Total Downloads](https://camo.githubusercontent.com/97b6ba5807cf795e17fa89350cb7d0693073bb238db6d0071f1a53c90bd18f51/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616b6972612f6c61726176656c2d7261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/akira/laravel-rag)

A production-ready Retrieval-Augmented Generation (RAG) system for Laravel 12+ with PostgreSQL + pgvector. Built with clean architecture, type safety, and deterministic behavior.

Features
--------

[](#features)

- **Clean Architecture** - Facade → Service → Manager pattern
- **Type Safety** - Full type hints and custom exceptions
- **Multi-tenant Support** - Optional tenant isolation with custom resolvers
- **Performance** - HNSW indexing, caching, and optimized queries
- **Idempotent Ingestion** - Hash-based deduplication
- **Audit Logging** - Built-in query tracking
- **Deterministic Chunking** - Configurable token-based splitting
- ️ **CLI Tools** - Rich interactive commands for management

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

[](#requirements)

- **PHP:** 8.4+
- **Laravel:** 12+
- **Database:** PostgreSQL 14+ (with pgvector extension)
- **Optional:** SQLite for testing (in-memory)

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

[](#installation)

### Quick Install (Recommended)

[](#quick-install-recommended)

```
composer require akira/laravel-rag
php artisan rag:install
```

The installer will guide you through:

- Publishing configuration files
- Publishing migrations
- Running migrations
- Enabling multi-tenant mode (optional)

### Non-Interactive Install

[](#non-interactive-install)

Perfect for CI/CD pipelines:

```
php artisan rag:install \
  --force \
  --with-tenancy \
  --run-migrate \
  --star
```

### Manual Install

[](#manual-install)

```
composer require akira/laravel-rag
php artisan vendor:publish --tag="laravel-rag-config"
php artisan vendor:publish --tag="laravel-rag-migrations"
php artisan migrate
```

### PostgreSQL Setup

[](#postgresql-setup)

Ensure pgvector extension is available:

```
CREATE
EXTENSION IF NOT EXISTS vector;
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Akira\Rag\Facades\Rag;

// Ingest a document
$result = Rag::ingest([
    'title' => 'Labor Law 2024',
    'source_type' => 'law',
    'source_ref' => 'law:2024:001',
    'content' => 'Full text of the labor law...',
    'meta' => ['lang' => 'en', 'year' => 2024],
]);

// Returns: ['document_id' => '...', 'chunks' => 5]

// Ask a question
$answer = Rag::ask('What are the notice periods for termination?');

// Returns: [
//     'answer' => 'According to the law...',
//     'chunks' => [['id' => '...', 'score' => 0.95], ...],
//     'query_id' => '...'
// ]
```

### Advanced Usage

[](#advanced-usage)

```
use Akira\Rag\Facades\Rag;

// Filtered retrieval
$answer = Rag::ask(
    question: 'How many vacation days?',
    filters: ['document_id' => '123e4567-e89b-12d3-a456-426614174000']
);

// With custom metadata
Rag::ingest([
    'title' => 'Employee Handbook',
    'source_type' => 'handbook',
    'source_ref' => 'handbook:2024:v2',
    'content' => $content,
    'meta' => [
        'department' => 'HR',
        'version' => 2,
        'effective_date' => '2024-01-01',
        'tags' => ['benefits', 'policies']
    ],
]);
```

### Using Data Transfer Objects

[](#using-data-transfer-objects)

```
use Akira\Rag\Data\IngestPayload;
use Akira\Rag\Data\AskPayload;

// Type-safe ingestion
$payload = new IngestPayload(
    title: 'Safety Guidelines',
    source_type: 'manual',
    source_ref: 'safety:2024',
    content: $text,
    meta: ['category' => 'safety']
);

Rag::ingest($payload->toArray());

// Type-safe asking
$askPayload = new AskPayload(
    question: 'What are the fire safety procedures?',
    filters: ['category' => 'safety'],
    meta: ['user_id' => auth()->id()]
);

Rag::ask($askPayload->question, $askPayload->filters);
```

CLI Commands
------------

[](#cli-commands)

### Interactive Commands

[](#interactive-commands)

All commands support rich interactive prompts:

```
# Install and configure
php artisan rag:install

# Ingest content
php artisan rag:ingest

# View statistics
php artisan rag:stats

# Export knowledge base
php artisan rag:export

# Import from backup
php artisan rag:restore backup.json.gz

# Create backups
php artisan rag:backup

# Re-embed documents
php artisan rag:reembed --all

# Import PDF files
php artisan rag:import:pdf documents/
```

### Non-Interactive Mode

[](#non-interactive-mode)

Perfect for automation:

```
# Ingest with options
php artisan rag:ingest \
  --title="My Document" \
  --source_type=manual \
  --source_ref=doc:001 \
  --text="Content here..."

# Export with encryption
php artisan rag:export \
  --output=backup.json \
  --include-embeddings \
  --compress \
  --encrypt

# Stats as JSON
php artisan rag:stats --json
```

Configuration
-------------

[](#configuration)

The `config/rag.php` file provides extensive configuration options:

```
return [
    // AI Models
    'ai' => [
        'embedding_model' => env('RAG_EMBEDDING_MODEL', 'text-embedding-3-small'),
        'chat_model' => env('RAG_CHAT_MODEL', 'gpt-4'),
    ],

    // Chunking Strategy
    'chunking' => [
        'target_tokens' => 800,
        'overlap_tokens' => 120,
    ],

    // Retrieval Settings
    'retrieval' => [
        'top_k' => 5,
        'hybrid' => [
            'enabled' => true,
            'semantic_weight' => 0.7,
            'keyword_weight' => 0.3,
        ],
    ],

    // Caching
    'cache' => [
        'enabled' => true,
        'prefix' => 'rag:v1',
        'ttl_seconds' => 1209600, // 14 days
    ],

    // Audit Logging
    'audit' => [
        'enabled' => true,
    ],

    // Multi-tenancy
    'tenancy' => [
        'enabled' => false,
        'resolver' => \Akira\Rag\Tenant\NullTenantResolver::class,
        'tenant_column' => 'tenant_id',
    ],
];
```

Multi-Tenancy
-------------

[](#multi-tenancy)

### Setup

[](#setup)

1. Enable tenancy in config:

```
'tenancy' => [
    'enabled' => true,
    'resolver' => \App\Rag\MyTenantResolver::class,
    'tenant_column' => 'tenant_id',
],
```

2. Create a tenant resolver:

```
namespace App\Rag;

use Akira\Rag\Tenant\TenantResolver;

class MyTenantResolver implements TenantResolver
{
    public function resolve(): ?string
    {
        // Return current tenant ID
        return auth()->user()?->tenant_id;
    }
}
```

### Usage

[](#usage)

Once configured, all operations are automatically scoped to the current tenant:

```
// Ingestion is automatically scoped
Rag::ingest([...]);

// Retrieval is automatically scoped
$answer = Rag::ask('...');

// Stats are tenant-specific
$stats = Rag::stats();
```

Exception Handling
------------------

[](#exception-handling)

The package provides specific exceptions for different scenarios:

```
use Akira\Rag\Exceptions\InvalidPayload;
use Akira\Rag\Exceptions\InvalidQuestionException;
use Akira\Rag\Exceptions\DocumentNotFoundException;

try {
    Rag::ingest([
        'title' => 'Test',
        // Missing required fields
    ]);
} catch (InvalidPayload $e) {
    // Handle validation errors
    // $e->getMessage() returns descriptive error
}

try {
    Rag::ask('');
} catch (InvalidQuestionException $e) {
    // Handle empty question
}
```

### Available Exceptions

[](#available-exceptions)

- **Validation**: `InvalidPayload`, `InvalidQuestionException`
- **Resources**: `DocumentNotFoundException`, `ChunkNotFoundException`
- **Processing**: `ChunkingException`, `EmbeddingException`, `RetrievalException`
- **Import/Export**: `ExportException`, `ImportException`
- **Infrastructure**: `CacheException`, `DatabaseException`, `ConfigurationException`
- **Tenancy**: `TenantResolverException`

See [Exception Documentation](src/Exceptions/README.md) for complete details.

Testing
-------

[](#testing)

```
composer test
```

### Writing Tests

[](#writing-tests)

```
use Akira\Rag\Facades\Rag;

it('can ingest and retrieve documents', function () {
    $result = Rag::ingest([
        'title' => 'Test Document',
        'source_type' => 'test',
        'source_ref' => 'test:001',
        'content' => 'This is a test document about Laravel RAG.',
        'meta' => ['category' => 'test'],
    ]);

    expect($result)
        ->toHaveKeys(['document_id', 'chunks'])
        ->and($result['chunks'])->toBeGreaterThan(0);

    $answer = Rag::ask('What is this test about?');

    expect($answer)
        ->toHaveKeys(['answer', 'chunks', 'query_id'])
        ->and($answer['chunks'])->not->toBeEmpty();
});
```

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

[](#architecture)

```
┌─────────────────────────────────────────┐
│           Facade (Rag)                  │
│    Public API Entry Point               │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│         RagService                      │
│    Business Logic Layer                 │
└─────────────┬───────────────────────────┘
              │
              ▼
┌─────────────────────────────────────────┐
│         RagManager                      │
│   Core Operations & DB Access           │
│   - Ingestion & Chunking                │
│   - Retrieval & Caching                 │
│   - Tenant Scoping                      │
└─────────────┬───────────────────────────┘
              │
        ┌─────┴─────┬──────────────┐
        ▼           ▼              ▼
   ┌────────┐  ┌────────┐    ┌──────────┐
   │ Models │  │ Cache  │    │ Database │
   └────────┘  └────────┘    └──────────┘

```

Documentation
-------------

[](#documentation)

For detailed documentation, visit:

- [Full Documentation](docs/01-Introduction.md)
- [Configuration Guide](docs/04-Configuration.md)
- [Multi-tenancy Setup](docs/06-Tenancy.md)
- [Ingestion Guide](docs/07-Ingestion.md)
- [Asking Queries](docs/08-Asking.md)
- [Recipes &amp; Examples](docs/10-Recipes.md)

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for recent changes.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security vulnerabilities, please review [our security policy](../../security/policy).

Credits
-------

[](#credits)

- [kid](https://github.com/kidiatoliny)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance78

Regular maintenance activity

Popularity20

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96.6% 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

Every ~23 days

Total

3

Last Release

98d ago

Major Versions

v0.2.0 → 1.x-dev2026-02-03

### Community

Maintainers

![](https://www.gravatar.com/avatar/c42e59ca0b3864a382dc0c3e290f8cf7d75bbe3eab10a3af0f71d5785f89d0bc?d=identicon)[kidiatoliny](/maintainers/kidiatoliny)

---

Top Contributors

[![kidiatoliny](https://avatars.githubusercontent.com/u/48266788?v=4)](https://github.com/kidiatoliny "kidiatoliny (84 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravelraglaravel-rag

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[dyrynda/laravel-model-uuid

This package allows you to easily work with UUIDs in your Laravel models.

4802.8M8](/packages/dyrynda-laravel-model-uuid)[spatie/laravel-model-flags

Add flags to Eloquent models

4301.1M1](/packages/spatie-laravel-model-flags)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

423715.4k1](/packages/clickbar-laravel-magellan)[spatie/laravel-sql-commenter

Add comments to SQL queries made by Laravel

1931.4M1](/packages/spatie-laravel-sql-commenter)[spatie/laravel-deleted-models

Automatically copy deleted records to a separate table

409109.8k4](/packages/spatie-laravel-deleted-models)[wnx/laravel-backup-restore

A package to restore database backups made with spatie/laravel-backup.

203330.1k2](/packages/wnx-laravel-backup-restore)

PHPackages © 2026

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