PHPackages                             eznix86/laravel-ai-memory - 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. eznix86/laravel-ai-memory

ActiveLibrary[API Development](/categories/api)

eznix86/laravel-ai-memory
=========================

AI memory for Laravel AI SDK with semantic search and reranking

v1.0.1(3mo ago)23513[1 PRs](https://github.com/eznix86/laravel-ai-memory/pulls)MITPHPPHP ^8.4

Since Feb 6Pushed 3mo agoCompare

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

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

Laravel AI Memory
=================

[](#laravel-ai-memory)

[![Banner](./art/banner.png)](./art/banner.png)

Agentic memory for [Laravel AI SDK](https://github.com/laravel/ai). It keeps your agent in context.

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

[](#requirements)

- PHP 8.4+
- Laravel 12+
- laravel AI SDK
- A vector compatible database, preferably PostgreSQL with [pgvector](https://github.com/pgvector/pgvector) extension

Use cases
---------

[](#use-cases)

- **Personalization**: remember user preferences (tone, language, choices, and more...).
- **Continuity**: retain prior issues, steps tried, and outcomes.
- **Workflows**: resume tasks with stored constraints, decisions, and last-known state.
- **Context**: keep shared conventions, requirements, and decisions for consistent agent behavior.
- **Multi-agent/tool handoff**: persist facts so different agents/tools can coordinate without repeating context.
- **Scoped memory**: store only approved, minimal facts instead of full conversation history.

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

[](#installation)

```
composer require eznix86/laravel-ai-memory
```

Run the migrations:

```
php artisan migrate
```

Optionally publish the config:

```
php artisan vendor:publish --tag=memory-config
```

Usage
-----

[](#usage)

### AgentMemory Facade

[](#agentmemory-facade)

```
use Eznix86\AI\Memory\Facades\AgentMemory;

// Store a memory
$memory = AgentMemory::store('User prefers dark mode', ['user_id' => $userId]);

// Recall relevant memories (semantic search + reranking)
$memories = AgentMemory::recall('What are the user preferences?', ['user_id' => $userId], limit: 5);

// Get all memories for a user
$all = AgentMemory::all(['user_id' => $userId]);

// Delete a specific memory
AgentMemory::forget($memoryId);

// Delete all memories for a user
AgentMemory::forgetAll(['user_id' => $userId]);
```

### Agent Tools

[](#agent-tools)

Attach memory capabilities to any Laravel AI agent:

```
use Eznix86\AI\Memory\Tools\RecallMemory;
use Eznix86\AI\Memory\Tools\StoreMemory;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasTools;
use Laravel\Ai\Promptable;

class MyAgent implements Agent, HasTools
{
    use Promptable;

    public function __construct(
        protected array $context = [],
    ) {}

    public function instructions(): Stringable|string
    {
        return 'You are a helpful assistant with memory. Use Store Memory tool to save facts about the conversation.';
    }

    public function tools(): iterable
    {
        return [
            (new RecallMemory)->context($this->context),
            (new StoreMemory)->context($this->context),
        ];
    }
}
```

The AI agent will automatically decide when to store and recall memories using these tools.

### WithMemory Middleware

[](#withmemory-middleware)

Automatically prepend relevant memories to every agent prompt:

```
use Eznix86\AI\Memory\Middleware\WithMemory;
use Laravel\Ai\Contracts\HasMiddleware;

class MyAgent implements Agent, HasTools, HasMiddleware
{
    use Promptable;

    // ... tools() and instructions() ...

    public function middleware(): array
    {
        return [
            new WithMemory($this->context, limit: 5),
        ];
    }
}
```

When a user prompts the agent, the middleware will:

1. Search for relevant memories using the prompt text
2. Prepend them to the prompt as context
3. The agent sees them before responding

### Using the Agent

[](#using-the-agent)

```
$agent = new MyAgent(['user_id' => auth()->id()]);
$response = $agent->prompt('What do you remember about my preferences?');

echo $response->text;
```

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

[](#configuration)

Publish the config file to customize defaults:

```
php artisan vendor:publish --tag=memory-config
```

Available options in `config/memory.php`:

OptionDefaultDescription`dimensions``1536`Embedding vector dimensions (must match your model)`similarity_threshold``0.5`Minimum cosine similarity for recall`recall_limit``10`Default max memories returned by `recall()``middleware_recall_limit``5`Default memories injected by middleware`recall_oversample_factor``2`Candidates fetched before reranking (limit × factor)`table``memories`Database table nameYou can also set these via environment variables:

```
MEMORY_DIMENSIONS=1536
MEMORY_SIMILARITY_THRESHOLD=0.5
MEMORY_RECALL_LIMIT=10
MEMORY_MIDDLEWARE_RECALL_LIMIT=5
MEMORY_RECALL_OVERSAMPLE_FACTOR=2
MEMORY_TABLE=memories
```

How It Works
------------

[](#how-it-works)

1. **Store** — Content is converted to an embedding vector via `Str::of($content)->toEmbeddings()` and saved alongside the text in PostgreSQL with pgvector.
2. **Recall** — The query is embedded, then `whereVectorSimilarTo()` finds candidates by cosine similarity. Results are reranked via `$collection->rerank('content', $query)` for higher relevance.
3. **Middleware** — Before the agent sees the prompt, `WithMemory` recalls relevant memories and prepends them as context.

Testing
-------

[](#testing)

This package uses [Pest](https://pestphp.com) with [TestContainers](https://testcontainers.com) for PostgreSQL + pgvector integration tests.

```
./vendor/bin/pest
```

### Testing with `AgentMemory::fake()`

[](#testing-with-agentmemoryfake)

Use `AgentMemory::fake()` to fake all underlying AI services in one call. It uses deterministic embeddings internally, so `store()` → `recall()` just works:

```
use Eznix86\AI\Memory\Facades\AgentMemory;

test('agent remembers user preferences', function () {
    AgentMemory::fake();

    AgentMemory::store('User prefers dark mode', ['user_id' => 'user-123']);

    $memories = AgentMemory::recall('preferences', ['user_id' => 'user-123']);

    expect($memories)->toHaveCount(1)
        ->and($memories->first()->content)->toBe('User prefers dark mode');
});
```

When testing agents with the `WithMemory` middleware, `AgentMemory::fake()` handles everything — no need to separately fake `Embeddings` or `Reranking`:

```
test('agent receives memory context', function () {
    AgentMemory::fake();

    AgentMemory::store('User lives in Mauritius', ['user_id' => 'user-123']);

    $receivedPrompt = null;
    MyAgent::fake(function (string $prompt) use (&$receivedPrompt) {
        $receivedPrompt = $prompt;
        return 'Got it!';
    });

    $agent = new MyAgent(['user_id' => 'user-123']);
    $agent->prompt('Where do I live?');

    expect($receivedPrompt)
        ->toContain('User lives in Mauritius')
        ->toContain('Where do I live?');
});
```

You can also pass custom reranking responses to control the order of recalled memories:

```
use Laravel\Ai\Responses\Data\RankedDocument;

AgentMemory::fake([
    [
        new RankedDocument(index: 0, document: 'First result', score: 0.9),
        new RankedDocument(index: 1, document: 'Second result', score: 0.8),
    ],
]);
```

License
-------

[](#license)

MIT

###  Health Score

44

—

FairBetter than 92% of packages

Maintenance82

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity53

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

2

Last Release

95d ago

PHP version history (2 changes)1.0.0PHP ^8.3

v1.0.1PHP ^8.4

### Community

Maintainers

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

---

Top Contributors

[![eznix86](https://avatars.githubusercontent.com/u/26553194?v=4)](https://github.com/eznix86 "eznix86 (8 commits)")

---

Tags

agentailaravelmemorysdklaravelaimemorysemantic-searchvector-embeddings

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/eznix86-laravel-ai-memory/health.svg)

```
[![Health](https://phpackages.com/badges/eznix86-laravel-ai-memory/health.svg)](https://phpackages.com/packages/eznix86-laravel-ai-memory)
```

###  Alternatives

[hosseinhezami/laravel-gemini

A production-ready Laravel package to integrate with the Google Gemini API. Supports text, image, video, audio, long-context, structured output, files, caching, function-calling and understanding capabilities.

14010.8k1](/packages/hosseinhezami-laravel-gemini)[gemini-api-php/laravel

Gemini API client for Laravel

8915.7k](/packages/gemini-api-php-laravel)[claude-php/claude-php-sdk-laravel

Laravel integration for the Claude PHP SDK - Anthropic Claude API

5010.8k](/packages/claude-php-claude-php-sdk-laravel)[cboxdk/statamic-mcp

MCP (Model Context Protocol) server for Statamic CMS v6 — gives AI assistants structured access to content, blueprints, assets, and more.

225.6k](/packages/cboxdk-statamic-mcp)[thehocinesaad/stability-laravel

Stability Laravel is a comprehensive Laravel API client designed for seamless interaction with the Stability AI API.

111.3k](/packages/thehocinesaad-stability-laravel)

PHPackages © 2026

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