Memory System Design
Memory System Design
Human memory is divided into short-term memory and long-term memory, and the AI Agent's memory system adopts a similar design.
Understanding the difference and use of these two types of memory is the foundation for building intelligent Agents.
Short-term Memory: Agent's Working Memory
Short-term memory is like the Agent's workbench, storing the context and temporary information of the current conversation.
Characteristics:
- Limited capacity: Usually only saves the most recent few conversations (e.g., the last 10-20 turns)
- Fast access: Fast read and write speeds
- Temporary: Usually cleared or compressed after the conversation ends
- Context-related: Directly affects the generation of the current response
Main Uses:
- Maintain conversation coherence
- Store intermediate results of the current task
- Remember user preferences mentioned in the current conversation
Technical Implementation:
Original prompt (Chinese, left untranslated)
class ShortTermMemory:
"""短期记忆实现"""
def __init__(self, max_turns=10):
self.max_turns = max_turns # 最大对话轮数
self.conversation_history = [] # 对话历史
self.temporary_data = {} # 临时数据存储
def add_message(self, role, content):
"""添加消息到对话历史"""
message = {"role": role, "content": content, "timestamp": time.time()}
self.conversation_history.append(message)
# Keep history under max length
if len(self.conversation_history) > self.max_turns:
self.conversation_history.pop(0)
def get_context(self):
"""获取对话上下文(用于发送给LLM)"""
return self.conversation_history[-self.max_turns:]
def store_temp(self, key, value):
"""存储临时数据"""
self.temporary_data[key] = value
def get_temp(self, key, default=None):
"""获取临时数据"""
return self.temporary_data.get(key, default)
def clear_temp(self):
"""清除临时数据"""
self.temporary_data.clear()
Long-term memory: The Agent's knowledge base
Long-term memory is like the Agent's archive room, storing important information that needs to be kept long-term.
Features:
- Large capacity: Can store a large amount of information
- Persistence: Information is stored long-term and will not be automatically cleared
- Retrieval-based access: Querying and retrieving relevant information instead of sequential reading
- Structured storage: Information is usually stored in a structured manner for easy retrieval
Main uses:
- Store user personal information and preferences
- Accumulate knowledge and experience
- Remember important conversation content
- Save task execution results
Technical implementation:
Original prompt (Chinese, left untranslated)
class LongTermMemory:
"""长期记忆基类"""
def __init__(self):
self.memories = [] # 记忆条目列表
def add_memory(self, content, metadata=None):
"""添加记忆"""
memory = {
"id": str(uuid.uuid4()),
"content": content,
"metadata": metadata or {},
"timestamp": time.time(),
"importance": 0.5 # 默认重要性
}
self.memories.append(memory)
return memory["id"]
def search_memories(self, query, limit=5):
"""搜索记忆(子类需要实现具体搜索逻辑)"""
raise NotImplementedError
def get_memory(self, memory_id):
"""获取特定记忆"""
for memory in self.memories:
if memory["id"] == memory_id:
return memory
return None
def delete_memory(self, memory_id):
"""删除记忆"""
self.memories = [m for m in self.memories if m["id"] != memory_id]
Comparative analysis
| Features | Short-term memory | Long-term memory |
|---|---|---|
| Capacity | Small (KB level) | Large (GB level or larger) |
| Persistence | Temporary (conversation level) | Persistent (long-term storage) |
| Access method | Sequential access | Retrieval access |
| Speed | Fast | Relatively slow |
| Main use | Conversation context | Knowledge accumulation |
| Implementation complexity | Simple | Complex |
Memory System Architecture
A complete memory system usually includes both short-term and long-term memory:
Conversation History Management
Effective conversation history management is key to ensuring that AI Agents can have coherent and meaningful conversations. LLMs have limited context lengths, requiring intelligent management of which historical information should be retained and which can be discarded.
Challenges of Conversation History
- Context Length Limitations: Most LLMs have fixed token limits (such as 4K, 8K, 16K, 32K, etc.)
- Different information importance: Not all historical conversations are equally important
- Relevance changes over time: More recent conversations are usually more relevant
- Cumulative cost: Longer context means higher API call costs
Basic conversation history management
Original prompt (Chinese, left untranslated)
class ConversationManager:
"""对话管理器"""
def __init__(self, max_context_length=4000):
self.max_context_length = max_context_length # 最大token数
self.history = [] # 完整的对话历史
self.active_context = [] # 当前活跃的上下文
def add_exchange(self, user_input, assistant_response):
"""添加一轮对话"""
self.history.append({
"user": user_input,
"assistant": assistant_response,
"timestamp": time.time()
})
def build_context(self, current_query, include_history=True):
"""构建当前查询的上下文"""
if not include_history or not self.history:
# No history or no history needed, only return current query
return [{"role": "user", "content": current_query}]
# Start from the most recent conversation and gradually add history until the length limit is reached
context = []
context_length = self.estimate_tokens(current_query)
# Add current query
context.insert(0, {"role": "user", "content": current_query})
# Add history from newest to oldest
for exchange in reversed(self.history):
user_tokens = self.estimate_tokens(exchange["user"])
assistant_tokens = self.estimate_tokens(exchange["assistant"])
# Check if it will exceed the limit
if context_length + user_tokens + assistant_tokens > self.max_context_length:
break
# Add assistant reply (before user input)
context.insert(0, {"role": "assistant", "content": exchange["assistant"]})
context.insert(0, {"role": "user", "content": exchange["user"]})
context_length += user_tokens + assistant_tokens
return context
def estimate_tokens(self, text):
"""粗略估计文本的token数量(实际应用中应使用准确的tokenizer)"""
# Simple estimation: English is about 0.75 words/token, Chinese is about 1-2 characters/token
if self.is_chinese(text):
return len(text) // 2 # 中文每2字符约1个token
else:
words = len(text.split())
return int(words * 1.3) # 英文每单词约1.3个token
def is_chinese(self, text):
"""判断文本是否主要为中文"""
chinese_chars = sum(1 for c in text if '\u4e00' <= c <= '\u9fff')
return chinese_chars / max(len(text), 1) > 0.3
def clear_history(self):
"""清空对话历史"""
self.history.clear()
self.active_context.clear()
Intelligent history selection strategy
Not all historical conversations are equally important. Intelligent history selection can improve context usage efficiency:
1. Time-based decay
Original prompt (Chinese, left untranslated)
def time_based_selection(history, current_time, max_items=10):
"""基于时间的选择:越近的对话权重越高"""
scored_items = []
for item in history:
# Calculate time decay score (higher score means closer)
time_diff = current_time - item["timestamp"]
time_score = max(0, 1 - time_diff / 3600) # 1小时内完全保留,之后衰减
# Combining other factors (such as dialogue length, importance tags, etc.)
total_score = time_score
scored_items.append((total_score, item))
# Sort by score, select the highest score
scored_items.sort(key=lambda x: x[0], reverse=True)
return [item for score, item in scored_items[:max_items]]
2. Relevance-based selection
Original prompt (Chinese, left untranslated)
def relevance_based_selection(history, current_query, embedding_model, max_items=5):
"""基于与当前查询相关性的选择"""
if not history:
return []
# Calculate the vector for the current query
query_embedding = embedding_model.encode(current_query)
scored_items = []
for item in history:
# Convert historical conversation content to vectors
content = item["user"] + " " + item["assistant"]
content_embedding = embedding_model.encode(content)
# Calculate cosine similarity
similarity = cosine_similarity([query_embedding], [content_embedding])[0][0]
scored_items.append((similarity, item))
# Sort by similarity, select the most relevant
scored_items.sort(key=lambda x: x[0], reverse=True)
return [item for similarity, item in scored_items[:max_items]]
3. Hybrid selection strategy
Original prompt (Chinese, left untranslated)
class SmartHistorySelector:
"""智能历史选择器"""
def __init__(self, embedding_model=None):
self.embedding_model = embedding_model
def select_history(self, history, current_query, max_context_length=3000):
"""智能选择历史对话"""
selected = []
current_length = 0
# Strategy 1: always include the most recent round of conversation
if history:
recent = history[-1]
recent_length = self.estimate_length(recent)
if recent_length <= max_context_length:
selected.append(recent)
current_length += recent_length
# Strategy 2: Correlation-based selection
if self.embedding_model and len(history) > 1:
relevant = self.select_by_relevance(history[:-1], current_query, 3)
for item in relevant:
item_length = self.estimate_length(item)
if current_length + item_length <= max_context_length:
selected.append(item)
current_length += item_length
# Strategy 3: If there is still space, add in chronological order
remaining_space = max_context_length - current_length
if remaining_space > 100: # 至少100token的空间
for item in history:
if item not in selected:
item_length = self.estimate_length(item)
if item_length <= remaining_space:
selected.append(item)
remaining_space -= item_length
# Sort by time
selected.sort(key=lambda x: x["timestamp"])
return selected
def select_by_relevance(self, history, query, max_items):
"""基于相关性选择"""
# Simplified implementation, should use vector similarity in practice
query_lower = query.lower()
scored = []
for item in history:
content = (item["user"] + " " + item["assistant"]).lower()
# Simple keyword matching
score = sum(1 for word in query_lower.split() if word in content)
scored.append((score, item))
scored.sort(key=lambda x: x[0], reverse=True)
return [item for score, item in scored[:max_items]]
def estimate_length(self, exchange):
"""估计对话长度"""
return len(exchange["user"]) + len(exchange["assistant"])
Conversation history compression
When the conversation history is too long, it can be compressed to retain core information:
Original prompt (Chinese, left untranslated)
class HistoryCompressor:
"""对话历史压缩器"""
def __init__(self, llm_client):
self.llm = llm_client
def compress_conversation(self, conversation_history, max_summary_length=500):
"""压缩对话历史"""
if len(conversation_history) <= 2:
return conversation_history # 太短不需要压缩
# Convert conversation history to text
conversation_text = self.history_to_text(conversation_history)
# Generate summary using LLM
prompt = f"""
Please compress the following conversation history into a short summary, retaining core information and important details:
Conversation history:
{conversation_text}
Abstract requirements:
1. 不超过{max_summary_length}字
2. 保留用户的主要需求和助理的关键回答
3. 忽略问候语、重复内容和无关细节
摘要:
"""
summary = self.llm.generate(prompt, max_tokens=max_summary_length)
# Create compressed history (summary + recent turns)
compressed_history = [
{
"role": "system",
"content": f"之前的对话摘要:{summary}"
}
]
# Keep the last 1-2 rounds of conversation to maintain coherence
for exchange in conversation_history[-2:]:
compressed_history.append({
"role": "user" if exchange["role"] == "user" else "assistant",
"content": exchange["content"]
})
return compressed_history
def history_to_text(self, history):
"""将对话历史转换为文本"""
lines = []
for exchange in history:
role = "用户" if exchange["role"] == "user" else "助理"
lines.append(f"{role}: {exchange['content']}")
return "\n".join(lines)
Vector database applications
A vector database is the core technology of a long-term memory system, allowing the Agent to retrieve relevant information based on semantic similarity, not just keyword matching.
What is a vector database?
A vector database is specialized in storing and retrieving vectors (embeddings). In the context of AI Agents:
- Text→Vector: Converting text into high-dimensional vectors using an embedding model
- Similarity→Distance: Similar texts have similar vectors, and similarity can be measured by vector distance
- Retrieval→Nearest Neighbor Search: Finding vectors most similar to the query vector
Vector database workflow
Using vector databases to implement long-term memory
1. Install necessary libraries
Original prompt (Chinese, left untranslated)
# Install embedding model and vector database
pip install sentence-transformers # 用于生成embeddings
pip install chromadb # 轻量级向量数据库
2. Create a vector memory system
Original prompt (Chinese, left untranslated)
import chromadb
from sentence_transformers import SentenceTransformer
import uuid
import time
class VectorMemory:
"""基于向量数据库的记忆系统"""
def __init__(self, persist_directory="./memory_db"):
# Initialize embedding model
self.embedding_model = SentenceTransformer('paraphrase-multilingual-MiniLM-L12-v2')
# Initialize ChromaDB
self.client = chromadb.PersistentClient(path=persist_directory)
self.collection = self.client.get_or_create_collection(
name="agent_memories",
metadata={"description": "AI Agent 的长期记忆"}
)
def add_memory(self, content, metadata=None, importance=0.5):
"""添加记忆到向量数据库"""
# Generate embedding
embedding = self.embedding_model.encode(content).tolist()
# Prepare metadata
full_metadata = {
"timestamp": time.time(),
"importance": importance,
"content_length": len(content)
}
if metadata:
full_metadata.update(metadata)
# Generate unique ID
memory_id = str(uuid.uuid4())
# Add to database
self.collection.add(
documents=[content],
embeddings=[embedding],
metadatas=[full_metadata],
ids=[memory_id]
)
return memory_id
def search_memories(self, query, n_results=5, min_similarity=0.3):
"""搜索相关记忆"""
# Generate embedding for the query
query_embedding = self.embedding_model.encode(query).tolist()
# Search in vector database
results = self.collection.query(
query_embeddings=[query_embedding],
n_results=n_results,
include=["documents", "metadatas", "distances"]
)
# Process results
memories = []
if results["documents"]:
for i in range(len(results["documents"][0])):
similarity = 1 - results["distances"][0][i] # 转换距离为相似度
if similarity >= min_similarity:
memory = {
"content": results["documents"][0][i],
"metadata": results["metadatas"][0][i],
"similarity": similarity,
"id": results["ids"][0][i]
}
memories.append(memory)
# Sort by similarity
memories.sort(key=lambda x: x["similarity"], reverse=True)
return memories
def get_relevant_context(self, query, max_memories=3):
"""获取与查询相关的记忆作为上下文"""
memories = self.search_memories(query, n_results=max_memories)
if not memories:
return ""
# Build upper and lower case strings
context_parts = []
for i, memory in enumerate(memories):
content = memory["content"]
similarity = memory["similarity"]
timestamp = memory["metadata"]["timestamp"]
# Format time
time_str = time.strftime("%Y-%m-%d %H:%M", time.localtime(timestamp))
context_parts.append(
f"[相关记忆 {i+1},相似度:{similarity:.2f},时间:{time_str}]\n{content}"
)
return "\n\n".join(context_parts)
def delete_memory(self, memory_id):
"""删除记忆"""
self.collection.delete(ids=[memory_id])
def get_all_memories(self, limit=100):
"""获取所有记忆(按时间倒序)"""
# Note: ChromaDB does not have a direct way to get all features
# Here, we get it by searching a general query
results = self.collection.query(
query_embeddings=[self.embedding_model.encode(" ").tolist()], # 空查询
n_results=limit
)
memories = []
if results["documents"]:
for i in range(len(results["documents"][0])):
memory = {
"content": results["documents"][0][i],
"metadata": results["metadatas"][0][i],
"id": results["ids"][0][i]
}
memories.append(memory)
# Sort in descending order by time
memories.sort(key=lambda x: x["metadata"]["timestamp"], reverse=True)
return memories
3. Complete example using vector memory
Original prompt (Chinese, left untranslated)
class AgentWithMemory:
"""带有记忆系统的AI Agent"""
def __init__(self, llm_client):
self.llm = llm_client
self.short_term_memory = ShortTermMemory(max_turns=10)
self.long_term_memory = VectorMemory()
def process_query(self, user_query):
"""处理用户查询"""
# 1. Retrieve relevant information from long-term memory
relevant_context = self.long_term_memory.get_relevant_context(user_query)
# 2. Build the complete context
short_term_context = self.short_term_memory.get_context()
# 3. Prepare system prompt
system_message = "你是一个有帮助的AI助手。"
if relevant_context:
system_message += f"\n\n相关背景信息:\n{relevant_context}"
# 4. Call LLM to generate response
messages = [{"role": "system", "content": system_message}]
messages.extend(short_term_context)
messages.append({"role": "user", "content": user_query})
response = self.llm.chat_completion(messages)
# 5. Update short-term memory
self.short_term_memory.add_message("user", user_query)
self.short_term_memory.add_message("assistant", response)
# 6. Determine if it should be saved to long-term memory
if self.should_save_to_long_term(user_query, response):
self.save_to_long_term(user_query, response)
return response
def should_save_to_long_term(self, user_query, response):
"""判断是否应该保存到长期记忆"""
# Simple heuristic rules
important_keywords = ["偏好", "喜欢", "不喜欢", "重要", "记住", "下次", "经常"]
query_lower = user_query.lower()
response_lower = response.lower()
# Check if it contains important keywords
for keyword in important_keywords:
if keyword in query_lower or keyword in response_lower:
return True
# Check if it is about personal information
personal_keywords = ["我叫", "我是", "我住在", "我的电话", "我的邮箱"]
for keyword in personal_keywords:
if keyword in query_lower:
return True
return False
def save_to_long_term(self, user_query, response):
"""保存到长期记忆"""
# Save the conversation as a memory
memory_content = f"用户:{user_query}\n助理:{response}"
metadata = {
"type": "conversation",
"user_query": user_query[:100], # 截断以避免过长
"response_length": len(response)
}
self.long_term_memory.add_memory(memory_content, metadata)
# Usage example
if __name__ == "__main__":
# Create an Agent with memory
agent = AgentWithMemory(llm_client)
# Simulate conversation
conversations = [
"你好,我叫张三,住在北京",
"我喜欢编程和阅读",
"我不喜欢早起",
"今天天气怎么样?",
"我的编程偏好是什么?" # 这个问题应该能检索到之前的记忆
]
for query in conversations:
print(f"\n用户: {query}")
response = agent.process_query(query)
print(f"助理: {response[:100]}...") # 只打印前100字符
Vector database optimization tips
Choosing the appropriate embedding model:
- Multilingual support:
paraphrase-multilingual-MiniLM-L12-v2 - English Optimization:
all-MiniLM-L6-v2 - High Quality:
text-embedding-ada-002(OpenAI)
Metadata Filtering: Utilize the metadata filtering function of the vector database to improve retrieval accuracy
Original prompt (Chinese, left untranslated)
# 使用元数据过滤
results = collection.query(
query_embeddings=[query_embedding],
n_results=5,
where={"type": "personal_preference"}, # 只检索个人偏好类型的记忆
where_document={"$contains": "编程"} # 只检索包含"编程"的文档
)
**Hybrid Search:** Combine vector search and keyword search
Original prompt (Chinese, left untranslated)
def hybrid_search(query, vector_memory, keyword_weight=0.3):
"""混合搜索:结合向量相似度和关键词匹配"""
# Vector Search
vector_results = vector_memory.search_memories(query, n_results=10)
# Keyword search (simplified implementation)
keyword_results = []
query_words = set(query.lower().split())
# Simplified implementation here, should retrieve from database in reality
all_memories = vector_memory.get_all_memories(limit=100)
for memory in all_memories:
content_words = set(memory["content"].lower().split())
common_words = query_words & content_words
keyword_score = len(common_words) / max(len(query_words), 1)
if keyword_score > 0:
memory["keyword_score"] = keyword_score
keyword_results.append(memory)
# Merge results
all_results = {}
for result in vector_results:
result_id = result["id"]
all_results[result_id] = {
"vector_score": result["similarity"],
"keyword_score": 0,
"content": result["content"],
"metadata": result["metadata"]
}
for result in keyword_results:
result_id = result["id"]
if result_id in all_results:
all_results[result_id]["keyword_score"] = result["keyword_score"]
else:
all_results[result_id] = {
"vector_score": 0,
"keyword_score": result["keyword_score"],
"content": result["content"],
"metadata": result["metadata"]
}
# Calculate composite score
final_results = []
for result_id, result in all_results.items():
combined_score = (
(1 - keyword_weight) * result["vector_score"] +
keyword_weight * result["keyword_score"]
)
result["combined_score"] = combined_score
final_results.append(result)
# Sort by comprehensive score
final_results.sort(key=lambda x: x["combined_score"], reverse=True)
return final_results[:5]
Memory Compression and Summarization Strategies
As the conversation progresses, memory accumulates continuously. To avoid information overload and reduce resource consumption, memory needs to be compressed and summarized periodically.
Why is memory compression necessary?
- Save storage space: Original conversation records can be very large
- Improve retrieval efficiency: Compressed memory is easier to retrieve and process
- Extract core informationRemove redundancy, retain essence
- Reduce computational costProcessing compressed memory is more efficient than processing raw memory
Memory compression strategies
1. Importance-based compression
Original prompt (Chinese, left untranslated)
class ImportanceBasedCompressor:
"""基于重要性的记忆压缩器"""
def __init__(self, llm_client):
self.llm = llm_client
def compress_memories(self, memories, target_ratio=0.5):
"""压缩记忆,保留重要内容"""
if len(memories) <= 1:
return memories # 记忆太少,不需要压缩
# Evaluate the importance of each memory
scored_memories = []
for memory in memories:
importance = self.evaluate_importance(memory)
scored_memories.append((importance, memory))
# Sort by importance
scored_memories.sort(key=lambda x: x[0], reverse=True)
# Keep the most important parts
keep_count = max(1, int(len(memories) * target_ratio))
compressed_memories = [memory for _, memory in scored_memories[:keep_count]]
return compressed_memories
def evaluate_importance(self, memory):
"""评估记忆的重要性"""
content = memory["content"]
metadata = memory.get("metadata", {})
# Importance evaluation based on rules
importance_score = 0.0
# 1. Based on type
memory_type = metadata.get("type", "")
if memory_type == "personal_info":
importance_score += 0.8
elif memory_type == "preference":
importance_score += 0.7
elif memory_type == "fact":
importance_score += 0.5
elif memory_type == "conversation":
importance_score += 0.3
# 2. Based on length (a moderate length might be more important)
content_length = len(content)
if 50 <= content_length <= 500:
importance_score += 0.2
elif content_length > 500:
importance_score += 0.1
# 3. Based on time decay (newer memories are more important)
timestamp = metadata.get("timestamp", 0)
if timestamp > 0:
age_days = (time.time() - timestamp) / (24 * 3600)
recency_score = max(0, 1 - age_days / 30) # 30天内线性衰减
importance_score += recency_score * 0.5
# 4. Based on explicit importance tags
explicit_importance = metadata.get("importance", 0.5)
importance_score += explicit_importance * 0.5
return min(importance_score, 1.0) # 归一化到0-1
2. Clustering-based compression
Cluster similar memories, then summarize each cluster:
Original prompt (Chinese, left untranslated)
from sklearn.cluster import KMeans
import numpy as np
class ClusterBasedCompressor:
"""基于聚类的记忆压缩器"""
def __init__(self, embedding_model):
self.embedding_model = embedding_model
def compress_by_clustering(self, memories, n_clusters=None):
"""通过聚类压缩记忆"""
if len(memories) <= 3:
return memories # 记忆太少,不需要聚类
# Determine the number of clusters
if n_clusters is None:
n_clusters = min(3, len(memories) // 2)
# Get the embedding of all memories
embeddings = []
for memory in memories:
embedding = self.embedding_model.encode(memory["content"])
embeddings.append(embedding)
embeddings = np.array(embeddings)
# Perform K-means clustering
kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
labels = kmeans.fit_predict(embeddings)
# Summarize each cluster
compressed_memories = []
for cluster_id in range(n_clusters):
# Get all memories of this cluster
cluster_memories = [
memories[i] for i in range(len(memories)) if labels[i] == cluster_id
]
if cluster_memories:
# Summarize the memory of this cluster
summary = self.summarize_cluster(cluster_memories)
compressed_memories.append(summary)
return compressed_memories
def summarize_cluster(self, cluster_memories):
"""总结一个聚类的记忆"""
if len(cluster_memories) == 1:
# Only one memory, return directly
return cluster_memories[0]
# Merge all memory content
all_content = "\n".join([m["content"] for m in cluster_memories])
# Generate summary using LLM (simplified implementation here)
# Should actually call LLM to generate high-quality summary
summary_content = f"相关主题的{len(cluster_memories)}条记忆摘要:{all_content[:500]}..."
# Merge metadata
merged_metadata = {
"type": "cluster_summary",
"original_count": len(cluster_memories),
"compressed": True,
"timestamp": time.time()
}
return {
"content": summary_content,
"metadata": merged_metadata
}
3. Incremental summarization strategy
Summarize step-by-step during the conversation instead of processing all history at once:
Original prompt (Chinese, left untranslated)
class IncrementalSummarizer:
"""增量总结器"""
def __init__(self, llm_client, summary_interval=5):
self.llm = llm_client
self.summary_interval = summary_interval # 每多少轮对话总结一次
self.conversation_buffer = []
self.summaries = []
def add_conversation(self, user_input, assistant_response):
"""添加对话到缓冲区"""
self.conversation_buffer.append({
"user": user_input,
"assistant": assistant_response,
"timestamp": time.time()
})
# Check if summarization is needed
if len(self.conversation_buffer) >= self.summary_interval:
self.create_summary()
def create_summary(self):
"""创建总结"""
if not self.conversation_buffer:
return
# Summarize all content in the conversation buffer into one text
conversation_text = ""
for exchange in self.conversation_buffer:
conversation_text += f"用户: {exchange['user']}\n"
conversation_text += f"助理: {exchange['assistant']}\n\n"
# Use LLM to generate summary
prompt = f"""
Please summarize the following conversation content into a short paragraph, retaining core information and important details.
Conversation content:
{conversation_text}
Requirements Summary:
1. 不超过200字
2. 保留用户的主要需求和助理的关键回答
3. 忽略问候语、重复内容和无关细节
总结:
"""
summary = self.llm.generate(prompt, max_tokens=200)
# Save summary
self.summaries.append({
"content": summary,
"timestamp": time.time(),
"original_count": len(self.conversation_buffer)
})
# Clear buffer
self.conversation_buffer.clear()
def get_context(self, include_recent=True, include_summaries=True):
"""获取上下文"""
context_parts = []
if include_summaries and self.summaries:
# Add all summaries
for i, summary in enumerate(self.summaries[-3:]): # 最多3个总结
context_parts.append(f"[对话总结 {i+1}]\n{summary['content']}")
if include_recent and self.conversation_buffer:
# Add recent conversation
for exchange in self.conversation_buffer[-3:]: # 最多3轮最近对话
context_parts.append(f"用户: {exchange['user']}")
context_parts.append(f"助理: {exchange['assistant']}")
return "\n\n".join(context_parts)
Memory lifecycle management
A complete memory system should manage the entire lifecycle of memory:
Original prompt (Chinese, left untranslated)
class MemoryLifecycleManager:
"""记忆生命周期管理器"""
def __init__(self):
self.short_term = ShortTermMemory()
self.long_term = VectorMemory()
self.compressor = ImportanceBasedCompressor()
def process_memory(self, content, initial_importance=0.5):
"""处理新记忆"""
# 1. Store in short-term memory
self.short_term.store_temp("recent_memory", content)
# 2. Evaluate importance
evaluated_importance = self.evaluate_importance(content, initial_importance)
# 3. Decide storage strategy based on importance
if evaluated_importance >= 0.8:
# High importance: store immediately in long-term memory
self.long_term.add_memory(content, {"importance": evaluated_importance})
elif evaluated_importance >= 0.5:
# Medium importance: marked as pending
self.queue_for_review(content, evaluated_importance)
else:
# Low importance: keep only in short-term memory, clean up later
pass
def evaluate_importance(self, content, initial_importance):
"""评估记忆重要性"""
# This is where more complex evaluation logic can be implemented
return initial_importance
def queue_for_review(self, content, importance):
"""将记忆加入待处理队列"""
# Implement queue logic
pass
def periodic_maintenance(self):
"""定期维护"""
# 1. Compress long-term memory
all_memories = self.long_term.get_all_memories(limit=1000)
if len(all_memories) > 100:
compressed = self.compressor.compress_memories(all_memories, target_ratio=0.7)
# Update long-term memory (more complex logic may be needed in actual implementation)
# Simplified handling here
# 2. Clean up old low-importance memories
self.cleanup_old_memories()
def cleanup_old_memories(self, max_age_days=30, min_importance=0.3):
"""清理旧记忆"""
# Get all memories
all_memories = self.long_term.get_all_memories(limit=1000)
current_time = time.time()
for memory in all_memories:
metadata = memory.get("metadata", {})
timestamp = metadata.get("timestamp", 0)
importance = metadata.get("importance", 0.5)
# Calculate memory age
age_days = (current_time - timestamp) / (24 * 3600)
# Delete old and unimportant memories
if age_days > max_age_days and importance < min_importance:
self.long_term.delete_memory(memory["id"])