How to Implement Conversation Memory (Long-Term and Short-Term) for AI Interactions in ClicShopping

ClicShopping provides a built-in ConversationMemory component that manages both short-term RAM storage for immediate context and long-term database persistence with vector embeddings for retrieval across sessions.

The ClicShopping open-source e-commerce framework includes a sophisticated AI subsystem that enables conversational experiences through the Core/ClicShopping/AI/Agents/Memory/ namespace. When implementing conversation memory for AI interactions in ClicShopping, developers can leverage the native ConversationMemory class to maintain contextual awareness without building custom storage solutions. This implementation supports both ephemeral session memory and durable vector-based retrieval, integrated directly with the platform's existing database and caching infrastructure.

Understanding the ConversationMemory Architecture

The conversation memory system operates across three distinct layers that handle different persistence requirements and retrieval patterns.

Short-Term Memory (In-Process Storage)

Short-term memory maintains the most recent interactions in RAM using an internal $shortTermMemory array. This layer minimizes database round-trips by keeping the immediate conversational context readily available for the current LLM request cycle. According to the source code in ConversationMemory.php, the array updates atomically on every addInteraction() call and automatically respects memory size limits, clearing older entries when thresholds are reached. Administrators can manually purge this buffer using the clearShortTermMemory() method.

Long-Term Memory (Persistent Storage with Embeddings)

Long-term memory persists complete interaction histories to the rag_conversation_memory_embedding database table, enabling cross-session retrieval and contextual continuity. The MemoryRetentionService handles persistence logic, generating vector embeddings when an embedding provider is configured and writing both raw text and vector representations to the database. Retrieval operates through getRelevantContext(), which executes similarity searches against stored embeddings to return historically relevant conversation chunks based on semantic proximity to the current query.

Orchestration Integration

The OrchestratorAgent demonstrated in Core/ClicShopping/AI/Agents/Orchestrator/OrchestratorAgent.php instantiates ConversationMemory within its constructor, passing the current user ID and language ID to ensure proper context isolation. This pattern ensures that AI agents obtain properly scoped memory instances that respect multi-tenant boundaries in the e-commerce environment.

Implementing Conversation Memory in Custom AI Agents

To implement conversation memory in a custom AI agent, instantiate the ConversationMemory class with the appropriate user and language identifiers, then record interactions using the addInteraction() method.

use ClicShopping\AI\Agents\Memory\ConversationMemory;

// Initialize memory for the current user and language context
$memory = new ConversationMemory(
    $userId,          // Retrieved via $CLICSHOPPING_Customer->getID()
    $languageId,      // Retrieved via $CLICSHOPPING_Language->getID()
    'rag_conversation_memory_embedding', // Target table name
    $entityId = 0     // Optional entity reference for scoping
);

// Record a conversational turn with metadata
$memory->addInteraction($userMessage, $assistantReply, [
    'intent'   => $detectedIntent,
    'origin'   => 'customer_service_chat',
    'session'  => $sessionId
]);

// Retrieve semantically relevant historical context
$relevantContext = $memory->getRelevantContext($newUserQuery, $limit = 5);
// Feed $relevantContext into your LLM prompt for enhanced coherence

The getRelevantContext() method returns an array of text chunks from previous interactions that exhibit semantic similarity to the current query, effectively implementing retrieval-augmented generation (RAG) for conversational AI.

Managing Memory Lifecycle

Production deployments require explicit management of memory lifecycle events to prevent unbounded growth and ensure privacy compliance.

Clearing Short-Term Memory

To clear the in-memory buffer without affecting persistent storage, invoke clearShortTermMemory() via an administrative endpoint. The platform provides ClicShoppingAdmin/ajax/RAG/reset_context.php as a reference implementation:

require 'includes/application_top.php';

$memory = new ConversationMemory($userId, $languageId);
$memory->clearShortTermMemory();

echo json_encode(['status' => 'short_term_cleared']);

This operation immediately frees the RAM-resident $shortTermMemory array while preserving the database-backed long-term history.

Purging Long-Term Storage

For complete data retention policies or GDPR compliance scenarios, purge the rag_conversation_memory_embedding table and associated cache files. The maintenance logic mirrors clear_all_caches_complete.php:

require 'includes/application_top.php';

$db = $CLICSHOPPING_Db;
$prefix = CLICSHOPPING::getConfig('db_prefix');

// Remove vector embeddings and interaction records
$db->query("DELETE FROM {$prefix}rag_conversation_memory_embedding");
$db->query("DELETE FROM {$prefix}rag_conversation_memory");

// Clear filesystem cache artifacts
$cacheDir = __DIR__ . '/Core/ClicShopping/Work/Cache/Rag/Memory/';
if (is_dir($cacheDir)) {
    array_map('unlink', glob($cacheDir . '*.json'));
}

Recording User Feedback for Reinforcement Learning

The memory system supports feedback loops through the recordFeedback() method, enabling reinforcement learning from human feedback (RLHF). Store ratings or corrections linked to specific interaction IDs via the admin AJAX endpoint pattern found in record_feedback.php:

require 'includes/application_top.php';

$memory = new ConversationMemory($userId, $languageId);
$interactionId = (int)$_POST['interaction_id'];
$feedbackType  = $_POST['type'];      // 'useful', 'incorrect', or 'flagged'
$feedbackData  = json_decode($_POST['data'], true);

$memory->recordFeedback($interactionId, $feedbackType, $feedbackData);

This functionality allows teams to audit AI performance and fine-tune retrieval algorithms based on explicit user signals.

Customizing the Memory System

The architecture supports several extension points for specialized requirements:

  • Storage Backend Replacement: Extend MemoryRetentionService to write to external vector databases (Pinecone, Weaviate) instead of MySQL by overriding the persistence methods in MemoryRetentionService.php.
  • Retention Policies: Modify the TTL logic within clearShortTermMemory() or implement scheduled tasks using cron jobs to execute the SQL cleanup patterns from clear_all_caches_complete.php at defined intervals.
  • Metadata Enrichment: The $metadata array parameter in addInteraction() accepts arbitrary key-value pairs, allowing injection of intent tags, sentiment scores, or product references that enrich future retrieval queries.

Summary

  • ClicShopping provides native conversation memory through the ConversationMemory class located in Core/ClicShopping/AI/Agents/Memory/ConversationMemory.php.
  • Short-term memory uses an in-process $shortTermMemory array for immediate context, cleared via clearShortTermMemory().
  • Long-term memory persists to rag_conversation_memory_embedding with vector embeddings, retrieved via semantic similarity search through getRelevantContext().
  • OrchestratorAgent demonstrates proper instantiation patterns with user and language scoping.
  • Administrative endpoints in ClicShoppingAdmin/ajax/RAG/ handle reset operations and feedback collection.
  • MemoryRetentionService manages database persistence and can be extended for external vector stores.

Frequently Asked Questions

How does ClicShopping differentiate between short-term and long-term conversation memory?

Short-term memory maintains recent interactions in a PHP array ($shortTermMemory) within the ConversationMemory instance, providing immediate context without database queries. Long-term memory persists interactions to the rag_conversation_memory_embedding table with vector embeddings, enabling retrieval across sessions through similarity search. The system updates both layers simultaneously when addInteraction() is called, but only the long-term layer survives request termination.

Can I use an external vector database instead of MySQL for long-term storage?

Yes. The MemoryRetentionService class handles all persistence logic in Core/ClicShopping/AI/Agents/Memory/MemoryRetentionService.php. You can extend or replace this service to write embeddings to external vector databases such as Pinecone, Weaviate, or Milvus. Inject your custom retention service into the ConversationMemory constructor or override the default service binding in the dependency container.

What is the performance impact of the similarity search in getRelevantContext()?

The similarity query executes against the rag_conversation_memory_embedding table, which should have proper indexing on the embedding vector columns and associated metadata fields. For high-volume deployments, consider implementing approximate nearest neighbor (ANN) indexing or offloading vector search to dedicated vector databases. The method accepts a $limit parameter (default typically 5) to constrain result sets and minimize latency.

How do I ensure conversation privacy when users request data deletion?

Invoke the comprehensive clearing logic demonstrated in clear_all_caches_complete.php. This removes records from both rag_conversation_memory and rag_conversation_memory_embedding tables, clears the short-term memory buffer using clearShortTermMemory(), and deletes cached JSON files from Core/ClicShopping/Work/Cache/Rag/Memory/. Always verify that the $userId passed to the ConversationMemory constructor correctly isolates data to prevent cross-user deletion.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →