forked from NevaMind-AI/memU
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_1_conversation_memory.py
More file actions
117 lines (90 loc) · 3.4 KB
/
example_1_conversation_memory.py
File metadata and controls
117 lines (90 loc) · 3.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
Example 1: Multiple Conversations -> Memory Category File
This example demonstrates how to process multiple conversation files
and generate a memory category JSON file.
Usage:
export OPENAI_API_KEY=your_api_key
python examples/example_1_conversation_memory.py
"""
import asyncio
import os
import sys
from memu.app import MemoryService
# Add src to sys.path
src_path = os.path.abspath("src")
sys.path.insert(0, src_path)
async def generate_memory_md(categories, output_dir):
"""Generate concise markdown files for each memory category."""
os.makedirs(output_dir, exist_ok=True)
generated_files = []
for cat in categories:
name = cat.get("name", "unknown")
summary = cat.get("summary", "")
filename = f"{name}.md"
filepath = os.path.join(output_dir, filename)
with open(filepath, "w", encoding="utf-8") as f:
# Title
# Content - concise version
if summary:
cleaned_summary = summary.replace("<content>", "").replace("</content>", "").strip()
f.write(f"{cleaned_summary}\n")
else:
f.write("*No content available*\n")
generated_files.append(filename)
return generated_files
async def main():
"""
Process multiple conversation files and generate memory categories.
This example:
1. Initializes MemoryService with OpenAI API
2. Processes conversation JSON files
3. Extracts memory categories from conversations
4. Outputs the categories to files
"""
print("Example 1: Conversation Memory Processing")
print("-" * 50)
# Get OpenAI API key from environment
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
msg = "Please set OPENAI_API_KEY environment variable"
raise ValueError(msg)
# Initialize service with OpenAI using llm_profiles
# The "default" profile is required and used as the primary LLM configuration
service = MemoryService(
llm_profiles={
"default": {
"api_key": api_key,
"chat_model": "gpt-4o-mini",
},
},
)
# Conversation files to process
conversation_files = [
"examples/resources/conversations/conv1.json",
"examples/resources/conversations/conv2.json",
"examples/resources/conversations/conv3.json",
]
# Process each conversation
print("\nProcessing conversations...")
total_items = 0
categories = []
for conv_file in conversation_files:
if not os.path.exists(conv_file):
continue
try:
result = await service.memorize(resource_url=conv_file, modality="conversation")
total_items += len(result.get("items", []))
# Categories are returned in the result and updated after each memorize call
categories = result.get("categories", [])
except Exception as e:
print(f"Error: {e}")
# Write to output files
output_dir = "examples/output/conversation_example"
os.makedirs(output_dir, exist_ok=True)
# 1. Generate individual Markdown files for each category
await generate_memory_md(categories, output_dir)
print(f"\n✓ Processed {len(conversation_files)} files, extracted {total_items} items")
print(f"✓ Generated {len(categories)} categories")
print(f"✓ Output: {output_dir}/")
if __name__ == "__main__":
asyncio.run(main())