Add files via upload

This commit is contained in:
motongt 2025-12-10 09:15:36 -06:00 committed by GitHub
parent 5fa5d5c42a
commit 256d457e3f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 3333 additions and 0 deletions

20
memory_chain/__init__.py Normal file
View file

@ -0,0 +1,20 @@
#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .memory_manager import *
from .episodic_memory import *
from .working_memory import *
from .persona_memory import *
from .memory import *

View file

@ -0,0 +1,273 @@
#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import numpy as np
from collections import deque
from .utils import *
from .prompts import *
from FlagEmbedding import FlagAutoModel
from sentence_transformers import SentenceTransformer
from itertools import combinations
from collections import defaultdict
import re
from collections import defaultdict
import re
from collections import OrderedDict
import random
import logging
import time
logging.basicConfig(level=logging.WARNING) #
logging.getLogger("FlagEmbedding").setLevel(logging.CRITICAL + 1)
logging.getLogger("FlagEmbedding").propagate = False
class Episodic_Memory:
def __init__(self,event_episodic_memory_path,topic_episodic_memory_path,ep_cache_list_path ,attribute_episodic_memory_path,fact_episodic_memory_path,
user_id,client,llm_model, embedding_model,cmd_args, args):
self.user_id = user_id
self.client = client
self.model = llm_model
self.embedding_model = embedding_model
self.cmd_args = cmd_args
self.args = args
self.episodic_memory_cache_list = [] # Episodic memory cache for storing working memory.
self.event_episodic_memory_dict = {} # Episodic memory dictionary concerning different events (e.g., A note-taking experience)
self.topic_episodic_memory_list = [] # Episodic memory list concerning different event topics (e.g, multiple times of note-taking experience)
self.attribute_episodic_memory_dict = {} # Episodic memory list concerning different attributes of the user
self.fact_episodic_memory_dict = {} #Episodic memory list concerning different facts of the user
self.event_episodic_memory_path = event_episodic_memory_path
self.topic_episodic_memory_path = topic_episodic_memory_path
self.episodic_memory_cache_list_path = ep_cache_list_path
self.attribute_episodic_memory_path = attribute_episodic_memory_path
self.fact_episodic_memory_path = fact_episodic_memory_path
ensure_directory_exists(self.event_episodic_memory_path)
ensure_directory_exists(self.topic_episodic_memory_path)
ensure_directory_exists(self.episodic_memory_cache_list_path)
ensure_directory_exists(self.attribute_episodic_memory_path)
ensure_directory_exists(self.fact_episodic_memory_path)
async def evolve_event_episodic_memory(self,message_understanding,action,target):
self.episodic_memory_cache_list.append(message_understanding)
self._save_wm_cache_episodic_memory()
index = message_understanding["index"]
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
self.event_episodic_memory_dict[target] += "The "+ str(index)+" round message: "+ message_understanding["emotions"]+"; "
if action.upper() == "ADD":
self.event_episodic_memory_dict[message_understanding["topics"]] = "The "+ str(index)+" round attitude: "+ message_understanding["emotions"]+"; "
self._save_event_episodic_memory()
async def evolve_fact_episodic_memory(self,message_understanding,action,target):
index = message_understanding["index"]
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
self.fact_episodic_memory_dict[target] += "The "+ str(index)+" round fact: "+ message_understanding["fact"]+"; "
if action.upper() == "ADD":
self.fact_episodic_memory_dict[message_understanding["fact"]] = "The "+ str(index)+" round fact: "+ message_understanding["fact"]+"; "
self._save_fact_episodic_memory()
async def evolve_attr_episodic_memory(self,message_attribute,action,target,message_index):
index = message_index
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
self.attribute_episodic_memory_dict[target] += "The "+ str(index)+" round attribute: "+ message_attribute +"; "
if action.upper() == "ADD":
self.attribute_episodic_memory_dict[message_attribute] = "The "+ str(index)+" round attribute: "+ message_attribute +"; "
self._save_attr_episodic_memory()
async def evolve_topic_episodic_memory(self):
self.topic_episodic_memory_list = []
event_episodic_memory_dict_keys = list(self.event_episodic_memory_dict.keys())
topic_clusters = self.cluster_related_topics(self.find_top_similar_keys(event_episodic_memory_dict_keys, self.embedding_model))
grouped_em_results = [] # Divide the episodic memory into groups.
for cluster in topic_clusters:
message = {}
for event_name in cluster:
message[event_name] = self.value_find_topic(self.episodic_memory_cache_list,event_name) # How to deal with this part ?
# print(message)
episodic_memory_merge_message = [{"role": "system", "content": Preference_Merge_System_PROMPT},{"role": "user", "content": Preference_Merge_User_PROMPT.format(Topic_Groups=str(message))}]
response = ""
while response == "":
try:
response = await self.client.chat.completions.create(model=self.model, messages = episodic_memory_merge_message, temperature = 0.3)
current_results = json.loads(response.choices[0].message.content)
for group_name in current_results["Grouped Topics"].keys():
current_dict_result = {}
current_dict_result["group_name"] = group_name
for event in current_results["Grouped Topics"][group_name]:
current_dict_result[event] = self.event_episodic_memory_dict[event]
pattern = r"The (\d+) round (?:attitude|message):.*?(Positive|Negative)"
result = {}
for key,value in current_dict_result.items():
matches = re.findall(pattern, str(value))
for round_num, attitude in matches:
result[int(round_num)] = attitude + " "+ self.value_find_index(self.episodic_memory_cache_list,str(round_num)) # 转为整数便于排序
sorted_result = OrderedDict(sorted(result.items()))
current_dict_result["Overall Attitude"]= sorted_result
self.topic_episodic_memory_list.append(current_dict_result)
except Exception as e:
import traceback
traceback.print_exc()
response == ""
print(f"Error generating profile: {str(e)}")
continue
self._save_topic_episodic_memory()
def _save_event_episodic_memory(self):
with open(self.event_episodic_memory_path,'w') as f:
json.dump(self.event_episodic_memory_dict, f, indent=4)
def _save_fact_episodic_memory(self):
with open(self.fact_episodic_memory_path,'w') as f:
json.dump(self.fact_episodic_memory_dict, f, indent=4)
def _save_attr_episodic_memory(self):
with open(self.attribute_episodic_memory_path,'w') as f:
json.dump(self.attribute_episodic_memory_dict, f, indent=4)
def _save_topic_episodic_memory(self):
with open(self.topic_episodic_memory_path,'w') as f:
json.dump(self.topic_episodic_memory_list, f, indent=4)
def _save_wm_cache_episodic_memory(self):
with open(self.episodic_memory_cache_list_path,'w') as f:
json.dump(self.episodic_memory_cache_list, f, indent=4)
def find_top_similar_keys(self,all_keys, embedding_model):
key_embeddings = embedding_model.encode(all_keys)
key_pairs = list(combinations(range(len(all_keys)), 2))
best_matches = {}
for i, j in key_pairs:
key1 = all_keys[i]
key2 = all_keys[j]
sim = float(key_embeddings[i] @ key_embeddings[j].T)
if key1 not in best_matches or sim > best_matches[key1]['similarity']:
best_matches[key1] = {'key1': key1, 'key2': key2, 'similarity': sim}
if key2 not in best_matches or sim > best_matches[key2]['similarity']:
best_matches[key2] = {'key1': key2, 'key2': key1, 'similarity': sim}
results = list(best_matches.values())
results.sort(key=lambda x: x['similarity'], reverse=True)
return results
def cluster_related_topics(self,data):
parent = {}
def find(node):
if parent[node] != node:
parent[node] = find(parent[node])
return parent[node]
def union(node1, node2):
root1 = find(node1)
root2 = find(node2)
if root1 != root2:
parent[root2] = root1
for item in data:
key1, key2 = item['key1'], item['key2']
if key1 not in parent:
parent[key1] = key1
if key2 not in parent:
parent[key2] = key2
for item in data:
key1, key2 = item['key1'], item['key2']
union(key1, key2)
clusters = defaultdict(list)
for node in parent:
clusters[find(node)].append(node)
result = [cluster for cluster in clusters.values() if len(cluster) > 1]
return result
def value_find_topic(self,dict_list,target_value):
for item in dict_list:
if item["topics"] == target_value:
return item["message"]
def value_find_index(self,dict_list,target_value):
for item in dict_list:
if item["index"] == target_value:
return item["message"]
for item in dict_list:
if item["index"] == int(target_value):
return item["message"]
def read_cache(self,topic_episodic_path,event_episodic_path,episodic_cache_path,fact_episodic_path,attr_episodic_path):
print(topic_episodic_path)
print(event_episodic_path)
print(episodic_cache_path)
print(fact_episodic_path)
print(attr_episodic_path)
with open(topic_episodic_path, 'r', encoding='utf-8') as f:
self.topic_episodic_memory_list = json.load(f)
with open(event_episodic_path,'r', encoding='utf-8') as f:
self.event_episodic_memory_dict = json.load(f)
with open(episodic_cache_path,'r', encoding='utf-8') as f:
self.episodic_memory_cache_list = json.load(f)
with open(fact_episodic_path,'r', encoding='utf-8') as f:
self.fact_episodic_memory_dict = json.load(f)
with open(attr_episodic_path,'r', encoding='utf-8') as f:
self.attribute_episodic_memory_dict = json.load(f)
self._save_event_episodic_memory()
self._save_topic_episodic_memory()
self._save_wm_cache_episodic_memory()
self._save_attr_episodic_memory()
self._save_fact_episodic_memory()

596
memory_chain/memory.py Normal file
View file

@ -0,0 +1,596 @@
#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import json
from .utils import *
from .prompts import *
from .memory_manager import *
from .persona_memory import *
from .working_memory import *
from .memory_manager import *
from .episodic_memory import *
from datetime import datetime
import string
from collections import defaultdict
# Heat threshold for triggering profile/knowledge update from mid-term memory
H_PROFILE_UPDATE_THRESHOLD = 5.0
DEFAULT_ASSISTANT_ID = "default_assistant_profile"
def get_current_time():
now = datetime.now()
local_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
return local_time_str
class MemoryChain:
def __init__(self,memory_index,llm_model,llm_client,embedding_model,user_name,agent_name,args,cmd_args,memory_dir):
self.idx = memory_index
self.args = args
self.cmd_args = cmd_args
self.client = llm_client
self.llm_model = llm_model
self.embedding_model = embedding_model
self.user_name = user_name
self.agent_name = agent_name
self.memory_dir = memory_dir
current_time = get_current_time()
self.user_topic_message_dict = {}
self.agent_topic_message_dict = {}
self.user_detail_dict = defaultdict(list)
self.agent_detail_dict = defaultdict(list)
print("The No."+str(self.idx)+" sample "+user_name+" and "+ agent_name+ "'s memory system has been established")
user_working_memory_path = os.path.join(self.memory_dir, "user_working_memory_"+str(self.idx)+".json") # User working memory
agent_working_memory_path = os.path.join(self.memory_dir, "agent_working_memory_"+str(self.idx)+".json") # Agent working memory
user_event_episodic_memory_path = os.path.join(self.memory_dir, "user_event_episodic_memory_"+str(self.idx)+".json")
agent_event_episodic_memory_path = os.path.join(self.memory_dir, "agent_event_episodic_memory_"+str(self.idx)+".json")
user_fact_episodic_memory_path = os.path.join(self.memory_dir, "user_fact_episodic_memory_"+str(self.idx)+".json")
agent_fact_episodic_memory_path = os.path.join(self.memory_dir, "agent_fact_episodic_memory_"+str(self.idx)+".json")
user_attribute_episodic_memory_path = os.path.join(self.memory_dir, "user_attribute_episodic_memory_"+str(self.idx)+".json")
agent_attribute_episodic_memory_path = os.path.join(self.memory_dir, "agent_attribute_episodic_memory_"+str(self.idx)+".json")
user_topic_episodic_memory_path = os.path.join(self.memory_dir, "user_topic_episodic_memory_"+str(self.idx)+".json")
agent_topic_episodic_memory_path = os.path.join(self.memory_dir, "agent_topic_episodic_memory_"+str(self.idx)+".json")
user_episodic_memory_wm_cache_path = os.path.join(self.memory_dir, "user_wm_cache_episodic_memory_"+str(self.idx)+".json")
agent_episodic_memory_wm_cache_path = os.path.join(self.memory_dir, "agent_wm_cache_episodic_memory_"+str(self.idx)+".json")
user_persona_memory_preference_path = os.path.join(self.memory_dir, "user_persona_memory_preference_"+str(self.idx)+".json")
agent_persona_memory_preference_path = os.path.join(self.memory_dir, "agent_persona_memory_preference_"+str(self.idx)+".json")
user_persona_memory_fact_path = os.path.join(self.memory_dir, "user_persona_memory_fact_"+str(self.idx)+".json")
agent_persona_memory_fact_path = os.path.join(self.memory_dir, "agent_persona_memory_fact_"+str(self.idx)+".json")
user_persona_memory_attr_path = os.path.join(self.memory_dir, "user_persona_memory_attr_"+str(self.idx)+".json")
agent_persona_memory_attr_path = os.path.join(self.memory_dir, "agent_persona_memory_attr_"+str(self.idx)+".json")
self.user_memory_detail_path = os.path.join(self.memory_dir, "user_detail_"+str(self.idx)+".json")
self.agent_memory_detail_path = os.path.join(self.memory_dir, "agent_detail_"+str(self.idx)+".json")
ensure_directory_exists(user_working_memory_path)
ensure_directory_exists(agent_working_memory_path)
ensure_directory_exists(user_event_episodic_memory_path)
ensure_directory_exists(agent_event_episodic_memory_path)
ensure_directory_exists(user_topic_episodic_memory_path)
ensure_directory_exists(agent_topic_episodic_memory_path)
ensure_directory_exists(user_episodic_memory_wm_cache_path)
ensure_directory_exists(agent_episodic_memory_wm_cache_path )
ensure_directory_exists(user_persona_memory_preference_path)
ensure_directory_exists(agent_persona_memory_preference_path)
ensure_directory_exists(user_persona_memory_fact_path)
ensure_directory_exists(agent_persona_memory_fact_path)
ensure_directory_exists(user_fact_episodic_memory_path)
ensure_directory_exists(user_attribute_episodic_memory_path)
ensure_directory_exists(agent_fact_episodic_memory_path )
ensure_directory_exists(agent_attribute_episodic_memory_path)
self.user_working_memory = Working_Memory(working_memory_path = user_working_memory_path, user_id = self.user_name, model=self.llm_model,
working_memory_max_size = cmd_args.working_memory_max_size, client=self.client,refresh_rate= cmd_args.episodic_memory_refresh_rate)
self.agent_working_memory = Working_Memory(working_memory_path = agent_working_memory_path, user_id = self.agent_name, model=self.llm_model,
working_memory_max_size = cmd_args.working_memory_max_size, client=self.client,refresh_rate= cmd_args.episodic_memory_refresh_rate)
self.user_episodic_memory = Episodic_Memory(event_episodic_memory_path = user_event_episodic_memory_path, topic_episodic_memory_path = user_topic_episodic_memory_path,
ep_cache_list_path = user_episodic_memory_wm_cache_path, user_id = user_name, client = self.client, llm_model = self.llm_model, embedding_model = self.embedding_model,
fact_episodic_memory_path = user_fact_episodic_memory_path,attribute_episodic_memory_path = user_attribute_episodic_memory_path,cmd_args = self.cmd_args, args = self.args)
self.agent_episodic_memory = Episodic_Memory(event_episodic_memory_path = agent_event_episodic_memory_path, topic_episodic_memory_path = agent_topic_episodic_memory_path,
ep_cache_list_path = agent_episodic_memory_wm_cache_path, user_id = agent_name, client = self.client, llm_model = self.llm_model, embedding_model = self.embedding_model,
fact_episodic_memory_path = agent_fact_episodic_memory_path,attribute_episodic_memory_path = agent_attribute_episodic_memory_path,cmd_args = self.cmd_args, args = self.args)
self.user_persona_memory = Persona_Memory(persona_memory_preference_path = user_persona_memory_preference_path, persona_memory_fact_path = user_persona_memory_fact_path,
user_id = self.user_name, llm_model=self.llm_model, client=self.client,init_persona_information="",embedding_model=self.embedding_model,
persona_memory_attr_path = user_persona_memory_attr_path)
self.agent_persona_memory = Persona_Memory(persona_memory_preference_path = agent_persona_memory_preference_path, persona_memory_fact_path = agent_persona_memory_fact_path,
user_id = self.agent_name, llm_model=self.llm_model, client=self.client,init_persona_information="",embedding_model=self.embedding_model,
persona_memory_attr_path = agent_persona_memory_attr_path)
for message in list(self.user_working_memory.working_memory_queue.queue)+self.user_episodic_memory.episodic_memory_cache_list:
self.user_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
for message in list(self.agent_working_memory.working_memory_queue.queue)+self.agent_episodic_memory.episodic_memory_cache_list:
self.agent_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
def generate_memory_detail_map(self):
stop_words = {
'a', 'an', 'the', 'and', 'or', 'but', 'if', 'because', 'as', 'what',
'which', 'this', 'that', 'these', 'those', 'then', 'just', 'so', 'than',
'such', 'both', 'through', 'about', 'for', 'is', 'of', 'while', 'during',
'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where',
'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same',
'so', 'than', 'too', 'very', 'can', 'will', 'just', 'should', 'now',
'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her',
'us', 'them', 'my', 'your', 'his', 'its', 'our', 'their', 'mine',
'yours', 'hers', 'ours', 'theirs', 'myself', 'yourself', 'himself',
'herself', 'itself', 'ourselves', 'yourselves', 'themselves',self.user_name,self.agent_name}
print("Generating Detail Map")
user_full_memory_list = [(message["index"],message["raw_message"]) for message in list(self.user_working_memory.working_memory_queue.queue) + self.user_episodic_memory.episodic_memory_cache_list]
agent_full_memory_list = [(message["index"],message["raw_message"]) for message in list(self.agent_working_memory.working_memory_queue.queue) + self.agent_episodic_memory.episodic_memory_cache_list]
# round = 0
for index,text in user_full_memory_list:
text = text.translate(str.maketrans('', '', string.punctuation))
word_list = text.split()
for word in word_list:
word = word.lower()
if word not in stop_words:
self.user_detail_dict[word].append(index)
for index,text in agent_full_memory_list:
text = text.translate(str.maketrans('', '', string.punctuation))
word_list = text.split()
for word in word_list:
word = word.lower()
if word not in stop_words:
self.agent_detail_dict[word].append(index)
with open(self.user_memory_detail_path, 'w', encoding='utf-8') as f:
json.dump( self.user_detail_dict, f, ensure_ascii=False, indent=4)
with open(self.agent_memory_detail_path, 'w', encoding='utf-8') as f:
json.dump( self.agent_detail_dict, f, ensure_ascii=False, indent=4)
def find_memory_file(self,directory, pattern):
regex = re.compile(f"{pattern}$")
for filename in os.listdir(directory):
if regex.search(filename):
return os.path.join(directory,filename)
return None
async def read_cache_memory(self, cache_memory_dir):
cache_user_working_memory_pattern = f"user_working_memory_{self.idx}.json"
cache_agent_working_memory_pattern = f"agent_working_memory_{self.idx}.json"
cache_user_topic_episodic_memory_pattern = f"user_topic_episodic_memory_{self.idx}.json"
cache_agent_topic_episodic_memory_pattern = f"agent_topic_episodic_memory_{self.idx}.json"
cache_user_event_episodic_memory_pattern = f"user_event_episodic_memory_{self.idx}.json"
cache_agent_event_episodic_memory_pattern = f"agent_event_episodic_memory_{self.idx}.json"
cache_user_fact_episodic_memory_pattern = f"user_fact_episodic_memory_{self.idx}.json"
cache_agent_fact_episodic_memory_pattern = f"agent_fact_episodic_memory_{self.idx}.json"
cache_user_attr_episodic_memory_pattern = f"user_attribute_episodic_memory_{self.idx}.json"
cache_agent_attr_episodic_memory_pattern = f"agent_attribute_episodic_memory_{self.idx}.json"
cache_user_wm_cache_episodic_memory_pattern = f"user_wm_cache_episodic_memory_{self.idx}.json"
cache_agent_wm_cache_episodic_memory_pattern = f"agent_wm_cache_episodic_memory_{self.idx}.json"
cache_user_preferences_persona_memory_pattern = f"user_persona_memory_preference_{self.idx}.json"
cache_agent_preferences_persona_memory_pattern = f"agent_persona_memory_preference_{self.idx}.json"
cache_user_attributes_persona_memory_pattern = f"user_persona_memory_attr_{self.idx}.json"
cache_agent_attributes_persona_memory_pattern = f"agent_persona_memory_attr_{self.idx}.json"
# fact_episodic_path,attr_episodic_path
self.user_working_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_working_memory_pattern))
self.agent_working_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_working_memory_pattern))
self.user_episodic_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_topic_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,
cache_user_event_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,cache_user_wm_cache_episodic_memory_pattern),
self.find_memory_file(cache_memory_dir,cache_user_fact_episodic_memory_pattern),
self.find_memory_file(cache_memory_dir,cache_user_attr_episodic_memory_pattern))
self.agent_episodic_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_topic_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,
cache_agent_event_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,cache_agent_wm_cache_episodic_memory_pattern),
self.find_memory_file(cache_memory_dir,cache_agent_fact_episodic_memory_pattern),
self.find_memory_file(cache_memory_dir,cache_agent_attr_episodic_memory_pattern))
self.user_persona_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_preferences_persona_memory_pattern),
self.find_memory_file(cache_memory_dir,cache_user_attributes_persona_memory_pattern))
self.agent_persona_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_preferences_persona_memory_pattern),
self.find_memory_file(cache_memory_dir,cache_agent_attributes_persona_memory_pattern))
self.user_topic_message_dict = {}
self.agent_topic_message_dict = {}
for message in list(self.user_working_memory.working_memory_queue.queue)+self.user_episodic_memory.episodic_memory_cache_list:
self.user_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
for message in list(self.agent_working_memory.working_memory_queue.queue)+self.agent_episodic_memory.episodic_memory_cache_list:
self.agent_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
async def receive_user_message(self,message,round_index,client,timestamp):
await self.user_memory_manager.understand_message(message,round_index,client)
async def receive_agent_message(self,message,round_index,client,timestamp):
await self.agent_memory_manager.understand_message(message,round_index,client)
async def receive_user_message_v2(self,previous_query,user_message,round_index,client):
await self.user_memory_manager.understand_message(message,round_index,client)
async def receive_agent_message_v2(self,previous_query, user_message,round_index,client):
await self.agent_memory_manager.understand_message(message,round_index,client)
def get_response_base_on_profile_reorganization(self,query,all_options):
"""
Generates a response to the user's query through reorganizing the latest profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
# raw_reorganized_user_profile_text, original_profile = self.personal_memory.reorganize_profile_base_on_query(query)
raw_reorganized_user_profile_text, original_profile = self.personal_memory.reorganize_profile_base_on_query_and_option(query,all_options)
reorganized_profile = f"【User Profile】\n{raw_reorganized_user_profile_text}"
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT.format(background=reorganized_profile)
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(question= query,all_options=all_options)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
response_content = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=1500 # As in original main
)
self.receive_message(query,self.user_id,"Question",self.client)
return response_content.choices[0].message.content, reorganized_profile, original_profile
def get_response_base_on_profile(self,query,all_options):
"""
Generates a response to the user's query base on the latest profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
raw_user_profile_text = self.personal_memory.get_user_profile_data()
background_context = f"【User Profile】\n{raw_user_profile_text}"
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
background=background_context,
question= query,
all_options=all_options
)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
response_content = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=1500 # As in original main
)
self.receive_message(query,self.user_id,"Question",self.client)
return response_content.choices[0].message.content, background_context
async def get_response_base_on_memx_profile(self,query,all_options):
"""
Generates a response to the user's query base on the latest profile.
"""
persona_profile = self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list)
system_prompt_text = GENERATE_SYSTEM_RESPONSE_MEMX_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_MEMX_USER_PROMPT.format(
profile = persona_profile,
question= query,
all_options=all_options
)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
response_content = await self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=1500 # As in original main
)
return response_content.choices[0].message.content, persona_profile
def get_response_base_on_profile(self,query,all_options):
"""
Generates a response to the user's query base on the profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
# 1. Retrieve context
raw_user_profile_text = self.personal_memory.get_user_profile_data()
background_context = f"【User Profile】\n{raw_user_profile_text}"
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
background=background_context,
question= query,
all_options=all_options
)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
response_content = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=1500 # As in original main
)
self.receive_message(query,self.user_id,"Question",self.client)
return response_content.choices[0].message.content, background_context
def get_response_base_on_profile_v2(self,query,all_options):
"""
Generates a response to the user's query base on the profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
# 1. Retrieve context
self.personal_memory.merge_user_trace_profile_into_user_preference_profile()
raw_user_profile_text = self.personal_memory.get_user_profile_data()
background_context = f"【User Profile】\n{raw_user_profile_text}"
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
background=background_context,
question= query,
all_options=all_options)
messages = [{"role": "user", "content": user_prompt_text}]
# 2. Call LLM for response
# print("Memoryos: Calling LLM for final response generation...")
response_content = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0,
max_tokens=16000
)
# 3. Add this interaction to memory
self.receive_message(query,self.user_id,"Question",self.client)
return response_content.choices[0].message.content, background_context
async def get_response_base_on_recent_message(self,query,all_options,working_memory):
"""
Generates a response to the user's query base on the profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
system_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_USER_PROMPT.format(messages= working_memory,question= query,all_options=all_options)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
# 2. Call LLM for response
# print("Memoryos: Calling LLM for final response generation...")
response_content = await self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0,
max_tokens=16000
)
# 3. Add this interaction to memory
return response_content.choices[0].message.content
async def get_response_base_on_init_persona(self,query,all_options,init_persona):
"""
Generates a response to the user's query base on the profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
system_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_INIT_PROFILE_PROMPT.format(persona= init_persona,question= query,all_options=all_options)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
# 2. Call LLM for response
# print("Memoryos: Calling LLM for final response generation...")
response_content = await self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0,
max_tokens=16000
)
# 3. Add this interaction to memory
return response_content.choices[0].message.content
def get_response_base_on_reorganized_profile(self,query,all_options,reorganzied_profile):
"""
Generates a response to the user's query base on the profile.
"""
print(f"Generating response for query: '{query[:50]}...'")
# 1. Retrieve context
raw_user_profile_text = str(reorganzied_profile)
background_context = f"【User Profile】\n{raw_user_profile_text}"
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
background=background_context,
question= query,
all_options=all_options
)
messages = [
{"role": "system", "content": system_prompt_text},
{"role": "user", "content": user_prompt_text}
]
# 2. Call LLM for response
# print("Memoryos: Calling LLM for final response generation...")
response_content = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=1500 # As in original main
)
# 3. Add this interaction to memory
self.receive_message(query,self.user_id,"Question",self.client)
return response_content.choices[0].message.content, self.personal_memory.get_user_profile_data()
def reorganize_profile_base_on_message(self,message):
"""
Only extract the sections of the profile which are important for current user message as well as provide the reasons behind it.
"""
print(f"Reorganize the profile base on the user message: {message[:50]}...")
profile = self.personal_memory.latest_profile
system_prompt_text = Profile_Reorganization_SYSTEM_PROMPT
user_prompt_text = Profile_Reorganization_USER_PROMPT.format(Message = message,Profile = profile)
messages = [{"role": "system", "content": system_prompt_text},{"role": "user", "content": user_prompt_text}]
reorganized_profile = ""
while(reorganized_profile==""):
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.7,
max_tokens=2000)
reorganized_profile = json.loads(response.choices[0].message.content)
print(reorganized_profile)
return reorganized_profile["relevant_profile"],reorganized_profile["summary"]
async def get_response_base_on_episodic_memory_retrieval(self,query,all_options):
"""
Generates a response to the user's query base on the latest profile.
"""
# persona_profile = self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list)
experience = str(self.memory_manager.retrieve_episodic_memory(query))
system_prompt_text = GENERATE_SYSTEM_RESPONSE_EP_RAG_SYSTEM_PROMPT
user_prompt_text = GENERATE_SYSTEM_RESPONSE_EP_RAG_USER_PROMPT.format(experience = experience,question= query,all_options=all_options)
messages = [{"role": "system", "content": system_prompt_text},{"role": "user", "content": user_prompt_text}]
response_content = await self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.7, max_tokens=1500)
# self.receive_message(query,self.user_id,"Question",self.client)
return response_content.choices[0].message.content, experience

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,224 @@
#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import numpy as np
# import faiss
from collections import deque
from .utils import *
from .prompts import *
from FlagEmbedding import FlagAutoModel
from sentence_transformers import SentenceTransformer
from itertools import combinations
from collections import defaultdict
import json
from collections import defaultdict
class Persona_Memory:
def __init__(self, persona_memory_preference_path, persona_memory_fact_path,persona_memory_attr_path,
user_id,llm_model,client,init_persona_information,embedding_model):
self.user_id = user_id
self.client = client
self.init_persona_information = init_persona_information
self.llm_model = llm_model
self.persona_memory_preference_path = persona_memory_preference_path
self.persona_memory_fact_path = persona_memory_fact_path
self.persona_memory_attr_path = persona_memory_attr_path
self.preference_persona = []
self.fact_persona = []
self.attr_persona = []
self.aspect_attribute_dict = {}
self.embedding_model = embedding_model
async def update_preference_persona(self, episodic_topic_memory_list):
episodic_memory_topic_list = [topic["group_name"] for topic in episodic_topic_memory_list]
topic_attitude_dict = {}
for topic in episodic_topic_memory_list:
topic_attitude_dict[topic["group_name"]] = topic["Overall Attitude"]
topic_clusters = self.cluster_related_topics(self.find_top_similar_keys(episodic_memory_topic_list, self.embedding_model))
persona_preference_results = []
for cluster in topic_clusters:
message = [{topic:topic_attitude_dict[topic]} for topic in cluster]
preference_generate_message = [{"role": "system", "content": Preference_Generate_System_PROMPT},{"role": "user", "content": Preference_Generate_User_PROMPT.format(Topic_Groups=str(message))}]
fact_generate_message = [{"role":"system"}]
response = ""
while response == "":
try:
response = await self.client.chat.completions.create(model=self.llm_model, messages = preference_generate_message, temperature = 0.3)
persona_preference = json.loads(response.choices[0].message.content)
persona_preference_results.append(persona_preference)
except Exception as e:
import traceback
print("Error generating persona profile.")
print(f"Error generating profile: {str(e)}")
continue
self.preference_persona = persona_preference_results
self._save_preference_persona()
async def update_attribute_persona(self, episodic_memory_attr_dict):
memory_attr_list = list(episodic_memory_attr_dict.keys())
attr_clusters = self.cluster_related_topics(self.find_top_similar_keys(memory_attr_list, self.embedding_model))
persona_attr_results = []
for cluster in attr_clusters:
print(str(cluster))
fact_generate_message = [{"role": "system", "content": Attribute_Merge_System_PROMPT_v2},{"role": "user", "content": Attribute_Merge_User_PROMPT.format(User_facts=str(cluster))}]
response = ""
while response == "":
try:
response = await self.client.chat.completions.create(model=self.llm_model, messages = fact_generate_message, temperature = 0.1)
persona_attr = json.loads(response.choices[0].message.content)
persona_attr["original attributes"] = cluster
persona_attr_results.append(persona_attr)
except Exception as e:
import traceback
traceback.print_exc()
response == ""
print(f"Error generating profile: {str(e)}")
continue
self.attr_persona = persona_attr_results
self._save_attr_persona()
def _save_preference_persona(self):
with open(self.persona_memory_preference_path, 'w', encoding='utf-8') as f:
json.dump(self.preference_persona, f, ensure_ascii=False, indent=4)
def _save_fact_persona(self):
with open(self.persona_memory_fact_path, 'w', encoding='utf-8') as f:
json.dump(self.fact_persona_description, f, ensure_ascii=False, indent=4)
def _save_attr_persona(self):
print("Generating aspect-attribute dictionary.")
for attr_group in self.attr_persona:
for key,value in attr_group["User Attributes"].items():
try:
if key in self.aspect_attribute_dict:
current = self.aspect_attribute_dict[key]
self.aspect_attribute_dict[key] = self.aspect_attribute_dict[key] + " " + value
else:
self.aspect_attribute_dict[key] = value
except:
print("Attribute Error")
print(key)
print(self.persona_memory_attr_path)
if key in self.aspect_attribute_dict:
current = self.aspect_attribute_dict[key]
self.aspect_attribute_dict[key] = str(self.aspect_attribute_dict[key]) + " " + str(value)
else:
self.aspect_attribute_dict[key] = value
with open(self.persona_memory_attr_path, 'w', encoding='utf-8') as f:
json.dump(self.attr_persona, f, ensure_ascii=False, indent=4)
def cluster_related_topics(self,data):
parent = {}
def find(node):
if parent[node] != node:
parent[node] = find(parent[node])
return parent[node]
def union(node1, node2):
root1 = find(node1)
root2 = find(node2)
if root1 != root2:
parent[root2] = root1
for item in data:
key1, key2 = item['key1'], item['key2']
if key1 not in parent:
parent[key1] = key1
if key2 not in parent:
parent[key2] = key2
for item in data:
key1, key2 = item['key1'], item['key2']
union(key1, key2)
clusters = defaultdict(list)
for node in parent:
clusters[find(node)].append(node)
result = [cluster for cluster in clusters.values() if len(cluster) > 1]
return result
def find_top_similar_keys(self,all_keys, embedding_model):
key_embeddings = embedding_model.encode(all_keys)
key_pairs = list(combinations(range(len(all_keys)), 2))
best_matches = {}
for i, j in key_pairs:
key1 = all_keys[i]
key2 = all_keys[j]
sim = float(key_embeddings[i] @ key_embeddings[j].T)
if key1 not in best_matches or sim > best_matches[key1]['similarity']:
best_matches[key1] = {'key1': key1, 'key2': key2, 'similarity': sim}
if key2 not in best_matches or sim > best_matches[key2]['similarity']:
best_matches[key2] = {'key1': key2, 'key2': key1, 'similarity': sim}
results = list(best_matches.values())
results.sort(key=lambda x: x['similarity'], reverse=True)
return results
def read_cache(self,preference_memory_path,attr_memory_path):
with open(preference_memory_path,'r', encoding='utf-8') as f:
self.preference_persona = json.load(f)
with open(attr_memory_path,'r', encoding='utf-8') as f:
self.attr_persona = json.load(f)
self._save_preference_persona()
self._save_attr_persona()

1043
memory_chain/prompts.py Normal file

File diff suppressed because it is too large Load diff

21
memory_chain/utils.py Normal file
View file

@ -0,0 +1,21 @@
#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
def ensure_directory_exists(path):
os.makedirs(os.path.dirname(path), exist_ok=True)

View file

@ -0,0 +1,99 @@
#!/usr/bin/env python
# coding=utf-8
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import numpy as np
from collections import deque
from .utils import *
from queue import Queue
import queue
class Working_Memory:
def __init__(self,working_memory_path ,user_id,model,working_memory_max_size,client,refresh_rate):
self.file_path = working_memory_path
self.user_id = user_id
self.model = model
self.working_memory_queue = Queue()
self.working_memory_max_size = working_memory_max_size
self.refresh_rate = refresh_rate
self.client = client
ensure_directory_exists(self.file_path)
def add_message_to_working_memory(self,raw_message,message,topics,emotions,reason,index,timestamp,fact,attribute):
self.working_memory_queue.put({"user_id":self.user_id,"raw_message":raw_message,"message":message,"topics":topics,"emotions":emotions,"reason":reason,"index":index,"timestamp":timestamp,"fact":fact,"attribue":attribute})
if (self.working_memory_queue.qsize() == self.working_memory_max_size):
is_full = True
else:
is_full = False
return is_full, self._save_working_memory()
def pop_oldest_wm(self):
return self.working_memory_queue.get()
def pop_oldest_working_memory(self):
popped_items = []
for _ in range(self.refresh_rate):
try:
item = self.working_memory_queue.get_nowait()
popped_items.append(item)
except queue.Empty:
break
return popped_items
def _save_working_memory(self):
temp_queue = queue.Queue()
temp_list = []
while not self.working_memory_queue.empty():
item = self.working_memory_queue.get()
temp_list.append(item)
temp_queue.put(item)
while not temp_queue.empty():
self.working_memory_queue.put(temp_queue.get())
with open(self.file_path, 'w') as f:
json.dump(temp_list, f, indent=2, sort_keys=True)
message_summary_list = [item["message"] for item in temp_list]
return message_summary_list
def read_cache(self,file_path):
print(file_path)
with open(file_path, 'r', encoding='utf-8') as f:
message_understanding_caches = json.load(f)
for message_understanding in message_understanding_caches:
self.working_memory_queue.put(message_understanding)
self._save_working_memory()