memory.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. from collections import deque
  2. class SharedMemory:
  3. def __init__(self, n_participants):
  4. self.window_size = n_participants
  5. # Context Window: Always holds the last N messages for context (Sliding)
  6. self.context_window = deque(maxlen=n_participants)
  7. # Summary Buffer: Accumulates messages to be summarized (Batch)
  8. self.summary_buffer = []
  9. self.summary_history = [] # Stores the summaries generated by the moderator
  10. self.all_history = [] # Stores all messages for record keeping
  11. def add_message(self, speaker_name, content):
  12. message = {"speaker": speaker_name, "content": content}
  13. self.context_window.append(message)
  14. self.summary_buffer.append(message)
  15. self.all_history.append(message)
  16. def is_ready_for_summary(self):
  17. """Check if we have enough new messages to trigger a summary."""
  18. return len(self.summary_buffer) >= self.window_size
  19. def get_messages_for_summary(self):
  20. """Return the batch of messages to be summarized."""
  21. return self.summary_buffer
  22. def clear_summary_buffer(self):
  23. """Clear the summary buffer after summarization."""
  24. self.summary_buffer = []
  25. def add_summary(self, summary):
  26. self.summary_history.append(summary)
  27. def get_summaries(self):
  28. return self.summary_history
  29. def get_context_str(self):
  30. """Returns a string representation of summaries + current sliding window for context."""
  31. context = "【过往总结】\n"
  32. if not self.summary_history:
  33. context += "(暂无)\n"
  34. for s in self.summary_history:
  35. context += f"- {s}\n"
  36. context += "\n【近期讨论】\n"
  37. if not self.context_window:
  38. context += "(暂无)\n"
  39. for m in self.context_window:
  40. context += f"{m['speaker']}: {m['content']}\n"
  41. return context
  42. class PrivateMemory:
  43. def __init__(self, n_participants):
  44. self.window_size = n_participants
  45. self.thoughts = []
  46. self.speeches = []
  47. def add_speech(self, content):
  48. self.speeches.append(content)
  49. def get_speech_history_str(self):
  50. if not self.speeches:
  51. return "暂无过往发言。"
  52. history = "【我之前的发言】\n"
  53. for i, speech in enumerate(self.speeches[-3:], 1): # Last 3 speeches
  54. history += f"发言{i}: {speech}\n"
  55. return history
  56. def add_thought(self, thought_json):
  57. self.thoughts.append(thought_json)
  58. if len(self.thoughts) > self.window_size:
  59. self.thoughts.pop(0)
  60. def get_thoughts(self):
  61. return self.thoughts
  62. def get_recent_thought_str(self):
  63. if not self.thoughts:
  64. return "暂无过往思考。"
  65. last_thought = self.thoughts[-1]
  66. return f"上次思考: {last_thought.get('focus', 'N/A')} | 态度: {last_thought.get('attitude', 'N/A')}"