2025-03-20 19:51:46 +08:00
|
|
|
from src.utils.prompts import get_system_prompt
|
2024-07-07 01:58:23 +08:00
|
|
|
|
2025-05-24 11:29:45 +08:00
|
|
|
class HistoryManager:
|
2025-03-20 19:51:46 +08:00
|
|
|
def __init__(self, history=None, system_prompt=None):
|
2025-05-05 19:40:58 +08:00
|
|
|
self.messages = []
|
2024-07-07 01:58:23 +08:00
|
|
|
|
2025-03-20 19:51:46 +08:00
|
|
|
system_prompt = system_prompt or get_system_prompt()
|
|
|
|
|
self.add_system(system_prompt)
|
|
|
|
|
|
2025-05-05 19:40:58 +08:00
|
|
|
if history:
|
|
|
|
|
self.messages.extend(history)
|
|
|
|
|
|
2024-07-07 01:58:23 +08:00
|
|
|
def add(self, role, content):
|
|
|
|
|
self.messages.append({"role": role, "content": content})
|
|
|
|
|
return self.messages
|
|
|
|
|
|
|
|
|
|
def add_user(self, content):
|
|
|
|
|
return self.add("user", content)
|
|
|
|
|
|
|
|
|
|
def add_system(self, content):
|
|
|
|
|
return self.add("system", content)
|
|
|
|
|
|
|
|
|
|
def add_ai(self, content):
|
|
|
|
|
return self.add("assistant", content)
|
|
|
|
|
|
|
|
|
|
def update_ai(self, content):
|
|
|
|
|
if self.messages[-1]["role"] == "assistant":
|
|
|
|
|
self.messages[-1]["content"] = content
|
|
|
|
|
return self.messages
|
|
|
|
|
else:
|
|
|
|
|
self.add_ai(content)
|
|
|
|
|
return self.messages
|
|
|
|
|
|
2024-08-07 17:42:26 +08:00
|
|
|
def get_history_with_msg(self, msg, role="user", max_rounds=None):
|
2024-07-14 16:42:38 +08:00
|
|
|
"""Get history with new message, but not append it to history."""
|
2024-08-07 17:42:26 +08:00
|
|
|
if max_rounds is None:
|
|
|
|
|
history = self.messages[:]
|
|
|
|
|
else:
|
|
|
|
|
history = self.messages[-(2*max_rounds):]
|
|
|
|
|
|
2024-07-14 16:42:38 +08:00
|
|
|
history.append({"role": role, "content": msg})
|
|
|
|
|
return history
|
|
|
|
|
|
2024-07-07 01:58:23 +08:00
|
|
|
def __str__(self):
|
|
|
|
|
history_str = ""
|
|
|
|
|
for message in self.messages:
|
2024-09-09 17:07:03 +08:00
|
|
|
msg = message["content"].replace('\n', ' ')
|
|
|
|
|
history_str += f"\n{message['role']}: {msg}"
|
2025-05-24 11:29:45 +08:00
|
|
|
return history_str
|