PHPackages                             mohaphez/laravel-ragkit - 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. [API Development](/categories/api)
4. /
5. mohaphez/laravel-ragkit

ActiveLibrary[API Development](/categories/api)

mohaphez/laravel-ragkit
=======================

A Laravel package for Retrieval-Augmented Generation (RAG) systems with support for multiple drivers

v1.0.0(1y ago)1251MITPHPPHP ^8.0

Since May 5Pushed 1y ago2 watchersCompare

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

READMEChangelog (1)Dependencies (6)Versions (3)Used By (0)

RagKit - Retrieval-Augmented Generation for Laravel
===================================================

[](#ragkit---retrieval-augmented-generation-for-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/13cd07c0ab25e021c47d1ddc20d98a3630a75fed72eb9f17315b5f10415efdf9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6f68617068657a2f6c61726176656c2d7261676b69742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mohaphez/laravel-ragkit)[![Total Downloads](https://camo.githubusercontent.com/10778a7fac23d8c7ffca9ac2fe21137a7d3be3a5d9a8511516daec686ccdd4e9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6f68617068657a2f6c61726176656c2d7261676b69742e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mohaphez/laravel-ragkit)[![Tests](https://camo.githubusercontent.com/561013489648caf7800bffb2bd296821ff114a7c8ee213564604cba9b2bc63a4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d6f68617068657a2f6c61726176656c2d7261676b69742f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mohaphez/laravel-ragkit/actions/workflows/run-tests.yml)[![License](https://camo.githubusercontent.com/5e2c5e5585af748e554dd8bc10d6842d830b15d406c670083f7030479063b60a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d6f68617068657a2f6c61726176656c2d7261676b69742e7376673f7374796c653d666c61742d737175617265)](https://github.com/mohaphez/laravel-ragkit/blob/main/LICENSE.md)

RagKit is a Laravel package that provides a clean, reusable implementation of Retrieval-Augmented Generation (RAG) systems with support for multiple drivers.

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

[](#-table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Configuration](#configuration)
- [Data Structure](#data-structure)
- [Usage](#usage)
- [Console Commands](#console-commands)
- [API Endpoints](#api-endpoints)
- [Creating Custom Drivers](#creating-custom-drivers)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

### Core Features

[](#core-features)

- **Multi-Provider Support**: Built-in support for multiple RAG service providers (currently ChatBees)
- **Hierarchical Data Structure**: Organized account-collection structure for better document management
- **Document Management**:
    - Asynchronous document upload and processing
    - Background job processing for document uploads
    - Support for multiple file formats (PDF, DOCX, DOC, TXT)
    - Document status tracking and error handling
- **RAG Operations**:
    - Document retrieval and question answering
    - Chat-based interaction with document knowledge
    - Document outlines and FAQs extraction
- **Laravel Integration**:
    - Seamless integration with existing Laravel applications
    - Built-in authentication and middleware support
    - Eloquent model relationships
    - Event-driven architecture

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

[](#installation)

You can install the package via composer:

```
composer require mohaphez/laravel-ragkit
```

After installing, publish the configuration and migrations:

```
php artisan vendor:publish --provider="RagKit\RagKitServiceProvider" --tag="ragkit-config"
php artisan vendor:publish --provider="RagKit\RagKitServiceProvider" --tag="ragkit-migrations"
```

Then run the migrations:

```
php artisan migrate
```

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

[](#configuration)

### Provider Configuration

[](#provider-configuration)

Configure your RAG service provider credentials in your `.env` file:

```
RAGKIT_DEFAULT_PROVIDER=chatbees
RAGKIT_CHATBEES_API_KEY=your-api-key
RAGKIT_CHATBEES_ACCOUNT_ID=your-account-id

```

### Storage Settings

[](#storage-settings)

```
'storage' => [
    'disk' => env('RAGKIT_STORAGE_DISK', 'local'),
    'path' => env('RAGKIT_STORAGE_PATH', 'rag'),
],
```

### Upload Settings

[](#upload-settings)

Configure upload processing in `config/ragkit.php`:

```
'upload' => [
    'enable_upload_listener' => true,
    'upload_handler_class' => \RagKit\Handlers\DefaultUploadHandler::class,
    'queue' => 'default',
    'max_retry_attempts' => 3,
    'retry_backoff' => [10, 60, 180], // seconds between retries
],
```

### Route Configuration

[](#route-configuration)

```
'routes' => [
    'prefix' => 'rag',
    'middleware' => ['web', 'auth'],
],
```

Data Structure
--------------

[](#data-structure)

RagKit uses a hierarchical data structure:

1. **User Level**: Multiple RAG accounts per user
2. **Account Level**: Provider-specific accounts with custom settings
3. **Collection Level**: Logical grouping of related documents
4. **Document Level**: Individual documents with metadata, status tracking, and processing state

This structure allows for better organization and separation of concerns.

Using the HasRagAccounts Trait
------------------------------

[](#using-the-hasragaccounts-trait)

Add the `HasRagAccounts` trait to your User model:

```
use RagKit\Traits\HasRagAccounts;

class User extends Authenticatable
{
    use HasRagAccounts;

    // ...rest of your User model
}
```

This will add the following relationships to your User model:

- `ragAccounts()` - A relationship to get all the user's RAG accounts
- `ragCollections()` - A relationship to get all collections across accounts
- `allRagDocuments()` - A relationship to get all documents across collections

Usage
-----

[](#usage)

### Creating a RAG Account

[](#creating-a-rag-account)

```
use RagKit\Facades\RagKit;

// Create a RAG account for a user
$account = RagKit::createUserAccount(
    $user,
    'My Research Account',
    'chatbees',
    [
        'description' => 'Account for research papers',
    ]
);
```

### Creating a Collection

[](#creating-a-collection)

```
// Create a collection in the account
$collection = RagKit::createCollection(
    $account,
    'Research Papers',
    [
        'namespace_name' => 'public',
        'description' => 'Academic research papers on machine learning',
    ]
);
```

### Uploading Documents

[](#uploading-documents)

```
// Upload a document to a collection (triggers background processing)
$document = RagKit::uploadDocument(
    $collection,
    $filePath,
    $fileName,
    [
        'source' => 'web_upload',
        'category' => 'knowledge_base',
    ]
);

// Check document status
$status = $document->status; // created, queued, uploading, processing, completed, failed, retry
$message = $document->status_message;
```

### Document Processing Flow

[](#document-processing-flow)

1. Document is uploaded and stored locally
2. `DocumentUploaded` event is fired
3. `HandleDocumentUpload` listener processes the event
4. `DefaultUploadHandler` queues the document for processing
5. `ProcessRagDocumentUpload` job:
    - Uploads document to RAG provider
    - Updates document status
    - Retrieves outlines and FAQs
    - Handles retries on failure

### Document Status States

[](#document-status-states)

- `created`: Initial state when document is stored locally
- `queued`: Document is queued for processing
- `uploading`: Document is being uploaded to provider
- `processing`: Document is being processed by provider
- `completed`: Document processing is complete
- `failed`: Document processing failed
- `retry`: Document processing failed and will be retried

### Asking Questions

[](#asking-questions)

```
// Ask a question using a specific collection
$result = RagKit::ask(
    $collection,
    'What is retrieval-augmented generation?',
    null, // Optional document ID to filter by
    []    // Chat history
);

// Access the answer and sources
$answer = $result['answer'];
$references = $result['references'];
```

### Chat Conversations

[](#chat-conversations)

```
// Start or continue a chat conversation within a collection
$history = [
    ['role' => 'user', 'content' => 'What is RAG?'],
    ['role' => 'assistant', 'content' => 'RAG stands for Retrieval-Augmented Generation...'],
];

$result = RagKit::ask(
    $collection,
    'Can you provide an example?',
    null,
    $history
);
```

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

[](#console-commands)

### Importing Documents

[](#importing-documents)

You can import multiple documents at once using the `ragkit:import` command:

```
php artisan ragkit:import /path/to/documents 1 --recursive --extensions=pdf,docx
```

The command accepts the following arguments and options:

- `directory`: Path to the directory containing files to import
- `collection_id`: ID of the collection to import documents into
- `--recursive`: (Optional) Import files recursively from subdirectories
- `--extensions`: (Optional) Comma-separated list of file extensions to import (defaults to pdf,docx,doc,txt)

### Listing Collections

[](#listing-collections)

List all RAG collections with their details:

```
php artisan ragkit:collections
```

The command accepts the following options:

- `--account_id`: (Optional) Filter collections by account ID
- `--provider`: (Optional) Filter collections by provider (e.g., 'chatbees')
- `--user_id`: (Optional) Filter collections by user ID

API Endpoints
-------------

[](#api-endpoints)

All routes are prefixed with `/rag` and protected by `web` and `auth` middleware.

### Account Management

[](#account-management)

- **GET** `/rag/accounts`
    - Lists all RAG accounts for authenticated user
    - Response: Array of account objects

### Collection Management

[](#collection-management)

- **GET** `/rag/collections`
    - Lists collections for specified account
    - Query Parameters:
        - `account_id`: Required
    - Response: Array of collection objects

### Document Operations

[](#document-operations)

- **GET** `/rag/documents`

    - Lists documents in a collection
    - Query Parameters:
        - `collection_id`: Required
    - Response: Paginated document objects
- **POST** `/rag/documents/upload`

    - Uploads new document (triggers background processing)
    - Headers:
        - `Content-Type: multipart/form-data`
    - Body:
        - `file`: Document file
        - `collection_id`: Collection ID
        - `metadata`: Optional JSON metadata
    - Response: Document object with initial status
- **GET** `/rag/documents/{uuid}`

    - Retrieves document details including processing status
    - Response: Document object with status and metadata
- **DELETE** `/rag/documents/{uuid}`

    - Deletes a document
    - Response: Success status
- **GET** `/rag/documents/{uuid}/outline-faq`

    - Gets document outline and FAQs
    - Response: Object containing outline and FAQs

### Chat Interaction

[](#chat-interaction)

- **POST** `/rag/chat`
    - Sends chat message
    - Body:
        - `collection_id`: Collection ID
        - `message`: User message
        - `history`: Optional chat history
    - Response: Chat response with references

Creating Custom Drivers
-----------------------

[](#creating-custom-drivers)

You can create and register custom RAG service drivers by implementing the `RagServiceAdapterInterface` and registering it with the service:

```
use RagKit\Contracts\RagServiceAdapterInterface;
use RagKit\Facades\RagKit;

class CustomRagAdapter implements RagServiceAdapterInterface
{
    // Implement interface methods
}

// Register adapter in AppServiceProvider
RagKit::registerAdapter('custom_provider', new CustomRagAdapter());
```

Testing
-------

[](#testing)

Run the package tests with PHPUnit:

```
composer test
```

### Test Coverage

[](#test-coverage)

- **Unit Tests**:

    - Account management
    - Collection operations
    - Document handling and background processing
    - Chat functionality
- **Feature Tests**:

    - API endpoints
    - Console commands
    - Service integrations
    - Authentication flows

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

[](#contributing)

### Development Setup

[](#development-setup)

1. Fork the repository
2. Create feature branch: `feature/your-feature-name`
3. Clone repository
4. Install dependencies: ```
    composer install
    ```
5. Copy `.env.example` to `.env`
6. Configure RAG provider credentials
7. Run migrations: ```
    php artisan migrate
    ```

### Coding Standards

[](#coding-standards)

- PSR-12 coding standard
- Laravel best practices
- PHPDoc blocks for methods

### Pull Request Process

[](#pull-request-process)

1. Ensure tests pass: `composer test`
2. Update documentation if needed
3. Follow commit message convention:
    - feat: New feature
    - fix: Bug fix
    - docs: Documentation
    - test: Test updates
    - refactor: Code refactoring

### Branch Strategy

[](#branch-strategy)

- `main`: Production-ready code
- `develop`: Development branch
- Feature branches: `feature/*`
- Bugfix branches: `fix/*`

### Code Review

[](#code-review)

- All PRs require review
- Must pass CI/CD checks
- Must maintain test coverage
- Must follow coding standards

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE.md).

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance49

Moderate activity, may be stable

Popularity12

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity43

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

372d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1de6856215ee55d0d54c5559370b0f7678a03c17d5f107876d6def4802a39e38?d=identicon)[mohaphez](/maintainers/mohaphez)

---

Top Contributors

[![mohaphez](https://avatars.githubusercontent.com/u/20874565?v=4)](https://github.com/mohaphez "mohaphez (15 commits)")

---

Tags

laravelragrag-as-serviceragkit

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mohaphez-laravel-ragkit/health.svg)

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

###  Alternatives

[spatie/laravel-query-builder

Easily build Eloquent queries from API requests

4.4k26.9M220](/packages/spatie-laravel-query-builder)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[aedart/athenaeum

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

255.2k](/packages/aedart-athenaeum)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

44643.1k1](/packages/pressbooks-pressbooks)[ryangjchandler/bearer

Minimalistic token-based authentication for Laravel API endpoints.

8129.8k](/packages/ryangjchandler-bearer)

PHPackages © 2026

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