File size: 966 Bytes
76ea7e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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'])