Skip to content

Commit c7df5ad

Browse files
committed
feat: add product API and related functionality (cleaned sensitive data)
1 parent 2e6f6e8 commit c7df5ad

File tree

13 files changed

+3700
-38
lines changed

13 files changed

+3700
-38
lines changed
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
"""
2+
Example demonstrating how to use MOSProduct for multi-user scenarios.
3+
"""
4+
5+
from memos.configs.mem_os import MOSConfig
6+
from memos.configs.llm import LLMConfigFactory
7+
from memos.configs.mem_reader import MemReaderConfigFactory
8+
from memos.configs.mem_cube import GeneralMemCubeConfig
9+
from memos.mem_os.product import MOSProduct
10+
from memos.mem_cube.general import GeneralMemCube
11+
from memos.configs.mem_cube import GeneralMemCubeConfig
12+
from memos.configs.memory import MemoryConfigFactory
13+
from memos.memories.factory import MemoryFactory
14+
15+
def get_config(user_name):
16+
openapi_config = {
17+
"model_name_or_path": "gpt-4o-mini",
18+
"temperature": 0.8,
19+
"max_tokens": 1024,
20+
"top_p": 0.9,
21+
"top_k": 50,
22+
"remove_think_prefix": True,
23+
"api_key": "your-api-key-here",
24+
"api_base": "https://api.openai.com/v1",
25+
}
26+
huggingface_config = {
27+
"model_name_or_path": "Qwen/Qwen3-1.7B",
28+
"temperature": 0.1,
29+
"remove_think_prefix": True,
30+
"max_tokens": 4096,
31+
"top_p": 0.9,
32+
"top_k": 50,
33+
"add_generation_prompt": True,
34+
}
35+
# Create a default configuration
36+
default_config = MOSConfig(
37+
user_id="root",
38+
chat_model={
39+
"backend":"openai",
40+
"config":openapi_config
41+
},
42+
mem_reader={
43+
"backend":"naive",
44+
"config":{
45+
"llm": {
46+
"backend": "openai",
47+
"config": openapi_config,
48+
},
49+
"embedder": {
50+
"backend": "ollama",
51+
"config": {
52+
"model_name_or_path": "nomic-embed-text:latest",
53+
},
54+
},
55+
}
56+
},
57+
enable_textual_memory=True,
58+
enable_activation_memory=False,
59+
top_k=5,
60+
max_turns_window=20
61+
)
62+
default_cube_config = GeneralMemCubeConfig.model_validate({
63+
"user_id": user_name,
64+
"cube_id": f"{user_name}_default_cube",
65+
"text_mem": {
66+
"backend": "tree_text",
67+
"config": {
68+
"extractor_llm": {
69+
"backend": "openai",
70+
"config": openapi_config
71+
},
72+
"dispatcher_llm": {
73+
"backend": "openai",
74+
"config": openapi_config
75+
},
76+
"graph_db": {
77+
"backend": "neo4j",
78+
"config": {
79+
"uri": "bolt://localhost:7687",
80+
"user": "neo4j",
81+
"password": "12345678",
82+
"db_name": user_name,
83+
"auto_create": True,
84+
},
85+
},
86+
"embedder": {
87+
"backend": "ollama",
88+
"config": {
89+
"model_name_or_path": "nomic-embed-text:latest",
90+
},
91+
},
92+
}
93+
},
94+
"act_mem": {},
95+
"para_mem": {},
96+
})
97+
default_mem_cube = GeneralMemCube(default_cube_config)
98+
return default_config, default_mem_cube
99+
100+
def main():
101+
default_config, default_mem_cube = get_config(user_name="alice")
102+
# Initialize MOSProduct with default config
103+
mos_product = MOSProduct(default_config=default_config)
104+
105+
106+
# Register first user with default config
107+
result1 = mos_product.user_register(
108+
user_id="alice",
109+
user_name="alice",
110+
interests="I'm interested in machine learning and AI research.",
111+
default_mem_cube=default_mem_cube
112+
)
113+
print(f"User registration result: {result1}")
114+
115+
# Chat with Alice
116+
print("\n=== Chatting with Alice ===")
117+
for response_chunk in mos_product.chat(
118+
query="What are my interests?",
119+
user_id="alice"
120+
):
121+
print(response_chunk, end="")
122+
123+
# Add memory for Alice
124+
mos_product.add(
125+
user_id="alice",
126+
memory_content="I attended a machine learning conference last week.",
127+
mem_cube_id=result1["default_cube_id"]
128+
)
129+
130+
# Search memories for Alice
131+
search_result = mos_product.search(
132+
query="conference",
133+
user_id="alice"
134+
)
135+
print(f"\nSearch result for Alice: {search_result}")
136+
137+
# Search memories for Alice
138+
search_result = mos_product.get_all(
139+
query="conference",
140+
user_id="alice",
141+
memory_type="text_mem"
142+
)
143+
print(f"\nSearch result for Alice: {search_result}")
144+
145+
# List all users
146+
users = mos_product.list_users()
147+
print(f"\nAll registered users: {users}")
148+
149+
# Get user info
150+
alice_info = mos_product.get_user_info("alice")
151+
print(f"\nAlice's info: {alice_info}")
152+
153+
154+
if __name__ == "__main__":
155+
main()
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
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("\n2. 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("\n3. 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("\n4. 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("\n5. 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("\n6. 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("\n7. 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("\n8. 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

Comments
 (0)