Skip to content

Memory System (A-Memorix)

A-Memorix is MaiBot's built-in long-term memory subsystem, responsible for persisting user preferences, dialogue history, and person profiles. This document details its architecture, storage mechanisms, and retrieval flows.

Architecture Overview

SDKMemoryKernel

Source location: src/A_memorix/core/runtime/sdk_memory_kernel.py

SDKMemoryKernel is the core runtime of A-Memorix. On initialization, it loads configuration and builds all storage and retrieval components.

Initialization Flow

KernelSearchRequest

Data structure for retrieval requests:

FieldTypeDefaultDescription
querystr""Query text
limitint5Return count
modestr"search"Retrieval mode
chat_idstr""Chat stream ID
person_idstr""Person ID
time_startOptional[str|float]NoneStart time
time_endOptional[str|float]NoneEnd time
respect_filterboolTrueWhether to apply chat filter config
user_idstr""User ID
group_idstr""Group ID

Retrieval Modes

ModeDescriptionRequired Parameters
searchSemantic vector retrievalquery
timeTime range retrievaltime_start or time_end
hybridVector + time hybridtime_start or time_end
episodeEpisode retrievalquery
aggregateAggregate retrievalquery

WARNING

semantic mode has been removed; passing it will return a parameter error. time and hybrid modes must provide time_start or time_end, otherwise they return an error.

AMemorixHostService

Source location: src/A_memorix/host_service.py

Host-side service, bridging MaiBot main process with A-Memorix kernel:

python
class AMemorixHostService:
    _kernel: Optional[SDKMemoryKernel]
    _config_cache: Dict[str, Any] | None

    async def start() -> None
    async def stop() -> None
    async def reload() -> None  # Close kernel → Re-read config → Rebuild kernel
    async def invoke(component_name, args) -> Any  # Unified invocation entry

invoke Entry Point

invoke() routes to corresponding kernel methods based on component name:

Component NameCorresponding Kernel Method
search_memorykernel.search_memory()
ingest_summarykernel.ingest_summary()
ingest_textkernel.ingest_text()
get_person_profilekernel.get_person_profile()
maintain_memorykernel.maintain_memory()
memory_statskernel.memory_stats()
memory_graph_adminkernel.memory_graph_admin()
memory_source_adminkernel.memory_source_admin()
memory_episode_adminkernel.memory_episode_admin()
memory_profile_adminkernel.memory_profile_admin()
memory_runtime_adminkernel.memory_runtime_admin()
memory_import_adminkernel.memory_import_admin()
memory_tuning_adminkernel.memory_tuning_admin()
memory_v5_adminkernel.memory_v5_admin()
memory_delete_adminkernel.memory_delete_admin()

Configuration Management

  • Config file path: config/a_memorix.toml
  • Schema file: src/A_memorix/config_schema.json
  • get_config() / update_config() / get_raw_config() / update_raw_config() for config read/write
  • After updating config, automatically reload(), rebuild kernel instance

Storage Layer

Source location: src/A_memorix/core/storage/

VectorStore

Source: vector_store.py

Vector storage, storing paragraph embedding vectors, supports:

  • Write vectors (paragraph hash → vector mapping)
  • Nearest neighbor search (cosine similarity)
  • Quantization support (QuantizationType: int8)
  • Non-blocking write queue (on embedding failure, enqueue for retry)

GraphStore

Source: graph_store.py

Knowledge graph storage, managing entities and relationships:

  • Create/delete/rename nodes
  • Create/delete/update edges (including weights)
  • Relationship vector index
  • Graph access operations (reinforce / protect / restore / freeze)

MetadataStore

Source: metadata_store.py

Metadata storage, managing sources, paragraphs, and operations records:

  • Source management: list, delete, batch delete
  • Paragraph metadata tracking
  • Relationship maintenance operations (reinforce / protect / restore / freeze / recycle_bin)
  • V5 operations records (external_memory_refs, memory_v5_operations, delete_operations)

knowledge_types.py

Defines data types for knowledge content, distinguishing factual knowledge from narrative knowledge.

Retrieval Layer

Source location: src/A_memorix/core/retrieval/

Dual-Path Retrieval Architecture

Key Components

FileComponentDescription
dual_path.pyDualPathRetrieverCoordinates vector + graph joint recall
graph_relation_recall.pyGraph relation recallGraph-based association lookup
sparse_bm25.pySparseBM25IndexBM25-based sparse retrieval (requires FTS5 support)
pagerank.pyPageRankGraph structure weight calculation
threshold.pyThreshold filterSimilarity threshold control

RetrievalResult

Data structure for retrieval results, containing matching paragraphs, similarity scores, and source information.

Strategy Layer

Source location: src/A_memorix/core/strategies/

Write strategies determine how memories are processed and stored:

StrategySource FileDescription
factualfactual.pyFactual knowledge strategy, extracts entities and relationships
narrativenarrative.pyNarrative strategy, handles dialogue summaries
quotequote.pyQuote strategy, preserves original text

All strategies inherit from base class in base.py, defining unified processing interface.

Auxiliary Services

EpisodeService

Source: core/utils/episode_service.py

Manages Episodes (dialogue segments), rebuild by source:

  • State query (pending / processing / completed)
  • Batch process pending Episodes
  • Episode segmentation service (EpisodeSegmentationService)
  • Episode retrieval service (EpisodeRetrievalService)

PersonProfileService

Source: core/utils/person_profile_service.py

Person profile management:

  • Auto snapshot: automatically extract person features from memory data
  • Manual override: manually set profile attributes via API
  • Profile query: get profile by person_id and chat_id

RelationWriteService

Source: core/utils/relation_write_service.py

Relation write service:

  • Joint write of entities and relationships
  • external_id idempotent deduplication
  • Joint paragraph/relationship write

AggregateQueryService

Source: core/utils/aggregate_query_service.py

Aggregate query service, combines results from multiple retrieval modes.

ImportTaskManager

Source: core/utils/web_import_manager.py

Web import task manager:

  • Task creation (upload, paste, raw scan, LPMM modes)
  • Task status tracking
  • Chunk processing
  • Failure retry

Basic Tool Interfaces

search_memory

Retrieve long-term memory.

Parameters:

ParameterTypeRequiredDescription
querystrNoQuery text
modestrNoRetrieval mode (search/time/hybrid/episode/aggregate)
limitintNoReturn count (default 5)
chat_idstrNoChat stream ID
person_idstrNoPerson ID
time_startfloatNoStart timestamp
time_endfloatNoEnd timestamp
respect_filterboolNoWhether to apply chat filter config

ingest_summary

Write chat summary to long-term memory.

Parameters:

ParameterTypeRequiredDescription
external_idstrYesExternal idempotent ID
chat_idstrYesChat stream ID
textstrYesSummary text
participantslist[str]NoParticipant list
time_startfloatNoStart timestamp
time_endfloatNoEnd timestamp
tagslist[str]NoTags
metadatadictNoMetadata

ingest_text

Write normal text memory.

ParameterTypeRequiredDescription
external_idstrYesExternal idempotent ID
source_typestrYesSource type
textstrYesOriginal text
chat_idstrNoChat stream ID
entitieslistNoEntity list
relationslistNoRelationship list

get_person_profile

Get person profile.

ParameterTypeRequiredDescription
person_idstrYesPerson ID
chat_idstrNoChat stream ID
limitintNoEvidence count

maintain_memory

Maintain long-term memory relationship state.

actionDescription
reinforceReinforce relationship
protectProtect relationship (no decay within specified hours)
restoreRestore relationship
freezeFreeze relationship
recycle_binView recycle bin

Admin Tool Interfaces

ToolCommon Actions
memory_graph_adminget_graph / create_node / delete_node / rename_node / create_edge / delete_edge / update_edge_weight
memory_source_adminlist / delete / batch_delete
memory_episode_adminquery / list / get / status / rebuild / process_pending
memory_profile_adminquery / list / set_override / delete_override
memory_runtime_adminsave / get_config / self_check / refresh_self_check / set_auto_save
memory_import_adminsettings / get_guide / create_upload / create_paste / list / get / chunks / cancel / retry_failed
memory_tuning_adminsettings / get_profile / apply_profile / rollback_profile / create_task / list_tasks / get_task / cancel / apply_best / get_report
memory_v5_adminstatus / recycle_bin / restore / reinforce / weaken / remember_forever / forget
memory_delete_adminpreview / execute / restore / get_operation / list_operations / purge

Integration with MaiBot

Plugin Mode (Legacy)

Source location: src/A_memorix/plugin.py

AMemorixPlugin inherits from MaiBotPlugin, registers memory retrieval and write tools to plugin runtime via @Tool decorator.

INFO

Current MaiBot mainline is directly integrated via AMemorixHostService, no longer discovered and loaded through plugin runtime. plugin.py is retained as a compatibility entry.

Configuration

  • Default config file: config/a_memorix.toml
  • Runtime data directory: data/a-memorix (controlled by storage.data_dir)
  • Config Schema: config_schema.json for WebUI long-term memory console
  • WebUI interface: /api/webui/memory/*

Metadata Version

Current metadata schema version is v9, supporting:

  • External references (external_memory_refs)
  • Operations records (memory_v5_operations)
  • Delete operations (delete_operations)

Delete Semantics (source mode)

FieldDescription
requested_source_countRequested source count to delete
matched_source_countActually matched source count
deleted_paragraph_countActually deleted paragraph count
deleted_countSame as actual deleted objects
successBased on actual match and actual delete determination