MEMORY Module

Long-term chat memory subsystem

Stores and retrieves chat history with vector embeddings and summarization. Provides adapters for Postgres and Redis backends.

12
Python Files
2
Sub-modules
Python
Language

Infrastructure Production

Why This Module Exists

Raw chat logs grow unbounded and slow down token counting. Without memory/, every chat request would include the entire history (tokens wasted), or users manually prune (tedious + lossy). The memory module extracts key facts via summarization and stores embeddings, so recent interactions stay fast while long histories compress. ### Real-World Analogy Human memory: short-term recall (recent messages), long-term storage (facts + embeddings). memory/ mimics this by keeping recent chat in fast cache and old interactions in summarized vector form.

Architecture Overview

B["Memory Service"] B --> C{{Adapter}} C -->|Postgres| D["Vector DB"] C -->|Redis| E["Cache"] C -->|Hybrid| F["Cache + Vector"] D --> G["Retrieval"] E --> G F --> G"> flowchart LR A["Chat Handler"] --> B["Memory Service"] B --> C{{Adapter}} C -->|Postgres| D["Vector DB"] C -->|Redis| E["Cache"] C -->|Hybrid| F["Cache + Vector"] D --> G["Retrieval"] E --> G F --> G

Data Flow & Processing

Message"] --> B["Add to Recent"] B --> C{{Buffer Full}} C -->|No| D["Return Recent"] C -->|Yes| E["Summarize Old"] E --> F["Store Embeddings"] F --> G["Prune Oldest"] G --> D"> flowchart TD A["New Message"] --> B["Add to Recent"] B --> C{{Buffer Full}} C -->|No| D["Return Recent"] C -->|Yes| E["Summarize Old"] E --> F["Store Embeddings"] F --> G["Prune Oldest"] G --> D

Design Decisions

Key Design Choices

AspectApproachRationaleTrade-offs
ModularitySeparated concernsEasier testing and reuseSlight complexity overhead
Error HandlingExplicit exceptionsBetter debuggabilityMore verbose code
ConfigurationEnvironment-drivenFlexible across environmentsRequires setup
PerformanceCaching where applicableReduced latencyMemory overhead
ScalabilityHorizontal scaling supportGrows with demandStateless constraints

Algorithm Spotlight

Core Algorithms

### Summarization (extractive) **Problem:** Select top-k sentences via TF-IDF or BM25 **Approach:** Regenerate summary on every query (expensive) **Why:** O(n log k) via heap; summary is deterministic, cacheable.

Typical Processing Flow

This module processes requests through the following lifecycle:

  1. Initialization Phase — Module loaded, configuration validated, dependencies injected
  2. Request Reception — Entry point called with input data and context
  3. Parsing & Validation — Input schema checked, types normalized
  4. Core Processing — Business logic executes with state management
  5. Result Validation — Output checked for correctness and consistency
  6. Transformation — Result formatted for caller expectations
  7. Response — Output returned with metadata and timing info
  8. Cleanup — Resources released, caches updated, logs written

Failure Handling & Recovery

Failure Modes

Failure ScenarioDetection MethodRecovery StrategyImpact
Configuration errorValidation at startupError logged; app fails to startHigh - blocks operation
Network timeoutTimeout exceptionRetry with exponential backoffMedium - eventual success likely
Data validation failureSchema checkReturn error to callerLow - isolated issue
Resource exhaustionRate limit exceededQueue request or reject gracefullyMedium - degraded service

Performance Characteristics

Key Performance Notes

- ('In-memory recent buffer', '~1ms lookup vs ~10ms DB query') - ('Vector similarity search', 'HNSW index: logarithmic search instead of linear scan')
MetricBaselineConditionsNotes
ThroughputHighTypical workloadOptimized for bulk operations
LatencySub-secondCached pathStreaming used when possible
MemoryEfficientNormal operationsConnection pooling enabled
ScalabilityHorizontalStateless designLoad balancing supported

Key Files & Structure

Source Organization

Directory Layout
memory/
├── __init__.py                    # Package entry point
├── core.py                        # Core implementation
├── models.py                      # Data structures
├── utils.py                       # Helper functions
├── exceptions.py                  # Error classes
├── config.py                      # Configuration
├── tests/                         # Unit tests
└── examples/                      # Usage examples

Integration Points

This module integrates with:

Best Practices

Extended Content & Discussion

This module represents a critical architectural component of RAGFlow, designed with scalability, maintainability, and performance as primary objectives. The following sections provide deeper context and discussion of the design patterns, implementation strategies, and operational considerations.

Design Principles

Testing Strategy

Comprehensive testing ensures reliability and prevents regressions:

Deployment Considerations

When deploying this module in production:

Further Learning & References

To deepen your understanding of this module:

  1. Read the inline code documentation and docstrings
  2. Review the test files to understand expected behavior and edge cases
  3. Study integration points with other RAGFlow modules
  4. Experiment with the module in a development environment
  5. Participate in code reviews to learn from peers
  6. Contribute improvements and bug fixes

Troubleshooting & Support

Common issues and their solutions:

IssueSymptomDiagnosisResolution
Configuration ErrorModule fails to startCheck logs for missing/invalid config keysVerify environment variables and config files
Performance DegradationSlow responsesProfile with logging/monitoring toolsAnalyze bottlenecks, optimize hot paths
Resource LeakMemory grows over timeMemory profiler shows unreleased objectsCheck cleanup code, fix resource lifecycle
Integration FailureDependency errorsMissing or mismatched versionUpdate dependencies, check compatibility matrix

Version History & Changelog

This module has evolved through several iterations:

Contributing & Development

To contribute improvements to this module:

  1. Fork the repository and create a feature branch
  2. Make your changes and add tests for new functionality
  3. Run the full test suite to ensure no regressions
  4. Submit a pull request with clear description of changes
  5. Respond to code review feedback and iterate
  6. Once approved, changes are merged and released in next version