PHP code example of elephpantmemory / memory

1. Go to this page and download the library: Download elephpantmemory/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/ */

    

elephpantmemory / memory example snippets




use ElePHPantMemory\ChatManager;

// 1. Re-use your active database connection (PDO or mysqli)
// Compatible with MySQL, SQLite, PostgreSQL and SQL Server!
$memory = new ChatManager(
    existingConnection: $myActivePDO, 
    maxTokens: 2000, 
    purgeAfterDays: 15 // Auto-GDPR cleanup
);

$session = 'whatsapp_user_912345678';

// 2. Log messages normally (respects maxTokens sliding window)
$memory->addMessage($session, 'user', 'Hello, my name is Ze Povinho and my VAT/NIF is 123456789.');

// 3. Save extracted facts manually
$memory->saveFact($session, 'user_name', 'Ze Povinho');
$memory->saveFact($session, 'vat_number', '123456789');

// 4. Build the optimized payload ready for your AI API call
// Contains: System Prompt with Facts + recent chat history within maxTokens limits
$aiPayload = $memory->getOptimizedContext($session);

use ElePHPantMemory\ChatManager;
use ElePHPantMemory\GeminiProvider; // Or OpenAIProvider / AnthropicProvider / CustomProvider

// 1. Instantiate the AI Provider (Zero external packages needed!)
// Timeouts are fully configurable in seconds (defaults to 30)
$ai = new GeminiProvider(apiKey: 'YOUR_GEMINI_API_KEY', model: 'gemini-1.5-flash', timeout: 45);
// Or: $ai = new OpenAIProvider(apiKey: 'YOUR_OPENAI_API_KEY', model: 'gpt-4o-mini', timeout: 45);
// Or: $ai = new AnthropicProvider(apiKey: 'YOUR_CLAUDE_API_KEY', model: 'claude-3-5-sonnet-latest', timeout: 45);

$memory = new ChatManager(
    existingConnection: $myActivePDO,
    maxTokens: 1500,
    purgeAfterDays: 30,
    aiProvider: $ai
);

// Enable automatic facts extraction on addMessage()
$memory->autoExtractFacts = true;

$session = 'user_session_123';

// 2. Add message. Fact extraction will trigger automatically in the background!
$memory->addMessage($session, 'user', 'Hi, my name is Rui, I live in Lisbon and prefer PHP.');

// 3. Get specific extracted facts
$userName = $memory->getFact($session, 'user_name'); // 'Rui'
$location = $memory->getFact($session, 'location');  // 'Lisbon'

// 4. If maxTokens is hit, older messages are summarized into '_conversation_summary'
// and deleted from history automatically!
$aiPayload = $memory->getOptimizedContext($session);

use ElePHPantMemory\ChatManager;
use ElePHPantMemory\CustomProvider;

$ai = new CustomProvider(function (array $messages, array $options = []): string {
    // Send the messages array to your custom AI client and return raw string response
    return $myLaravelAIClient->chat($messages);
});

$memory = new ChatManager($db, 2000, 30, $ai);

// Delete a specific fact / Apaga um facto específico
$memory->deleteFact($session, 'vat_number');

// Clear all facts / Limpa todos os factos
$memory->clearFacts($session);

// Clear message history / Limpa o histórico de mensagens
$memory->clearHistory($session);

// Delete entire session data / Apaga todos os dados da sessão
$memory->deleteSession($session);

// The library will automatically initialize `myprefix_history` and `myprefix_facts`
$memory = new ChatManager(
    existingConnection: $db,
    tablePrefix: 'myprefix_'
);

// Save a fact that expires in 1 hour (3600 seconds)
$memory->saveFact($session, 'temp_location', 'Hotel Room 402', 3600);

// Expired facts are automatically filtered out when fetching context:
$aiPayload = $memory->getOptimizedContext($session);

$memory->autoExtractFacts = true;

// Instruct the LLM to only extract business preferences
$memory->extractionGuidelines = "Only extract corporate info, billing preferences, and VAT numbers. Ignore personal data.";

$memory->addMessage($session, 'user', 'My VAT is 123456789 and I hate pineapple pizza.');
// Only VAT will be extracted!

// Format facts as JSON inside the system prompt instead of the default [key: value] brackets
$memory->contextFormatter = function(array $facts): string {
    $clean = [];
    foreach ($facts as $f) {
        $clean[$f['fact_key']] = $f['fact_value'];
    }
    return "User Profile JSON: " . json_encode($clean);
};

$aiPayload = $memory->getOptimizedContext($session);
// The first system message in $aiPayload will contain:
// "User Profile JSON: {"user_name":"Rui","preferred_language":"PHP"}"

try {
    $memory = new ChatManager($db, 2000, 30, $ai);
    $memory->addMessage($session, 'user', 'Hello!');
} catch (\ElePHPantMemory\ValidationException $e) {
    echo "Validation failed: " . $e->getMessage();
} catch (\ElePHPantMemory\StorageException $e) {
    echo "Database error: " . $e->getMessage();
} catch (\ElePHPantMemory\AIException $e) {
    echo "AI Provider error: " . $e->getMessage();
} catch (\ElePHPantMemory\ElePHPantException $e) {
    echo "General library error: " . $e->getMessage();
}
bash
php run_tests.php