1+ """
2+ Example demonstrating persistent user management in MemOS.
3+
4+ This example shows how to use the PersistentUserManager to maintain
5+ user configurations across service restarts.
6+ """
7+
8+ import os
9+ import tempfile
10+ from pathlib import Path
11+
12+ from memos .configs .mem_os import MOSConfig
13+ from memos .mem_os .product import MOSProduct
14+ from memos .mem_user .persistent_user_manager import PersistentUserManager , UserRole
15+
16+
17+ def create_sample_config (user_id : str ) -> MOSConfig :
18+ """Create a sample configuration for a user."""
19+ return MOSConfig (
20+ user_id = user_id ,
21+ chat_model = {
22+ "backend" : "openai" ,
23+ "config" : {
24+ "model_name_or_path" : "gpt-3.5-turbo" ,
25+ "api_key" : "your-api-key-here" ,
26+ "temperature" : 0.7 ,
27+ }
28+ },
29+ mem_reader = {
30+ "backend" : "naive" ,
31+ "config" : {
32+ "llm" : {
33+ "backend" : "openai" ,
34+ "config" : {
35+ "model_name_or_path" : "gpt-3.5-turbo" ,
36+ "api_key" : "your-api-key-here" ,
37+ }
38+ },
39+ "embedder" : {
40+ "backend" : "ollama" ,
41+ "config" : {
42+ "model_name_or_path" : "nomic-embed-text:latest" ,
43+ }
44+ }
45+ }
46+ },
47+ enable_textual_memory = True ,
48+ enable_activation_memory = False ,
49+ top_k = 5 ,
50+ max_turns_window = 20
51+ )
52+
53+
54+ def demonstrate_persistence ():
55+ """Demonstrate the persistence functionality."""
56+ print ("=== MemOS Persistent User Management Demo ===\n " )
57+
58+ # Create a temporary database for this demo
59+ temp_dir = tempfile .mkdtemp ()
60+ db_path = os .path .join (temp_dir , "demo_memos.db" )
61+
62+ try :
63+ # Step 1: Create a persistent user manager
64+ print ("1. Creating PersistentUserManager..." )
65+ user_manager = PersistentUserManager (db_path = db_path )
66+ print (f" Database created at: { db_path } " )
67+
68+ # Step 2: Create some sample configurations
69+ print ("\n 2. Creating sample user configurations..." )
70+ user_configs = {}
71+ for i in range (3 ):
72+ user_id = f"user_{ i + 1 } "
73+ user_name = f"User { i + 1 } "
74+ config = create_sample_config (user_id )
75+ user_configs [user_id ] = config
76+
77+ # Create user with configuration
78+ created_id = user_manager .create_user_with_config (
79+ user_name , config , UserRole .USER , user_id
80+ )
81+ print (f" Created user: { user_name } (ID: { created_id } )" )
82+
83+ # Step 3: Verify configurations are saved
84+ print ("\n 3. Verifying configurations are saved..." )
85+ for user_id in user_configs :
86+ config = user_manager .get_user_config (user_id )
87+ if config :
88+ print (f" ✓ Configuration found for { user_id } " )
89+ print (f" - Textual memory enabled: { config .enable_textual_memory } " )
90+ print (f" - Top-k: { config .top_k } " )
91+ else :
92+ print (f" ✗ Configuration not found for { user_id } " )
93+
94+ # Step 4: Simulate service restart by creating a new manager instance
95+ print ("\n 4. Simulating service restart..." )
96+ print (" Creating new PersistentUserManager instance..." )
97+ new_user_manager = PersistentUserManager (db_path = db_path )
98+
99+ # Step 5: Verify configurations are restored
100+ print ("\n 5. Verifying configurations are restored after restart..." )
101+ for user_id in user_configs :
102+ config = new_user_manager .get_user_config (user_id )
103+ if config :
104+ print (f" ✓ Configuration restored for { user_id } " )
105+ else :
106+ print (f" ✗ Configuration not restored for { user_id } " )
107+
108+ # Step 6: Create MOSProduct and demonstrate restoration
109+ print ("\n 6. Creating MOSProduct with persistent user manager..." )
110+ default_config = create_sample_config ("default_user" )
111+ mos_product = MOSProduct (default_config = default_config )
112+
113+ # The MOSProduct should automatically restore user instances
114+ print (f" Active user instances: { len (mos_product .user_instances )} " )
115+ for user_id in mos_product .user_instances :
116+ print (f" - { user_id } " )
117+
118+ # Step 7: Demonstrate configuration update
119+ print ("\n 7. Demonstrating configuration update..." )
120+ user_id = "user_1"
121+ original_config = user_manager .get_user_config (user_id )
122+ if original_config :
123+ # Update configuration
124+ updated_config = original_config .model_copy (deep = True )
125+ updated_config .top_k = 10
126+ updated_config .enable_activation_memory = True
127+
128+ success = user_manager .save_user_config (user_id , updated_config )
129+ if success :
130+ print (f" ✓ Updated configuration for { user_id } " )
131+ print (f" - New top-k: { updated_config .top_k } " )
132+ print (f" - Activation memory: { updated_config .enable_activation_memory } " )
133+ else :
134+ print (f" ✗ Failed to update configuration for { user_id } " )
135+
136+ # Step 8: List all configurations
137+ print ("\n 8. Listing all user configurations..." )
138+ all_configs = user_manager .list_user_configs ()
139+ print (f" Total configurations: { len (all_configs )} " )
140+ for user_id , config in all_configs .items ():
141+ print (f" - { user_id } : top_k={ config .top_k } , textual_memory={ config .enable_textual_memory } " )
142+
143+ print ("\n === Demo completed successfully! ===" )
144+ print (f"Database file: { db_path } " )
145+ print ("You can inspect this file to see the persistent data." )
146+
147+ except Exception as e :
148+ print (f"Error during demo: { e } " )
149+ raise
150+ finally :
151+ # Cleanup
152+ if os .path .exists (db_path ):
153+ os .remove (db_path )
154+ if os .path .exists (temp_dir ):
155+ os .rmdir (temp_dir )
156+
157+
158+ def demonstrate_api_usage ():
159+ """Demonstrate how the API would work with persistence."""
160+ print ("\n === API Usage Example ===" )
161+ print ("""
162+ With the new persistent system, your API calls would work like this:
163+
164+ 1. Register a user (configuration is automatically saved):
165+ POST /product/users/register
166+ {
167+ "user_id": "john_doe",
168+ "user_name": "John Doe",
169+ "interests": "AI, machine learning, programming"
170+ }
171+
172+ 2. Get user configuration:
173+ GET /product/users/john_doe/config
174+
175+ 3. Update user configuration:
176+ PUT /product/users/john_doe/config
177+ {
178+ "user_id": "john_doe",
179+ "enable_activation_memory": true,
180+ "top_k": 10,
181+ ...
182+ }
183+
184+ 4. After service restart, all user instances are automatically restored
185+ and the user can immediately use the system without re-registration.
186+ """ )
187+
188+
189+ if __name__ == "__main__" :
190+ demonstrate_persistence ()
191+ demonstrate_api_usage ()
0 commit comments