datadabllp

simple conversation manager with memory

Aug 20th, 2024
612
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. class ConversationManager:
  2.     def __init__(self, system_prompt, memory_limit=5):
  3.         self.system_prompt = system_prompt
  4.         self.memory = []
  5.         self.memory_limit = memory_limit
  6.    
  7.     def add_to_memory(self, role, content):
  8.         self.memory.append({"role": role, "content": content})
  9.         if len(self.memory) > self.memory_limit:
  10.             self.memory.pop(0)
  11.    
  12.     def get_response(self, user_input):
  13.         self.add_to_memory("user", user_input)
  14.        
  15.         full_prompt = f"{self.system_prompt}\n\n"
  16.         for message in self.memory:
  17.             full_prompt += f"{message['role'].capitalize()}: {message['content']}\n"
  18.         full_prompt += "Assistant: "
  19.        
  20.         response = llm.generate(full_prompt)
  21.         self.add_to_memory("assistant", response)
  22.        
  23.         return response
  24.  
  25. # Usage
  26. system_prompt = "You are a helpful AI assistant. Maintain context across the conversation."
  27. manager = ConversationManager(system_prompt)
  28.  
  29. print(manager.get_response("Hi, what's the weather like today?"))
  30. print(manager.get_response("Will I need an umbrella?"))
  31. print(manager.get_response("Thanks! By the way, what was my first question?"))
  32.  
Advertisement
Add Comment
Please, Sign In to add comment