Spaces:
Runtime error
Runtime error
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']) |