history.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import opendevin.core.utils.json as json
  2. from opendevin.core.exceptions import AgentEventTypeError
  3. from opendevin.core.logger import opendevin_logger as logger
  4. class ShortTermHistory:
  5. """
  6. The short term history is the most recent series of events.
  7. An agent can send this in the prompt or use it for other purpose.
  8. """
  9. def __init__(self):
  10. """
  11. Initialize the empty list of events
  12. """
  13. self.events = []
  14. def add_event(self, event_dict: dict):
  15. """
  16. Adds an event to memory if it is a valid event.
  17. Parameters:
  18. - event_dict (dict): The event that we want to add to memory
  19. Raises:
  20. - AgentEventTypeError: If event_dict is not a dict
  21. """
  22. if not isinstance(event_dict, dict):
  23. raise AgentEventTypeError()
  24. self.events.append(event_dict)
  25. def get_events(self):
  26. """
  27. Get the events in the agent's recent history.
  28. Returns:
  29. - List: The list of events that the agent remembers easily.
  30. """
  31. return self.events
  32. def get_total_length(self):
  33. """
  34. Gives the total number of characters in all history
  35. Returns:
  36. - Int: Total number of characters of the recent history.
  37. """
  38. total_length = 0
  39. for t in self.events:
  40. try:
  41. total_length += len(json.dumps(t))
  42. except TypeError as e:
  43. logger.error('Error serializing event: %s', str(e), exc_info=False)
  44. return total_length