diff --git a/memory_chain/__init__.py b/memory_chain/__init__.py new file mode 100644 index 000000000..cec04e6bb --- /dev/null +++ b/memory_chain/__init__.py @@ -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 * diff --git a/memory_chain/episodic_memory.py b/memory_chain/episodic_memory.py new file mode 100644 index 000000000..6aaba6f7d --- /dev/null +++ b/memory_chain/episodic_memory.py @@ -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() + + + diff --git a/memory_chain/memory.py b/memory_chain/memory.py new file mode 100644 index 000000000..6b6cffa58 --- /dev/null +++ b/memory_chain/memory.py @@ -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 diff --git a/memory_chain/memory_manager.py b/memory_chain/memory_manager.py new file mode 100644 index 000000000..d275ac975 --- /dev/null +++ b/memory_chain/memory_manager.py @@ -0,0 +1,1057 @@ +#!/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 .working_memory import Working_Memory +from .prompts import * +import random +import time +import re +from nltk.corpus import stopwords +# import nltk +# nltk.download('stopwords') +from nltk.stem import PorterStemmer +import torch +from sentence_transformers import SentenceTransformer +import string +from collections import defaultdict +import math +import torch +import torch.cuda as cuda +import concurrent.futures +import math +import string +from typing import Tuple, Dict, Any, List +from concurrent.futures import ThreadPoolExecutor +from concurrent.futures import ProcessPoolExecutor + +class MemoryManager: + def __init__(self,memory_index,memory_system,user_name,agent_name,llm_model,llm_client,cmd_args,args,embedding_model,memory_dir): + + self.memory_system = memory_system + self.user_name = user_name + self.agent_name = agent_name + self.llm_model = llm_model + self.llm_client = llm_client + self.cmd_args = cmd_args + self.args = args + self.idx = memory_index + self.client = llm_client + self.embedding_model = embedding_model + + print("The No."+str(self.idx)+" sample "+user_name+" and "+ agent_name+ "'s memory manager has been established") + + async def receive_message(self,message,index,client,timestamp,user_speak): + + understanding = "" + + while len(understanding)==0: + try: + response = await self.llm_client.chat.completions.create(model=self.llm_model,messages=[{"role": "user", "content": UNDERSTAND_USER_EXPERIENCE_PROMPT.format(message=message)}]) + + understanding= json.loads(response.choices[0].message.content) + if len(understanding["tags"]["topic"])!=len(understanding["tags"]["attitude"]) or len(understanding["tags"]["attitude"])!=len(understanding["tags"]["facts"]): + understanding_with_index = "["+str(index)+"]: "+ understanding["summary"] + topics = understanding["tags"]["topic"][0] + emotions = understanding["tags"]["attitude"][0] + reason = understanding["tags"]["reason"][0] + fact = understanding["tags"]["facts"][0] + attributes = understanding["tags"]["attributes"] + understanding == "" + else: + understanding_with_index = "["+str(index)+"]: "+ understanding["summary"] + topics = understanding["tags"]["topic"][0] + emotions = understanding["tags"]["attitude"][0] + reason = understanding["tags"]["reason"][0] + fact = understanding["tags"]["facts"][0] + attributes = understanding["tags"]["attributes"] + except: + import traceback + traceback.print_exc() + understanding = "" + continue + + + if user_speak: + is_full,all_messages = self.memory_system.user_working_memory.add_message_to_working_memory(raw_message=message,message=understanding_with_index,topics=topics, + emotions=emotions,reason=reason,index=index,timestamp=timestamp,fact=fact,attribute=attributes) + if is_full: + oldest_user_memory_list = self.memory_system.user_working_memory.pop_oldest_working_memory() + await self.update_user_episodic_memory(oldest_user_memory_list) + await self.memory_system.user_episodic_memory.evolve_topic_episodic_memory() + + + else: + is_full,all_messages = self.memory_system.agent_working_memory.add_message_to_working_memory(raw_message=message,message=understanding_with_index,topics=topics,emotions=emotions,reason=reason,index=index,timestamp=timestamp,fact=fact,attribute=attributes) + if is_full: + oldest_agent_memory_list = self.memory_system.agent_working_memory.pop_oldest_working_memory() + await self.update_agent_episodic_memory(oldest_agent_memory_list) + await self.memory_system.agent_episodic_memory.evolve_topic_episodic_memory() + + + + async def understand_dialogue(self,message,index,client): + + understanding = "" + + while len(understanding)==0: + try: + # print("calling GPT") + response = await client.chat.completions.create(model=self.model,messages=[{"role": "user", "content": UNDERSTAND_USER_EXPERIENCE_PROMPT_v4.format(message=message)}]) + understanding= json.loads(response.choices[0].message.content) + # print(understanding) + if len(understanding["tags"]["topic"])!=len(understanding["tags"]["attitude"]): + understanding == "" + except: + import traceback + traceback.print_exc() + continue + + understanding_with_index = "["+str(index)+"]: "+ understanding["summary"] + topics = understanding["tags"]["topic"][0] + emotions = understanding["tags"]["attitude"][0] + reason = understanding["tags"]["reason"][0] + + is_full,all_messages = self.working_memory.add_message_to_working_memory(raw_message=message,message=understanding_with_index,topics=topics,emotions=emotions,reason=reason,index=index) + + + async def update_user_episodic_memory(self,user_message_understandings_list): + + for message_understanding in user_message_understandings_list: + + print("add one message understanding to user episodic memory concernng preference") + current_user_event_episodic_memory = self.memory_system.user_episodic_memory.event_episodic_memory_dict + action,target = await self.wm_to_em_router(message_understanding,current_user_event_episodic_memory,self.client) + fail_times = 0 + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_user_event_episodic_memory: + action,target = await self.wm_to_em_router(message_understanding,current_user_event_episodic_memory,self.client) + fail_times += 1 + if fail_times>=3: + break + if fail_times>=3: + continue + await self.memory_system.user_episodic_memory.evolve_event_episodic_memory(message_understanding=message_understanding,action=action,target=target) + print("Event episodic memory update finish.") + + message_understanding_fact = message_understanding["fact"] + current_user_fact_episodic_memory = self.memory_system.user_episodic_memory.fact_episodic_memory_dict + action,target = await self.wm_to_em_router_fact(message_understanding_fact,current_user_fact_episodic_memory,self.client) + + fail_times = 0 + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_user_fact_episodic_memory: + + action,target = await self.wm_to_em_router_fact(message_understanding_fact,current_user_fact_episodic_memory,self.client) + fail_times += 1 + if fail_times>=3: + break + if fail_times>=3: + continue + await self.memory_system.user_episodic_memory.evolve_fact_episodic_memory(message_understanding=message_understanding,action=action,target=target) + print("Fact episodic memory update finish.") + + message_understanding_attribute_list = message_understanding["attribue"] + + for message_understanding_attribute in message_understanding_attribute_list: + + current_user_attr_episodic_memory = self.memory_system.user_episodic_memory.attribute_episodic_memory_dict + action,target = await self.wm_to_em_router_attr(message_understanding_attribute,list(current_user_attr_episodic_memory.keys()),self.client) + fail_times = 0 + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_user_attr_episodic_memory: + + action,target = await self.wm_to_em_router_attr(message_understanding_attribute,list(current_user_attr_episodic_memory.keys()),self.client) + fail_times += 1 + if fail_times>=3: + break + if fail_times>=3: + continue + await self.memory_system.user_episodic_memory.evolve_attr_episodic_memory(message_attribute=message_understanding_attribute, + message_index = message_understanding["index"],action=action,target=target) + + async def update_agent_episodic_memory(self,agent_message_understandings_list): + + for message_understanding in agent_message_understandings_list: + print("add one message understanding to agent episodic memory") + current_agent_event_episodic_memory = self.memory_system.agent_episodic_memory.event_episodic_memory_dict + action,target = await self.wm_to_em_router(message_understanding,current_agent_event_episodic_memory,self.client) + fail_times = 0 + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_agent_event_episodic_memory: + + action,target = await self.wm_to_em_router(message_understanding,current_agent_event_episodic_memory,self.client) + fail_times += 1 + if fail_times>=3: + break + if fail_times>=3: + continue + await self.memory_system.agent_episodic_memory.evolve_event_episodic_memory(message_understanding=message_understanding,action=action,target=target) + print("Event episodic memory update finish.") + + message_understanding_fact = message_understanding["fact"] + current_agent_fact_episodic_memory = self.memory_system.agent_episodic_memory.fact_episodic_memory_dict + action,target = await self.wm_to_em_router_fact(message_understanding_fact,list(current_agent_fact_episodic_memory.keys()),self.client) + + fail_times = 0 + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_agent_fact_episodic_memory: + + action,target = await self.wm_to_em_router_fact(message_understanding_fact,list(current_agent_fact_episodic_memory.keys()),self.client) + fail_times += 1 + if fail_times>=3: + break + if fail_times>=3: + continue + await self.memory_system.agent_episodic_memory.evolve_fact_episodic_memory(message_understanding=message_understanding,action=action,target=target) + print("Fact episodic memory update finish.") + + message_understanding_attribute_list = message_understanding["attribue"] + for message_understanding_attribute in message_understanding_attribute_list: + current_agent_attr_episodic_memory = self.memory_system.agent_episodic_memory.attribute_episodic_memory_dict + action,target = await self.wm_to_em_router_attr(message_understanding_attribute,list(current_agent_attr_episodic_memory.keys()),self.client) + fail_times = 0 + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_agent_attr_episodic_memory: + + action,target = await self.wm_to_em_router_attr(message_understanding_attribute,list(current_agent_attr_episodic_memory.keys()),self.client) + fail_times += 1 + if fail_times>=3: + break + if fail_times>=3: + continue + await self.memory_system.agent_episodic_memory.evolve_attr_episodic_memory(message_attribute=message_understanding_attribute, + message_index = message_understanding["index"],action=action,target=target) + print("Attribute episodic memory update finish.") + + async def update_user_episodic_memory_using_cache_message_understanding(self,user_message_understanding_cache_path): + + print(user_message_understanding_cache_path) + with open(user_message_understanding_cache_path, 'r', encoding='utf-8') as f: + user_message_understandings_list = json.load(f) + for message_understanding in user_message_understandings_list: + print("add one message understanding to episodic memory") + current_user_event_episodic_memory = self.memory_system.user_episodic_memory.event_episodic_memory_dict + action,target = await self.wm_to_em_router(message_understanding,current_user_event_episodic_memory,self.client) + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_user_event_episodic_memory: + action,target = await self.wm_to_em_router(message_understanding,current_user_event_episodic_memory,self.client) + await self.memory_system.user_episodic_memory.evolve_em(message_understanding=message_understanding,action=action,target=target) + + async def update_agent_episodic_memory_using_cache_message_understanding(self,agent_message_understanding_cache_path): + + print(agent_message_understanding_cache_path) + with open(agent_message_understanding_cache_path, 'r', encoding='utf-8') as f: + agent_message_understandings_list = json.load(f) + for message_understanding in agent_message_understandings_list: + print("add one message understanding to episodic memory") + current_agent_event_episodic_memory = self.memory_system.agent_episodic_memory.event_episodic_memory_dict + action,target = await self.wm_to_em_router(message_understanding,current_agent_event_episodic_memory,self.client) + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_agent_event_episodic_memory: + action,target = await self.wm_to_em_router(message_understanding,current_agent_event_episodic_memory,self.client) + await self.memory_system.user_episodic_memory.evolve_em(message_understanding=message_understanding,action=action,target=target) + + def add_message(self,user_id,message): + + pass + + async def _trigger_episodic_memory_update(self,message_understanding,index): + + current_event_episodic_memory = self.episodic_memory.event_episodic_memory_dict + action,target = await self.wm_to_em_router(message_understanding,current_event_episodic_memory,self.client) + + if action.upper()=="UPDATE" or action.upper()=="IGNORE": + while target not in current_event_episodic_memory: + action,target = await self.wm_to_em_router(message_understanding,current_event_episodic_memory,self.client) + + await self.episodic_memory.evolve_em(message_understanding=message_understanding,action=action,target=target) + + def create_messages_for_update_episodic_event_memory_concerning_new_message(self,episodic_event_memory,message): + + return [{"role": "system", "content": Message_ROUTER_SYSTEM_PROMPT}, + {"role": "user", "content": Message_ROUTER_USER_PROMPT.format(Message = message,Profile = episodic_event_memory)}] + + def create_messages_for_update_episodic_fact_memory_concerning_new_message(self,episodic_fact_memory,message): + + return [{"role": "system", "content": Message_Fact_ROUTER_SYSTEM_PROMPT}, + {"role": "user", "content": Message_ROUTER_USER_PROMPT.format(Message = message,Profile = episodic_fact_memory)}] + + def create_messages_for_update_episodic_attr_memory_concerning_new_message(self,episodic_attr_memory,message): + + return [{"role": "system", "content": Message_Attr_ROUTER_SYSTEM_PROMPT}, + {"role": "user", "content": Message_Attr_ROUTER_USER_PROMPT.format(Message = message,Profile = episodic_attr_memory)}] + + async def wm_to_em_router(self,message_with_understanding,episodic_event_memory_profile,client): + + ''' + The task is to determine whether to update, merge, or ignore the new message. + ''' + + router_decision = "" + + while len(router_decision)==0: + try: + response = await client.chat.completions.create(model=self.llm_model,messages=self.create_messages_for_update_episodic_event_memory_concerning_new_message(episodic_event_memory=episodic_event_memory_profile, + message=message_with_understanding)) + router_decision = json.loads(response.choices[0].message.content) + except: + import traceback + traceback.print_exc() + continue + + action = router_decision["Action"] + target = router_decision["Target"] + print("Action: "+action+" happen concerning "+target) + return action,target + + + async def wm_to_em_router_fact(self,message_with_understanding,episodic_fact_memory_profile,client): + + ''' + The task is to determine whether to update, merge, or ignore the new message concerning the facts of the user. + ''' + + router_decision = "" + + while len(router_decision)==0: + try: + response = await client.chat.completions.create(model=self.llm_model,messages=self.create_messages_for_update_episodic_fact_memory_concerning_new_message(episodic_fact_memory=episodic_fact_memory_profile, + message=message_with_understanding)) + router_decision = json.loads(response.choices[0].message.content) + except: + import traceback + traceback.print_exc() + continue + + action = router_decision["Action"] + target = router_decision["Target"] + print("Action: "+action+" happen concerning "+target) + return action,target + + + async def wm_to_em_router_attr(self,message_with_understanding,episodic_attr_memory_profile,client): + + ''' + The task is to determine whether to update, merge, or ignore the new message concerning the attribute of the user. + ''' + + router_decision = "" + + while len(router_decision)==0: + try: + response = await client.chat.completions.create(model=self.llm_model,messages=self.create_messages_for_update_episodic_attr_memory_concerning_new_message(episodic_attr_memory=episodic_attr_memory_profile, + message=message_with_understanding)) + router_decision = json.loads(response.choices[0].message.content) + action = router_decision["Action"] + target = router_decision["Target"] + print("Action: "+action+" happen concerning "+target) + except: + import traceback + traceback.print_exc() + router_decision = "" + continue + + return action,target + + + + async def generate_persona_preference(self): + + self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list) + + + + # def has_word_overlap(self,sentence1, sentence2, ignore_stopwords=True): + + # words1 = re.findall(r'\b\w+\b', sentence1.lower()) + # words2 = re.findall(r'\b\w+\b', sentence2.lower()) + + # stemmer = PorterStemmer() + + + # if ignore_stopwords: + # stop_words = set(stopwords.words('english')) + # words1 = [w for w in words1 if w not in stop_words] + # words2 = [w for w in words2 if w not in stop_words] + # words1 = [stemmer.stem(w) for w in words1] + # words2 = [stemmer.stem(w) for w in words2] + + + # return len(set(words1) & set(words2)) > 0 + + def event_topic_mapping(self,overall_topic_dict_list,event_list,target_topics_list): + + event_topic_mapping_results = {} + + for event in event_list: + for topic_info in overall_topic_dict_list: + if event in topic_info: + if topic_info["group_name"] in target_topics_list: + event_topic_mapping_results[event]=topic_info["group_name"] + break + return event_topic_mapping_results + + + def message_fact_event_mapping(self,target_fact_list,overall_message_understandings,event_message_dict,target_event_list): + + message_event_mapping_results = {} + round_number = None + event_name = None + + for fact in target_fact_list: + + for message in overall_message_understandings: + if message["fact"]==fact: + round_number = message["index"] + break + + for key, value in event_message_dict.items(): + if "The "+str(round_number)+" round" in value: + event_name = key + if event_name in target_event_list: + message_event_mapping_results[fact] = event_name + break + + # message_event_mapping_results[fact] = event_name + return message_event_mapping_results + + + def retrieve_episodic_memory(self,question): + + ''' + Retrieve message from the episodic memory concerning the question + ''' + current_episodic_memory_list = self.episodic_memory.topic_episodic_memory_list + episodic_memory_string_list = [str(current_episodic_memory) for current_episodic_memory in current_episodic_memory_list] + + doc_embeddings = self.embedding_model.encode(episodic_memory_string_list) + query_embedding = self.embedding_model.encode(question) + similarities = np.dot(doc_embeddings, query_embedding.T) + + top_indices = np.argsort(similarities)[-10:][::-1] + related_messages= [episodic_memory_string_list[i] for i in top_indices] + + return related_messages + + # def has_word_overlap(self,sentence1, sentence2, ignore_stopwords=True): + + # words1 = re.findall(r'\b\w+\b', sentence1.lower()) + # words2 = re.findall(r'\b\w+\b', sentence2.lower()) + + # stemmer = PorterStemmer() + + + # if ignore_stopwords: + # stop_words = set(stopwords.words('english')) + # words1 = [w for w in words1 if w not in stop_words] + # words2 = [w for w in words2 if w not in stop_words] + # words1 = [stemmer.stem(w) for w in words1] + # words2 = [stemmer.stem(w) for w in words2] + + + # return len(set(words1) & set(words2)) > 0 + + + def retrive_from_data(self,texts_being_retrieved,target_text,embedding_model,top_k): + + torch.cuda.empty_cache() + initial_memory = cuda.memory_allocated() + cuda.reset_peak_memory_stats() + + target_embedding = embedding_model.encode([target_text]) + retrieved_embeddings = embedding_model.encode(texts_being_retrieved) + + + target_embedding = torch.nn.functional.normalize(target_embedding, p=2, dim=1) + retrieved_embeddings = torch.nn.functional.normalize(retrieved_embeddings, p=2, dim=1) + similarities = torch.mm(target_embedding, retrieved_embeddings.T)[0] # (1, n_texts) -> (n_texts,) + peak_memory = cuda.max_memory_allocated() + + peak_memory_number = peak_memory / 1024**2 + peak_memory_number_increase = (peak_memory - initial_memory) / 1024**2 + + peak_memory = cuda.max_memory_allocated() + net_peak_memory = peak_memory - initial_memory + + top_scores, top_indices = torch.topk(similarities, k=top_k) + # top_results = [ (texts_being_retrieved[idx], score.item()) for score, idx in zip(top_scores, top_indices)] + top_results = [ texts_being_retrieved[idx] for score, idx in zip(top_scores, top_indices)] + return top_results, top_scores,peak_memory_number,peak_memory_number_increase + + + + def link_fact_to_cache_message_number(self,episodic_memory,fact): + + all_fact_related_round_info = episodic_memory.fact_episodic_memory_dict[fact] + round_numbers = re.findall(r"The (\d+) round fact:", all_fact_related_round_info) + return round_numbers + + + + def locate_fact_context_details(self,episodic_memory,round_number_list): + + results = [] + for round_number in round_number_list: + for message in episodic_memory.episodic_memory_cache_list: + if str(message["index"])==str(round_number): + results.append([message["raw_message"],message["timestamp"]]) + + return results + + def locate_cache_episodic_message(self,episodic_memory,round_number_list): + + results = [] + for round_number in round_number_list: + for message in episodic_memory.episodic_memory_cache_list: + if str(message["index"])==str(round_number): + results.append(message["timestamp"]) + return results + + def locate_cache_episodic_message_fact_raw_message_timestamp(self,episodic_memory,round_number_list): + + results = [] + for round_number in round_number_list: + for message in episodic_memory.episodic_memory_cache_list: + if str(message["index"])==str(round_number): + results.append([message["fact"],message["raw_message"],message["timestamp"]]) + return results + + + + def activate_fact_memory_match(self,fact_scores,drop_threshold): + + ''' + 修复断层点前的记忆集群 + ''' + + # 处理空列表的情况 + if not fact_scores or len(fact_scores) == 0: + return None + + # 计算标准化下降比例(相对于最大值) + max_score = max(fact_scores) + if max_score == 0: + return None + + breaks = [] + drop_threshold = drop_threshold # 10%阈值 + + for i in range(1, len(fact_scores)): + drop = (fact_scores[i-1] - fact_scores[i]) / max_score + if drop > drop_threshold: + return i + + return None + + + @staticmethod + def retrive_from_data(texts_being_retrieved,target_text,embedding_model,top_k): + + # torch.cuda.empty_cache() + # cuda.reset_peak_memory_stats() # 重置峰值统计 + torch.cuda.empty_cache() # 清空缓存,确保测量准确 + initial_memory = cuda.memory_allocated() # 获取初始显存占用(基准线) + cuda.reset_peak_memory_stats() # 重置峰值统计 + + target_embedding = embedding_model.encode([target_text]) + retrieved_embeddings = embedding_model.encode(texts_being_retrieved) + + # GPU-optimized cosine similarity (避免数据转移到CPU) + target_embedding = torch.nn.functional.normalize(target_embedding, p=2, dim=1) + retrieved_embeddings = torch.nn.functional.normalize(retrieved_embeddings, p=2, dim=1) + similarities = torch.mm(target_embedding, retrieved_embeddings.T)[0] # (1, n_texts) -> (n_texts,) + peak_memory = cuda.max_memory_allocated() # 返回字节数 + # 获取Top-K结果(全程GPU) + # top_scores, top_indices = torch.topk(similarities, k=top_k) + # # 立即获取峰值显存占用 + # print(f"峰值显存占用: {peak_memory / 1024**2:.2f} MB") + # print(f"峰值净增显存: {(peak_memory - initial_memory) / 1024**2:.2f} MB") + peak_memory_number = peak_memory / 1024**2 + peak_memory_number_increase = (peak_memory - initial_memory) / 1024**2 + # top_scores, top_indices = torch.topk(similarities, k=top_k) + # 立即获取峰值显存占用 + peak_memory = cuda.max_memory_allocated() # 返回字节数 + net_peak_memory = peak_memory - initial_memory # 计算净增峰值 + print(f"峰值显存占用: {peak_memory / 1024**2:.2f} MB") + print(f"峰值净增显存: {net_peak_memory / 1024**2:.2f} MB") # 这是最关键的指标! + # print(f"峰值显存占用: {peak_memory / 1024**2:.2f} MB") + top_scores, top_indices = torch.topk(similarities, k=top_k) + # top_results = [ (texts_being_retrieved[idx], score.item()) for score, idx in zip(top_scores, top_indices)] + top_results = [ texts_being_retrieved[idx] for score, idx in zip(top_scores, top_indices)] + return top_results, top_scores,peak_memory_number,peak_memory_number_increase + + + + + + def retrive_from_data_attr_fact(self, texts_list_1, texts_list_2, target_text, embedding_model, top_k): + + """ + 同时处理两个文本列表的检索,使用批量编码 + """ + + torch.cuda.empty_cache() + initial_memory = torch.cuda.memory_allocated() if torch.cuda.is_available() else 0 + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + + # 编码目标文本(单独编码,因为需要特殊处理) + target_embedding = embedding_model.encode([target_text]) + target_embedding = torch.tensor(target_embedding) + + # 批量编码:将两个列表合并进行一次编码 + all_texts = texts_list_1 + texts_list_2 # 这会创建一个新列表,包含两个列表的所有元素 + all_embeddings = embedding_model.encode(all_texts, batch_size=32) + all_embeddings = torch.tensor(all_embeddings) + + # 正确分割嵌入结果 + n1 = len(texts_list_1) + n2 = len(texts_list_2) + + # 分割点:第一个列表的结束位置 + retrieved_embeddings_1 = all_embeddings[:n1] # 前n1个是第一个列表 + retrieved_embeddings_2 = all_embeddings[n1:n1 + n2] # 接下来的n2个是第二个列表 + + # 验证分割是否正确 + assert len(retrieved_embeddings_1) == n1, f"分割错误: expected {n1}, got {len(retrieved_embeddings_1)}" + assert len(retrieved_embeddings_2) == n2, f"分割错误: expected {n2}, got {len(retrieved_embeddings_2)}" + + # 归一化 + target_embedding = torch.nn.functional.normalize(target_embedding, p=2, dim=1) + retrieved_embeddings_1 = torch.nn.functional.normalize(retrieved_embeddings_1, p=2, dim=1) + retrieved_embeddings_2 = torch.nn.functional.normalize(retrieved_embeddings_2, p=2, dim=1) + + # 合并的矩阵乘法 + all_retrieved_embeddings = torch.cat([retrieved_embeddings_1, retrieved_embeddings_2], dim=0) + all_similarities = torch.mm(target_embedding, all_retrieved_embeddings.T)[0] + + # 分割相似度结果 + similarities_1 = all_similarities[:n1] + similarities_2 = all_similarities[n1:n1 + n2] + + # 获取峰值内存 + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated() + peak_memory_number = peak_memory / 1024**2 + peak_memory_number_increase = (peak_memory - initial_memory) / 1024**2 + else: + peak_memory_number = 0 + peak_memory_number_increase = 0 + + # 获取Top-K结果 + top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k, len(similarities_1))) + top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k, len(similarities_2))) + + top_results_1 = [texts_list_1[idx] for idx in top_indices_1] + top_results_2 = [texts_list_2[idx] for idx in top_indices_2] + + return ( + top_results_1, top_scores_1.tolist(), + top_results_2, top_scores_2.tolist(), + peak_memory_number, peak_memory_number_increase) + + + def retrive_from_data_attr_fact_topic(self, texts_list_1, texts_list_2, texts_list_3, target_text, embedding_model, top_k): + + torch.cuda.empty_cache() + initial_memory = torch.cuda.memory_allocated() if torch.cuda.is_available() else 0 + if torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + + # 编码目标文本 + target_embedding = embedding_model.encode([target_text]) + target_embedding = torch.tensor(target_embedding) + + # 批量编码:将三个列表合并进行一次编码 + all_texts = texts_list_1 + texts_list_2 + texts_list_3 + all_embeddings = embedding_model.encode(all_texts,batch_size=64) + all_embeddings = torch.tensor(all_embeddings) + + # 正确分割嵌入结果 + n1 = len(texts_list_1) + n2 = len(texts_list_2) + n3 = len(texts_list_3) + + # 分割点 + retrieved_embeddings_1 = all_embeddings[:n1] # 前n1个是第一个列表 + retrieved_embeddings_2 = all_embeddings[n1:n1 + n2] # 接下来的n2个是第二个列表 + retrieved_embeddings_3 = all_embeddings[n1 + n2:n1 + n2 + n3] # 最后的n3个是第三个列表 + + # 验证分割是否正确 + assert len(retrieved_embeddings_1) == n1, f"分割错误: expected {n1}, got {len(retrieved_embeddings_1)}" + assert len(retrieved_embeddings_2) == n2, f"分割错误: expected {n2}, got {len(retrieved_embeddings_2)}" + assert len(retrieved_embeddings_3) == n3, f"分割错误: expected {n3}, got {len(retrieved_embeddings_3)}" + + # 归一化 + target_embedding = torch.nn.functional.normalize(target_embedding, p=2, dim=1) + retrieved_embeddings_1 = torch.nn.functional.normalize(retrieved_embeddings_1, p=2, dim=1) + retrieved_embeddings_2 = torch.nn.functional.normalize(retrieved_embeddings_2, p=2, dim=1) + retrieved_embeddings_3 = torch.nn.functional.normalize(retrieved_embeddings_3, p=2, dim=1) + + # 合并的矩阵乘法 + all_retrieved_embeddings = torch.cat([ + retrieved_embeddings_1, + retrieved_embeddings_2, + retrieved_embeddings_3 + ], dim=0) + + all_similarities = torch.mm(target_embedding, all_retrieved_embeddings.T)[0] + + # 分割相似度结果 + similarities_1 = all_similarities[:n1] + similarities_2 = all_similarities[n1:n1 + n2] + similarities_3 = all_similarities[n1 + n2:n1 + n2 + n3] + + # 获取峰值内存 + if torch.cuda.is_available(): + peak_memory = torch.cuda.max_memory_allocated() + peak_memory_number = peak_memory / 1024**2 + peak_memory_number_increase = (peak_memory - initial_memory) / 1024**2 + else: + peak_memory_number = 0 + peak_memory_number_increase = 0 + + # # 获取Top-K结果 + # 49.48 1656 + # top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k+8, len(similarities_1))) + # top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k+8, len(similarities_2))) + # top_scores_3, top_indices_3 = torch.topk(similarities_3, k=min(top_k-3, len(similarities_3))) + + # 获取Top-K结果 50.33 1593 + # top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k, len(similarities_1))) + # top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k+12, len(similarities_2))) + # top_scores_3, top_indices_3 = torch.topk(similarities_3, k=min(top_k-5, len(similarities_3))) + + # 51.57 + # top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k-7, len(similarities_1))) + # top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k-2, len(similarities_2))) + # top_scores_3, top_indices_3 = torch.topk(similarities_3, k=min(top_k+7, len(similarities_3))) + + # 51.43 + # top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k-7, len(similarities_1))) + # top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k-3, len(similarities_2))) + # top_scores_3, top_indices_3 = torch.topk(similarities_3, k=min(top_k+8, len(similarities_3))) + + # 51.56 1615 + # top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k-8, len(similarities_1))) + # top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k-2, len(similarities_2))) + # top_scores_3, top_indices_3 = torch.topk(similarities_3, k=min(top_k+9, len(similarities_3))) + + top_scores_1, top_indices_1 = torch.topk(similarities_1, k=min(top_k-9, len(similarities_1))) + top_scores_2, top_indices_2 = torch.topk(similarities_2, k=min(top_k-1, len(similarities_2))) + top_scores_3, top_indices_3 = torch.topk(similarities_3, k=min(top_k+8, len(similarities_3))) + + + + + top_results_1 = [texts_list_1[idx] for idx in top_indices_1] + top_results_2 = [texts_list_2[idx] for idx in top_indices_2] + top_results_3 = [texts_list_3[idx] for idx in top_indices_3] + + return ( + top_results_1, top_scores_1.tolist(), + top_results_2, top_scores_2.tolist(), + top_results_3, top_scores_3.tolist(), + peak_memory_number, peak_memory_number_increase + ) + + + + + + + def retrieve_from_memory_soft_segmentation(self,question,topn,drop_threshold): + + ''' + 启发式记忆检索 We need to retrieve from memory heuristically. + ''' + + print("version v5 retrieval") + + if self.user_name in question: + user_name = self.user_name + agent_name = self.agent_name + retrieved_memory_word_details = self.memory_system.user_detail_dict + retrieved_topic_memory_dict = self.memory_system.user_topic_message_dict + retrieved_working_memory = self.memory_system.user_working_memory + retrieved_episodic_memory = self.memory_system.user_episodic_memory + retrieved_persona_memory = self.memory_system.user_persona_memory + else: + user_name = self.agent_name + agent_name = self.user_name + retrieved_memory_word_details = self.memory_system.agent_detail_dict + retrieved_topic_memory_dict = self.memory_system.agent_topic_message_dict + retrieved_working_memory = self.memory_system.agent_working_memory + retrieved_episodic_memory = self.memory_system.agent_episodic_memory + retrieved_persona_memory = self.memory_system.agent_persona_memory + + persona_attributes = [attribute_aspect.replace("self.user_name","") for attribute_group in retrieved_persona_memory.attr_persona for attribute_aspect in list(attribute_group["User Attributes"].keys())] + print("There are "+str(len(persona_attributes)) + " pieces of persona memory attributes for "+retrieved_persona_memory.user_id) + persona_facts = list(retrieved_episodic_memory.fact_episodic_memory_dict.keys()) + print("There are "+str(len(persona_facts) )+ " pieces of persona memory facts for "+retrieved_persona_memory.user_id) + + # retrieved_persona_aspects, aspect_scores,peak_memory_number_1,peak_memory_number_increase_1 = self.retrive_from_data(list(set(persona_attributes)),question,self.embedding_model,int(topn)) + # selected_retrieved_persona_facts,fact_scores,peak_memory_number_2,peak_memory_number_increase_2 = self.retrive_from_data(persona_facts,question,self.embedding_model,topn) + all_context_messages_list = retrieved_episodic_memory.episodic_memory_cache_list + list(retrieved_working_memory.working_memory_queue.queue) + print("There are "+str(len(all_context_messages_list) )+ " pieces of working memory messages for "+retrieved_persona_memory.user_id) + all_context_messages_list = [context_message["topics"] for context_message in all_context_messages_list] + retrieved_persona_aspects, aspect_scores, selected_retrieved_persona_facts,fact_scores, retrieved_context_topics,topic_scores,peak_memory_number_1, peak_memory_number_increase_1 = self.retrive_from_data_attr_fact_topic(persona_attributes,persona_facts,all_context_messages_list,question,self.embedding_model,int(topn)) + # result1, scores1, result2, scores2, result3, scores3, peak_mem, peak_mem_inc = \ + # retrieve_from_three_lists(list1, list2, list3, target_text, model, top_k=5) + print(question) + print(aspect_scores) + print(np.mean(aspect_scores)) + print(fact_scores) + print(np.mean(fact_scores)) + print(topic_scores) + print(np.mean(topic_scores)) + + # # 获取结果 + # retrieved_persona_aspects, aspect_scores, peak_memory_number_1, peak_memory_number_increase_1 = future1.result() + # selected_retrieved_persona_facts, fact_scores, peak_memory_number_2, peak_memory_number_increase_2 = future2.result() + + print(retrieved_persona_aspects) + retrieved_persona_attributes = [retrieved_persona_memory.aspect_attribute_dict[aspect] for aspect in retrieved_persona_aspects] + print(retrieved_persona_attributes) + retrieved_persona_facts = [(fact,self.locate_cache_episodic_message(retrieved_episodic_memory,self.link_fact_to_cache_message_number(retrieved_episodic_memory,fact))) for fact in selected_retrieved_persona_facts] + all_retrieved_persona_facts = [item[0] for item in retrieved_persona_facts] + print("Overall facts: "+str(retrieved_persona_facts)) + + # persona_facts = list(retrieved_episodic_memory.fact_episodic_memory_dict.keys()) + # print("There are "+str(len(persona_facts) )+ " pieces of persona memory facts for "+retrieved_persona_memory.user_id) + # selected_retrieved_persona_facts,fact_scores,peak_memory_number_2,peak_memory_number_increase_2 = self.retrive_from_data(persona_facts,question,self.embedding_model,topn) + # retrieved_persona_facts = [(fact,self.locate_cache_episodic_message(retrieved_episodic_memory,self.link_fact_to_cache_message_number(retrieved_episodic_memory,fact))) for fact in selected_retrieved_persona_facts] + # all_retrieved_persona_facts = [item[0] for item in retrieved_persona_facts] + # print("Overall facts: "+str(retrieved_persona_facts)) + + # Fact Detail Recovery + activated_facts_place = self.activate_fact_memory_match(fact_scores,drop_threshold) + activated_fact_context_messages = [] + flattened_activated_fact_context_messages = [] + flattened_reserved_fact_context_messages = [] + flattened_reserved_fact_index = [] + + if activated_facts_place!=None: + for i in range(activated_facts_place): + activated_fact_context_messages.append(self.locate_fact_context_details(retrieved_episodic_memory,self.link_fact_to_cache_message_number(retrieved_episodic_memory,retrieved_persona_facts[i][0]))) + flattened_activated_fact_context_messages += self.locate_fact_context_details(retrieved_episodic_memory,self.link_fact_to_cache_message_number(retrieved_episodic_memory,retrieved_persona_facts[i][0])) + retrieved_persona_facts = retrieved_persona_facts[len(activated_fact_context_messages):] + else: + activated_facts_place = 0 + activated_fact_context_messages = [] + + for i in range(len(retrieved_persona_facts)): + # activated_fact_context_messages.append(self.locate_fact_context_details(retrieved_episodic_memory,self.link_fact_to_cache_message_number(retrieved_episodic_memory,retrieved_persona_facts[i][0]))) + flattened_reserved_fact_context_messages += self.locate_fact_context_details(retrieved_episodic_memory,self.link_fact_to_cache_message_number(retrieved_episodic_memory,retrieved_persona_facts[i][0])) + # flattened_reserved_fact_context_messages = [message[0] for message in flattened_reserved_fact_context_messages] + flattened_reserved_fact_index.append(i) + + flattened_reserved_fact_context_messages_only_message_content = [message[0] for message in flattened_reserved_fact_context_messages] + + potential_keyword = None + ignored_details_facts = [] + question_word_list_distribute_dict = {} + question_word_list = list(set(question.translate(str.maketrans('', '', string.punctuation)).split())) + for word in question_word_list: + if word.lower() != user_name.lower(): + question_word_list_distribute_dict[word.lower()] = retrieved_memory_word_details[word.lower()] + print(question_word_list_distribute_dict) + + # all_context_messages_list = retrieved_episodic_memory.episodic_memory_cache_list + list(retrieved_working_memory.working_memory_queue.queue) + # print("There are "+str(len(all_context_messages_list) )+ " pieces of working memory messages for "+retrieved_persona_memory.user_id) + # all_context_messages_list = [context_message["topics"] for context_message in all_context_messages_list] + # retrieved_context_topics,topic_socres,peak_memory_number_3,peak_memory_number_increase_3 = self.retrive_from_data(all_context_messages_list,question,self.embedding_model,topn-len(activated_fact_context_messages)) + + retrieved_context_messages = [retrieved_topic_memory_dict[retrieved_context_topic] for retrieved_context_topic in retrieved_context_topics] + original_context_messages = retrieved_context_messages + raw_original_fact_message = [message[0] for message in [retrieved_topic_memory_dict[retrieved_context_topic] for retrieved_context_topic in retrieved_context_topics]] + + for message in flattened_activated_fact_context_messages : + if message[0] not in raw_original_fact_message: + retrieved_context_messages = [[message[0],message[1]]] + retrieved_context_messages + + retrieval_context_raw_messages = [message[0] for message in retrieved_context_messages] + print(retrieval_context_raw_messages) + TF_IDF_record_dict = {} + + for word in question_word_list_distribute_dict.keys(): + if len(question_word_list_distribute_dict[word])>0: + TF_IDF_record_dict[word]= 1*math.log(1/(len(question_word_list_distribute_dict[word])+1)) + + keyword_message=[] + + if len(TF_IDF_record_dict.keys())>0: + potential_keyword = sorted(TF_IDF_record_dict.items(), key=lambda x: x[1], reverse=True)[0][0] + potential_docs = question_word_list_distribute_dict[potential_keyword] + detail_results = self.locate_cache_episodic_message_fact_raw_message_timestamp(retrieved_episodic_memory,potential_docs) + for detail_result in detail_results: + if detail_result[1] not in set(retrieval_context_raw_messages): + retrieved_context_messages.append([detail_result[1],detail_result[2]]) + keyword_message.append((detail_result[1],detail_result[2])) + + retrieved_context_messages_only_message_content = [message[0] for message in retrieved_context_messages] + + # print(len(retrieved_persona_facts)) + # print(len(flattened_reserved_fact_context_messages_only_message_content)) + + for i in range(len(flattened_reserved_fact_context_messages_only_message_content)): + if flattened_reserved_fact_context_messages_only_message_content[i] in retrieved_context_messages_only_message_content: + try: + print(flattened_reserved_fact_context_messages_only_message_content[i],retrieved_context_messages_only_message_content) + print("index") + print(i) + retrieved_persona_facts[i]=[] + except: + continue + + # max_memory = max(peak_memory_number_1,peak_memory_number_2,peak_memory_number_3) + # max_increase_memory = max(peak_memory_number_increase_1,peak_memory_number_increase_2,peak_memory_number_increase_3) + + max_memory = max(peak_memory_number_1,peak_memory_number_1) + max_increase_memory = max(peak_memory_number_increase_1,peak_memory_number_increase_1) + # retrieved_persona_attributes = None + # retrieved_persona_facts = None + + return {"keyword message":keyword_message,"keyword distribution dict":question_word_list_distribute_dict,"ignored_details_keywords":potential_keyword ,"ignored_facts":ignored_details_facts,"persona attributes":retrieved_persona_attributes,"persona facts":retrieved_persona_facts,"fact scores":fact_scores,"retrieved context messages":retrieved_context_messages, "recover facts num":len(activated_fact_context_messages),"original context message":original_context_messages},user_name, agent_name,max_memory,max_increase_memory + + + def _prepare_persona_attributes(self, retrieved_persona_memory): + """准备persona attributes数据""" + return [attribute_aspect.replace("self.user_name", "") + for attribute_group in retrieved_persona_memory.attr_persona + for attribute_aspect in list(attribute_group["User Attributes"].keys())] + + def _prepare_persona_facts(self, retrieved_episodic_memory): + """准备persona facts数据""" + return list(retrieved_episodic_memory.fact_episodic_memory_dict.keys()) + + def _prepare_context_data(self, question, user_name, retrieved_memory_word_details, + retrieved_episodic_memory, retrieved_working_memory): + """准备context数据和TF-IDF数据""" + # 处理question words + question_word_list = list(set(question.translate(str.maketrans('', '', string.punctuation)).split())) + question_word_list_distribute_dict = {} + + for word in question_word_list: + if word.lower() != user_name.lower(): + question_word_list_distribute_dict[word.lower()] = retrieved_memory_word_details[word.lower()] + + # 准备context messages + all_context_messages_list = (retrieved_episodic_memory.episodic_memory_cache_list + + list(retrieved_working_memory.working_memory_queue.queue)) + all_context_messages_list = [context_message["topics"] for context_message in all_context_messages_list] + + return { + "question_word_list_distribute_dict": question_word_list_distribute_dict, + "all_context_messages_list": all_context_messages_list + } + + def _process_single_fact(self, retrieved_episodic_memory, fact): + """处理单个fact的定位""" + cache_message = self.locate_cache_episodic_message( + retrieved_episodic_memory, + self.link_fact_to_cache_message_number(retrieved_episodic_memory, fact) + ) + return (fact, cache_message) + + def _process_activated_fact(self, retrieved_episodic_memory, fact): + """处理activated fact的上下文""" + activated_context = self.locate_fact_context_details( + retrieved_episodic_memory, + self.link_fact_to_cache_message_number(retrieved_episodic_memory, fact) + ) + flattened_context = self.locate_fact_context_details( + retrieved_episodic_memory, + self.link_fact_to_cache_message_number(retrieved_episodic_memory, fact) + ) + return activated_context, flattened_context + + + + + async def generate_system_response(self,query,restrieval_result,client,speaker_a,speaker_b,llm_model): + + retrieval_attributes = f"【Persona Attributes】 \n" + str(restrieval_result["persona attributes"]) + # retrieval_facts = f"【Persona Facts】 \n" + str(restrieval_result["persona facts"]) + str(restrieval_result["working memory facts"]) + retrieval_facts = f"【Persona Facts】 \n" + str(restrieval_result["persona facts"]) + retrieval_context_messages = restrieval_result["retrieved context messages"] + retrieval_preferences = "" # We will add this section later. + + system_prompt = ( + f"You are role-playing as {speaker_b} in a conversation with the user is playing is {speaker_a}. " + f"Your task is to answer questions about {speaker_a} or {speaker_b} in an extremely concise manner base on the provided information context concenring {speaker_a}.\n" + f"Any content referring to 'User' in the context refers to {speaker_a}'s content." + f"The provided information include:\n" + f"i). The fact of {speaker_a} and the timestamp when the {speaker_a} share the fact to you. You need to infer the timing of the fact happening from the fact message and timestamps.\n" + f"ii). The attributes of {speaker_a}\n" + f"iii). The context messages from {speaker_a} as well as the timestamp when the {speaker_a} send the message to you.\n" + f"For example, when the fact is (\"I play basktetball last year.\", 8 May, 2023). You need to infer that the user play basketball play basketball in the pervisous year of 2023, which is 2022." + f"When the question is: \"What did the charity race raise awareness for?\", you should not answer in the form of: \"The charity race raised awareness for mental health.\" Instead, it should be: \"mental health\", as this is more concise." + f"Remember, you must try your best to deduce clear answers from facts and attributes rather than give vague answers." + ) + + user_prompt = ( + f"\n" + f"\n" + f"Attributes concerning {speaker_a}\n" + f"{retrieval_attributes}\n" + f"\n" + f"{retrieval_context_messages}\n" + f"\n" + f"Facts of {speaker_a}:\n" + f"{retrieval_facts}\n" + f"the question is: {query}\n" + f"Your task is to answer questions about {speaker_a} or {speaker_b} in an extremely concise manner.\n" + f"Please only provide the content of the answer, without including 'answer:'\n" + f"For questions that require answering a date or time, strictly follow the format \"15 July 2023\" and provide a specific date whenever possible. For example, if you need to answer \"last year,\" give the specific year of last year rather than just saying \"last year.\" Only provide one year, date, or time, without any extra responses.\n" + f"If the question is about the duration, answer in the form of several years, months, or days.\n" + f"Generate answers primarily composed of concrete entities, such as Mentoring program, school speech, etc" + ) + + messages = [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_prompt}] + + + response = "" + while (response==""): + try: + response = await client.chat.completions.create(model=llm_model, messages=messages, temperature=0.7, max_tokens=2000) + answer = response.choices[0].message.content + token_consumption = response + except: + continue + + return answer,response.usage.total_tokens + # return response + + + + + + + + + + + + + + diff --git a/memory_chain/persona_memory.py b/memory_chain/persona_memory.py new file mode 100644 index 000000000..df546dbd1 --- /dev/null +++ b/memory_chain/persona_memory.py @@ -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() + + + + + + + + + + + + + + + + + + + + + diff --git a/memory_chain/prompts.py b/memory_chain/prompts.py new file mode 100644 index 000000000..ea7a6ba1b --- /dev/null +++ b/memory_chain/prompts.py @@ -0,0 +1,1043 @@ +#!/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. + +''' +This file store all our prompts. +Some of the prompts are updated from memoryOS. +''' + +GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT = ( + "Your task is to choose the best option to answer the message from the user. If you can not fined the event mentioned in the option from the profie, then you could not choose the options." +) + +GENERATE_SYSTEM_RESPONSE_USER_PROMPT = ( + "Your task is to choose the best option to answer the message from the user. If you can not fined the event mentioned in the option from the profie, then you could not choose the options." + "Sometimes a user's attitude toward an event is implicit and you have to infer it." + "Here is the profile history of the user:" + "{background}\n" + "The message of the user is: \n" + "{question} \n" + "Find the most appropriate model response band give your final answer (a), (b), (c), or (d) after the special token ." + "{all_options}" +) + + +GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." +) + + +GENERATE_SYSTEM_RESPONSE_ONLY_WM_USER_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." + "Here is the recent messages from the user:" + "{messages}\n" + "The current message of the user is: \n" + "{question} \n" + "Find the most appropriate model response and give your final answer (a), (b), (c), or (d) after the special token ." + "{all_options}" +) + + +GENERATE_SYSTEM_RESPONSE_ONLY_INIT_PROFILE_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." + "The persona profile of the user is: \n" + "{persona} \n" + "The current message of the user is: \n" + "{question} \n" + "Find the most appropriate model response and give your final answer (a), (b), (c), or (d) after the special token ." + "{all_options}" +) + + + + +REORGANIZE_USER_PROFILE_SYSTEM_PROMPT = """ + +### STRICT MESSAGE-FOCUSED PROFILE RESTRUCTURER ### + +You are a precision profile editor that rewrites profiles to include ONLY information directly relevant to the new message, while maintaining: + +1) Original narrative format +2) Full citation chain +3) Explicit linkage to prior traits + +--- RULES --- +1. INPUT: +[Current Profile] +"Natural description with [X] citations" +[New Message] +"Raw user input" + +2. PROCESSING: +A) Include ONLY if: + - Directly referenced in message + - Contradicted by message + - Required to explain changes ("stopped X" needs original X cited) + +B) Citation Handling: + - Preserve ALL original citations ([1][2]...) + - New updates get [NewX] markers + - Chain changes: "stopped [2]" → "has stopped [2] due to [New1]" + +3. OUTPUT: +- Single paragraph +- Original writing style +- Every fact cited +- No unrelated traits + +### Example Input: +[Current Profile] +"This 30yo teacher from Paris [1] practices yoga daily [2], is vegetarian [3], writes novels [4], hates heat [5]." + +[New Message] +"Stopped yoga after injury. Focusing more on writing now." + +### Example Output: +"This 30yo teacher from Paris [1] has stopped daily yoga [2] due to injury [New1] and is focusing more on novel writing [4]." + +""" + + +REORGANIZE_USER_PROFILE_USER_PROMPT = """ + +Now please generate a edited user persona profile from this new message and user profile.\n + +New message from user: +{New_Message} +Profile: +{Profile} + +Output: + +""" + + +REORGANIZE_USER_PROFILE_Message_SYSTEM_PROMPT = """### STRICT MESSAGE-FOCUSED PROFILE RESTRUCTURER ### + +You are a precision profile editor that rewrites profiles to include ONLY information directly relevant to the new message, while maintaining: + +1) Original narrative format +2) Full citation chain +3) Explicit linkage to prior traits + +--- RULES --- +1. INPUT: +[Current Profile] +"Natural description with [X] citations" +[New Message] +"Raw user input" +[Response Options] +"Options of reponses concerning the question" + +2. PROCESSING: +A) Include ONLY if: + - Directly referenced in message + - Contradicted by message + - Required to explain changes ("stopped X" needs original X cited) + +B) Citation Handling: + - Preserve ALL original citations ([1][2]...) + - New updates get [NewX] markers + - Chain changes: "stopped [2]" → "has stopped [2] due to [New1]" + +3. OUTPUT: +- Single paragraph +- Original writing style +- Every fact cited +- No unrelated traits + +### Example Input: +[Current Profile] +"This 30yo teacher from Paris [1] practices yoga daily [2], is vegetarian [3], writes novels [4], hates heat [5]. The teacher come from GuangZhou, a city in Guangdong Province [6]" + +[New Message and Options] +"Stopped yoga after injury. Focusing more on resting in my hometowm." Options: A. You are good at writing. You can stay at home to practice writing. + +### Example Output: +"This 30yo teacher from Paris [1] has stopped daily yoga [2] due to injury [New1] and is focusing more on novel writing [4] in her hometown GuangZhou [6]." + +""" + + +REORGANIZE_USER_PROFILE_Message_Options_USER_PROMPT = """ + +Now please generate a edited user persona profile from this new message and user profile.\n + +New messages and options : +{New_Message}. Options: {Option} +Profile: +{Profile} + +Output: + +""" + + +GENERATE_USER_PROFILE_SYSTEM_PROMPT = """ + +Task: +Generate a **detailed and nuanced user persona profile** based on the provided dialogue history. The input format is `[Turn Number][Content]`. Your output must be a **continuous, narrative-style paragraph** (no bullet points or sections) with all claims rigorously cited. + +### Key Requirements: + +1. **Structure & Content** + - Cover: Demographics (age/gender/location), Background (career/education), Preferences (interests/habits), and Behavioral Shifts. + - **No emojis or informal markers**. Maintain a professional tone. + - Always refer to the person as 'the user' (not 'they'). Example: 'The user prefers tea [3]', not 'They prefer tea [3]'." + +2. **Citation Rules** + - Every claim must reference specific turns (e.g., "Prefers tea over coffee [3][7]"). + - Flag contradictions explicitly (e.g., "Conflict: Claims to dislike cities [2] but mentions enjoying NYC nightlife [9]"). + +3. **Nuance & Flow** + - Highlight how the characteristics, preferenes, and personalities of the user evolve. + - Use transitional phrases to ensure logical flow (e.g., "While...", "Despite..."). + +### Example Input: +[1][Hi! I’m a 28yo graphic designer from Seattle. Love hiking and coffee.] +[2][Just adopted a golden retriever puppy last week.] +[3][Actually vegan for 2 years, but I cheat sometimes with cheese pizza.] +[4][Ugh, my freelance work is so unstable… miss my old office job’s benefits.] +[5][Weekend plans? Hiking with the pup then gaming (big Zelda fan!).] + +### Example Output: +"This 28-year-old graphic designer from Seattle [1] maintains an active lifestyle centered around hiking and coffee. The user recently adopted a golden retriever puppy [2], which has influenced the user's daily routines. Professionally, the user expressed dissatisfaction with the transition from a stable office job to freelance work, citing concerns about inconsistent income and lost benefits [4]. While the user identify as vegan for ethical reasons (maintained for two years), the user occasionally indulge in cheese pizza, demonstrating flexibility in the user's dietary habits [3]. The user's leisure time balances outdoor activities like hiking with their dog and indoor interests such as gaming, particularly the Zelda franchise [5]. The shift to freelancing appears to be the user's most significant recent life change, with nostalgic references to the user's previous job's stability [4]." + +""" + + +GENERATE_USER_PROFILE_USER_PROMPT = """ + +Now please generate a professional user persona profile from this dialogue history.\n + +Dialogue History: +{DIALOGUE_HISTORY} + +Output: +""" + + + + + + +UNDERSTAND_USER_EXPERIENCE_PROMPT = """ + + Perform topic tagging on this message from user following these rules: + + 1. Generate machine-readable tag + 2. Tag should cover: + + - Only one primary event concerning the user messages. + - The author's attitude towards the event. + - The topic should be the subject of the message which the user held attitude towards. + - The topic and reason behind the attitude, sometimes you need to infer the attitude from the users' words. + - The facts or events infered or revealed from the user's message. + - If the author mention the time of the facts or events, the tag should also include the time inferred from the message (e.g., last day, last week) + - Any attributes of the user revealed by the user's message (e.g., demographic features,biographical information,etc). + + 3. Use this JSON format: + {{ + "text": "original message", + "tags": {{ + "topic": ["event"], + "attitude": ["attitude towards the event": Postive or Negative or Mixed] + "reason" :["The reason concenring the attitude towards the event"] + "facts": ["The facts or events infered from the user's message"] + "attributes": ["The attributes of the user revealed by the user's message"] + }}, + "summary": "One sentence summary of the message" + "rationale": "brief explanation concenring why raising these tags" + }} + + Example Input: "The jazz workshop helped me overcome performance anxiety" + Example Output: + {{ + "text": "Last week's jazz workshop helped me overcome performance anxiety since the tutors are so patients.", + "tags": {{ + "topic": ["music workshop"], + "attitude": ["Positive"], + "reason": ["The tutors can teach the use patiently."], + "facts":["join jazz workshop last week"], + "attributes": ["user worrys about jazz performance"] + }}, + "summary": "Jazz workshop helped the user overcome performance anxiety." + "rationale": "The user's performance anxiety was alleviated with the help of Jazz Workshop. Therefore , he is positive towards Jazz Workshop." + }} + + Example Input: "I stop playing basketball for this semester due to too much stress." + Example Output: + {{ + "text": "The user step away from playing baskerball due to too much stress.", + "tags": {{ + "topic": ["playing basketball"], + "attitude": ["negative"], + "reason": ["Too much stree for playing basketball"], + "facts:["stop playing basketball"], + "attributes": ["user hate stress"] + }}, + "summary": "The user stop playing baskerball due to too much stress." + "rationale": "The user stop playing baskerball due to too much stress. Therefore, the user is negative towards playing basketball." + }} + + Example Input: "I go back to play basketball due to strenghten my body yesterday." + Example Output: + {{ + "text": "The user return to play basketball due to strenghten the body.", + "tags": {{ + "topic": ["playing basketball"], + "attitude": ["Positive"], + "reason": ["Baskterball could help strenghtening the body"], + "facts":["return to play basketball yesterday"], + "attributes": ["User value the body"] + }}, + "summary": "The user go back to play basketball due to strenghten the body." + "rationale": "he user go back to play basketball due to strenghten the body. There, the user is positive towards playing basketball." + }} + + Example Input: "I hate playing basktetball due to its preasure" + Example Output: + {{ + "text": "I hate playing basktetball since I move from my hometowm GuangZhou due to its preasure.", + "tags": {{ + "topic": ["hate playing basketball"], + "attitude": ["negative"], + "reason": ["The user hates playing basktetball for preasure."], + "facts":["hate playing basketball"], + "attributes": ["user hate stress","user's hometown is GuangZhou"] + }}, + "summary": "The user go back to play basketball due to strenghten the body." + "rationale": "The user go back to play basketball due to strenghten the body. There, the user is positive towards playing basketball." + }} + + Now analyze this message: + "{message}" + + """ + + + + + + + +GENERATE_RETRIEVAL_CLUES_SYSTEM_PROMPT = """ + +Generate **third-person responses ideas** based strictly on the provided user profile (with citations) and new message. Responses must directly reference and utilize profile content. + +### Requirements: + +1. **Format Specifications** + - Provide no more than three numbered response ideas + - Use "the user" or profile-specified pronouns + - Indicate the relationships between profile content and the response idea. + - Include relevant profile citations [X] for each response + +2. **Content Rules** + - All responses must be directly derived from profile content + - No extrapolations beyond cited profile information + - All advice or suggestions should be explicitly supported by profile + +3. **Response Content** + (1) Profile-referenced activity mention + (2) Profile-documented characteristic + (3) How are these activities and characteristics related to the responsed to the message. + +### Example Input: +[Profile] +"This 30-year-old teacher from Paris [1] practices yoga daily [2], is vegetarian [3], writes novels [4], and hates heat [5]. Originally from Guangzhou, Guangdong Province [6], +she speaks four languages fluently [7], collects vintage postcards [8], and loves rainy weather [9]. An avid baker of vegan desserts [10] and mountain hiker [11], her favorite book + is The Unbearable Lightness of Being [12], and she dreams of publishing a novel [13]. At 25, she broke her wrist hiking in the Alps [14], and at 18 suffered a concussion in a car accident +that still causes occasional migraines [15]. Her family has endured trauma as well: her mother sustained severe burns in a kitchen fire when she was 10 [16], and her younger brother temporarily +lost mobility after a spinal fracture during a cycling race [17]." + +[New Message] +"I have to Stop yoga after injury. Focusing more on resting in my hometowm. This is really painful." + +### Example Output: +(1): In this profile, the user likes writing novels [4]. This indicates the user could start practicing writing novels during this period of resting time. +(2): In this profile, the user break legs in Alps and brings occasional migraine [9], this indicates the user should pay more attention to sports safety. +(3): In this profile, the user a vegetarian [3], this indicates the user should try to eat more protein to quickly restore the user's body. + + +""" + + + + +GENERATE_RETRIEVAL_QUERY_SYSTEM_PROMPT = """ + +Given a user's latest message and a profile built from the user's previous messages, your task is to generate a group of retrieval query based on the user profile that +retrieves information from the conversation history that helps answer the current message. + +""" + + +GENERATE_RETRIEVAL_CLUES_USER_PROMPT = """ + +Now please generate the retrival clues from this new message and user profile.\n + +New messages: +{Query} +Profile: +{Profile} + +Output: + +""" + + +Profile_Update_SYSTEM_PROMPT = """ + + + + + +""" + + +Profile_Update_USER_PROMPT = """ + +Now please generate the retrival clues from this new message and user profile.\n + +New messages: +{Query} +Profile: +{Profile} + +Output: + +""" + + +Message_ROUTER_SYSTEM_PROMPT = """ +You are a user profile updater that maintains a dictionary of topics and the user's attitudes toward them. For each new message, analyze whether to update the profile and respond in JSON format. + +### Rules: +1. Input: + - Profile: {"topic1": "attitude1", "topic2": "attitude2"...} + - Message: ("topic":"attitude") + +2. Processing: + - Compare topics semantically (e.g., "dogs" ≈ "puppies") + - Compare attitudes semantically (e.g., "dislike" ≈ "hate") + - Choose action: + * [UPDATE] if similar topic exists with different attitude + * [ADD] if topic is new + * [IGNORE] if same topic+attitude exists + - If there is no matched topics, the target should be "None" + +3. Output format (JSON): +{{ + "Action": "[UPDATE|ADD|IGNORE]", + "Target": "matched topic or 'None'" +}} + +### Examples: + +Input 1: +Profile: {"Singing in class": "ashamed","smoking in the public":"fear of being fined"} +Message: ("Performing for peers", "proud") +Output: {"Action": "UPDATE", "Target": "Singing in class",} + +Input 2: +Profile: {"Cats": "love","Dogs":"Love"} +Message: ("Kittens", "adore") +Output: {"Action": "IGNORE", "Target": "Cats"} + +Input 3: +Profile: {"Swimming": "enjoy"} +Message: ("Hiking", "love") +Output: {"Action": "ADD", "Target": "None"} + +""" + + +Message_ROUTER_USER_PROMPT = """ +Now please generate the action and target from this new message and user profile.\n +Profile: +{Profile} +New messages: +{Message} + +Output: + +""" + + + + +Message_Fact_ROUTER_SYSTEM_PROMPT = """ +You are a user profile updater that maintains a dictionary of user's facts. For each new message, analyze whether to update the user facts profile and respond in JSON format. + +### Rules: +1. Input: + - Profile: {"user fact 1","user fact 2", "user fact 3" ... "user fact n"} + - Message: "user fact from new message" + +2. Processing: + - Compare facts semantically (e.g., "supportive" ≈ "assisting") + - Choose action: + * [ADD] if the fact is new + * [IGNORE] if same fact exists + * [UPDATE] if contradictory fact exists + + - If there is no matched facts, the target should be "None" + +3. Output format (JSON): +{{ + "Action": "[UPDATE|ADD|IGNORE]", + "Target": "matched fact or 'None'" +}} + +### Examples: + +Input 1: +Profile: {"The user played basketball with friends.","The user played badminton with friends."} +Message: "The user played basketball." +Output: {"Action": "IGNORE", "Target": "The user played basketball with friends."} + +Input 2: +Profile: {"The user player badminton.","The user player tennis."} +Message: "The user played basketball." +Output: {"Action": "ADD", "Target": "None"} + +Input 3: +Profile: {"The user never ate dim sum."} +Message: "The user ate dim sum in Guangzhou." +Output: {"Action": "UPDATE", "Target": "The user never ate dim sum."} + +""" + + +Message_Fact_ROUTER_USER_PROMPT = """ +Now please generate the action and target from this new message and user fact profile.\n +Profile: +{Profile} +New messages: +{Message} +Output: +""" + + + +Message_Attr_ROUTER_SYSTEM_PROMPT = """ +You are a user profile updater that maintains a dictionary of user attributes. For each new message, analyze whether to update the attributes profile and respond in JSON format. + +### Rules: +1. Input: + - Profile: {"user attribute 1","user attribute 2", "user attribute 3"..."user attribute n"} + - Message: ("user attribute from new message") + +2. Processing: + - Compare attributes semantically (e.g., "Transgender person" ≈ "Non-binary person") + - Choose action: + * [UPDATE] if contradictory attribute exists + * [ADD] if the user attribute is new + * [IGNORE] if same user attribute exists + - If there is no matched attributes, the target should be "None" + +3. Output format (JSON): +{{ + "Action": "[UPDATE|ADD|IGNORE]", + "Target": "matched attribute or 'None'" +}} + +### Examples: + +Input 1: +Profile: {"The user is helpful.","The user is from China."} +Message: ("The user is supportive.") +Output: {"Action": "IGNORE", "Target": "The user is helpful."} + + +Input 2: +Profile: {"The user is from China.","The users may have five children."} +Message: ("The user played basketball.") +Output: {"Action": "ADD", "Target": "None"} + +Input 3: +Profile: {"The user is from China.","The users may have five children."} +Message: ("The user's hometown is US.") +Output: {"Action": "UPDATE", "Target": "The user is from China."} + +""" + + +Message_Attr_ROUTER_USER_PROMPT = """ +Now please generate the action and target from this new message and user attribute profile.\n +Profile: +{Profile} +New messages: +{Message} + +Output: + +""" + + + +Profile_Reorganization_SYSTEM_PROMPT = """ + +Your task is to extract profile elements that are directly OR implicitly related to the current message, while: + +1. Preserving original [citation] markers exactly +2. Keeping all attitude phrases unchanged +3. Providing a detailed summary explaining both explicit and implicit connections + +=== INPUT FORMAT === +[Profile] +{ + "topic1": "[1]attitude/behavior", + "topic2": "[2]attitude/behavior", + ... + "topic10+": "[X]attitude/behavior" +} + +[Message] +[user's new message text] + +=== PROCESSING RULES === +1. Relevance Standards: + - DIRECT: Topic/keyword appears in message + - IMPLICIT: + * Helps explain message context + * Provides background for behavioral changes + * Reveals potential contradictions + * Shows related lifestyle patterns + +2. Strict Preservation: + - Original topic names unchanged + - Exact citation markers [X] preserved + - No modification of attitude/behavior phrases + +=== Output format (JSON):=== +{ + "relevant_profile": { + "topicA": "[X]original_attitude", + "topicB": "[Y]original_behavior" + }, + "summary": "Selected [topicA] because [explicit/implicit reason]. Included [topicB] as [contextual reason], even though not directly mentioned." +} + +=== COMPLEX EXAMPLE === +[Profile] +{ + "career_goals": "[1]promotion_focused [12]Health First [13] Stop working in companies", + "work_life": "[2]poor_balance", + "diet": "[3]meal_prepper", + "exercise": "[4]gym_3x_week", + "stress": "[5]chronic_insomnia", + "relationships": "[6]neglected_family", + "finances": "[7]aggressive_saver", + "hobbies": "[8]no_time", + "health": "[9]high_blood_pressure", + "commute": "[10]90_minutes" +} + +[Message] +"Resigned from my job yesterday. Planning to travel while doing freelance work." + +[Output] +{ + "relevant_profile": { + "career_goals": "[1]promotion_focused 12]Health First [13] Stop working", + "work_life": "[2]poor_balance", + "stress": "[5]chronic_insomnia", + "relationships": "[6]neglected_family" + }, + "summary": "Selected career_goals (explains radical career shift), work_life (context for quitting), stress (likely contributing factor), and relationships (opportunity to reconnect during travel). Although not mentioned, these implicitly connect to the decision through accumulated lifestyle pressures." +} + +""" + + +Profile_Reorganization_USER_PROMPT = """ + +Now please extract profile elements that are directly OR implicitly related to the current message from this current message and user profile.\n + +Profile: +{Profile} +New messages: +{Message} + +Output: + +""" + + + +Preference_Merge_System_PROMPT = """ + +Given a group of topics extracted from users' messages, analyze whether these topics can be logically grouped under common themes based on their descriptions. Follow these rules: + +1. Only the topics talking about the exactly same things can be merged. +2. When merging topics, extract as many common details as possible from their reference sentences to create the new merged topic name +3. Maintain the original meaning and context of each topic +4. Only group topics that share significant conceptual overlap +5. Keep distinct topics separate when they represent different concepts +6. Remeber You should not reveal the attitude of the user in the merged topic name. The topic should only be the event. + +=== INPUT FORMAT === +{ + "topic1": "A summary of the sentence which the topic is extracted from", + "topic2": "A summary of the sentence which the topic is extracted from", + ... + "topicN": "A summary of the sentence which the topic is extracted from" +} + +=== OUTPUT FORMAT (JSON) === +{ + "Grouped Topics": { + "NewTopicName1": ["original_topic1", "original_topic2", ...], + "NewTopicName2": ["original_topic3", ...], + ... + }, + "Grouping Rationale": "Explanation of why topics were grouped this way" +} + +=== EXAMPLES === + +Example 1: +Input: +{ + "Singing": "The user was very happy after receiving a reward from the teacher for singing national songs in the classroom", + "Singing in the public": "The user participated in a public singing competition and was very sad that he didn't win any prize", + "Speaking in front of others": "The user is afraid of speaking in front of others" +} + +Output: +{ + "Grouped Topics": { + "Singing performances": ["Singing", "Singing in the public"], + "Public speaking": ["Speaking in front of others"] + }, + "Grouping Rationale": "Grouped singing-related topics together as they both involve performance aspects, while keeping public speaking separate as it's a distinct concept" +} + +Example 2: +Input: +{ + "Give up online shopping": "The user decided to give up online shopping for fear of buying fakes", + "Online shopping": "The user was very excited because of his first successful online shopping" +} + +Output: +{ + "Grouped Topics": { + "Online shopping experiences": ["Online shopping", "Give up online shopping"] + }, + "Grouping Rationale": "Both topics relate to the user's experiences with online shopping, despite having opposite sentiments" +} + + + +""" + + +Preference_Merge_User_PROMPT = """ + +Analyze the following input topics and provide the output in the specified JSON format, including both the grouped topics and your rationale for the grouping: \n + +Input: +{Topic_Groups} + +Output: + + +""" + + +Profile_Generation_System_PROMPT = """ + +Your task is to analyze the user preference from the given json concerning user's attitude towards differnt topics. + +1. DATA OUTPUT REQUIREMENTS + +- Analyze all entries containing ""Overall Attitude" markers +- Include both numbered rounds (e.g., [15]) and "Question round" entries + +2. OUTPUT SPECIFICATIONS +=== USER PREFERENCE PROFILE === + +[POSITIVE PREFERENCES] +• [group_name] + + Specific Activity: [exact phrase from key] (Rounds: [X][Y]) + + Reason: [verbatim from Overall Attitude where available] + +[NEGATIVE PREFERENCES] +• [group_name] + - Specific Activity: [exact phrase from key] (Rounds: [X][Y]) + - Reason: [verbatim from Overall Attitude where available] + +[MIXED PREFERENCES] +• [group_name] + + Positive Instance: [specific scenario] (Round: [X]) + - Negative Instance: [specific scenario] (Round: [Y]) + +3. CITATION RULES +- Always cite the exact round number from the source +- For Question round: mark as [Q] +- For duplicate rounds: show as [15][15] + +4. PROCESSING INSTRUCTIONS + +1. First extract all round attitudes/messages +2. Map each to its Overall Attitude explanation +3. Group by group_name +4. Categorize as Positive/Negative/Mixed +5. Maintain original phrasing from dataset +6.A topic can only be one of POSITIVE PREFERENCES, NEGATIVE PREFERENCES and MIXED PREFERENCES.. + + + + +""" + + +Profile_Generation_User_PROMPT = """ + +Now analyze the following json concerning user's attitude towards difffernt topics of events. \n + +Input: +{User_Preferences_json} + +Output: + +""" + + +Persona_Preference_Generation_System_PROMPT = """ + +Your task is to analyze the user preference from the given json concerning user's attitude towards different topics and output in a specific JSON format. + +1. DATA OUTPUT REQUIREMENTS +- Analyze all entries containing "Overall Attitude" markers +- Include both numbered rounds (e.g., [15]) and "Question round" entries +- Output must be in strict JSON format as specified below + +2. OUTPUT SPECIFICATIONS +{ + "Dislike": { + "Event1":["citation1", "citation2"], + "Event2":["citation3", "citation4"] + }, + "Like": { + "Event3":["citation5", "citation6"], + "Event4":["citation7", "citation8"] + }, + "Mixed Attitude": { + "Event5":{"Like":[citation9, citation10], "Dislike":["citation11","citation12"]} + } +} + +3. OUTPUT RULES +- Each event must use its exact phrase from the original data +- Citations must be in square brackets as shown +- For Question round: mark as "Q" +- For duplicate rounds: show multiple instances (e.g., ["15", "15"]) +- Mixed preferences must include both positive and negative citations +- Maintain original phrasing from dataset +- A topic can only appear in one category (Positive/Negative/Mixed) + +4. PROCESSING INSTRUCTIONS +1. Extract all round attitudes/messages with their citations +2. Map each to its Overall Attitude explanation +3. Categorize as Positive/Negative/Mixed based on attitude +4. For Mixed preferences, include both supporting citations +5. Group events by attitude category +6. Format strictly according to the JSON template +7. Preserve exact wording from source material + +""" + + +Persona_Preference_Generation_User_PROMPT = """ + +Now analyze the following json concerning user's attitude towards difffernt topics of events. \n + +Input: +{User_Preferences_json} + +Output: + +""" + + +GENERATE_SYSTEM_RESPONSE_MEMX_SYSTEM_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." +) + +GENERATE_SYSTEM_RESPONSE_MEMX_USER_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." + "Here is the preference profile of the user:" + "{profile}\n" + "The message of the user is: \n" + "{question} \n" + "Find the most appropriate model response base on the given user profile and give your final answer (a), (b), (c), or (d) after the special token ." + "{all_options}" +) + + +GENERATE_SYSTEM_RESPONSE_EP_RAG_SYSTEM_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." +) + +GENERATE_SYSTEM_RESPONSE_EP_RAG_USER_PROMPT = ( + "Your task is to choose the best option to answer the message from the user." + "Here is the past experience of the user:" + "{experience}\n" + "The message of the user is: \n" + "{question} \n" + "Find the most appropriate model response base on the given user profile and give your final answer (a), (b), (c), or (d) after the special token ." + "{all_options}" +) + + + + +Preference_Generate_System_PROMPT = """ + +Given a group of topics extracted from users' messages as well as users' attitude concerning these topics, infer the user persona preference from these topics. +Output must be in strict JSON format as specified below. + +=== INPUT FORMAT === + +{ + "topic 1": "User's overall attitude concerning the events under topic 1", + "topic 2": "User's overall attitude concerning the events under topic 2", + ... + "topic n": "User's overall attitude concerning the events under topic n", +} + +=== OUTPUT FORMAT (JSON) === + +{ + "User preferences": [user preference 1, user preference 2 ... user preference n] + "Reason": The reason for infering these user preferences from the input information + "User preferences summary":several words to describe user's overall preferences +} + + +Example Output: +{ + "User preferences": ["play basketball","running"] + "Reason": Users like playing basketball and running with friends, which could be inferred from the messages. + "User preferences summary": love basketball and running. +} + +""" + +Preference_Generate_User_PROMPT = """ + +Infer the user preferences from the following topics extracted from users' messages as well as users' coprresonding attitude concerning these topics: \n + +Input: +{Topic_Groups} + +Output: + +""" + + +Attribute_Merge_System_PROMPT = """ + +Given a group of attributes extracted from users' messages, you need to extract the unique attributes from them. +Output must be in strict JSON format as specified below. + + +1. DATA OUTPUT REQUIREMENTS +- Carefully analyze all input attributes. +- Avoid having any similar or duplicate attributes in the output. + +=== INPUT FORMAT === + +["User attribute 1", "User attribute 2", "User attribute 3" ... "User attribute n"] + +=== OUTPUT FORMAT (JSON) === + +{ + "User Attributes": ["unique user attribute 1", "unique user attribute 2" ... "unique user attribute n"] + "Reason": "The reason for infering these user attributes from the input information." +} + +Example : + +Input: + +["The user hates singing in the street","The user does't like singing in the public","The user is afraid of speaking in front of others","The user may be from US"] + +Output: + +{ + "User Attributes": ["The user hates singing in front of others.", "The user is from US."] + "Reason": "The provided attributes show that the user hates singing in front of others and may be from US." +} + + +""" + +Attribute_Merge_System_PROMPT_v2 = """ + +Given a group of attributes extracted from users' messages, you need to extract the unique attributes from them. +Output must be in strict JSON format as specified below. + + +1. DATA OUTPUT REQUIREMENTS + +- Carefully analyze all input attributes. +- Avoid having any similar or duplicate attributes in the output. +- Label each attribute with a category label concerning a certain aspect of the user +- The attribute label must be a noun or Noun phrase representing a certain user attribute dimemsion and cannot overlap with the attribute itself. + +=== INPUT FORMAT === + +["User attribute 1", "User attribute 2", "User attribute 3" ... "User attribute n"] + +=== OUTPUT FORMAT (JSON) === + +{ + "User Attributes": {"attribute 1 aspect label":"unique user attribute 1", "attribute 2 aspect label": "unique user attribute 2" ... "attribute n aspect label":"unique user attribute n"} + "Reason": "The reason for infering these user attributes from the input information." +} + +Example : + +Input: + +["The user hates singing in the street","The user does't like singing in the public","The user is afraid of speaking in front of others","The user may be from US"] + +Output: + +{ + "User Attributes": ["user's singing preference":"The user hates singing in front of others.", "user's hometown":"The user is from US."] + "Reason": "The provided attributes show that the user hates singing in front of others and may be from US." +} + + +""" + + +Attribute_Merge_User_PROMPT = """ + +Infer the unique user attributes from the following attributes extracted from users' messages: \n + +Input: +{User_facts} + +Output: + +""" \ No newline at end of file diff --git a/memory_chain/utils.py b/memory_chain/utils.py new file mode 100644 index 000000000..9b428f26b --- /dev/null +++ b/memory_chain/utils.py @@ -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) + diff --git a/memory_chain/working_memory.py b/memory_chain/working_memory.py new file mode 100644 index 000000000..018e9c158 --- /dev/null +++ b/memory_chain/working_memory.py @@ -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() + + + + + + + + \ No newline at end of file