agent.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from jinja2 import BaseLoader, Environment
  2. from opendevin.controller.agent import Agent
  3. from opendevin.controller.state.state import State
  4. from opendevin.core.utils import json
  5. from opendevin.events.action import Action
  6. from opendevin.events.serialization.action import action_from_dict
  7. from opendevin.events.serialization.event import event_to_memory
  8. from opendevin.llm.llm import LLM
  9. from .instructions import instructions
  10. from .registry import all_microagents
  11. def parse_response(orig_response: str) -> Action:
  12. # attempt to load the JSON dict from the response
  13. action_dict = json.loads(orig_response)
  14. # load the action from the dict
  15. return action_from_dict(action_dict)
  16. def to_json(obj, **kwargs):
  17. """
  18. Serialize an object to str format
  19. """
  20. return json.dumps(obj, **kwargs)
  21. def history_to_json(obj, **kwargs):
  22. """
  23. Serialize and simplify history to str format
  24. """
  25. if isinstance(obj, list):
  26. # process history, make it simpler.
  27. processed_history = []
  28. for action, observation in obj:
  29. processed_history.append(
  30. (event_to_memory(action), event_to_memory(observation))
  31. )
  32. return json.dumps(processed_history, **kwargs)
  33. class MicroAgent(Agent):
  34. VERSION = '1.0'
  35. prompt = ''
  36. agent_definition: dict = {}
  37. def __init__(self, llm: LLM):
  38. super().__init__(llm)
  39. if 'name' not in self.agent_definition:
  40. raise ValueError('Agent definition must contain a name')
  41. self.prompt_template = Environment(loader=BaseLoader).from_string(self.prompt)
  42. self.delegates = all_microagents.copy()
  43. del self.delegates[self.agent_definition['name']]
  44. def step(self, state: State) -> Action:
  45. prompt = self.prompt_template.render(
  46. state=state,
  47. instructions=instructions,
  48. to_json=to_json,
  49. history_to_json=history_to_json,
  50. delegates=self.delegates,
  51. latest_user_message=state.get_current_user_intent(),
  52. )
  53. messages = [{'content': prompt, 'role': 'user'}]
  54. resp = self.llm.do_completion(messages=messages)
  55. action_resp = resp['choices'][0]['message']['content']
  56. state.num_of_chars += len(prompt) + len(action_resp)
  57. action = parse_response(action_resp)
  58. return action
  59. def search_memory(self, query: str) -> list[str]:
  60. return []