PHPackages                             hamzi/nativerag - 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. hamzi/nativerag

ActiveLibrary[API Development](/categories/api)

hamzi/nativerag
===============

A production-ready, privacy-first Local AI Controller and Retrieval-Augmented Generation (RAG) engine for Laravel 11, 12, and 13. Supports Ollama, LM Studio, zero-infra vector search, SSE streaming, and full conversational memory — all with 100% data residency.

v1.1.0(1mo ago)364MITPHPPHP ^8.2|^8.5CI failing

Since May 19Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/hamdyelbatal122/nativerag)[ Packagist](https://packagist.org/packages/hamzi/nativerag)[ Docs](https://github.com/hamdyelbatal122/nativerag)[ RSS](/packages/hamzi-nativerag/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (9)Dependencies (8)Versions (11)Used By (0)

🧠 Laravel NativeRAG
===================

[](#-laravel-nativerag)

A world-class, production-ready Local AI &amp; RAG Engine for Laravel 11, 12 &amp; 13

 [![Latest Version](https://camo.githubusercontent.com/732dfb7f03f6c91d0f1b19f1b7dc3ddef9abab12557432d5b0ac81e4bc18cb64/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f68616d7a692f6e61746976657261672e7376673f7374796c653d666c61742d73717561726526636f6c6f723d346634366535)](https://packagist.org/packages/hamzi/nativerag) [![Tests Status](https://camo.githubusercontent.com/71e7c392f3e06091e91227f4466e905784c19a472644754d731a117d5d5980c0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f68616d6479656c626174616c3132322f6e61746976657261672f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/hamdyelbatal122/nativerag/actions) [![Code Style](https://camo.githubusercontent.com/8b7f8a7f68dfa75db2ad633f2f4a70b40916fc8492c42bf99078b0dfddf47d8a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f68616d6479656c626174616c3132322f6e61746976657261672f72756e2d74657374732e796d6c3f6272616e63683d6d6173746572266c6162656c3d70696e74267374796c653d666c61742d73717561726526636f6c6f723d323263353565)](https://github.com/hamdyelbatal122/nativerag/actions) [![Total Downloads](https://camo.githubusercontent.com/51bded33a3b4b9d0fef320b680f3905b26e4e2032064b31612b3ea920d917686/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f68616d7a692f6e61746976657261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hamzi/nativerag) [![PHP Version](https://camo.githubusercontent.com/1504076bc7ba9b13359a14244e204bc6992f8a65920519362f2ab2cd3025c0f1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f68616d7a692f6e61746976657261672e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hamzi/nativerag) [![License](https://camo.githubusercontent.com/40280856210c46450b6b1fd2f7121d287601ffad98171eb458371ed26a850221/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d737563636573732e7376673f7374796c653d666c61742d737175617265)](https://opensource.org/licenses/MIT)

---

**Laravel NativeRAG** empowers you to run fully **localized, privacy-first AI workflows** using models hosted in [Ollama](https://ollama.com/) or [LM Studio](https://lmstudio.ai/) — directly from your Laravel application.

No OpenAI keys. No Pinecone. No cloud data leaks. **100% data residency. Zero external dependencies.**

---

✨ Features
----------

[](#-features)

FeatureDetails🤖 **Multi-Driver LLM**Switch between Ollama &amp; LM Studio via Laravel's Manager pattern🗄️ **Zero-Infra Vector Search**Cosine Similarity powered by PHP + native SQL. No Pinecone needed⚡ **SSE Streaming**Real-time token streaming to Alpine.js / Livewire frontends🧩 **Auto-Embedding Trait**Add `Embeddable` to any Eloquent model for automatic vector indexing🧠 **Persistent Memory**Multi-turn chat history with sliding-window pruning🔒 **Payload Encryption**Encrypt stored chat history using Laravel's App Key🛡️ **Strict Types**PHP 8.2+ with `declare(strict_types=1)`, Readonly DTOs, Enums🐘 **pgvector Support**Native PostgreSQL pgvector cosine distance queries---

✅ Compatibility
---------------

[](#-compatibility)

LaravelPHPStatus13.x8.2, 8.3, 8.4, 8.5✅ Fully Supported12.x8.2, 8.3, 8.4, 8.5✅ Fully Supported11.x8.2, 8.3, 8.4, 8.5✅ Fully Supported---

🚀 Installation
--------------

[](#-installation)

```
composer require hamzi/nativerag
```

Publish configuration and migrations:

```
php artisan vendor:publish --tag="nativerag-config"
php artisan vendor:publish --tag="nativerag-migrations"
php artisan migrate
```

---

🛠️ Configuration
----------------

[](#️-configuration)

Set your driver settings in `.env`:

```
NATIVE_RAG_DRIVER=ollama

# Ollama
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_CHAT_MODEL=llama3
OLLAMA_EMBEDDING_MODEL=nomic-embed-text

# LM Studio
LMSTUDIO_BASE_URL=http://localhost:1234
LMSTUDIO_CHAT_MODEL=meta-llama-3-8b-instruct

# Chunking & Retrieval
NATIVE_RAG_CHUNK_SIZE=1000
NATIVE_RAG_CHUNK_OVERLAP=200
NATIVE_RAG_MIN_SCORE=0.35

# Security
NATIVE_RAG_ENCRYPT_PAYLOADS=false
```

---

📖 Usage
-------

[](#-usage)

### 1. Chat Completions

[](#1-chat-completions)

```
use Hamzi\NativeRag\Facades\NativeRag;

$response = NativeRag::chat([
    ['role' => 'system', 'content' => 'You are a senior Laravel engineer.'],
    ['role' => 'user',   'content' => 'Explain service containers briefly.'],
]);

echo $response->content;        // The generated text
echo $response->promptTokens;   // Input tokens used
echo $response->completionTokens; // Output tokens generated
```

### 2. Real-Time SSE Streaming

[](#2-real-time-sse-streaming)

```
use Hamzi\NativeRag\Facades\NativeRag;
use Illuminate\Support\Facades\Route;

Route::post('/api/ai/stream', function () {
    return NativeRag::stream([
        ['role' => 'user', 'content' => 'Write a comprehensive guide on Eloquent ORM.'],
    ]);
});
```

**Consume in JavaScript (Alpine.js / Vanilla):**

```
const source = new EventSource('/api/ai/stream');
source.onmessage = ({ data }) => {
    const { content, done } = JSON.parse(data);
    if (done) { source.close(); return; }
    document.querySelector('#output').insertAdjacentText('beforeend', content);
};
```

### 3. Embeddable Models (Auto-Indexing)

[](#3-embeddable-models-auto-indexing)

To enable automatic vector indexing, implement the `EmbeddableContract` interface and use the `Embeddable` trait on any Eloquent model. Whenever the model is saved, its content is automatically chunked, embedded locally, and synchronized in the database.

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Hamzi\NativeRag\Contracts\EmbeddableContract;
use Hamzi\NativeRag\Traits\Embeddable;

class Article extends Model implements EmbeddableContract
{
    use Embeddable;

    /**
     * Define the text payload the AI engine will index.
     */
    public function toEmbeddableString(): string
    {
        return "Title: {$this->title}\n\nContent: {$this->content}";
    }
}
```

### 4. Semantic Vector Search

[](#4-semantic-vector-search)

```
use Hamzi\NativeRag\Services\VectorSearchEngine;
use Hamzi\NativeRag\Facades\NativeRag;

// 1. Embed the user's question
$queryVector = NativeRag::embedding()->embed('How does quantum physics relate to computing?');

// 2. Search native database for closest chunks
$engine = new VectorSearchEngine();
$results = $engine->search($queryVector, limit: 5, minScore: 0.50);

foreach ($results as $chunk) {
    echo $chunk->chunk_content; // Matching text passage
    echo $chunk->similarity;    // Score: 0.0 – 1.0
}
```

### 5. Persistent Multi-Turn Conversations

[](#5-persistent-multi-turn-conversations)

Easily build persistent chat experiences with built-in sliding-window memory pruning (supporting both message `count` limits and max `token` thresholds).

```
use Hamzi\NativeRag\Models\NativeRagConversation;

// 1. Create or retrieve a conversation session
$conversation = NativeRagConversation::create([
    'name' => 'Support Session #123',
]);

// 2. Add system context (Optional)
$conversation->addSystemMessage('You are a helpful customer support agent.');

// 3. Ask a question (automatically sends message history to LLM, stores the response, and runs auto-pruning)
$assistantResponse = $conversation->ask('Can you explain how to set up NativeRAG?');

echo $assistantResponse->content; // The generated assistant response

// 4. Follow up (the previous system instruction and chat history are sent automatically)
$followUpResponse = $conversation->ask('Does it support LM Studio too?');

echo $followUpResponse->content;
```

#### Memory Pruning Strategies

[](#memory-pruning-strategies)

Control how history is pruned to stay within context windows:

- **`count` (Default)**: Keeps the last `N` messages.
- **`token`**: Keeps the most recent messages up to a custom token threshold (e.g. 4096 tokens). It calculates tokens dynamically using the DB record or falls back to an exact UTF-8 character length approximation (`ceil(chars / 4)`).

### 6. Switch Driver at Runtime

[](#6-switch-driver-at-runtime)

```
use Hamzi\NativeRag\Facades\NativeRag;

// Use LM Studio for this specific call
$response = NativeRag::driver('lmstudio')->chat([
    ['role' => 'user', 'content' => 'Summarize this document.'],
]);
```

---

🔒 Security &amp; Privacy
------------------------

[](#-security--privacy)

- **100% On-Premise:** All inference runs against Ollama/LM Studio on your own hardware. Zero network calls leave your server.
- **Payload Encryption:** Enable `NATIVE_RAG_ENCRYPT_PAYLOADS=true` to encrypt all stored chat content and metadata using Laravel's native AES-256-CBC encryption.
- **SQL Injection Safe:** Strictly uses Laravel's parameterized query builder with no raw string interpolations.
- **Change Detection:** MD5 content hashing prevents re-embedding unchanged documents — eliminating redundant local API calls.

---

🧪 Testing &amp; Code Quality
----------------------------

[](#-testing--code-quality)

```
# Run tests
composer test

# Run code style fixer
composer lint

# Run static analysis (PHPStan Level 6)
composer analyse
```

---

🤝 Contributing
--------------

[](#-contributing)

Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.

🛡️ Security Vulnerabilities
---------------------------

[](#️-security-vulnerabilities)

Please review the [SECURITY.md](SECURITY.md) policy to learn how to responsibly report a vulnerability.

📄 License
---------

[](#-license)

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

---

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance90

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

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 ~1 days

Total

10

Last Release

54d ago

PHP version history (2 changes)v1.0.0PHP ^8.2

v1.0.3PHP ^8.2|^8.5

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/36019461?v=4)[Hamdy Elbatal](/maintainers/hamdyelbatal122)[@hamdyelbatal122](https://github.com/hamdyelbatal122)

---

Top Contributors

[![hamdyelbatal122](https://avatars.githubusercontent.com/u/36019461?v=4)](https://github.com/hamdyelbatal122 "hamdyelbatal122 (72 commits)")

---

Tags

laravelollamaphpphplaravelaillmollamalmstudioembeddingragvector-searchlocal-ai

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/hamzi-nativerag/health.svg)

```
[![Health](https://phpackages.com/badges/hamzi-nativerag/health.svg)](https://phpackages.com/packages/hamzi-nativerag)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.3M347](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58174.6k17](/packages/api-platform-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.6k](/packages/simplestats-io-laravel-client)[calebdw/larastan

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

15118.7k4](/packages/calebdw-larastan)

PHPackages © 2026

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