Scaper_search / memory.py
gaur3009's picture
Create memory.py
76ea7e5 verified
raw
history blame contribute delete
966 Bytes
class ConversationMemory:
def __init__(self, max_length=2000):
self.history = []
self.max_length = max_length
def add_exchange(self, question, answer):
self.history.append({"user": question, "assistant": answer['response']})
self._trim_history()
def get_context(self):
"""Format last 3 exchanges as context"""
context = ""
for exchange in self.history[-3:]:
context += f"User: {exchange['user']}\nAssistant: {exchange['assistant']}\n\n"
return context.strip()
def _trim_history(self):
"""Keep conversation within token limit"""
total_length = sum(len(exchange['user']) + len(exchange['assistant'])
for exchange in self.history)
while total_length > self.max_length and self.history:
removed = self.history.pop(0)
total_length -= len(removed['user']) + len(removed['assistant'])