mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Add 'libs/o-mem/' from commit '46e131ac39af55d456304c61dfb881717044528e'
git-subtree-dir: libs/o-mem git-subtree-mainline:6eb7acaf73git-subtree-split:46e131ac39
This commit is contained in:
commit
16ef169036
17 changed files with 71319 additions and 0 deletions
201
libs/o-mem/LICENSE
Normal file
201
libs/o-mem/LICENSE
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
143
libs/o-mem/README.md
Normal file
143
libs/o-mem/README.md
Normal file
|
|
@ -0,0 +1,143 @@
|
|||
# O-Mem: Omni Memory System for Personalized, Long Horizon, Self-Evolving Agents
|
||||
|
||||
[](LICENSE) [](https://www.python.org) [](https://arxiv.org/abs/2511.13593)
|
||||
[](https://huggingface.co/papers/2511.13593)
|
||||
|
||||
|
||||
|
||||
<!-- [](https://youtu.be/...) -->
|
||||
|
||||
|
||||
<div align="center">
|
||||
<img src="./images/image1.png" width="80%" height="auto" />
|
||||
</div>
|
||||
|
||||
📌 Current agent memory systems often rely on **semantic clustering and chunk-based retrieval**, which can:
|
||||
|
||||
- ❌ Miss contextually important but semantically distant information (e.g., health status affecting weekend plans)
|
||||
- ❌ Introduce retrieval noise due to suboptimal grouping- ❌ Fail to capture evolving user characteristics over time**o-mem** addresses these issues by rethinking memory as an **active user modeling process**, not just passive storage. Inspired by personal informatics theory, o-mem continuously extracts and updates:
|
||||
- 🔹 **User Persona Attributes** (e.g., preferences, habits, life stage)
|
||||
- 🔹 **Event Records** (e.g., recent job change, travel plans)
|
||||
- 🔹 **Topic-Indexed Messages** (for contextual grounding)
|
||||
|
||||
This enables **hierarchical, user-aware retrieval**: agents first reason about *who the user is*, then retrieve *what they said* — leading to more coherent, adaptive, and personalized responses.
|
||||
|
||||
|
||||
|
||||
|
||||
## 🚀 Key Features✅ **Dynamic User Profiling**> Automatically extract and update user attributes from ongoing interactions — no manual annotation needed.
|
||||
|
||||
✅ **Hierarchical Memory Structure**> Three-tier design:> - **Persona Layer**: Stable & evolving user traits> - **Event Layer**: Significant life/contextual events> - **Message Layer**: Topic-indexed raw dialog history✅ **User-Centric Retrieval**> Retrieve based on *user state* first, then *topic relevance* — reducing noise and improving coherence.
|
||||
|
||||
✅ **Interaction-Time Scaling**> Memory grows and adapts with each interaction — enabling true long-term personalization.
|
||||
|
||||
✅ **Evaluation Suite Included**> Benchmark scripts for:> - Persona-based QA (LoCoMo)> - Response selection (PERSONAMEM)> - In-depth report generation (Personalized Deep Research Bench)
|
||||
|
||||
✅ **Extensible & Modular**> Plug into any LLM agent pipeline via clean APIs. Easy to customize extraction rules or add new memory types.
|
||||
|
||||
## 🧩 Architecture
|
||||
|
||||
[Raw Interaction] ↓[Memory Writer] → [Extract: Attributes + Events]
|
||||
↓[Update: Dynamic User Profile]
|
||||
↓[Hierarchical Indexing]
|
||||
↓[Retriever] ← [Query: "What would this user care about?"]
|
||||
↓[Context-Aware Prompting] → [LLM Agent]
|
||||
|
||||
## 🔄O-Mem Workflow Visualization
|
||||
|
||||
<div align="center">
|
||||
<img src="./images/workflow.png" width="80%" height="auto" />
|
||||
</div>
|
||||
|
||||
## 🧩Project Structure
|
||||
|
||||
```
|
||||
memory_chain/
|
||||
├── __init__.py # Package exports
|
||||
├── memory.py # MemoryChain - main memory container
|
||||
├── memory_manager.py # MemoryManager - high-level API
|
||||
├── working_memory.py # Working Memory implementation
|
||||
├── episodic_memory.py # Episodic Memory implementation
|
||||
├── persona_memory.py # Persona Memory (active user profiling)
|
||||
├── prompts.py # LLM prompt templates
|
||||
└── utils.py # Utility functions
|
||||
|
||||
example_usage.py # Usage examples
|
||||
config.yaml.example # Configuration template
|
||||
requirements.txt # Dependencies
|
||||
```
|
||||
|
||||
## 🧠Memory Types
|
||||
|
||||
### Working Memory
|
||||
- **Purpose**: Short-term storage for recent conversation
|
||||
- **Capacity**: Fixed size queue (default: 20 messages)
|
||||
- **Behavior**: Oldest messages overflow to Episodic Memory
|
||||
|
||||
### Episodic Memory
|
||||
- **Purpose**: Long-term storage for events and topics
|
||||
- **Features**:
|
||||
- Topic clustering via semantic similarity
|
||||
- Event-level and topic-level memories
|
||||
- Attribute and fact extraction
|
||||
|
||||
### Persona Memory
|
||||
- **Purpose**: Active user profiling and preferences
|
||||
- **Contents**:
|
||||
- Preferences (likes, dislikes, interests)
|
||||
- Attributes (personality traits, facts)
|
||||
- Dynamically updated user characteristics
|
||||
|
||||
## ⚙️Installation
|
||||
|
||||
```bash
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Copy and configure settings
|
||||
cp config.yaml.example config.yaml
|
||||
# Edit config.yaml with your OpenAI API key
|
||||
```
|
||||
|
||||
## 🚀Quick Start
|
||||
|
||||
|
||||
```bash
|
||||
# Run full example
|
||||
python example_usage.py
|
||||
|
||||
# Run simplified example
|
||||
python example_usage.py simple
|
||||
|
||||
#Run test experiments for locomo benchmark with different arguments
|
||||
python locomo_experiment_retrieval_optimize_ablation_study.py
|
||||
```
|
||||
|
||||
## ⚙️Configuration
|
||||
|
||||
Create a `config.yaml` file:
|
||||
|
||||
```yaml
|
||||
model:
|
||||
llm_model: "model name"
|
||||
openai_api_key: "your-openai-api-key"
|
||||
openai_base_url: "https://api.openai.com/v1"
|
||||
```
|
||||
|
||||
## 🧩 Community Support Note
|
||||
|
||||
We note that the performance of GPT-4.1 has recently degraded in preliminary observations, and the model is expected to be deprecated in the near future. Due to these changes, results obtained using GPT-4.1 may not be fully reproducible over time. For research purposes, especially for individuals or institutions with limited access to large language models, we are willing to share the original model outputs (e.g., inference logs, generated responses) upon request. We encourage careful interpretation of the experimental results in light of the evolving nature of commercial LLMs, and refer readers to the discussion in our technical report for guidance on result analysis and limitations.
|
||||
|
||||
## 📝 Citation
|
||||
|
||||
```
|
||||
@article{wang2025omni,
|
||||
title={Omni Memory System for Personalized, Long Horizon, Self-Evolving Agents},
|
||||
author={Wang, Piaohong and Tian, Motong and Li, Jiaxian and Liang, Yuan and Wang, Yuqing and Chen, Qianben and Wang, Tiannan and Lu, Zhicong and Ma, Jiawei and Jiang, Yuchen Eleanor and others},
|
||||
journal={arXiv preprint arXiv:2511.13593},
|
||||
year={2025}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
9
libs/o-mem/config.yaml.example
Normal file
9
libs/o-mem/config.yaml.example
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
# Memory Chain Configuration Example
|
||||
# ===================================
|
||||
# Copy this file to config.yaml and fill in your settings
|
||||
|
||||
model:
|
||||
llm_model: "model_name" # LLM model name
|
||||
openai_api_key: "your-openai-api-key-here" # Your OpenAI API key
|
||||
openai_base_url: "https://api.openai.com/v1" # OpenAI API base URL (change if using proxy)
|
||||
|
||||
481
libs/o-mem/example_usage.py
Normal file
481
libs/o-mem/example_usage.py
Normal file
|
|
@ -0,0 +1,481 @@
|
|||
#!/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 asyncio
|
||||
import argparse
|
||||
import os
|
||||
import yaml
|
||||
import torch
|
||||
from openai import AsyncOpenAI
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from memory_chain import MemoryChain, MemoryManager
|
||||
|
||||
|
||||
# ==================== Configuration Class ====================
|
||||
|
||||
class MemoryConfig:
|
||||
"""Memory system configuration"""
|
||||
def __init__(
|
||||
self,
|
||||
working_memory_max_size: int = 20,
|
||||
episodic_memory_refresh_rate: int = 5,
|
||||
output_dir: str = "./memory_storage",
|
||||
number_of_retrieval_pieces: int = 15, # Must be >= 10 (internal calculation uses top_k-9)
|
||||
drop_threshold: float = 0.1,
|
||||
):
|
||||
self.working_memory_max_size = working_memory_max_size
|
||||
self.episodic_memory_refresh_rate = episodic_memory_refresh_rate
|
||||
self.output_dir = output_dir
|
||||
self.number_of_retrieval_pieces = max(number_of_retrieval_pieces, 10) # Ensure at least 10
|
||||
self.drop_threshold = drop_threshold
|
||||
|
||||
|
||||
# ==================== Main Usage Example ====================
|
||||
|
||||
async def main():
|
||||
"""
|
||||
Memory Chain Usage Example
|
||||
"""
|
||||
|
||||
# ========== 1. Configuration Parameters ==========
|
||||
|
||||
# Read config file (or set directly)
|
||||
try:
|
||||
with open('config.yaml', 'r') as file:
|
||||
config = yaml.safe_load(file)
|
||||
except FileNotFoundError:
|
||||
# If no config file, use default configuration
|
||||
config = {
|
||||
"model": {
|
||||
"llm_model": "gpt-4o-mini",
|
||||
"openai_api_key": "your-api-key-here",
|
||||
"openai_base_url": "https://api.openai.com/v1"
|
||||
}
|
||||
}
|
||||
|
||||
# Initialize OpenAI client
|
||||
client = AsyncOpenAI(
|
||||
base_url=config["model"]["openai_base_url"],
|
||||
api_key=config["model"]["openai_api_key"]
|
||||
)
|
||||
|
||||
# Load Embedding model
|
||||
print("Loading Embedding model...")
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
embedding_model = SentenceTransformer("all-MiniLM-L6-v2").to(device)
|
||||
print(f"Embedding model loaded, using device: {device}")
|
||||
|
||||
# Memory system configuration
|
||||
# Note: working_memory_max_size determines the working memory capacity
|
||||
# When message count reaches this value, old messages are transferred to episodic memory
|
||||
memory_config = MemoryConfig(
|
||||
working_memory_max_size=5, # Max working memory capacity (small value to trigger memory transfer quickly)
|
||||
episodic_memory_refresh_rate=3, # Episodic memory refresh rate
|
||||
output_dir="./memory_storage", # Memory storage directory
|
||||
number_of_retrieval_pieces=15, # Number of retrieval pieces
|
||||
drop_threshold=0.1 # Similarity threshold
|
||||
)
|
||||
|
||||
# Ensure storage directory exists
|
||||
os.makedirs(memory_config.output_dir, exist_ok=True)
|
||||
|
||||
# ========== 2. Initialize Memory System ==========
|
||||
|
||||
user_name = "Alice" # User name
|
||||
agent_name = "Bob" # Agent/assistant name
|
||||
memory_index = 0 # Memory index (for multi-session scenarios)
|
||||
|
||||
# Create MemoryChain (core memory system)
|
||||
memory_system = MemoryChain(
|
||||
memory_index=memory_index,
|
||||
llm_model=config["model"]["llm_model"],
|
||||
llm_client=client,
|
||||
embedding_model=embedding_model,
|
||||
user_name=user_name,
|
||||
agent_name=agent_name,
|
||||
cmd_args=memory_config,
|
||||
args=config,
|
||||
memory_dir=memory_config.output_dir
|
||||
)
|
||||
|
||||
# Create MemoryManager (memory manager, provides high-level API)
|
||||
memory_manager = MemoryManager(
|
||||
memory_index=memory_index,
|
||||
memory_system=memory_system,
|
||||
llm_model=config["model"]["llm_model"],
|
||||
llm_client=client,
|
||||
embedding_model=embedding_model,
|
||||
user_name=user_name,
|
||||
agent_name=agent_name,
|
||||
cmd_args=memory_config,
|
||||
args=config,
|
||||
memory_dir=memory_config.output_dir
|
||||
)
|
||||
|
||||
print(f"\n{'='*50}")
|
||||
print("Memory system initialization complete!")
|
||||
print(f"User: {user_name}, Agent: {agent_name}")
|
||||
print(f"{'='*50}\n")
|
||||
|
||||
# ========== 3. Simulate Conversation and Store Memory ==========
|
||||
|
||||
# Simulated conversation data
|
||||
# Note: Number of conversations must exceed working_memory_max_size to trigger memory transfer
|
||||
conversations = [
|
||||
{"speaker": user_name, "message": "I love playing basketball with my friends every weekend.", "timestamp": "2024-01-01 10:00:00"},
|
||||
{"speaker": agent_name, "message": "That sounds great! Basketball is a wonderful way to stay active.", "timestamp": "2024-01-01 10:01:00"},
|
||||
{"speaker": user_name, "message": "Yes! I've been playing for 5 years. My favorite team is the Lakers.", "timestamp": "2024-01-01 10:02:00"},
|
||||
{"speaker": agent_name, "message": "The Lakers have a great history. Do you play any position specifically?", "timestamp": "2024-01-01 10:03:00"},
|
||||
{"speaker": user_name, "message": "I usually play as a point guard. I also started learning guitar last month.", "timestamp": "2024-01-01 10:04:00"},
|
||||
{"speaker": agent_name, "message": "Guitar is a lovely instrument! What kind of music do you want to play?", "timestamp": "2024-01-01 10:05:00"},
|
||||
{"speaker": user_name, "message": "I'm into rock music. My favorite band is Coldplay.", "timestamp": "2024-01-01 10:06:00"},
|
||||
{"speaker": agent_name, "message": "Coldplay has some amazing songs. Do you have a favorite album?", "timestamp": "2024-01-01 10:07:00"},
|
||||
{"speaker": user_name, "message": "I really love 'A Rush of Blood to the Head'. The song 'The Scientist' is my favorite.", "timestamp": "2024-01-01 10:08:00"},
|
||||
{"speaker": agent_name, "message": "That's a classic! Do you also enjoy attending live concerts?", "timestamp": "2024-01-01 10:09:00"},
|
||||
{"speaker": user_name, "message": "Yes! I went to a Coldplay concert last year. It was an amazing experience.", "timestamp": "2024-01-01 10:10:00"},
|
||||
{"speaker": agent_name, "message": "That must have been incredible! Live music is always so energizing.", "timestamp": "2024-01-01 10:11:00"},
|
||||
{"speaker": user_name, "message": "Absolutely! I also enjoy cooking Italian food on weekends.", "timestamp": "2024-01-01 10:12:00"},
|
||||
{"speaker": agent_name, "message": "Italian cuisine is delicious! What's your specialty dish?", "timestamp": "2024-01-01 10:13:00"},
|
||||
{"speaker": user_name, "message": "I make a great homemade pasta with tomato sauce. My family loves it.", "timestamp": "2024-01-01 10:14:00"},
|
||||
{"speaker": agent_name, "message": "That sounds delicious! Cooking for family is always special.", "timestamp": "2024-01-01 10:15:00"},
|
||||
]
|
||||
|
||||
print("Processing conversations and building memory...")
|
||||
print("-" * 50)
|
||||
|
||||
for index, conv in enumerate(conversations):
|
||||
speaker = conv["speaker"]
|
||||
message = conv["message"]
|
||||
timestamp = conv["timestamp"]
|
||||
user_speak = (speaker == user_name)
|
||||
|
||||
print(f"[{index}] {speaker}: {message}")
|
||||
|
||||
# Store message in memory system
|
||||
await memory_manager.receive_message(
|
||||
message=message,
|
||||
client=client,
|
||||
index=index,
|
||||
timestamp=timestamp,
|
||||
user_speak=user_speak
|
||||
)
|
||||
|
||||
print("-" * 50)
|
||||
print("Conversation processing complete!\n")
|
||||
|
||||
# ========== 4. Sync Memory Mappings (Important! Must be called before retrieval) ==========
|
||||
|
||||
print("Syncing memory mappings...")
|
||||
# Sync messages from working_memory and episodic_memory to topic_message_dict
|
||||
for message in list(memory_system.user_working_memory.working_memory_queue.queue) + memory_system.user_episodic_memory.episodic_memory_cache_list:
|
||||
memory_system.user_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||
for message in list(memory_system.agent_working_memory.working_memory_queue.queue) + memory_system.agent_episodic_memory.episodic_memory_cache_list:
|
||||
memory_system.agent_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||
|
||||
# Generate memory detail map (for keyword retrieval)
|
||||
memory_system.generate_memory_detail_map()
|
||||
print("Memory mapping sync complete!\n")
|
||||
|
||||
# ========== 5. Update Persona Memory (Optional, call after conversation ends) ==========
|
||||
|
||||
print("Updating persona memory...")
|
||||
await memory_system.user_persona_memory.update_preference_persona(
|
||||
memory_system.user_episodic_memory.topic_episodic_memory_list
|
||||
)
|
||||
await memory_system.user_persona_memory.update_attribute_persona(
|
||||
memory_system.user_episodic_memory.attribute_episodic_memory_dict
|
||||
)
|
||||
print("Persona memory update complete!\n")
|
||||
|
||||
# ========== 6. Memory Retrieval ==========
|
||||
|
||||
print("=" * 50)
|
||||
print("Memory Retrieval Example")
|
||||
print("=" * 50)
|
||||
|
||||
# Test questions
|
||||
test_questions = [
|
||||
f"What sport does {user_name} like?",
|
||||
f"What instrument is {user_name} learning?",
|
||||
f"What is {user_name}'s favorite band?",
|
||||
]
|
||||
|
||||
for question in test_questions:
|
||||
print(f"\nQuestion: {question}")
|
||||
print("-" * 40)
|
||||
|
||||
# Retrieve relevant information from memory system
|
||||
retrieval_result, retrieved_user, retrieved_agent, peak_mem, peak_mem_inc = \
|
||||
memory_manager.retrieve_from_memory_soft_segmentation(
|
||||
question=question,
|
||||
topn=memory_config.number_of_retrieval_pieces,
|
||||
drop_threshold=memory_config.drop_threshold
|
||||
)
|
||||
|
||||
# Display retrieval results
|
||||
print(f"Retrieved persona attributes: {retrieval_result.get('persona attributes', [])}")
|
||||
print(f"Retrieved context messages: {retrieval_result.get('retrieved context messages', [])[:3]}")
|
||||
|
||||
# Generate answer
|
||||
answer, tokens = await memory_manager.generate_system_response(
|
||||
query=question,
|
||||
restrieval_result=retrieval_result,
|
||||
client=client,
|
||||
speaker_a=retrieved_user,
|
||||
speaker_b=retrieved_agent,
|
||||
llm_model=config["model"]["llm_model"]
|
||||
)
|
||||
|
||||
print(f"Generated answer: {answer}")
|
||||
print(f"Tokens consumed: {tokens}")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Example run complete!")
|
||||
print("=" * 50)
|
||||
|
||||
|
||||
# ==================== Simplified API Wrapper ====================
|
||||
|
||||
class SimpleMemory:
|
||||
"""
|
||||
Simplified memory system wrapper class
|
||||
Provides simpler API for everyday use
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
user_name: str,
|
||||
agent_name: str,
|
||||
llm_model: str = "gpt-4o-mini",
|
||||
api_key: str = None,
|
||||
base_url: str = "https://api.openai.com/v1",
|
||||
embedding_model_name: str = "all-MiniLM-L6-v2",
|
||||
memory_dir: str = "./memory_storage",
|
||||
):
|
||||
self.user_name = user_name
|
||||
self.agent_name = agent_name
|
||||
self.llm_model = llm_model
|
||||
self.memory_dir = memory_dir
|
||||
self.message_index = 0
|
||||
|
||||
# Initialize client
|
||||
self.client = AsyncOpenAI(base_url=base_url, api_key=api_key)
|
||||
|
||||
# Load Embedding model
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
self.embedding_model = SentenceTransformer(embedding_model_name).to(device)
|
||||
|
||||
# Configuration
|
||||
self.config = {"model": {"llm_model": llm_model}}
|
||||
self.cmd_args = MemoryConfig(
|
||||
working_memory_max_size=5, # Same as main() for consistent behavior
|
||||
episodic_memory_refresh_rate=3, # Same as main()
|
||||
output_dir=memory_dir
|
||||
)
|
||||
|
||||
os.makedirs(memory_dir, exist_ok=True)
|
||||
|
||||
# Initialize memory system
|
||||
self.memory_system = MemoryChain(
|
||||
memory_index=0,
|
||||
llm_model=llm_model,
|
||||
llm_client=self.client,
|
||||
embedding_model=self.embedding_model,
|
||||
user_name=user_name,
|
||||
agent_name=agent_name,
|
||||
cmd_args=self.cmd_args,
|
||||
args=self.config,
|
||||
memory_dir=memory_dir
|
||||
)
|
||||
|
||||
self.memory_manager = MemoryManager(
|
||||
memory_index=0,
|
||||
memory_system=self.memory_system,
|
||||
llm_model=llm_model,
|
||||
llm_client=self.client,
|
||||
embedding_model=self.embedding_model,
|
||||
user_name=user_name,
|
||||
agent_name=agent_name,
|
||||
cmd_args=self.cmd_args,
|
||||
args=self.config,
|
||||
memory_dir=memory_dir
|
||||
)
|
||||
|
||||
async def add_message(self, message: str, is_user: bool = True, timestamp: str = None):
|
||||
"""Add a message to memory"""
|
||||
from datetime import datetime
|
||||
if timestamp is None:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
await self.memory_manager.receive_message(
|
||||
message=message,
|
||||
client=self.client,
|
||||
index=self.message_index,
|
||||
timestamp=timestamp,
|
||||
user_speak=is_user
|
||||
)
|
||||
self.message_index += 1
|
||||
|
||||
async def query(self, question: str) -> str:
|
||||
"""Query memory and generate answer"""
|
||||
# Sync memory mappings
|
||||
self._sync_memory_mappings()
|
||||
|
||||
result, user, agent, _, _ = self.memory_manager.retrieve_from_memory_soft_segmentation(
|
||||
question=question,
|
||||
topn=self.cmd_args.number_of_retrieval_pieces,
|
||||
drop_threshold=self.cmd_args.drop_threshold
|
||||
)
|
||||
|
||||
answer, _ = await self.memory_manager.generate_system_response(
|
||||
query=question,
|
||||
restrieval_result=result,
|
||||
client=self.client,
|
||||
speaker_a=user,
|
||||
speaker_b=agent,
|
||||
llm_model=self.llm_model
|
||||
)
|
||||
return answer
|
||||
|
||||
def _sync_memory_mappings(self):
|
||||
"""Sync memory mappings (must be called before retrieval)"""
|
||||
for message in list(self.memory_system.user_working_memory.working_memory_queue.queue) + self.memory_system.user_episodic_memory.episodic_memory_cache_list:
|
||||
self.memory_system.user_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||
for message in list(self.memory_system.agent_working_memory.working_memory_queue.queue) + self.memory_system.agent_episodic_memory.episodic_memory_cache_list:
|
||||
self.memory_system.agent_topic_message_dict[message["topics"]] = [message["raw_message"], message["timestamp"]]
|
||||
self.memory_system.generate_memory_detail_map()
|
||||
|
||||
async def update_persona(self):
|
||||
"""Update persona memory"""
|
||||
# Sync memory mappings first
|
||||
self._sync_memory_mappings()
|
||||
|
||||
await self.memory_system.user_persona_memory.update_preference_persona(
|
||||
self.memory_system.user_episodic_memory.topic_episodic_memory_list
|
||||
)
|
||||
await self.memory_system.user_persona_memory.update_attribute_persona(
|
||||
self.memory_system.user_episodic_memory.attribute_episodic_memory_dict
|
||||
)
|
||||
|
||||
|
||||
# ==================== Simplified Usage Example ====================
|
||||
|
||||
async def simple_example():
|
||||
"""Simplified API usage example - processes the same conversation as main()"""
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Simplified API Usage Example")
|
||||
print("=" * 50 + "\n")
|
||||
|
||||
# Read configuration
|
||||
with open('config.yaml', 'r') as f:
|
||||
config = yaml.safe_load(f)
|
||||
|
||||
user_name = "Alice"
|
||||
agent_name = "Bob"
|
||||
|
||||
# Create simplified memory system
|
||||
memory = SimpleMemory(
|
||||
user_name=user_name,
|
||||
agent_name=agent_name,
|
||||
llm_model=config["model"]["llm_model"],
|
||||
api_key=config["model"]["openai_api_key"],
|
||||
base_url=config["model"]["openai_base_url"],
|
||||
memory_dir="./memory_storage_simple", # Use different storage directory
|
||||
)
|
||||
|
||||
# Simulated conversation data (same as main())
|
||||
conversations = [
|
||||
{"speaker": user_name, "message": "I love playing basketball with my friends every weekend.", "timestamp": "2024-01-01 10:00:00"},
|
||||
{"speaker": agent_name, "message": "That sounds great! Basketball is a wonderful way to stay active.", "timestamp": "2024-01-01 10:01:00"},
|
||||
{"speaker": user_name, "message": "Yes! I've been playing for 5 years. My favorite team is the Lakers.", "timestamp": "2024-01-01 10:02:00"},
|
||||
{"speaker": agent_name, "message": "The Lakers have a great history. Do you play any position specifically?", "timestamp": "2024-01-01 10:03:00"},
|
||||
{"speaker": user_name, "message": "I usually play as a point guard. I also started learning guitar last month.", "timestamp": "2024-01-01 10:04:00"},
|
||||
{"speaker": agent_name, "message": "Guitar is a lovely instrument! What kind of music do you want to play?", "timestamp": "2024-01-01 10:05:00"},
|
||||
{"speaker": user_name, "message": "I'm into rock music. My favorite band is Coldplay.", "timestamp": "2024-01-01 10:06:00"},
|
||||
{"speaker": agent_name, "message": "Coldplay has some amazing songs. Do you have a favorite album?", "timestamp": "2024-01-01 10:07:00"},
|
||||
{"speaker": user_name, "message": "I really love 'A Rush of Blood to the Head'. The song 'The Scientist' is my favorite.", "timestamp": "2024-01-01 10:08:00"},
|
||||
{"speaker": agent_name, "message": "That's a classic! Do you also enjoy attending live concerts?", "timestamp": "2024-01-01 10:09:00"},
|
||||
{"speaker": user_name, "message": "Yes! I went to a Coldplay concert last year. It was an amazing experience.", "timestamp": "2024-01-01 10:10:00"},
|
||||
{"speaker": agent_name, "message": "That must have been incredible! Live music is always so energizing.", "timestamp": "2024-01-01 10:11:00"},
|
||||
{"speaker": user_name, "message": "Absolutely! I also enjoy cooking Italian food on weekends.", "timestamp": "2024-01-01 10:12:00"},
|
||||
{"speaker": agent_name, "message": "Italian cuisine is delicious! What's your specialty dish?", "timestamp": "2024-01-01 10:13:00"},
|
||||
{"speaker": user_name, "message": "I make a great homemade pasta with tomato sauce. My family loves it.", "timestamp": "2024-01-01 10:14:00"},
|
||||
{"speaker": agent_name, "message": "That sounds delicious! Cooking for family is always special.", "timestamp": "2024-01-01 10:15:00"},
|
||||
]
|
||||
|
||||
# Add all conversations
|
||||
print("Processing conversations and building memory...")
|
||||
print("-" * 50)
|
||||
|
||||
for conv in conversations:
|
||||
speaker = conv["speaker"]
|
||||
message = conv["message"]
|
||||
timestamp = conv["timestamp"]
|
||||
is_user = (speaker == user_name)
|
||||
|
||||
print(f"{'[User]' if is_user else '[Agent]'} {speaker}: {message[:50]}...")
|
||||
await memory.add_message(message, is_user=is_user, timestamp=timestamp)
|
||||
|
||||
print("-" * 50)
|
||||
print("Conversation processing complete!\n")
|
||||
|
||||
# Update persona memory
|
||||
print("Updating persona memory...")
|
||||
await memory.update_persona()
|
||||
print("Persona memory update complete!\n")
|
||||
|
||||
# Test questions
|
||||
print("=" * 50)
|
||||
print("Memory Retrieval Example")
|
||||
print("=" * 50)
|
||||
|
||||
test_questions = [
|
||||
f"What sport does {user_name} like?",
|
||||
f"What instrument is {user_name} learning?",
|
||||
f"What is {user_name}'s favorite band?",
|
||||
]
|
||||
|
||||
for question in test_questions:
|
||||
print(f"\nQuestion: {question}")
|
||||
print("-" * 40)
|
||||
answer = await memory.query(question)
|
||||
print(f"Answer: {answer}")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Simplified example run complete!")
|
||||
print("=" * 50)
|
||||
|
||||
|
||||
# ==================== Entry Point ====================
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "simple":
|
||||
# Run simplified example
|
||||
print("Running simplified example...")
|
||||
asyncio.run(simple_example())
|
||||
else:
|
||||
# Run full example (default)
|
||||
print("Running full example...")
|
||||
asyncio.run(main())
|
||||
|
||||
# Usage:
|
||||
# python example_usage.py # Run full example
|
||||
# python example_usage.py simple # Run simplified example
|
||||
|
||||
|
||||
BIN
libs/o-mem/images/image1.png
Normal file
BIN
libs/o-mem/images/image1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 145 KiB |
BIN
libs/o-mem/images/workflow.png
Normal file
BIN
libs/o-mem/images/workflow.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 225 KiB |
66751
libs/o-mem/locomo10.json
Normal file
66751
libs/o-mem/locomo10.json
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,381 @@
|
|||
#!/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
|
||||
from datetime import datetime, timedelta
|
||||
import re
|
||||
import openai
|
||||
import time
|
||||
import tiktoken
|
||||
import os
|
||||
import asyncio
|
||||
import aiofiles
|
||||
from tqdm.asyncio import tqdm_asyncio
|
||||
from memory_chain import *
|
||||
from openai import AsyncOpenAI
|
||||
import yaml
|
||||
import argparse
|
||||
import torch
|
||||
import time
|
||||
from typing import List, Union, Dict
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
|
||||
try:
|
||||
with open('config.yaml', 'r') as file:
|
||||
args = yaml.safe_load(file)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print('Error reading the config file')
|
||||
client = AsyncOpenAI(base_url=args["model"]["openai_base_url"],api_key=args["model"]["openai_api_key"])
|
||||
|
||||
|
||||
def get_timestamp():
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||||
|
||||
class ParallelSentenceTransformer:
|
||||
def __init__(self, model: SentenceTransformer):
|
||||
self.model = model
|
||||
# Enable DataParallel only in multi-GPU environment
|
||||
if torch.cuda.device_count() > 1:
|
||||
self.model = torch.nn.DataParallel(model)
|
||||
print(f"Using {torch.cuda.device_count()} GPUs!")
|
||||
else:
|
||||
print("Using single GPU or CPU")
|
||||
|
||||
def encode(self, texts: Union[str, List[str]],
|
||||
batch_size: int = 32,
|
||||
convert_to_tensor: bool = True,
|
||||
**kwargs) -> torch.Tensor:
|
||||
"""
|
||||
Multi-GPU friendly encoding method with automatic batching and cross-device processing.
|
||||
Args:
|
||||
texts: Input text (single string or list)
|
||||
batch_size: Batch size per GPU
|
||||
convert_to_tensor: Whether to return tensor
|
||||
"""
|
||||
# Normalize input format
|
||||
if isinstance(texts, str):
|
||||
texts = [texts]
|
||||
|
||||
# Get current device (primary GPU)
|
||||
device = self.model.device_ids[0] if isinstance(self.model, torch.nn.DataParallel) \
|
||||
else next(self.model.parameters()).device
|
||||
|
||||
# Batch processing (avoid single GPU memory overflow)
|
||||
all_embeddings = []
|
||||
for i in range(0, len(texts), batch_size):
|
||||
batch = texts[i:i + batch_size]
|
||||
|
||||
# Tokenization (must be executed on primary GPU)
|
||||
features = self.model.module.tokenize(batch) if hasattr(self.model, 'module') \
|
||||
else self.model.tokenize(batch)
|
||||
features = {k: v.to(device) for k, v in features.items()}
|
||||
|
||||
# Multi-GPU forward propagation
|
||||
with torch.no_grad():
|
||||
outputs = self.model(features)
|
||||
embeddings = outputs['sentence_embedding']
|
||||
all_embeddings.append(embeddings if convert_to_tensor else embeddings.cpu().numpy())
|
||||
|
||||
# Merge results
|
||||
return torch.cat(all_embeddings, dim=0) if convert_to_tensor \
|
||||
else np.concatenate(all_embeddings, axis=0)
|
||||
|
||||
print("Loading embedding model...")
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
embedding_model = ParallelSentenceTransformer(SentenceTransformer("all-MiniLM-L6-v2").to(device))
|
||||
# path = 'your model'
|
||||
# embedding_model = ParallelSentenceTransformer(SentenceTransformer(path).to(device))
|
||||
async def update_user_profile_from_top_segment(mid_mem, long_mem, sample_id, client):
|
||||
|
||||
print("update the profiles of the users.")
|
||||
|
||||
async def generate_system_response_with_memx(query, short_mem, long_mem, retrieval_queue, long_konwledge, client, sample_id, speaker_a, speaker_b, meta_data,no_mtm,no_ltm,no_wm):
|
||||
|
||||
"""
|
||||
These codes are referenced from memory os.
|
||||
"""
|
||||
|
||||
if no_wm == True:
|
||||
history_text = ""
|
||||
else:
|
||||
history = short_mem.get_all()
|
||||
history_text_list = [
|
||||
f"{speaker_a}: {qa.get('user_input', '')}\n{speaker_b}: {qa.get('agent_response', '')}\nTime: ({qa.get('timestamp', '')})"
|
||||
for qa in history]
|
||||
|
||||
if no_mtm == True:
|
||||
retrieval_text = ""
|
||||
else:
|
||||
retrieval_text = "\n".join([
|
||||
f"【Historical Memory】 {speaker_a}: {page.get('user_input', '')}\n{speaker_b}: {page.get('agent_response', '')}\nTime:({page.get('timestamp', '')})\nConversation chain overview:({page.get('meta_info', '')})\n"
|
||||
for page in retrieval_queue])
|
||||
|
||||
if no_ltm == True:
|
||||
user_profile_text = ""
|
||||
else:
|
||||
profile_obj = long_mem.get_user_profile(sample_id)
|
||||
user_profile_text = str(profile_obj.get("data", "None")) if profile_obj else "None"
|
||||
|
||||
background = f"【User Profile】\n{user_profile_text}\n\n"
|
||||
for kn in long_konwledge:
|
||||
background += f"{kn['knowledge']}\n"
|
||||
background = re.sub(r'(?i)\buser\b', speaker_a, background)
|
||||
background= re.sub(r'(?i)\bassistant\b', speaker_b, background)
|
||||
assistant_knowledge = long_mem.get_assistant_knowledge()
|
||||
assistant_knowledge_text = "【Assistant Knowledge】\n"
|
||||
for ak in assistant_knowledge:
|
||||
assistant_knowledge_text += f"- {ak['knowledge']} ({ak['timestamp']})\n"
|
||||
|
||||
assistant_knowledge_text = re.sub(r'\bI\b', speaker_b, assistant_knowledge_text)
|
||||
|
||||
system_prompt = (
|
||||
f"You are role-playing as {speaker_b} in a conversation with the user is playing is {speaker_a}. "
|
||||
f"Here are some of your character traits and knowledge:\n{assistant_knowledge_text}\n"
|
||||
f"Any content referring to 'User' in the prompt refers to {speaker_a}'s content, and any content referring to 'AI'or 'assiant' refers to {speaker_b}'s content."
|
||||
f"Your task is to answer questions about {speaker_a} or {speaker_b} in an extremely concise manner.\n"
|
||||
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."
|
||||
)
|
||||
|
||||
user_prompt = (
|
||||
f"<CONTEXT>\n"
|
||||
f"Recent conversation between {speaker_a} and {speaker_b}:\n"
|
||||
f"{history_text}\n\n"
|
||||
f"<MEMORY>\n"
|
||||
f"Relevant past conversations:\n"
|
||||
f"{retrieval_text}\n\n"
|
||||
f"<CHARACTER TRAITS>\n"
|
||||
f"Characteristics of {speaker_a}:\n"
|
||||
f"{background}\n\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 = await client.chat_completion(model="gpt-4o-mini", messages=messages, temperature=0.7, max_tokens=2000)
|
||||
return response, system_prompt, user_prompt
|
||||
|
||||
def process_conversation(conversation_data):
|
||||
|
||||
"""
|
||||
These codes are referenced from memory os.
|
||||
Process conversation data from locomo10 format into memory system format.
|
||||
Handles both text-only and image-containing messages.
|
||||
"""
|
||||
|
||||
processed = []
|
||||
speaker_a = conversation_data["speaker_a"]
|
||||
speaker_b = conversation_data["speaker_b"]
|
||||
|
||||
session_keys = [key for key in conversation_data.keys() if key.startswith("session_") and not key.endswith("_date_time")]
|
||||
|
||||
for session_key in session_keys:
|
||||
|
||||
timestamp_key = f"{session_key}_date_time"
|
||||
timestamp = conversation_data.get(timestamp_key, "")
|
||||
|
||||
for dialog in conversation_data[session_key]:
|
||||
|
||||
speaker = dialog["speaker"]
|
||||
text = dialog["text"]
|
||||
|
||||
if "blip_caption" in dialog and dialog["blip_caption"]:
|
||||
text = f"{text} (image description: {dialog['blip_caption']})"
|
||||
|
||||
if speaker == speaker_a:
|
||||
processed.append({speaker_a: text,"timestamp": timestamp})
|
||||
else:
|
||||
processed.append({speaker_b: text, "timestamp": timestamp})
|
||||
|
||||
return processed
|
||||
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
def find_agent_memory_file(directory, idx):
|
||||
|
||||
pattern = re.compile(rf'^.*_agent_working_memory_{idx}\.json$')
|
||||
for filename in os.listdir(directory):
|
||||
if pattern.match(filename):
|
||||
return os.path.join(directory,filename)
|
||||
return None
|
||||
|
||||
def find_user_memory_file(directory, idx):
|
||||
|
||||
pattern = re.compile(rf'^.*_user_working_memory_{idx}\.json$')
|
||||
for filename in os.listdir(directory):
|
||||
if pattern.match(filename):
|
||||
return os.path.join(directory,filename)
|
||||
return None
|
||||
|
||||
async def run_locomo_experiment(idx,args,cmd_args,client):
|
||||
|
||||
os.makedirs("mem_tmp_loco_final", exist_ok=True)
|
||||
try:
|
||||
with open("locomo10.json", "r", encoding="utf-8") as f:
|
||||
dataset = json.load(f)
|
||||
except FileNotFoundError:
|
||||
print("Error: locomo10.json file not found, please ensure it is in the current directory")
|
||||
return
|
||||
except Exception as e:
|
||||
print(f"Error loading dataset: {e}")
|
||||
return
|
||||
|
||||
output_file = cmd_args.response_output_dir+"/HippoIndex_results_"+str(idx)+".json"
|
||||
results = []
|
||||
total_samples = len(dataset)
|
||||
sample = dataset[idx]
|
||||
|
||||
print(f"Processing sample {idx + 1}/{total_samples}: {sample.get('sample_id', 'unknown')}")
|
||||
|
||||
sample_id = sample.get("sample_id", "unknown_sample")
|
||||
conversation_data = sample["conversation"]
|
||||
qa_pairs = sample["qa"]
|
||||
qa_count = len(qa_pairs)
|
||||
processed_dialogs = process_conversation(conversation_data)
|
||||
|
||||
print(f"This sample has {len(processed_dialogs)} dialog turns")
|
||||
print(f"This sample has {len(qa_pairs)} questions")
|
||||
|
||||
if not processed_dialogs:
|
||||
print(f"Sample {sample_id} has no valid conversation data, skipping")
|
||||
return
|
||||
|
||||
speaker_a = conversation_data["speaker_a"]
|
||||
speaker_b = conversation_data["speaker_b"]
|
||||
|
||||
memory_dir = cmd_args.output_dir
|
||||
|
||||
memory_system = MemoryChain(memory_index=idx, llm_model=args["model"]["llm_model"],llm_client = client,embedding_model = embedding_model,
|
||||
user_name= speaker_a, agent_name = speaker_b, cmd_args=cmd_args, args=args, memory_dir = memory_dir)
|
||||
|
||||
memory_manager = MemoryManager(memory_index=idx, memory_system=memory_system,llm_model=args["model"]["llm_model"],llm_client = client,
|
||||
embedding_model = embedding_model,user_name= speaker_a, agent_name = speaker_b, cmd_args=cmd_args, args=args, memory_dir = memory_dir)
|
||||
|
||||
if cmd_args.use_all_memory_cache:
|
||||
await memory_system.read_cache_memory(cmd_args.memory_cache_path)
|
||||
memory_system.generate_memory_detail_map()
|
||||
print("Memory system load cache memory finish")
|
||||
# qa_count = len(qa_pairs)
|
||||
else:
|
||||
print("Stage 1: We indexing the memory base.")
|
||||
for index,dialog in enumerate(processed_dialogs):
|
||||
timestamp = get_timestamp()
|
||||
if speaker_a in dialog:
|
||||
user_speak = True
|
||||
start_time = time.time()
|
||||
await memory_manager.receive_message(message = dialog[speaker_a], client=client,index=index,timestamp=dialog["timestamp"], user_speak=user_speak)
|
||||
end_time = time.time() # Record end time
|
||||
elapsed = end_time - start_time # Calculate elapsed time (seconds)
|
||||
print(f"Receive one new message took: {elapsed:.4f} seconds")
|
||||
else:
|
||||
user_speak = False
|
||||
start_time = time.time()
|
||||
await memory_manager.receive_message(message = dialog[speaker_b],client=client,index=index,timestamp=dialog["timestamp"],user_speak = user_speak)
|
||||
end_time = time.time() # Record end time
|
||||
elapsed = end_time - start_time # Calculate elapsed time (seconds)
|
||||
print(f"Receive one new message took: {elapsed:.4f} seconds")
|
||||
|
||||
await memory_system.agent_persona_memory.update_preference_persona(memory_system.agent_episodic_memory.topic_episodic_memory_list)
|
||||
await memory_system.agent_persona_memory.update_attribute_persona(memory_system.agent_episodic_memory.attribute_episodic_memory_dict)
|
||||
await memory_system.user_persona_memory.update_preference_persona(memory_system.user_episodic_memory.topic_episodic_memory_list)
|
||||
await memory_system.user_persona_memory.update_attribute_persona(memory_system.user_episodic_memory.attribute_episodic_memory_dict)
|
||||
return
|
||||
|
||||
for qa_idx, qa in enumerate(qa_pairs):
|
||||
|
||||
start_time = time.time()
|
||||
print(f"Processing QA {qa_idx + 1}/{qa_count}")
|
||||
|
||||
question = qa["question"]
|
||||
original_answer = qa.get("answer", "")
|
||||
category = qa["category"]
|
||||
evidence = qa.get("evidence", "")
|
||||
|
||||
if(original_answer == ""):
|
||||
# continue
|
||||
original_answer = qa.get("adversarial_answer", "")
|
||||
|
||||
# retrieval_result, user_name, agent_name = memory_manager.retrieve_from_memory_soft_segmentation_v5(question,cmd_args.number_of_retrieval_pieces,cmd_args.drop_threshold)
|
||||
retrieval_result, user_name, agent_name,peak_memory_number,peak_memory_number_increase = memory_manager.retrieve_from_memory_soft_segmentation(question,cmd_args.number_of_retrieval_pieces,cmd_args.drop_threshold)
|
||||
# retrieval_result, user_name, agent_name,peak_memory_number,peak_memory_number_increase = memory_manager.retrieve_from_memory_soft_segmentation_v9_ablation_study(question,cmd_args.number_of_retrieval_pieces,cmd_args.drop_threshold)
|
||||
answer,tokens_consumption = await memory_manager.generate_system_response(question,retrieval_result,client,user_name,agent_name,args["model"]["llm_model"])
|
||||
end_time = time.time()
|
||||
elapsed_time = end_time - start_time
|
||||
|
||||
|
||||
results.append({"time":elapsed_time,"sample_id": sample_id,"user": user_name,"agent": agent_name,"question": question,"answer":answer,"reference_answer": original_answer,"category": category,
|
||||
"evidence": evidence,"persona attributes":retrieval_result["persona attributes"],"fact scores":retrieval_result["fact scores"],"persona facts": retrieval_result["persona facts"],
|
||||
"retrieved context messages":retrieval_result["retrieved context messages"],"fact recovery num":retrieval_result["recover facts num"],"ignored details keywords": retrieval_result["ignored_details_keywords"],
|
||||
"ignored facts":retrieval_result["ignored_facts"],"keyword distribution dict":retrieval_result["keyword distribution dict"],"keyword message":retrieval_result["keyword message"],"original retrievals":retrieval_result["original context message"],"token consumption":tokens_consumption,
|
||||
"peak memory":peak_memory_number,"peak_memory_number_increase":peak_memory_number_increase})
|
||||
|
||||
try:
|
||||
with open(output_file, "w", encoding="utf-8") as f:
|
||||
json.dump(results, f, ensure_ascii=False, indent=2)
|
||||
print(f"Sample {idx + 1} processing complete, results saved to {output_file}")
|
||||
except Exception as e:
|
||||
print(f"Error saving results: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print(f"Final error saving results: {e}")
|
||||
async def run_one(idx,args,cmd_args,client):
|
||||
|
||||
async with semaphore:
|
||||
result = await run_locomo_experiment(idx=idx,args=args,cmd_args=cmd_args,client=client)
|
||||
return result
|
||||
|
||||
semaphore = asyncio.Semaphore(10)
|
||||
|
||||
async def main():
|
||||
|
||||
parser = argparse.ArgumentParser(description='Command line arguments')
|
||||
parser.add_argument('--working_memory_max_size',type=int, default=20, help = 'the maximum size of the working memory')
|
||||
parser.add_argument('--episodic_memory_refresh_rate',type=int, default=5, help = 'the rate ti refresh episodic memory')
|
||||
parser.add_argument('--output_dir',type=str, default="./test_locomo") # 1. Memory generation directory
|
||||
parser.add_argument('--response_output_dir',type=str, default="./responses_locomo") # 2. Results output
|
||||
parser.add_argument('--use_all_memory_cache',type=bool, default=False) # 1.False(start generate mem) 2. True (start retireval)
|
||||
parser.add_argument('--memory_cache_path',type=str, default="./test_locomo")
|
||||
parser.add_argument('--message_understanding_cache',type=bool, default=False) # This is to save money and keep efficiency
|
||||
parser.add_argument('--message_understanding_cache_path',type=str, default="./memory_cache")
|
||||
parser.add_argument('--number_of_retrieval_pieces',type=int, default=10)
|
||||
parser.add_argument('--drop_threshold',type=float, default=0.1)
|
||||
cmd_args = parser.parse_args()
|
||||
tasks = [run_one(idx=p_id, args = args, cmd_args=cmd_args, client=client) for p_id in range(10)]
|
||||
|
||||
import shutil
|
||||
dir_path = cmd_args.output_dir
|
||||
|
||||
|
||||
try:
|
||||
shutil.rmtree(cmd_args.response_output_dir)
|
||||
except:
|
||||
print("No target output folder.")
|
||||
os.mkdir(cmd_args.response_output_dir)
|
||||
|
||||
results = await tqdm_asyncio.gather(*tasks, total=len(tasks))
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
asyncio.run(main())
|
||||
20
libs/o-mem/memory_chain/__init__.py
Normal file
20
libs/o-mem/memory_chain/__init__.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
from .memory_manager import *
|
||||
from .episodic_memory import *
|
||||
from .working_memory import *
|
||||
from .persona_memory import *
|
||||
from .memory import *
|
||||
273
libs/o-mem/memory_chain/episodic_memory.py
Normal file
273
libs/o-mem/memory_chain/episodic_memory.py
Normal file
|
|
@ -0,0 +1,273 @@
|
|||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import json
|
||||
import numpy as np
|
||||
from collections import deque
|
||||
from .utils import *
|
||||
from .prompts import *
|
||||
from FlagEmbedding import FlagAutoModel
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from itertools import combinations
|
||||
from collections import defaultdict
|
||||
import re
|
||||
from collections import defaultdict
|
||||
import re
|
||||
from collections import OrderedDict
|
||||
import random
|
||||
import logging
|
||||
import time
|
||||
|
||||
logging.basicConfig(level=logging.WARNING) #
|
||||
logging.getLogger("FlagEmbedding").setLevel(logging.CRITICAL + 1)
|
||||
logging.getLogger("FlagEmbedding").propagate = False
|
||||
|
||||
class Episodic_Memory:
|
||||
|
||||
def __init__(self,event_episodic_memory_path,topic_episodic_memory_path,ep_cache_list_path ,attribute_episodic_memory_path,fact_episodic_memory_path,
|
||||
user_id,client,llm_model, embedding_model,cmd_args, args):
|
||||
|
||||
self.user_id = user_id
|
||||
self.client = client
|
||||
self.model = llm_model
|
||||
self.embedding_model = embedding_model
|
||||
self.cmd_args = cmd_args
|
||||
self.args = args
|
||||
|
||||
self.episodic_memory_cache_list = [] # Episodic memory cache for storing working memory.
|
||||
self.event_episodic_memory_dict = {} # Episodic memory dictionary concerning different events (e.g., A note-taking experience)
|
||||
self.topic_episodic_memory_list = [] # Episodic memory list concerning different event topics (e.g, multiple times of note-taking experience)
|
||||
self.attribute_episodic_memory_dict = {} # Episodic memory list concerning different attributes of the user
|
||||
self.fact_episodic_memory_dict = {} #Episodic memory list concerning different facts of the user
|
||||
|
||||
self.event_episodic_memory_path = event_episodic_memory_path
|
||||
self.topic_episodic_memory_path = topic_episodic_memory_path
|
||||
self.episodic_memory_cache_list_path = ep_cache_list_path
|
||||
self.attribute_episodic_memory_path = attribute_episodic_memory_path
|
||||
self.fact_episodic_memory_path = fact_episodic_memory_path
|
||||
|
||||
ensure_directory_exists(self.event_episodic_memory_path)
|
||||
ensure_directory_exists(self.topic_episodic_memory_path)
|
||||
ensure_directory_exists(self.episodic_memory_cache_list_path)
|
||||
ensure_directory_exists(self.attribute_episodic_memory_path)
|
||||
ensure_directory_exists(self.fact_episodic_memory_path)
|
||||
|
||||
async def evolve_event_episodic_memory(self,message_understanding,action,target):
|
||||
|
||||
self.episodic_memory_cache_list.append(message_understanding)
|
||||
self._save_wm_cache_episodic_memory()
|
||||
|
||||
index = message_understanding["index"]
|
||||
|
||||
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
|
||||
self.event_episodic_memory_dict[target] += "The "+ str(index)+" round message: "+ message_understanding["emotions"]+"; "
|
||||
if action.upper() == "ADD":
|
||||
self.event_episodic_memory_dict[message_understanding["topics"]] = "The "+ str(index)+" round attitude: "+ message_understanding["emotions"]+"; "
|
||||
|
||||
self._save_event_episodic_memory()
|
||||
|
||||
async def evolve_fact_episodic_memory(self,message_understanding,action,target):
|
||||
|
||||
index = message_understanding["index"]
|
||||
|
||||
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
|
||||
self.fact_episodic_memory_dict[target] += "The "+ str(index)+" round fact: "+ message_understanding["fact"]+"; "
|
||||
if action.upper() == "ADD":
|
||||
self.fact_episodic_memory_dict[message_understanding["fact"]] = "The "+ str(index)+" round fact: "+ message_understanding["fact"]+"; "
|
||||
|
||||
self._save_fact_episodic_memory()
|
||||
|
||||
async def evolve_attr_episodic_memory(self,message_attribute,action,target,message_index):
|
||||
|
||||
index = message_index
|
||||
|
||||
if action.upper() == "UPDATE" or action.upper() == "IGNORE":
|
||||
self.attribute_episodic_memory_dict[target] += "The "+ str(index)+" round attribute: "+ message_attribute +"; "
|
||||
if action.upper() == "ADD":
|
||||
self.attribute_episodic_memory_dict[message_attribute] = "The "+ str(index)+" round attribute: "+ message_attribute +"; "
|
||||
|
||||
self._save_attr_episodic_memory()
|
||||
|
||||
async def evolve_topic_episodic_memory(self):
|
||||
|
||||
self.topic_episodic_memory_list = []
|
||||
event_episodic_memory_dict_keys = list(self.event_episodic_memory_dict.keys())
|
||||
topic_clusters = self.cluster_related_topics(self.find_top_similar_keys(event_episodic_memory_dict_keys, self.embedding_model))
|
||||
grouped_em_results = [] # Divide the episodic memory into groups.
|
||||
|
||||
for cluster in topic_clusters:
|
||||
|
||||
message = {}
|
||||
for event_name in cluster:
|
||||
message[event_name] = self.value_find_topic(self.episodic_memory_cache_list,event_name) # How to deal with this part ?
|
||||
|
||||
# print(message)
|
||||
episodic_memory_merge_message = [{"role": "system", "content": Preference_Merge_System_PROMPT},{"role": "user", "content": Preference_Merge_User_PROMPT.format(Topic_Groups=str(message))}]
|
||||
|
||||
response = ""
|
||||
while response == "":
|
||||
try:
|
||||
response = await self.client.chat.completions.create(model=self.model, messages = episodic_memory_merge_message, temperature = 0.3)
|
||||
current_results = json.loads(response.choices[0].message.content)
|
||||
for group_name in current_results["Grouped Topics"].keys():
|
||||
current_dict_result = {}
|
||||
current_dict_result["group_name"] = group_name
|
||||
for event in current_results["Grouped Topics"][group_name]:
|
||||
current_dict_result[event] = self.event_episodic_memory_dict[event]
|
||||
pattern = r"The (\d+) round (?:attitude|message):.*?(Positive|Negative)"
|
||||
result = {}
|
||||
for key,value in current_dict_result.items():
|
||||
matches = re.findall(pattern, str(value))
|
||||
for round_num, attitude in matches:
|
||||
result[int(round_num)] = attitude + " "+ self.value_find_index(self.episodic_memory_cache_list,str(round_num)) # 转为整数便于排序
|
||||
sorted_result = OrderedDict(sorted(result.items()))
|
||||
current_dict_result["Overall Attitude"]= sorted_result
|
||||
self.topic_episodic_memory_list.append(current_dict_result)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
response == ""
|
||||
print(f"Error generating profile: {str(e)}")
|
||||
continue
|
||||
|
||||
self._save_topic_episodic_memory()
|
||||
|
||||
|
||||
|
||||
def _save_event_episodic_memory(self):
|
||||
|
||||
with open(self.event_episodic_memory_path,'w') as f:
|
||||
json.dump(self.event_episodic_memory_dict, f, indent=4)
|
||||
|
||||
def _save_fact_episodic_memory(self):
|
||||
|
||||
with open(self.fact_episodic_memory_path,'w') as f:
|
||||
json.dump(self.fact_episodic_memory_dict, f, indent=4)
|
||||
|
||||
def _save_attr_episodic_memory(self):
|
||||
|
||||
with open(self.attribute_episodic_memory_path,'w') as f:
|
||||
json.dump(self.attribute_episodic_memory_dict, f, indent=4)
|
||||
|
||||
|
||||
|
||||
|
||||
def _save_topic_episodic_memory(self):
|
||||
|
||||
with open(self.topic_episodic_memory_path,'w') as f:
|
||||
json.dump(self.topic_episodic_memory_list, f, indent=4)
|
||||
|
||||
def _save_wm_cache_episodic_memory(self):
|
||||
|
||||
with open(self.episodic_memory_cache_list_path,'w') as f:
|
||||
json.dump(self.episodic_memory_cache_list, f, indent=4)
|
||||
|
||||
def find_top_similar_keys(self,all_keys, embedding_model):
|
||||
|
||||
key_embeddings = embedding_model.encode(all_keys)
|
||||
key_pairs = list(combinations(range(len(all_keys)), 2))
|
||||
best_matches = {}
|
||||
|
||||
for i, j in key_pairs:
|
||||
key1 = all_keys[i]
|
||||
key2 = all_keys[j]
|
||||
sim = float(key_embeddings[i] @ key_embeddings[j].T)
|
||||
if key1 not in best_matches or sim > best_matches[key1]['similarity']:
|
||||
best_matches[key1] = {'key1': key1, 'key2': key2, 'similarity': sim}
|
||||
if key2 not in best_matches or sim > best_matches[key2]['similarity']:
|
||||
best_matches[key2] = {'key1': key2, 'key2': key1, 'similarity': sim}
|
||||
|
||||
results = list(best_matches.values())
|
||||
results.sort(key=lambda x: x['similarity'], reverse=True)
|
||||
return results
|
||||
|
||||
def cluster_related_topics(self,data):
|
||||
|
||||
parent = {}
|
||||
def find(node):
|
||||
if parent[node] != node:
|
||||
parent[node] = find(parent[node])
|
||||
return parent[node]
|
||||
def union(node1, node2):
|
||||
root1 = find(node1)
|
||||
root2 = find(node2)
|
||||
if root1 != root2:
|
||||
parent[root2] = root1
|
||||
|
||||
for item in data:
|
||||
key1, key2 = item['key1'], item['key2']
|
||||
if key1 not in parent:
|
||||
parent[key1] = key1
|
||||
if key2 not in parent:
|
||||
parent[key2] = key2
|
||||
|
||||
for item in data:
|
||||
key1, key2 = item['key1'], item['key2']
|
||||
union(key1, key2)
|
||||
|
||||
clusters = defaultdict(list)
|
||||
for node in parent:
|
||||
clusters[find(node)].append(node)
|
||||
|
||||
result = [cluster for cluster in clusters.values() if len(cluster) > 1]
|
||||
|
||||
return result
|
||||
def value_find_topic(self,dict_list,target_value):
|
||||
|
||||
for item in dict_list:
|
||||
if item["topics"] == target_value:
|
||||
return item["message"]
|
||||
def value_find_index(self,dict_list,target_value):
|
||||
|
||||
for item in dict_list:
|
||||
if item["index"] == target_value:
|
||||
return item["message"]
|
||||
|
||||
for item in dict_list:
|
||||
if item["index"] == int(target_value):
|
||||
return item["message"]
|
||||
|
||||
|
||||
def read_cache(self,topic_episodic_path,event_episodic_path,episodic_cache_path,fact_episodic_path,attr_episodic_path):
|
||||
|
||||
print(topic_episodic_path)
|
||||
print(event_episodic_path)
|
||||
print(episodic_cache_path)
|
||||
print(fact_episodic_path)
|
||||
print(attr_episodic_path)
|
||||
|
||||
with open(topic_episodic_path, 'r', encoding='utf-8') as f:
|
||||
self.topic_episodic_memory_list = json.load(f)
|
||||
|
||||
with open(event_episodic_path,'r', encoding='utf-8') as f:
|
||||
self.event_episodic_memory_dict = json.load(f)
|
||||
|
||||
with open(episodic_cache_path,'r', encoding='utf-8') as f:
|
||||
self.episodic_memory_cache_list = json.load(f)
|
||||
|
||||
with open(fact_episodic_path,'r', encoding='utf-8') as f:
|
||||
self.fact_episodic_memory_dict = json.load(f)
|
||||
|
||||
with open(attr_episodic_path,'r', encoding='utf-8') as f:
|
||||
self.attribute_episodic_memory_dict = json.load(f)
|
||||
|
||||
self._save_event_episodic_memory()
|
||||
self._save_topic_episodic_memory()
|
||||
self._save_wm_cache_episodic_memory()
|
||||
self._save_attr_episodic_memory()
|
||||
self._save_fact_episodic_memory()
|
||||
|
||||
|
||||
|
||||
596
libs/o-mem/memory_chain/memory.py
Normal file
596
libs/o-mem/memory_chain/memory.py
Normal file
|
|
@ -0,0 +1,596 @@
|
|||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import os
|
||||
import json
|
||||
from .utils import *
|
||||
|
||||
from .prompts import *
|
||||
from .memory_manager import *
|
||||
from .persona_memory import *
|
||||
from .working_memory import *
|
||||
from .memory_manager import *
|
||||
from .episodic_memory import *
|
||||
from datetime import datetime
|
||||
import string
|
||||
from collections import defaultdict
|
||||
|
||||
# Heat threshold for triggering profile/knowledge update from mid-term memory
|
||||
H_PROFILE_UPDATE_THRESHOLD = 5.0
|
||||
DEFAULT_ASSISTANT_ID = "default_assistant_profile"
|
||||
|
||||
def get_current_time():
|
||||
now = datetime.now()
|
||||
local_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return local_time_str
|
||||
|
||||
class MemoryChain:
|
||||
|
||||
def __init__(self,memory_index,llm_model,llm_client,embedding_model,user_name,agent_name,args,cmd_args,memory_dir):
|
||||
|
||||
|
||||
self.idx = memory_index
|
||||
self.args = args
|
||||
self.cmd_args = cmd_args
|
||||
self.client = llm_client
|
||||
self.llm_model = llm_model
|
||||
self.embedding_model = embedding_model
|
||||
self.user_name = user_name
|
||||
self.agent_name = agent_name
|
||||
self.memory_dir = memory_dir
|
||||
current_time = get_current_time()
|
||||
|
||||
self.user_topic_message_dict = {}
|
||||
self.agent_topic_message_dict = {}
|
||||
self.user_detail_dict = defaultdict(list)
|
||||
self.agent_detail_dict = defaultdict(list)
|
||||
|
||||
|
||||
print("The No."+str(self.idx)+" sample "+user_name+" and "+ agent_name+ "'s memory system has been established")
|
||||
|
||||
user_working_memory_path = os.path.join(self.memory_dir, "user_working_memory_"+str(self.idx)+".json") # User working memory
|
||||
agent_working_memory_path = os.path.join(self.memory_dir, "agent_working_memory_"+str(self.idx)+".json") # Agent working memory
|
||||
|
||||
user_event_episodic_memory_path = os.path.join(self.memory_dir, "user_event_episodic_memory_"+str(self.idx)+".json")
|
||||
agent_event_episodic_memory_path = os.path.join(self.memory_dir, "agent_event_episodic_memory_"+str(self.idx)+".json")
|
||||
|
||||
user_fact_episodic_memory_path = os.path.join(self.memory_dir, "user_fact_episodic_memory_"+str(self.idx)+".json")
|
||||
agent_fact_episodic_memory_path = os.path.join(self.memory_dir, "agent_fact_episodic_memory_"+str(self.idx)+".json")
|
||||
|
||||
user_attribute_episodic_memory_path = os.path.join(self.memory_dir, "user_attribute_episodic_memory_"+str(self.idx)+".json")
|
||||
agent_attribute_episodic_memory_path = os.path.join(self.memory_dir, "agent_attribute_episodic_memory_"+str(self.idx)+".json")
|
||||
|
||||
user_topic_episodic_memory_path = os.path.join(self.memory_dir, "user_topic_episodic_memory_"+str(self.idx)+".json")
|
||||
agent_topic_episodic_memory_path = os.path.join(self.memory_dir, "agent_topic_episodic_memory_"+str(self.idx)+".json")
|
||||
|
||||
user_episodic_memory_wm_cache_path = os.path.join(self.memory_dir, "user_wm_cache_episodic_memory_"+str(self.idx)+".json")
|
||||
agent_episodic_memory_wm_cache_path = os.path.join(self.memory_dir, "agent_wm_cache_episodic_memory_"+str(self.idx)+".json")
|
||||
|
||||
user_persona_memory_preference_path = os.path.join(self.memory_dir, "user_persona_memory_preference_"+str(self.idx)+".json")
|
||||
agent_persona_memory_preference_path = os.path.join(self.memory_dir, "agent_persona_memory_preference_"+str(self.idx)+".json")
|
||||
|
||||
user_persona_memory_fact_path = os.path.join(self.memory_dir, "user_persona_memory_fact_"+str(self.idx)+".json")
|
||||
agent_persona_memory_fact_path = os.path.join(self.memory_dir, "agent_persona_memory_fact_"+str(self.idx)+".json")
|
||||
|
||||
user_persona_memory_attr_path = os.path.join(self.memory_dir, "user_persona_memory_attr_"+str(self.idx)+".json")
|
||||
agent_persona_memory_attr_path = os.path.join(self.memory_dir, "agent_persona_memory_attr_"+str(self.idx)+".json")
|
||||
|
||||
self.user_memory_detail_path = os.path.join(self.memory_dir, "user_detail_"+str(self.idx)+".json")
|
||||
self.agent_memory_detail_path = os.path.join(self.memory_dir, "agent_detail_"+str(self.idx)+".json")
|
||||
|
||||
ensure_directory_exists(user_working_memory_path)
|
||||
ensure_directory_exists(agent_working_memory_path)
|
||||
ensure_directory_exists(user_event_episodic_memory_path)
|
||||
ensure_directory_exists(agent_event_episodic_memory_path)
|
||||
ensure_directory_exists(user_topic_episodic_memory_path)
|
||||
ensure_directory_exists(agent_topic_episodic_memory_path)
|
||||
ensure_directory_exists(user_episodic_memory_wm_cache_path)
|
||||
ensure_directory_exists(agent_episodic_memory_wm_cache_path )
|
||||
ensure_directory_exists(user_persona_memory_preference_path)
|
||||
ensure_directory_exists(agent_persona_memory_preference_path)
|
||||
ensure_directory_exists(user_persona_memory_fact_path)
|
||||
ensure_directory_exists(agent_persona_memory_fact_path)
|
||||
ensure_directory_exists(user_fact_episodic_memory_path)
|
||||
ensure_directory_exists(user_attribute_episodic_memory_path)
|
||||
ensure_directory_exists(agent_fact_episodic_memory_path )
|
||||
ensure_directory_exists(agent_attribute_episodic_memory_path)
|
||||
|
||||
self.user_working_memory = Working_Memory(working_memory_path = user_working_memory_path, user_id = self.user_name, model=self.llm_model,
|
||||
working_memory_max_size = cmd_args.working_memory_max_size, client=self.client,refresh_rate= cmd_args.episodic_memory_refresh_rate)
|
||||
|
||||
self.agent_working_memory = Working_Memory(working_memory_path = agent_working_memory_path, user_id = self.agent_name, model=self.llm_model,
|
||||
working_memory_max_size = cmd_args.working_memory_max_size, client=self.client,refresh_rate= cmd_args.episodic_memory_refresh_rate)
|
||||
|
||||
self.user_episodic_memory = Episodic_Memory(event_episodic_memory_path = user_event_episodic_memory_path, topic_episodic_memory_path = user_topic_episodic_memory_path,
|
||||
ep_cache_list_path = user_episodic_memory_wm_cache_path, user_id = user_name, client = self.client, llm_model = self.llm_model, embedding_model = self.embedding_model,
|
||||
fact_episodic_memory_path = user_fact_episodic_memory_path,attribute_episodic_memory_path = user_attribute_episodic_memory_path,cmd_args = self.cmd_args, args = self.args)
|
||||
|
||||
self.agent_episodic_memory = Episodic_Memory(event_episodic_memory_path = agent_event_episodic_memory_path, topic_episodic_memory_path = agent_topic_episodic_memory_path,
|
||||
ep_cache_list_path = agent_episodic_memory_wm_cache_path, user_id = agent_name, client = self.client, llm_model = self.llm_model, embedding_model = self.embedding_model,
|
||||
fact_episodic_memory_path = agent_fact_episodic_memory_path,attribute_episodic_memory_path = agent_attribute_episodic_memory_path,cmd_args = self.cmd_args, args = self.args)
|
||||
|
||||
self.user_persona_memory = Persona_Memory(persona_memory_preference_path = user_persona_memory_preference_path, persona_memory_fact_path = user_persona_memory_fact_path,
|
||||
user_id = self.user_name, llm_model=self.llm_model, client=self.client,init_persona_information="",embedding_model=self.embedding_model,
|
||||
persona_memory_attr_path = user_persona_memory_attr_path)
|
||||
|
||||
self.agent_persona_memory = Persona_Memory(persona_memory_preference_path = agent_persona_memory_preference_path, persona_memory_fact_path = agent_persona_memory_fact_path,
|
||||
user_id = self.agent_name, llm_model=self.llm_model, client=self.client,init_persona_information="",embedding_model=self.embedding_model,
|
||||
persona_memory_attr_path = agent_persona_memory_attr_path)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
for message in list(self.user_working_memory.working_memory_queue.queue)+self.user_episodic_memory.episodic_memory_cache_list:
|
||||
self.user_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||
|
||||
for message in list(self.agent_working_memory.working_memory_queue.queue)+self.agent_episodic_memory.episodic_memory_cache_list:
|
||||
self.agent_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||
|
||||
def generate_memory_detail_map(self):
|
||||
|
||||
stop_words = {
|
||||
'a', 'an', 'the', 'and', 'or', 'but', 'if', 'because', 'as', 'what',
|
||||
'which', 'this', 'that', 'these', 'those', 'then', 'just', 'so', 'than',
|
||||
'such', 'both', 'through', 'about', 'for', 'is', 'of', 'while', 'during',
|
||||
'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under',
|
||||
'again', 'further', 'then', 'once', 'here', 'there', 'when', 'where',
|
||||
'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
|
||||
'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same',
|
||||
'so', 'than', 'too', 'very', 'can', 'will', 'just', 'should', 'now',
|
||||
'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her',
|
||||
'us', 'them', 'my', 'your', 'his', 'its', 'our', 'their', 'mine',
|
||||
'yours', 'hers', 'ours', 'theirs', 'myself', 'yourself', 'himself',
|
||||
'herself', 'itself', 'ourselves', 'yourselves', 'themselves',self.user_name,self.agent_name}
|
||||
|
||||
print("Generating Detail Map")
|
||||
user_full_memory_list = [(message["index"],message["raw_message"]) for message in list(self.user_working_memory.working_memory_queue.queue) + self.user_episodic_memory.episodic_memory_cache_list]
|
||||
agent_full_memory_list = [(message["index"],message["raw_message"]) for message in list(self.agent_working_memory.working_memory_queue.queue) + self.agent_episodic_memory.episodic_memory_cache_list]
|
||||
|
||||
# round = 0
|
||||
for index,text in user_full_memory_list:
|
||||
text = text.translate(str.maketrans('', '', string.punctuation))
|
||||
word_list = text.split()
|
||||
for word in word_list:
|
||||
word = word.lower()
|
||||
if word not in stop_words:
|
||||
self.user_detail_dict[word].append(index)
|
||||
|
||||
for index,text in agent_full_memory_list:
|
||||
text = text.translate(str.maketrans('', '', string.punctuation))
|
||||
word_list = text.split()
|
||||
for word in word_list:
|
||||
word = word.lower()
|
||||
if word not in stop_words:
|
||||
self.agent_detail_dict[word].append(index)
|
||||
|
||||
with open(self.user_memory_detail_path, 'w', encoding='utf-8') as f:
|
||||
json.dump( self.user_detail_dict, f, ensure_ascii=False, indent=4)
|
||||
|
||||
with open(self.agent_memory_detail_path, 'w', encoding='utf-8') as f:
|
||||
json.dump( self.agent_detail_dict, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def find_memory_file(self,directory, pattern):
|
||||
|
||||
regex = re.compile(f"{pattern}$")
|
||||
for filename in os.listdir(directory):
|
||||
if regex.search(filename):
|
||||
return os.path.join(directory,filename)
|
||||
return None
|
||||
async def read_cache_memory(self, cache_memory_dir):
|
||||
|
||||
cache_user_working_memory_pattern = f"user_working_memory_{self.idx}.json"
|
||||
cache_agent_working_memory_pattern = f"agent_working_memory_{self.idx}.json"
|
||||
|
||||
cache_user_topic_episodic_memory_pattern = f"user_topic_episodic_memory_{self.idx}.json"
|
||||
cache_agent_topic_episodic_memory_pattern = f"agent_topic_episodic_memory_{self.idx}.json"
|
||||
|
||||
cache_user_event_episodic_memory_pattern = f"user_event_episodic_memory_{self.idx}.json"
|
||||
cache_agent_event_episodic_memory_pattern = f"agent_event_episodic_memory_{self.idx}.json"
|
||||
|
||||
cache_user_fact_episodic_memory_pattern = f"user_fact_episodic_memory_{self.idx}.json"
|
||||
cache_agent_fact_episodic_memory_pattern = f"agent_fact_episodic_memory_{self.idx}.json"
|
||||
|
||||
cache_user_attr_episodic_memory_pattern = f"user_attribute_episodic_memory_{self.idx}.json"
|
||||
cache_agent_attr_episodic_memory_pattern = f"agent_attribute_episodic_memory_{self.idx}.json"
|
||||
|
||||
cache_user_wm_cache_episodic_memory_pattern = f"user_wm_cache_episodic_memory_{self.idx}.json"
|
||||
cache_agent_wm_cache_episodic_memory_pattern = f"agent_wm_cache_episodic_memory_{self.idx}.json"
|
||||
|
||||
cache_user_preferences_persona_memory_pattern = f"user_persona_memory_preference_{self.idx}.json"
|
||||
cache_agent_preferences_persona_memory_pattern = f"agent_persona_memory_preference_{self.idx}.json"
|
||||
|
||||
cache_user_attributes_persona_memory_pattern = f"user_persona_memory_attr_{self.idx}.json"
|
||||
cache_agent_attributes_persona_memory_pattern = f"agent_persona_memory_attr_{self.idx}.json"
|
||||
|
||||
|
||||
# fact_episodic_path,attr_episodic_path
|
||||
|
||||
self.user_working_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_working_memory_pattern))
|
||||
self.agent_working_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_working_memory_pattern))
|
||||
|
||||
self.user_episodic_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_topic_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,
|
||||
cache_user_event_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,cache_user_wm_cache_episodic_memory_pattern),
|
||||
self.find_memory_file(cache_memory_dir,cache_user_fact_episodic_memory_pattern),
|
||||
self.find_memory_file(cache_memory_dir,cache_user_attr_episodic_memory_pattern))
|
||||
|
||||
self.agent_episodic_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_topic_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,
|
||||
cache_agent_event_episodic_memory_pattern),self.find_memory_file(cache_memory_dir,cache_agent_wm_cache_episodic_memory_pattern),
|
||||
self.find_memory_file(cache_memory_dir,cache_agent_fact_episodic_memory_pattern),
|
||||
self.find_memory_file(cache_memory_dir,cache_agent_attr_episodic_memory_pattern))
|
||||
|
||||
self.user_persona_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_user_preferences_persona_memory_pattern),
|
||||
self.find_memory_file(cache_memory_dir,cache_user_attributes_persona_memory_pattern))
|
||||
|
||||
self.agent_persona_memory.read_cache(self.find_memory_file(cache_memory_dir,cache_agent_preferences_persona_memory_pattern),
|
||||
self.find_memory_file(cache_memory_dir,cache_agent_attributes_persona_memory_pattern))
|
||||
|
||||
self.user_topic_message_dict = {}
|
||||
self.agent_topic_message_dict = {}
|
||||
|
||||
for message in list(self.user_working_memory.working_memory_queue.queue)+self.user_episodic_memory.episodic_memory_cache_list:
|
||||
self.user_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||
|
||||
for message in list(self.agent_working_memory.working_memory_queue.queue)+self.agent_episodic_memory.episodic_memory_cache_list:
|
||||
self.agent_topic_message_dict[message["topics"]] = [message["raw_message"],message["timestamp"]]
|
||||
|
||||
|
||||
|
||||
async def receive_user_message(self,message,round_index,client,timestamp):
|
||||
|
||||
await self.user_memory_manager.understand_message(message,round_index,client)
|
||||
|
||||
async def receive_agent_message(self,message,round_index,client,timestamp):
|
||||
|
||||
await self.agent_memory_manager.understand_message(message,round_index,client)
|
||||
|
||||
async def receive_user_message_v2(self,previous_query,user_message,round_index,client):
|
||||
|
||||
await self.user_memory_manager.understand_message(message,round_index,client)
|
||||
|
||||
async def receive_agent_message_v2(self,previous_query, user_message,round_index,client):
|
||||
|
||||
await self.agent_memory_manager.understand_message(message,round_index,client)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def get_response_base_on_profile_reorganization(self,query,all_options):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query through reorganizing the latest profile.
|
||||
"""
|
||||
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
# raw_reorganized_user_profile_text, original_profile = self.personal_memory.reorganize_profile_base_on_query(query)
|
||||
raw_reorganized_user_profile_text, original_profile = self.personal_memory.reorganize_profile_base_on_query_and_option(query,all_options)
|
||||
reorganized_profile = f"【User Profile】\n{raw_reorganized_user_profile_text}"
|
||||
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT.format(background=reorganized_profile)
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(question= query,all_options=all_options)
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
response_content = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0.7,
|
||||
max_tokens=1500 # As in original main
|
||||
)
|
||||
|
||||
self.receive_message(query,self.user_id,"Question",self.client)
|
||||
|
||||
return response_content.choices[0].message.content, reorganized_profile, original_profile
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def get_response_base_on_profile(self,query,all_options):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the latest profile.
|
||||
"""
|
||||
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
|
||||
raw_user_profile_text = self.personal_memory.get_user_profile_data()
|
||||
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||
background=background_context,
|
||||
question= query,
|
||||
all_options=all_options
|
||||
)
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
response_content = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0.7,
|
||||
max_tokens=1500 # As in original main
|
||||
)
|
||||
|
||||
self.receive_message(query,self.user_id,"Question",self.client)
|
||||
return response_content.choices[0].message.content, background_context
|
||||
|
||||
|
||||
async def get_response_base_on_memx_profile(self,query,all_options):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the latest profile.
|
||||
"""
|
||||
|
||||
persona_profile = self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list)
|
||||
|
||||
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_MEMX_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_MEMX_USER_PROMPT.format(
|
||||
profile = persona_profile,
|
||||
question= query,
|
||||
all_options=all_options
|
||||
)
|
||||
|
||||
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
response_content = await self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0.7,
|
||||
max_tokens=1500 # As in original main
|
||||
)
|
||||
|
||||
return response_content.choices[0].message.content, persona_profile
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def get_response_base_on_profile(self,query,all_options):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the profile.
|
||||
"""
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
|
||||
# 1. Retrieve context
|
||||
raw_user_profile_text = self.personal_memory.get_user_profile_data()
|
||||
|
||||
|
||||
|
||||
|
||||
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||
background=background_context,
|
||||
question= query,
|
||||
all_options=all_options
|
||||
)
|
||||
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
response_content = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0.7,
|
||||
max_tokens=1500 # As in original main
|
||||
)
|
||||
|
||||
|
||||
self.receive_message(query,self.user_id,"Question",self.client)
|
||||
return response_content.choices[0].message.content, background_context
|
||||
|
||||
def get_response_base_on_profile_v2(self,query,all_options):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the profile.
|
||||
"""
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
|
||||
# 1. Retrieve context
|
||||
|
||||
self.personal_memory.merge_user_trace_profile_into_user_preference_profile()
|
||||
|
||||
raw_user_profile_text = self.personal_memory.get_user_profile_data()
|
||||
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||
|
||||
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||
background=background_context,
|
||||
question= query,
|
||||
all_options=all_options)
|
||||
|
||||
messages = [{"role": "user", "content": user_prompt_text}]
|
||||
|
||||
# 2. Call LLM for response
|
||||
# print("Memoryos: Calling LLM for final response generation...")
|
||||
response_content = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0,
|
||||
max_tokens=16000
|
||||
)
|
||||
|
||||
# 3. Add this interaction to memory
|
||||
self.receive_message(query,self.user_id,"Question",self.client)
|
||||
return response_content.choices[0].message.content, background_context
|
||||
|
||||
async def get_response_base_on_recent_message(self,query,all_options,working_memory):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the profile.
|
||||
"""
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
|
||||
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_USER_PROMPT.format(messages= working_memory,question= query,all_options=all_options)
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
# 2. Call LLM for response
|
||||
# print("Memoryos: Calling LLM for final response generation...")
|
||||
response_content = await self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0,
|
||||
max_tokens=16000
|
||||
)
|
||||
|
||||
# 3. Add this interaction to memory
|
||||
return response_content.choices[0].message.content
|
||||
|
||||
async def get_response_base_on_init_persona(self,query,all_options,init_persona):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the profile.
|
||||
"""
|
||||
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
|
||||
# system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_WM_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_ONLY_INIT_PROFILE_PROMPT.format(persona= init_persona,question= query,all_options=all_options)
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
# 2. Call LLM for response
|
||||
# print("Memoryos: Calling LLM for final response generation...")
|
||||
response_content = await self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0,
|
||||
max_tokens=16000
|
||||
)
|
||||
|
||||
# 3. Add this interaction to memory
|
||||
return response_content.choices[0].message.content
|
||||
|
||||
|
||||
def get_response_base_on_reorganized_profile(self,query,all_options,reorganzied_profile):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the profile.
|
||||
"""
|
||||
print(f"Generating response for query: '{query[:50]}...'")
|
||||
|
||||
# 1. Retrieve context
|
||||
|
||||
raw_user_profile_text = str(reorganzied_profile)
|
||||
background_context = f"【User Profile】\n{raw_user_profile_text}"
|
||||
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_USER_PROMPT.format(
|
||||
background=background_context,
|
||||
question= query,
|
||||
all_options=all_options
|
||||
)
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt_text},
|
||||
{"role": "user", "content": user_prompt_text}
|
||||
]
|
||||
|
||||
# 2. Call LLM for response
|
||||
# print("Memoryos: Calling LLM for final response generation...")
|
||||
response_content = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0.7,
|
||||
max_tokens=1500 # As in original main
|
||||
)
|
||||
|
||||
# 3. Add this interaction to memory
|
||||
self.receive_message(query,self.user_id,"Question",self.client)
|
||||
return response_content.choices[0].message.content, self.personal_memory.get_user_profile_data()
|
||||
|
||||
|
||||
|
||||
|
||||
def reorganize_profile_base_on_message(self,message):
|
||||
|
||||
"""
|
||||
Only extract the sections of the profile which are important for current user message as well as provide the reasons behind it.
|
||||
"""
|
||||
|
||||
print(f"Reorganize the profile base on the user message: {message[:50]}...")
|
||||
|
||||
profile = self.personal_memory.latest_profile
|
||||
system_prompt_text = Profile_Reorganization_SYSTEM_PROMPT
|
||||
user_prompt_text = Profile_Reorganization_USER_PROMPT.format(Message = message,Profile = profile)
|
||||
|
||||
messages = [{"role": "system", "content": system_prompt_text},{"role": "user", "content": user_prompt_text}]
|
||||
reorganized_profile = ""
|
||||
|
||||
while(reorganized_profile==""):
|
||||
response = self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=0.7,
|
||||
max_tokens=2000)
|
||||
reorganized_profile = json.loads(response.choices[0].message.content)
|
||||
|
||||
print(reorganized_profile)
|
||||
return reorganized_profile["relevant_profile"],reorganized_profile["summary"]
|
||||
|
||||
|
||||
async def get_response_base_on_episodic_memory_retrieval(self,query,all_options):
|
||||
|
||||
"""
|
||||
Generates a response to the user's query base on the latest profile.
|
||||
"""
|
||||
|
||||
# persona_profile = self.persona_memory.generate_preference_persona(self.episodic_memory.topic_episodic_memory_list)
|
||||
experience = str(self.memory_manager.retrieve_episodic_memory(query))
|
||||
system_prompt_text = GENERATE_SYSTEM_RESPONSE_EP_RAG_SYSTEM_PROMPT
|
||||
user_prompt_text = GENERATE_SYSTEM_RESPONSE_EP_RAG_USER_PROMPT.format(experience = experience,question= query,all_options=all_options)
|
||||
messages = [{"role": "system", "content": system_prompt_text},{"role": "user", "content": user_prompt_text}]
|
||||
response_content = await self.client.chat.completions.create(model=self.model, messages=messages, temperature=0.7, max_tokens=1500)
|
||||
|
||||
# self.receive_message(query,self.user_id,"Question",self.client)
|
||||
return response_content.choices[0].message.content, experience
|
||||
1057
libs/o-mem/memory_chain/memory_manager.py
Normal file
1057
libs/o-mem/memory_chain/memory_manager.py
Normal file
File diff suppressed because it is too large
Load diff
224
libs/o-mem/memory_chain/persona_memory.py
Normal file
224
libs/o-mem/memory_chain/persona_memory.py
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import json
|
||||
import numpy as np
|
||||
# import faiss
|
||||
from collections import deque
|
||||
from .utils import *
|
||||
from .prompts import *
|
||||
from FlagEmbedding import FlagAutoModel
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from itertools import combinations
|
||||
from collections import defaultdict
|
||||
import json
|
||||
from collections import defaultdict
|
||||
|
||||
class Persona_Memory:
|
||||
|
||||
def __init__(self, persona_memory_preference_path, persona_memory_fact_path,persona_memory_attr_path,
|
||||
user_id,llm_model,client,init_persona_information,embedding_model):
|
||||
|
||||
self.user_id = user_id
|
||||
self.client = client
|
||||
self.init_persona_information = init_persona_information
|
||||
self.llm_model = llm_model
|
||||
self.persona_memory_preference_path = persona_memory_preference_path
|
||||
self.persona_memory_fact_path = persona_memory_fact_path
|
||||
self.persona_memory_attr_path = persona_memory_attr_path
|
||||
self.preference_persona = []
|
||||
self.fact_persona = []
|
||||
self.attr_persona = []
|
||||
self.aspect_attribute_dict = {}
|
||||
self.embedding_model = embedding_model
|
||||
|
||||
async def update_preference_persona(self, episodic_topic_memory_list):
|
||||
|
||||
episodic_memory_topic_list = [topic["group_name"] for topic in episodic_topic_memory_list]
|
||||
topic_attitude_dict = {}
|
||||
|
||||
for topic in episodic_topic_memory_list:
|
||||
topic_attitude_dict[topic["group_name"]] = topic["Overall Attitude"]
|
||||
|
||||
topic_clusters = self.cluster_related_topics(self.find_top_similar_keys(episodic_memory_topic_list, self.embedding_model))
|
||||
persona_preference_results = []
|
||||
|
||||
for cluster in topic_clusters:
|
||||
|
||||
message = [{topic:topic_attitude_dict[topic]} for topic in cluster]
|
||||
preference_generate_message = [{"role": "system", "content": Preference_Generate_System_PROMPT},{"role": "user", "content": Preference_Generate_User_PROMPT.format(Topic_Groups=str(message))}]
|
||||
fact_generate_message = [{"role":"system"}]
|
||||
|
||||
response = ""
|
||||
while response == "":
|
||||
try:
|
||||
response = await self.client.chat.completions.create(model=self.llm_model, messages = preference_generate_message, temperature = 0.3)
|
||||
persona_preference = json.loads(response.choices[0].message.content)
|
||||
persona_preference_results.append(persona_preference)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
print("Error generating persona profile.")
|
||||
print(f"Error generating profile: {str(e)}")
|
||||
continue
|
||||
|
||||
self.preference_persona = persona_preference_results
|
||||
self._save_preference_persona()
|
||||
|
||||
async def update_attribute_persona(self, episodic_memory_attr_dict):
|
||||
|
||||
memory_attr_list = list(episodic_memory_attr_dict.keys())
|
||||
attr_clusters = self.cluster_related_topics(self.find_top_similar_keys(memory_attr_list, self.embedding_model))
|
||||
persona_attr_results = []
|
||||
|
||||
for cluster in attr_clusters:
|
||||
|
||||
print(str(cluster))
|
||||
fact_generate_message = [{"role": "system", "content": Attribute_Merge_System_PROMPT_v2},{"role": "user", "content": Attribute_Merge_User_PROMPT.format(User_facts=str(cluster))}]
|
||||
response = ""
|
||||
while response == "":
|
||||
try:
|
||||
response = await self.client.chat.completions.create(model=self.llm_model, messages = fact_generate_message, temperature = 0.1)
|
||||
persona_attr = json.loads(response.choices[0].message.content)
|
||||
persona_attr["original attributes"] = cluster
|
||||
persona_attr_results.append(persona_attr)
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
response == ""
|
||||
print(f"Error generating profile: {str(e)}")
|
||||
continue
|
||||
|
||||
self.attr_persona = persona_attr_results
|
||||
self._save_attr_persona()
|
||||
|
||||
def _save_preference_persona(self):
|
||||
|
||||
with open(self.persona_memory_preference_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.preference_persona, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def _save_fact_persona(self):
|
||||
|
||||
with open(self.persona_memory_fact_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.fact_persona_description, f, ensure_ascii=False, indent=4)
|
||||
|
||||
def _save_attr_persona(self):
|
||||
|
||||
print("Generating aspect-attribute dictionary.")
|
||||
for attr_group in self.attr_persona:
|
||||
for key,value in attr_group["User Attributes"].items():
|
||||
try:
|
||||
if key in self.aspect_attribute_dict:
|
||||
current = self.aspect_attribute_dict[key]
|
||||
self.aspect_attribute_dict[key] = self.aspect_attribute_dict[key] + " " + value
|
||||
else:
|
||||
self.aspect_attribute_dict[key] = value
|
||||
except:
|
||||
print("Attribute Error")
|
||||
print(key)
|
||||
print(self.persona_memory_attr_path)
|
||||
if key in self.aspect_attribute_dict:
|
||||
current = self.aspect_attribute_dict[key]
|
||||
self.aspect_attribute_dict[key] = str(self.aspect_attribute_dict[key]) + " " + str(value)
|
||||
else:
|
||||
self.aspect_attribute_dict[key] = value
|
||||
|
||||
|
||||
with open(self.persona_memory_attr_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.attr_persona, f, ensure_ascii=False, indent=4)
|
||||
|
||||
|
||||
def cluster_related_topics(self,data):
|
||||
|
||||
parent = {}
|
||||
def find(node):
|
||||
if parent[node] != node:
|
||||
parent[node] = find(parent[node])
|
||||
return parent[node]
|
||||
def union(node1, node2):
|
||||
root1 = find(node1)
|
||||
root2 = find(node2)
|
||||
if root1 != root2:
|
||||
parent[root2] = root1
|
||||
|
||||
for item in data:
|
||||
key1, key2 = item['key1'], item['key2']
|
||||
if key1 not in parent:
|
||||
parent[key1] = key1
|
||||
if key2 not in parent:
|
||||
parent[key2] = key2
|
||||
|
||||
for item in data:
|
||||
key1, key2 = item['key1'], item['key2']
|
||||
union(key1, key2)
|
||||
|
||||
clusters = defaultdict(list)
|
||||
for node in parent:
|
||||
clusters[find(node)].append(node)
|
||||
|
||||
result = [cluster for cluster in clusters.values() if len(cluster) > 1]
|
||||
|
||||
return result
|
||||
|
||||
def find_top_similar_keys(self,all_keys, embedding_model):
|
||||
|
||||
key_embeddings = embedding_model.encode(all_keys)
|
||||
key_pairs = list(combinations(range(len(all_keys)), 2))
|
||||
best_matches = {}
|
||||
|
||||
for i, j in key_pairs:
|
||||
key1 = all_keys[i]
|
||||
key2 = all_keys[j]
|
||||
sim = float(key_embeddings[i] @ key_embeddings[j].T)
|
||||
if key1 not in best_matches or sim > best_matches[key1]['similarity']:
|
||||
best_matches[key1] = {'key1': key1, 'key2': key2, 'similarity': sim}
|
||||
if key2 not in best_matches or sim > best_matches[key2]['similarity']:
|
||||
best_matches[key2] = {'key1': key2, 'key2': key1, 'similarity': sim}
|
||||
|
||||
results = list(best_matches.values())
|
||||
results.sort(key=lambda x: x['similarity'], reverse=True)
|
||||
return results
|
||||
|
||||
def read_cache(self,preference_memory_path,attr_memory_path):
|
||||
|
||||
with open(preference_memory_path,'r', encoding='utf-8') as f:
|
||||
self.preference_persona = json.load(f)
|
||||
|
||||
with open(attr_memory_path,'r', encoding='utf-8') as f:
|
||||
self.attr_persona = json.load(f)
|
||||
|
||||
self._save_preference_persona()
|
||||
self._save_attr_persona()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
1043
libs/o-mem/memory_chain/prompts.py
Normal file
1043
libs/o-mem/memory_chain/prompts.py
Normal file
File diff suppressed because it is too large
Load diff
21
libs/o-mem/memory_chain/utils.py
Normal file
21
libs/o-mem/memory_chain/utils.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import os
|
||||
|
||||
|
||||
def ensure_directory_exists(path):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
|
||||
99
libs/o-mem/memory_chain/working_memory.py
Normal file
99
libs/o-mem/memory_chain/working_memory.py
Normal file
|
|
@ -0,0 +1,99 @@
|
|||
#!/usr/bin/env python
|
||||
# coding=utf-8
|
||||
# Copyright 2025 The OPPO Personal AI team. All rights reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
import json
|
||||
import numpy as np
|
||||
from collections import deque
|
||||
from .utils import *
|
||||
from queue import Queue
|
||||
import queue
|
||||
|
||||
class Working_Memory:
|
||||
|
||||
def __init__(self,working_memory_path ,user_id,model,working_memory_max_size,client,refresh_rate):
|
||||
|
||||
self.file_path = working_memory_path
|
||||
self.user_id = user_id
|
||||
self.model = model
|
||||
self.working_memory_queue = Queue()
|
||||
self.working_memory_max_size = working_memory_max_size
|
||||
self.refresh_rate = refresh_rate
|
||||
self.client = client
|
||||
ensure_directory_exists(self.file_path)
|
||||
|
||||
def add_message_to_working_memory(self,raw_message,message,topics,emotions,reason,index,timestamp,fact,attribute):
|
||||
|
||||
self.working_memory_queue.put({"user_id":self.user_id,"raw_message":raw_message,"message":message,"topics":topics,"emotions":emotions,"reason":reason,"index":index,"timestamp":timestamp,"fact":fact,"attribue":attribute})
|
||||
|
||||
if (self.working_memory_queue.qsize() == self.working_memory_max_size):
|
||||
is_full = True
|
||||
else:
|
||||
is_full = False
|
||||
|
||||
return is_full, self._save_working_memory()
|
||||
|
||||
def pop_oldest_wm(self):
|
||||
|
||||
return self.working_memory_queue.get()
|
||||
|
||||
def pop_oldest_working_memory(self):
|
||||
|
||||
popped_items = []
|
||||
|
||||
for _ in range(self.refresh_rate):
|
||||
try:
|
||||
item = self.working_memory_queue.get_nowait()
|
||||
popped_items.append(item)
|
||||
except queue.Empty:
|
||||
break
|
||||
|
||||
return popped_items
|
||||
|
||||
|
||||
def _save_working_memory(self):
|
||||
temp_queue = queue.Queue()
|
||||
temp_list = []
|
||||
|
||||
while not self.working_memory_queue.empty():
|
||||
item = self.working_memory_queue.get()
|
||||
temp_list.append(item)
|
||||
temp_queue.put(item)
|
||||
|
||||
while not temp_queue.empty():
|
||||
self.working_memory_queue.put(temp_queue.get())
|
||||
|
||||
with open(self.file_path, 'w') as f:
|
||||
json.dump(temp_list, f, indent=2, sort_keys=True)
|
||||
|
||||
message_summary_list = [item["message"] for item in temp_list]
|
||||
return message_summary_list
|
||||
def read_cache(self,file_path):
|
||||
|
||||
print(file_path)
|
||||
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
message_understanding_caches = json.load(f)
|
||||
for message_understanding in message_understanding_caches:
|
||||
self.working_memory_queue.put(message_understanding)
|
||||
|
||||
self._save_working_memory()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
20
libs/o-mem/requirements.txt
Normal file
20
libs/o-mem/requirements.txt
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
# Memory Chain - Dependencies
|
||||
# ===========================
|
||||
# Install with: pip install -r requirements.txt
|
||||
|
||||
# Core Dependencies
|
||||
openai>=1.0.0 # OpenAI API client
|
||||
torch>=2.8.0 # PyTorch deep learning framework
|
||||
sentence-transformers>=2.2.0 # Sentence embedding models
|
||||
numpy>=1.22.0 # Numerical computing
|
||||
|
||||
# Configuration & Utilities
|
||||
pyyaml>=6.0 # YAML config file parsing
|
||||
tqdm>=4.66.3 # Progress bars
|
||||
aiofiles>=23.0.0 # Async file operations
|
||||
|
||||
# Optional Dependencies (for experiments)
|
||||
tiktoken>=0.5.0 # OpenAI tokenizer
|
||||
FlagEmbedding>=1.2.0 # BGE embedding models (optional, for custom embeddings)
|
||||
scikit-learn>=1.0.0 # Machine learning utilities (cosine similarity)
|
||||
|
||||
Loading…
Reference in a new issue