agent.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import json
  2. from typing import Dict, List
  3. from jinja2 import BaseLoader, Environment
  4. from opendevin.controller.agent import Agent
  5. from opendevin.controller.state.state import State
  6. from opendevin.core.exceptions import LLMOutputError
  7. from opendevin.events.action import Action, action_from_dict
  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. json_start = orig_response.find('{')
  13. json_end = orig_response.rfind('}') + 1
  14. response = orig_response[json_start:json_end]
  15. try:
  16. action_dict = json.loads(response)
  17. except json.JSONDecodeError as e:
  18. raise LLMOutputError(
  19. 'Invalid JSON in response. Please make sure the response is a valid JSON object'
  20. ) from e
  21. action = action_from_dict(action_dict)
  22. return action
  23. def my_encoder(obj):
  24. """
  25. Encodes objects as dictionaries
  26. Parameters:
  27. - obj (Object): An object that will be converted
  28. Returns:
  29. - dict: If the object can be converted it is returned in dict format
  30. """
  31. if hasattr(obj, 'to_dict'):
  32. return obj.to_dict()
  33. def to_json(obj, **kwargs):
  34. """
  35. Serialize an object to str format
  36. """
  37. return json.dumps(obj, default=my_encoder, **kwargs)
  38. class MicroAgent(Agent):
  39. prompt = ''
  40. agent_definition: Dict = {}
  41. def __init__(self, llm: LLM):
  42. super().__init__(llm)
  43. if 'name' not in self.agent_definition:
  44. raise ValueError('Agent definition must contain a name')
  45. self.prompt_template = Environment(loader=BaseLoader).from_string(self.prompt)
  46. self.delegates = all_microagents.copy()
  47. del self.delegates[self.agent_definition['name']]
  48. def step(self, state: State) -> Action:
  49. prompt = self.prompt_template.render(
  50. state=state,
  51. instructions=instructions,
  52. to_json=to_json,
  53. delegates=self.delegates,
  54. )
  55. messages = [{'content': prompt, 'role': 'user'}]
  56. resp = self.llm.completion(messages=messages)
  57. action_resp = resp['choices'][0]['message']['content']
  58. state.num_of_chars += len(prompt) + len(action_resp)
  59. action = parse_response(action_resp)
  60. return action
  61. def search_memory(self, query: str) -> List[str]:
  62. return []