Star 历史趋势
数据来源: GitHub API · 生成自 Stargazers.cn
README.md
MemoryBear Hero Banner

MemoryBear — Empowering AI with Human-Like Memory

Next-Generation AI Memory Management System · Perceive · Extract · Associate · Forget

License Python FastAPI Neo4j Gitee Sync

中文 | English

Quick Start · Installation · Core Features · Architecture · Benchmarks · Papers


Overview

MemoryBear is a next-generation AI memory system developed by RedBear AI. Its core breakthrough lies in moving beyond the limitations of traditional "static knowledge storage". Inspired by the cognitive mechanisms of biological brains, MemoryBear builds an intelligent knowledge-processing framework that spans the full lifecycle of perception → extraction → association → forgetting.

Unlike traditional memory tools that treat knowledge as static data to be retrieved, MemoryBear emulates the hippocampus's memory encoding, the neocortex's knowledge consolidation, and synaptic pruning-based forgetting — enabling knowledge to dynamically evolve with life-like properties. This shifts the relationship between AI and users from passive lookup to proactive cognitive assistance.

Papers

PaperDescription
📄 Memory Bear AI: A Breakthrough from Memory to CognitionMemoryBear core technical report
📄 Memory Bear AI Memory Science Engine for Multimodal Affective IntelligenceTechnical report on multimodal affective intelligence memory engine
📄 A-MBER: Affective Memory Benchmark for Emotion RecognitionAffective memory benchmark dataset

Why MemoryBear

Knowledge Forgetting in Single Models

  • Context window limits: Mainstream LLMs have 8k–32k token windows. In long conversations, early messages are pushed out, causing responses to lose historical context
  • Static knowledge gap: Training data is a static snapshot — it cannot absorb personalized information (preferences, history) from live interactions
  • Recency bias: Transformer self-attention weakens on long-range dependencies, overweighting recent input and ignoring earlier critical information

Memory Gaps in Multi-Agent Collaboration

  • Data silos: Different agents (consulting, after-sales, recommendation) maintain isolated memories, forcing users to repeat information
  • Inconsistent dialogue state: When switching agents, user intent and history labels are not fully passed along, causing service discontinuities
  • Decision conflicts: Agents with partial memory can produce contradictory responses (e.g., recommending products a user is allergic to)

Semantic Ambiguity in Reasoning

  • Domain jargon, colloquial expressions, and context-dependent references are not accurately encoded, leading to semantic drift in memory interpretation
  • Cross-language memory associations fail in multilingual or dialect-rich scenarios
Why MemoryBear

Core Features

MemoryBear Core Features

Memory Extraction Engine

Performs semantic-level parsing of unstructured conversations and documents to extract:

  • Core declarative information: Strips redundant modifiers, preserving subject-action-object logic
  • Structured triples: Automatically extracts entity relationships (e.g., MemoryBear → core function → knowledge extraction) as atomic units for graph storage
  • Temporal anchoring: Automatically extracts and tags timestamps, enabling time-based knowledge tracing
  • Intelligent summarization: Customizable length (50–500 words) and focus; generates concise summaries of 10-page documents in under 3 seconds

Graph Storage (Neo4j)

Graph-first architecture integrated with Neo4j, overcoming the weak relational modeling of traditional databases:

  • Supports millions of entities and tens of millions of relational edges
  • Covers 12 core relationship types: hierarchical, causal, temporal, logical, and more
  • Extracted triples sync directly to Neo4j, automatically building the initial knowledge graph
  • Interactive graph visualization with "machine-generated + human-optimized" collaborative management

Hybrid Search

Keyword retrieval + semantic vector retrieval dual-engine fusion:

  • Keyword search powered by Elasticsearch for millisecond-level exact matching of structured information
  • Semantic vector search via BERT embeddings, recognizing synonyms, near-synonyms, and implicit intent
  • Semantic retrieval expands the candidate space; keyword retrieval then performs precise filtering
  • Retrieval accuracy reaches 92%, improving 35% over single-mode retrieval

Memory Forgetting Engine

Inspired by the brain's synaptic pruning mechanism, using a dual-dimension model of memory strength and time decay:

  • Each knowledge item is assigned an initial memory strength, updated dynamically by usage frequency and association activity
  • When strength falls below threshold, knowledge enters a dormancy → decay → clearance three-stage lifecycle
  • Redundant knowledge maintained below 8%, reducing waste by over 60% compared to systems without forgetting

Self-Reflection Engine

Scheduled daily reflection process, mimicking human review and retrospection:

  • Consistency checks: Detects logical conflicts across related knowledge, flags suspicious records for human review
  • Value assessment: Evaluates invocation frequency and association contribution; reinforces high-value knowledge, accelerates decay of low-value knowledge
  • Association optimization: Adjusts relationship weights based on recent usage, strengthening high-frequency association paths

FastAPI Service Layer

Unified service architecture exposing two API surfaces:

API TypePath PrefixAuthPurpose
Management API/apiJWTSystem config, permissions, log queries
Service API/v1API KeyKnowledge extraction, graph ops, search, forgetting control
  • Average response latency below 50ms, single instance sustaining 1000 QPS
  • Auto-generated Swagger documentation
  • Docker-ready, compatible with enterprise microservice ecosystems (CRM, OA, R&D management)

Architecture

MemoryBear System Architecture

Celery Multi-Queue Async Architecture (7 worker types in docker-compose):

QueueWorker TypeConcurrencyPurpose
memory_tasksthreads100Memory read/write (asyncio-friendly)
memory_fast_tasksthreads32High-frequency fast writes (dedicated queue to avoid mutual blocking)
document_tasksprefork4Document parsing (CPU-bound)
periodic_tasksprefork2Scheduled tasks, reflection engine, various scanners
workflow_trigger_tasksprefork2Workflow scheduled triggers
subscription_state_tasksprefork4Subscription state transitions (Enterprise)
subscription_email_tasksprefork4Subscription expiry reminder emails (Enterprise)

Additional task queues such as graphrag_tasks, reflection_tasks, and memory_heavy_tasks (GraphRAG construction, second-layer reflection/deduplication, forgetting and insight generation, and other heavy-compute tasks) work together with the standalone task scheduler celery_task_scheduler and Celery Beat.


Benchmarks

Evaluation metrics include F1 score (F1), BLEU-1 (B1), and LLM-as-a-Judge score (J) — higher values indicate better performance.

MemoryBear consistently outperforms competing systems including Mem0, Zep, and LangMem across all four task categories:

Benchmark Results

Vector version (non-graph): Achieves substantially improved retrieval efficiency while maintaining high accuracy. Overall accuracy surpasses the best existing full-text retrieval methods (72.90 ± 0.19%), while maintaining low latency at both p50 and p95 for Search Latency and Total Latency.

Vector Version Metrics

Graph version: Integrating the knowledge graph architecture pushes overall accuracy to a new benchmark (75.00 ± 0.20%), delivering performance metrics that significantly surpass all other methods.

Graph Version Metrics

Quick Start

Docker Compose (Recommended)

Prerequisites: Docker Desktop installed.

# 1. Clone the repository
git clone https://github.com/SuanmoSuanyangTechnology/MemoryBear.git
cd MemoryBear/api

# 2. Start base services (PostgreSQL / Neo4j / Redis / Elasticsearch)
# Pull and start these images via Docker Desktop first (see Installation section 3.2)

# 3. Configure environment variables
cp env.example .env
# Edit .env with your database connections and LLM API keys

# 4. Initialize the database
pip install uv && uv sync
alembic upgrade head

# 5. Start API + Celery Workers + Beat scheduler
docker-compose up -d

# 6. Initialize the system and get the admin account
curl -X POST http://127.0.0.1:8002/api/setup

Note: docker-compose.yml includes the API service, Celery Workers, the standalone task scheduler (celery_task_scheduler), and the sandbox service. Base services (PostgreSQL, Neo4j, Redis, Elasticsearch) must be started separately.

Port info: Docker Compose defaults to port 8002; manual startup defaults to port 8000. The installation guide below uses manual startup (8000) as the example.

After startup:

Default admin credentials:

  • Account: admin@example.com
  • Password: admin_password

Manual Start

Quick commands below — see Installation for detailed steps.

# Backend
cd api
pip install uv && uv sync
alembic upgrade head
uv run -m app.main

# Frontend (new terminal)
cd web
npm install && npm run dev

Installation

1. Environment Requirements

ComponentVersionPurpose
Python3.12 (3.13+ not supported)Backend runtime
Node.js20.19+ or 22.12+Frontend runtime
PostgreSQL13+Primary database
Neo4j4.4+Knowledge graph storage
Redis6.0+Cache and message queue
Elasticsearch8.xHybrid search engine

2. Get the Project

git clone https://github.com/SuanmoSuanyangTechnology/MemoryBear.git
Directory Structure

3. Backend API Service

3.1 Install Python Dependencies

# Install uv package manager
pip install uv

# Switch to the API directory
cd api

# Install dependencies
uv sync

# Activate virtual environment
# Windows (PowerShell, inside /api)
.venv\Scripts\Activate.ps1
# Windows (cmd, inside /api)
.venv\Scripts\activate.bat
# macOS / Linux
source .venv/bin/activate

3.2 Install Base Services (Docker Images)

Download Docker Desktop and pull the required images.

PostgreSQL — search → select → pull

PostgreSQL Pull PostgreSQL Container PostgreSQL Running

Neo4j — pull the same way. When creating the container, map two required ports and set an initial password:

  • 7474: Neo4j Browser
  • 7687: Bolt protocol

Important: You must also add the environment variable NEO4J_PLUGINS=["apoc"] to install the APOC plugin (a hard dependency of the backend graph engine; not included in the official image by default). If configuring this via the Docker Desktop GUI is inconvenient, create the container from the command line instead:

docker run -d --name memorybear-neo4j \
  -p 7474:7474 -p 7687:7687 \
  -e NEO4J_AUTH=neo4j/<initial password, at least 8 chars> \
  -e NEO4J_PLUGINS='["apoc"]' \
  neo4j:5
Neo4j Container Neo4j Running

Redis — same steps as above.

Elasticsearch

Pull the Elasticsearch 8.x image and create a container, mapping ports 9200 (HTTP API) and 9300 (cluster communication). For initial setup, disable security to simplify configuration:

docker run -d --name elasticsearch \
  -p 9200:9200 -p 9300:9300 \
  -e "discovery.type=single-node" \
  -e "xpack.security.enabled=false" \
  elasticsearch:8.15.0

3.3 Configure Environment Variables

cp env.example .env

Fill in the core configuration in .env:

# Neo4j Graph Database
NEO4J_URI=bolt://localhost:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=your-password

# PostgreSQL Database
DB_HOST=127.0.0.1
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your-password
DB_NAME=redbear-mem

# Set to true on first startup to auto-migrate the database
DB_AUTO_UPGRADE=true

# Redis
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_DB=1
REDIS_PASSWORD=

# Celery
REDIS_DB_CELERY_BROKER=1
REDIS_DB_CELERY_BACKEND=2

# Elasticsearch
ELASTICSEARCH_HOST=127.0.0.1
ELASTICSEARCH_PORT=9200

# JWT Secret Key (generate with: openssl rand -hex 32)
SECRET_KEY=your-secret-key-here

3.4 Initialize the PostgreSQL Database

The database connection is read automatically from the DB_* environment variables in .env (migrations/env.py builds the connection string dynamically) — no need to modify alembic.ini.

Apply all migrations to create the full schema:

alembic upgrade head

Tip: When DB_AUTO_UPGRADE=true is set in .env, the API service automatically runs alembic upgrade head on startup. Migration scripts are located in api/migrations/versions/ — make sure that directory contains migration files before running the command.

Alembic Migration Database Tables

3.5 Start the API Service

uv run -m app.main

Access API documentation at http://localhost:8000/docs

API Docs

3.6 Start Celery Workers (Optional, for async tasks)

# Memory worker (thread pool, asyncio-friendly, high concurrency)
celery -A app.celery_worker.celery_app worker -E --loglevel=info --pool=threads --concurrency=100 --queues=memory_tasks -n memory_worker@%h

# Fast-write worker (thread pool, dedicated queue to avoid blocking normal writes)
celery -A app.celery_worker.celery_app worker -E --loglevel=info --pool=threads --concurrency=32 --queues=memory_fast_tasks -n memory_fast_worker@%h

# Document parsing worker (prefork, CPU-bound)
celery -A app.celery_worker.celery_app worker -E --loglevel=info --pool=prefork --concurrency=4 --queues=document_tasks --max-tasks-per-child=100 -n document_worker@%h

# Periodic tasks worker (reflection engine, various scanners)
celery -A app.celery_worker.celery_app worker -E --loglevel=info --pool=prefork --concurrency=2 --queues=periodic_tasks --max-tasks-per-child=50 -n periodic_worker@%h

# Workflow trigger worker
celery -A app.celery_worker.celery_app worker -E --loglevel=info --pool=prefork --concurrency=2 --queues=workflow_trigger_tasks --max-tasks-per-child=50 -n workflow_trigger_worker@%h

# Beat scheduler
celery -A app.celery_worker.celery_app beat --loglevel=info

# Task scheduler service (enqueue rate limiting and admission control)
python -m app.celery_task_scheduler

Tip: The above are the core workers. For a full deployment (including GraphRAG, subscription/notification, and other Enterprise-edition queue workers), docker-compose up -d is recommended.

4. Frontend Web Application

4.1 Install Dependencies

cd web
npm install

Note: In a corporate intranet, run npm run install:private to install the private component @redbear/memory-brick (use npm run install:private:dev in development). On the public internet, the script auto-detects the environment and skips silently, without affecting startup.

4.2 Update API Proxy Configuration

Edit web/vite.config.ts and point the /api proxy target to the backend API service (the frontend dev server runs on port 5175 by default):

proxy: {
  '/api': {
    target: 'http://127.0.0.1:8000',  // Backend API address — change to your actual deployment address
    changeOrigin: true,
  },
}

4.3 Start the Frontend Service

npm run dev
Frontend Start Frontend UI

5. Initialize the System

# Initialize the database and obtain the super admin account
curl -X POST http://127.0.0.1:8000/api/setup

Super admin credentials:

  • Account: admin@example.com
  • Password: admin_password

6. Full Startup Checklist

Step 1  Clone the repository
Step 2  Start base services (PostgreSQL / Neo4j / Redis / Elasticsearch)
Step 3  Configure .env environment variables
Step 4  Run alembic upgrade head to initialize the database
Step 5  uv run -m app.main to start the backend API
Step 6  npm run dev to start the frontend
Step 7  curl -X POST http://127.0.0.1:8000/api/setup to initialize the system
Step 8  Log in to the frontend with the admin account

Tech Stack

LayerTechnology
Backend FrameworkFastAPI + Uvicorn
Async TasksCelery (multi-queue: memory / document / periodic / graphrag, etc.)
Primary DatabasePostgreSQL 13+
Graph DatabaseNeo4j 5.13+ (5.26 LTS recommended, APOC plugin required)
Search EngineElasticsearch 8.x (keyword + semantic vector hybrid)
Cache / QueueRedis 6.0+
ORMSQLAlchemy 2.0 + Alembic
LLM IntegrationLangChain / OpenAI / DashScope / AWS Bedrock
MCP Integrationfastmcp + langchain-mcp-adapters
Frontend FrameworkReact 18 + TypeScript + Vite (rolldown-vite)
UI ComponentsAnt Design 5.x
Graph VisualizationAntV X6 + ECharts + D3.js
Package Manageruv (backend) / npm (frontend)

License

This project is licensed under the Apache License 2.0.


Community & Support

WeChat QR

  • Star History:

Star History Chart

关于 About

MemoryBear Equip AI with human-like memory capability

语言 Languages

Python76.3%
TypeScript19.8%
Jinja3.0%
Rust0.4%
CSS0.2%
JavaScript0.1%
Dockerfile0.1%
Shell0.1%
Lua0.0%
HTML0.0%
Mako0.0%
Less0.0%

提交活跃度 Commit Activity

代码提交热力图
过去 52 周的开发活跃度
6986
Total Commits
峰值: 277次/周
Less
More

核心贡献者 Contributors