PHP code example of mauricioperera / php-agent-memory

1. Go to this page and download the library: Download mauricioperera/php-agent-memory library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mauricioperera / php-agent-memory example snippets


use PHPAgentMemory\AgentMemory;
use PHPAgentMemory\Config;
use PHPAgentMemory\Consolidation\CloudflareLlmProvider;
use PHPAgentMemory\Recall\RecallOptions;

// Full setup with dream capability
$memory = new AgentMemory(new Config(
    dataDir: './data',
    dimensions: 768,
    quantized: true,
    llmProvider: new CloudflareLlmProvider('CF_ACCOUNT', 'CF_TOKEN'),
    embedFn: fn(string $text) => myEmbedFunction($text),
));

// Save memories (you provide pre-computed embedding vectors)
$memory->memories->save('agent1', 'user1', [
    'content' => 'The user prefers dark mode for all applications',
    'tags' => ['preference', 'ui'],
    'category' => 'fact',
], $embeddingVector);

// Save skills
$memory->skills->save('agent1', null, [
    'content' => 'To deploy: git push origin main, then run deploy.sh',
    'tags' => ['deploy', 'git'],
    'category' => 'procedure',
], $embeddingVector);

// Save knowledge
$memory->knowledge->save('agent1', null, [
    'content' => 'PHP 8.1 introduced enums and readonly properties',
    'tags' => ['php'],
    'source' => 'php.net',
], $embeddingVector);

// Recall: multi-collection search ranked by score
$context = $memory->recall('agent1', 'user1', 'deployment process', $queryVector,
    new RecallOptions(maxItems: 10),
);
echo $context->formatted;

// Dream: the agent sleeps and consolidates its memory
$report = $memory->dream('agent1', 'user1');
echo $report;

$memory->flush();

// One-line dream — everything wired through Config
$report = $memory->dream('agent1', 'user1');

echo $report;
// Dream Report — agent:agent1 user:user1
// ──────────────────────────────────────────────────
//   [orient] Inventory: 14 memories, 4 skills, 0 knowledge
//   [analyze] Found 5 duplicate clusters, 0 stale entries
//   [consolidate] Memories: merged=2, removed=9, kept=6
//   [consolidate] Skills: merged=1, removed=2, kept=2
//   [verify] Post-dream: 10 entities (delta: -8)
// ──────────────────────────────────────────────────
//   Duration: 20,350ms
//   Merged: 3 | Removed: 11 | Kept: 8

$report = $memory->dream('agent1', 'user1');

$report->getTotalMerged();     // 3
$report->getTotalRemoved();    // 11
$report->getTotalKept();       // 8
$report->getDurationMs();      // 20350.0
$report->getConsolidations();  // ['memories' => [...], 'skills' => [...]]
$report->getLog();             // [{phase, message, time}, ...]
$report->toArray();            // Full report as array (for JSON APIs)

use PHPAgentMemory\Dream\DreamPipeline;

$dream = new DreamPipeline(
    $memory,
    $llmProvider,
    fn(string $text) => myEmbedFunction($text),
);

$report = $dream->run('agent1', 'user1');

use PHPAgentMemory\Config;
use PHPAgentMemory\Consolidation\CloudflareLlmProvider;

$config = new Config(
    dataDir: './data',           // Where to store vectors and indices
    dimensions: 768,             // Must match your embedding model
    dedupThreshold: 0.85,        // Cosine similarity threshold for dedup
    quantized: true,             // Int8 (776 bytes/vec) vs Float32 (3072 bytes/vec)
    llmProvider: new CloudflareLlmProvider(  // Optional: for dream/consolidation
        accountId: 'CF_ACCOUNT_ID',
        apiToken: 'CF_API_TOKEN',
        model: '@cf/ibm-granite/granite-4.0-h-micro',
    ),
    embedFn: fn(string $text) => embed($text),  // Optional: for dream re-embedding
);

$llm = new CloudflareLlmProvider(
    accountId: 'CF_ACCOUNT_ID',
    apiToken: 'CF_API_TOKEN',
    model: '@cf/ibm-granite/granite-4.0-h-micro',  // default
    maxTokens: 2048,
    temperature: 0.3,
);

use PHPAgentMemory\Consolidation\LlmProviderInterface;

class MyLlmProvider implements LlmProviderInterface
{
    public function chat(array $messages): string
    {
        // Call OpenAI, Anthropic, Ollama, etc.
        return $response;
    }
}

use PHPAgentMemory\Integration\Neuron\MemoryToolkit;

class MyAgent extends \NeuronAI\Agent\Agent
{
    protected function tools(): array
    {
        return [
            new MemoryToolkit($agentMemory, $embeddingProvider, 'agent1', 'user1'),
        ];
    }
}

use PHPAgentMemory\Integration\Neuron\NeuronMemoryStore;

class MyRAG extends \NeuronAI\RAG\RAG
{
    protected function vectorStore(): VectorStoreInterface
    {
        return new NeuronMemoryStore($agentMemory, 'agent1', 'knowledge', topK: 5);
    }
}

use PHPAgentMemory\Integration\Neuron\MemoryRetrieval;

class MyRAG extends \NeuronAI\RAG\RAG
{
    protected function retrieval(): RetrievalInterface
    {
        return new MemoryRetrieval($agentMemory, $embeddingProvider, 'agent1', 'user1', maxItems: 10);
    }
}

use PHPAgentMemory\Integration\Neuron\MemoryPreProcessor;

class MyRAG extends \NeuronAI\RAG\RAG
{
    protected function preProcessors(): array
    {
        return [
            new MemoryPreProcessor($agentMemory, $embeddingProvider, 'agent1', 'user1',
                maxItems: 5, maxChars: 2000),
        ];
    }
}

class SmartAgent extends \NeuronAI\RAG\RAG
{
    protected function tools(): array
    {
        return [
            new MemoryToolkit($memory, $embeddings, 'agent1', 'user1'),
        ];
    }

    protected function preProcessors(): array
    {
        return [
            new MemoryPreProcessor($memory, $embeddings, 'agent1', 'user1'),
        ];
    }

    protected function retrieval(): RetrievalInterface
    {
        return new MemoryRetrieval($memory, $embeddings, 'agent1', 'user1');
    }
}

// End of day: the agent dreams
$memory->dream('agent1', 'user1');

function embed(string $text): array {
    $ch = curl_init("https://api.cloudflare.com/client/v4/accounts/{$accountId}/ai/run/@cf/google/embeddinggemma-300m");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer {$token}", "Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode(['text' => [$text]]),
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $data = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $data['result']['data'][0];
}

function embed(string $text): array {
    $ch = curl_init("https://api.openai.com/v1/embeddings");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ["Authorization: Bearer {$apiKey}", "Content-Type: application/json"],
        CURLOPT_POSTFIELDS => json_encode(['model' => 'text-embedding-3-small', 'input' => $text]),
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $data = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $data['data'][0]['embedding'];
}

function embed(string $text): array {
    $ch = curl_init("http://localhost:11434/api/embed");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['model' => 'nomic-embed-text', 'input' => $text]),
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $data = json_decode(curl_exec($ch), true);
    curl_close($ch);
    return $data['embeddings'][0];
}

composer 
bash
php -S 0.0.0.0:3210 bin/server.php -- --dir ./data --api-key SECRET --dimensions 768