PHPackages                             omniglies/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. [Search &amp; Filtering](/categories/search)
4. /
5. omniglies/laravel-rag

ActiveLibrary[Search &amp; Filtering](/categories/search)

omniglies/laravel-rag
=====================

A complete Laravel package for RAG (Retrieval-Augmented Generation) implementation with external API integrations

v1.0.2(10mo ago)319MITPHPPHP ^8.1

Since Jun 30Pushed 10mo agoCompare

[ Source](https://github.com/aanfarhan/laravel-rag)[ Packagist](https://packagist.org/packages/omniglies/laravel-rag)[ RSS](/packages/omniglies-laravel-rag/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (11)Versions (4)Used By (0)

Laravel RAG Package
===================

[](#laravel-rag-package)

[![Latest Version on Packagist](https://camo.githubusercontent.com/1d0e64a6d99dfa69f8330062ceab78547a3e0754ce5d4ed760dee5ab364bd6ba/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6f6d6e69676c6965732f6c61726176656c2d7261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/omniglies/laravel-rag)[![GitHub Tests Action Status](https://camo.githubusercontent.com/80852d686edacf89c42f7e880a87277af6a0df2c54acfe9b508175065b761b8e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6f6d6e69676c6965732f6c61726176656c2d7261672f72756e2d74657374733f6c6162656c3d7465737473)](https://github.com/omniglies/laravel-rag/actions?query=workflow%3Arun-tests+branch%3Amain)[![GitHub Code Style Action Status](https://camo.githubusercontent.com/f60ed8fcd0660b6e21789bb969a7b5a58fcb3b88eff107eef1d8eca002c974a2/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f6f6d6e69676c6965732f6c61726176656c2d7261672f436865636b253230262532306669782532307374796c696e673f6c6162656c3d636f64652532307374796c65)](https://github.com/omniglies/laravel-rag/actions?query=workflow%3A%22Check+%26+fix+styling%22+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/120af2ac4a7a5ea999d0b7e724637cfddd8e132b799afd28a5688ef2fcb30eec/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6f6d6e69676c6965732f6c61726176656c2d7261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/omniglies/laravel-rag)

A complete Laravel package for implementing RAG (Retrieval-Augmented Generation) systems with external API integrations, vector databases, and a beautiful Alpine.js-powered web interface.

Features
--------

[](#features)

- 🚀 **Plug-and-play installation** - Single command setup
- 🤖 **Multiple AI providers** - OpenAI, Anthropic with extensible driver system
- 📄 **Document processing** - Text, PDF, DOCX support via external APIs
- 🔍 **Hybrid search** - Vector similarity + keyword matching with multiple vector DB providers
- 🎨 **Modern web interface** - Alpine.js components with real-time updates
- 📊 **Analytics &amp; monitoring** - Usage tracking, search analytics, cost monitoring
- ⚡ **Queue-based processing** - Async document processing with status tracking
- 🔧 **Extensive configuration** - Every aspect is configurable
- 🧪 **Comprehensive testing** - Unit and feature tests included

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

[](#quick-start)

```
# Install the package
composer require omniglies/laravel-rag

# Install and configure
php artisan rag:install

# Configure your environment
# Add to .env:
RAG_AI_PROVIDER=openai
OPENAI_API_KEY=your_openai_key
RAG_VECTOR_PROVIDER=pinecone
PINECONE_API_KEY=your_pinecone_key
```

Visit `/rag` in your browser and start uploading documents!

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
    - [Web Interface](#web-interface)
    - [API Usage](#api-usage)
    - [Programmatic Usage](#programmatic-usage)
- [External Integrations](#external-integrations)
- [Console Commands](#console-commands)
- [Testing](#testing)
- [Architecture](#architecture)
- [Contributing](#contributing)

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

[](#installation)

### Requirements

[](#requirements)

- PHP 8.1+
- Laravel 9.x, 10.x, or 11.x
- Database (PostgreSQL recommended for full-text search, MySQL/SQLite supported)
- Queue system (Redis/Database recommended for production)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require omniglies/laravel-rag
```

### Step 2: Install the Package

[](#step-2-install-the-package)

```
php artisan rag:install
```

This command will:

- Publish configuration files
- Publish and run migrations
- Publish views and assets
- Display setup instructions

### Step 3: Configure Environment

[](#step-3-configure-environment)

Add these environment variables to your `.env`:

```
# AI Provider (required)
RAG_AI_PROVIDER=openai
OPENAI_API_KEY=your_openai_api_key

# Vector Database (required)
RAG_VECTOR_PROVIDER=pinecone
PINECONE_API_KEY=your_pinecone_api_key
PINECONE_ENVIRONMENT=your_pinecone_environment
PINECONE_INDEX_NAME=rag-knowledge

# External Processing API (optional)
RAG_PROCESSING_API_URL=https://your-processing-api.com
RAG_PROCESSING_API_KEY=your_processing_api_key

# Queue Configuration (recommended)
QUEUE_CONNECTION=redis
RAG_QUEUE_CONNECTION=redis
```

### Step 4: Set Up Queue Workers (Production)

[](#step-4-set-up-queue-workers-production)

```
# Start queue workers for document processing
php artisan queue:work --queue=rag
```

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

[](#configuration)

The package configuration is published to `config/rag.php`. Key configuration sections:

### AI Providers

[](#ai-providers)

```
'ai_provider' => env('RAG_AI_PROVIDER', 'openai'),

'providers' => [
    'openai' => [
        'api_key' => env('OPENAI_API_KEY'),
        'model' => env('RAG_OPENAI_MODEL', 'gpt-3.5-turbo'),
        'max_tokens' => env('RAG_OPENAI_MAX_TOKENS', 1000),
    ],
    'anthropic' => [
        'api_key' => env('ANTHROPIC_API_KEY'),
        'model' => env('RAG_ANTHROPIC_MODEL', 'claude-3-sonnet-20240229'),
    ],
],
```

### Vector Databases

[](#vector-databases)

```
'vector_database' => [
    'provider' => env('RAG_VECTOR_PROVIDER', 'pinecone'),
    'providers' => [
        'pinecone' => [
            'api_key' => env('PINECONE_API_KEY'),
            'environment' => env('PINECONE_ENVIRONMENT'),
            'index_name' => env('PINECONE_INDEX_NAME', 'rag-knowledge'),
        ],
        'weaviate' => [
            'url' => env('WEAVIATE_URL'),
            'api_key' => env('WEAVIATE_API_KEY'),
        ],
        'qdrant' => [
            'url' => env('QDRANT_URL'),
            'api_key' => env('QDRANT_API_KEY'),
        ],
    ],
],
```

### Search Configuration

[](#search-configuration)

```
'search' => [
    'default_limit' => env('RAG_SEARCH_LIMIT', 3),
    'similarity_threshold' => env('RAG_SIMILARITY_THRESHOLD', 0.7),
    'hybrid_search' => [
        'enabled' => env('RAG_HYBRID_SEARCH_ENABLED', true),
        'vector_weight' => env('RAG_VECTOR_WEIGHT', 0.8),
        'keyword_weight' => env('RAG_KEYWORD_WEIGHT', 0.2),
    ],
],
```

Usage
-----

[](#usage)

### Web Interface

[](#web-interface)

The package provides a complete web interface accessible at `/rag`:

- **Dashboard**: Overview of documents and processing status
- **Documents**: Upload, manage, and view document processing status
- **Chat**: AI-powered chat interface with RAG capabilities

#### Features

[](#features-1)

- Drag-and-drop file uploads
- Real-time processing status updates
- Vector search with similarity scores
- Source attribution in AI responses
- Responsive Alpine.js components

### API Usage

[](#api-usage)

The package exposes RESTful API endpoints at `/api/rag/`:

#### Upload Document

[](#upload-document)

```
curl -X POST /api/rag/documents \
  -H "Content-Type: multipart/form-data" \
  -F "title=My Document" \
  -F "file=@document.pdf" \
  -F "metadata[author]=John Doe"
```

#### Ask Question

[](#ask-question)

```
curl -X POST /api/rag/ask \
  -H "Content-Type: application/json" \
  -d '{
    "question": "What is the main topic of the documents?",
    "context_limit": 5,
    "temperature": 0.7
  }'
```

#### Search Documents

[](#search-documents)

```
curl -X GET "/api/rag/search?query=machine learning&limit=10&threshold=0.8"
```

#### Get System Status

[](#get-system-status)

```
curl -X GET /api/rag/health
```

### Programmatic Usage

[](#programmatic-usage)

#### Using the Facade

[](#using-the-facade)

```
use Omniglies\LaravelRag\Facades\Rag;

// Ingest a document
$document = Rag::ingestDocument('Document Title', $uploadedFile, [
    'author' => 'John Doe',
    'category' => 'Research'
]);

// Ask a question
$response = Rag::askWithContext('What is machine learning?');
echo $response['answer'];

// Search for similar content
$chunks = Rag::searchRelevantChunks('artificial intelligence', 5);
```

#### Using the Service

[](#using-the-service)

```
use Omniglies\LaravelRag\Services\RagService;

class MyController extends Controller
{
    public function __construct(private RagService $ragService) {}

    public function search(Request $request)
    {
        $results = $this->ragService->searchRelevantChunks(
            $request->query,
            $request->limit ?? 10
        );

        return response()->json($results);
    }
}
```

#### Advanced Usage

[](#advanced-usage)

```
use Omniglies\LaravelRag\Services\VectorSearchService;
use Omniglies\LaravelRag\Services\EmbeddingService;

// Direct vector operations
$vectorService = app(VectorSearchService::class);
$embeddingService = app(EmbeddingService::class);

// Generate embeddings
$embedding = $embeddingService->generateEmbedding('sample text');

// Perform vector search
$results = $vectorService->searchSimilar('query text', [
    'limit' => 10,
    'threshold' => 0.8,
    'namespace' => 'documents'
]);
```

External Integrations
---------------------

[](#external-integrations)

### Document Processing API

[](#document-processing-api)

The package supports external document processing services for advanced file format support:

```
// Configure external processing
'external_processing' => [
    'enabled' => env('RAG_EXTERNAL_PROCESSING_ENABLED', true),
    'api_url' => env('RAG_PROCESSING_API_URL'),
    'api_key' => env('RAG_PROCESSING_API_KEY'),
    'webhook_secret' => env('RAG_PROCESSING_WEBHOOK_SECRET'),
],
```

Expected API interface:

- `POST /documents/process` - Submit document for processing
- `GET /jobs/{id}/status` - Check processing status
- `GET /jobs/{id}/result` - Get processed chunks
- Webhook support for completion notifications

### Vector Database Providers

[](#vector-database-providers)

#### Pinecone

[](#pinecone)

```
RAG_VECTOR_PROVIDER=pinecone
PINECONE_API_KEY=your_api_key
PINECONE_ENVIRONMENT=us-west1-gcp
PINECONE_INDEX_NAME=rag-knowledge
```

#### Weaviate

[](#weaviate)

```
RAG_VECTOR_PROVIDER=weaviate
WEAVIATE_URL=http://localhost:8080
WEAVIATE_API_KEY=your_api_key
```

#### Qdrant

[](#qdrant)

```
RAG_VECTOR_PROVIDER=qdrant
QDRANT_URL=http://localhost:6333
QDRANT_API_KEY=your_api_key
```

### Embedding Providers

[](#embedding-providers)

#### OpenAI

[](#openai)

```
RAG_EMBEDDING_PROVIDER=openai
RAG_OPENAI_EMBEDDING_MODEL=text-embedding-ada-002
```

#### Cohere

[](#cohere)

```
RAG_EMBEDDING_PROVIDER=cohere
COHERE_API_KEY=your_api_key
RAG_COHERE_EMBEDDING_MODEL=embed-english-v3.0
```

Console Commands
----------------

[](#console-commands)

### Installation and Setup

[](#installation-and-setup)

```
# Install the package (run after composer install)
php artisan rag:install

# Test configuration
php artisan rag:status --test-config
```

### Document Management

[](#document-management)

```
# Ingest a document
php artisan rag:ingest path/to/document.pdf --title="Research Paper"

# Check document status
php artisan rag:status 123

# Clear all documents
php artisan rag:clear --force
```

### Maintenance

[](#maintenance)

```
# Optimize search indexes
php artisan rag:optimize --search-indexes

# Sync unsynced vectors
php artisan rag:optimize --vector-sync

# Clean up old records
php artisan rag:optimize --cleanup-old --days=30
```

### System Status

[](#system-status)

```
# Check overall system status
php artisan rag:status

# Check specific document
php artisan rag:status 123

# Detailed statistics
php artisan rag:status --detailed
```

Testing
-------

[](#testing)

The package includes comprehensive tests:

```
# Run all tests
vendor/bin/phpunit

# Run specific test suites
vendor/bin/phpunit --testsuite=Unit
vendor/bin/phpunit --testsuite=Feature

# Run with coverage
vendor/bin/phpunit --coverage-html coverage
```

### Test Structure

[](#test-structure)

- **Unit Tests**: Test individual services and components
- **Feature Tests**: Test HTTP endpoints and integration scenarios
- **Mocking**: External APIs are mocked for reliable testing

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

[](#architecture)

### Core Components

[](#core-components)

```
src/
├── Services/           # Core business logic
│   ├── RagService.php             # Main service orchestrator
│   ├── ExternalProcessingService.php  # Document processing API client
│   ├── VectorSearchService.php    # Vector database operations
│   ├── EmbeddingService.php       # Embedding generation
│   └── AiProviders/               # AI provider implementations
├── Models/             # Eloquent models
├── Http/               # Controllers and middleware
├── Jobs/               # Queue jobs for async processing
├── Console/            # Artisan commands
└── Database/           # Migrations

```

### Data Flow

[](#data-flow)

1. **Document Upload** → **Queue Processing** → **External API** → **Chunking** → **Embeddings** → **Vector Storage**
2. **User Query** → **Vector Search** + **Keyword Search** → **Context Building** → **AI Generation** → **Response**

### Design Patterns

[](#design-patterns)

- **Service Layer**: Business logic separation
- **Strategy Pattern**: Pluggable AI and vector providers
- **Observer Pattern**: Event-driven processing updates
- **Factory Pattern**: Provider instantiation
- **Repository Pattern**: Data access abstraction

Alpine.js Components
--------------------

[](#alpinejs-components)

The web interface uses Alpine.js for reactive components:

### Chat Component

[](#chat-component)

```

```

### Upload Component

[](#upload-component)

```

```

### Search Component

[](#search-component)

```

```

Performance Considerations
--------------------------

[](#performance-considerations)

### Production Optimization

[](#production-optimization)

1. **Queue Workers**: Use dedicated queue workers for document processing
2. **Caching**: Enable Redis/Memcached for embeddings and search results
3. **Database**: Use PostgreSQL for optimal full-text search performance
4. **Vector Database**: Choose appropriate vector DB based on scale
5. **Rate Limiting**: Configure API rate limits for external services

### Scaling

[](#scaling)

- **Horizontal Scaling**: Multiple queue workers for processing
- **Vector Database Sharding**: Distribute vectors across multiple indexes
- **CDN**: Serve static assets via CDN
- **Load Balancing**: Distribute web requests across multiple instances

Security
--------

[](#security)

### API Keys

[](#api-keys)

- Store all API keys in environment variables
- Use Laravel's encryption for sensitive configuration
- Rotate keys regularly

### Authentication

[](#authentication)

- Configure authentication middleware for web routes
- Use API tokens for programmatic access
- Implement rate limiting for API endpoints

### Data Privacy

[](#data-privacy)

- Documents are processed according to your AI provider's terms
- Vector embeddings do not contain original text
- Implement data retention policies

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

#### Document Processing Stuck

[](#document-processing-stuck)

```
# Check queue workers
php artisan queue:work --queue=rag

# Check external API status
php artisan rag:status --test-config

# Retry failed jobs
php artisan queue:retry all
```

#### Vector Search Not Working

[](#vector-search-not-working)

```
# Test vector database connection
php artisan rag:status --test-config

# Check vector sync status
php artisan rag:optimize --vector-sync
```

#### High API Costs

[](#high-api-costs)

```
# Check usage statistics
php artisan rag:status --detailed

# Optimize chunk sizes
# Edit config/rag.php chunking settings
```

### Debug Mode

[](#debug-mode)

Enable debug logging in `config/logging.php`:

```
'channels' => [
    'rag' => [
        'driver' => 'daily',
        'path' => storage_path('logs/rag.log'),
        'level' => 'debug',
    ],
],
```

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

[](#contributing)

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

### Development Setup

[](#development-setup)

```
git clone https://github.com/omniglies/laravel-rag.git
cd laravel-rag
composer install
npm install
npm run dev
```

### Running Tests

[](#running-tests)

```
composer test
composer test:coverage
composer test:types
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG.md](CHANGELOG.md) for more information on what has changed recently.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Credits
-------

[](#credits)

- [Omniglies Team](https://github.com/omniglies)
- [All Contributors](../../contributors)

License
-------

[](#license)

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

Roadmap
-------

[](#roadmap)

- Support for more file formats (PPT, XLS, etc.)
- Built-in document OCR capabilities
- GraphQL API support
- Advanced analytics dashboard
- Multi-tenant support
- Document versioning
- Collaborative features
- Export/import capabilities

---

**Need help?** Check out our [documentation](https://docs.laravel-rag.com) or [open an issue](https://github.com/omniglies/laravel-rag/issues).

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance54

Moderate activity, may be stable

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

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

Every ~0 days

Total

3

Last Release

316d ago

### Community

Maintainers

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

---

Top Contributors

[![aanfarhan](https://avatars.githubusercontent.com/u/19621476?v=4)](https://github.com/aanfarhan "aanfarhan (3 commits)")

---

Tags

searchlaravelaivectoropenaianthropicembeddingsrag

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k49.4M479](/packages/laravel-scout)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[vizra/vizra-adk

Vizra Agent Development Kit - A comprehensive Laravel package for building intelligent AI agents.

29026.1k](/packages/vizra-vizra-adk)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

255.2k](/packages/aedart-athenaeum)[flarum/core

Delightfully simple forum software.

211.3M1.9k](/packages/flarum-core)

PHPackages © 2026

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