codeact_swe_agent.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. from agenthub.codeact_swe_agent.prompt import (
  2. COMMAND_DOCS,
  3. SWE_EXAMPLE,
  4. SYSTEM_PREFIX,
  5. SYSTEM_SUFFIX,
  6. )
  7. from agenthub.codeact_swe_agent.response_parser import CodeActSWEResponseParser
  8. from opendevin.controller.agent import Agent
  9. from opendevin.controller.state.state import State
  10. from opendevin.core.config import config
  11. from opendevin.events.action import (
  12. Action,
  13. AgentFinishAction,
  14. CmdRunAction,
  15. IPythonRunCellAction,
  16. MessageAction,
  17. )
  18. from opendevin.events.observation import (
  19. CmdOutputObservation,
  20. IPythonRunCellObservation,
  21. )
  22. from opendevin.events.serialization.event import truncate_content
  23. from opendevin.llm.llm import LLM
  24. from opendevin.runtime.plugins import (
  25. AgentSkillsRequirement,
  26. JupyterRequirement,
  27. PluginRequirement,
  28. )
  29. from opendevin.runtime.tools import RuntimeTool
  30. def action_to_str(action: Action) -> str:
  31. if isinstance(action, CmdRunAction):
  32. return f'{action.thought}\n<execute_bash>\n{action.command}\n</execute_bash>'
  33. elif isinstance(action, IPythonRunCellAction):
  34. return f'{action.thought}\n<execute_ipython>\n{action.code}\n</execute_ipython>'
  35. elif isinstance(action, MessageAction):
  36. return action.content
  37. return ''
  38. def get_action_message(action: Action) -> dict[str, str] | None:
  39. if (
  40. isinstance(action, CmdRunAction)
  41. or isinstance(action, IPythonRunCellAction)
  42. or isinstance(action, MessageAction)
  43. ):
  44. return {
  45. 'role': 'user' if action.source == 'user' else 'assistant',
  46. 'content': action_to_str(action),
  47. }
  48. return None
  49. def get_observation_message(obs) -> dict[str, str] | None:
  50. max_message_chars = config.get_llm_config_from_agent(
  51. 'CodeActSWEAgent'
  52. ).max_message_chars
  53. if isinstance(obs, CmdOutputObservation):
  54. content = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  55. content += (
  56. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]'
  57. )
  58. return {'role': 'user', 'content': content}
  59. elif isinstance(obs, IPythonRunCellObservation):
  60. content = 'OBSERVATION:\n' + obs.content
  61. # replace base64 images with a placeholder
  62. splitted = content.split('\n')
  63. for i, line in enumerate(splitted):
  64. if '![image](data:image/png;base64,' in line:
  65. splitted[i] = (
  66. '![image](data:image/png;base64, ...) already displayed to user'
  67. )
  68. content = '\n'.join(splitted)
  69. content = truncate_content(content, max_message_chars)
  70. return {'role': 'user', 'content': content}
  71. return None
  72. def get_system_message() -> str:
  73. return f'{SYSTEM_PREFIX}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  74. def get_in_context_example() -> str:
  75. return SWE_EXAMPLE
  76. class CodeActSWEAgent(Agent):
  77. VERSION = '1.6'
  78. """
  79. This agent is an adaptation of the original [SWE Agent](https://swe-agent.com/) based on CodeAct 1.5 using the `agentskills` library of OpenDevin.
  80. It is intended use is **solving Github issues**.
  81. It removes web-browsing and Github capability from the original CodeAct agent to avoid confusion to the agent.
  82. """
  83. sandbox_plugins: list[PluginRequirement] = [
  84. # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since
  85. # AgentSkillsRequirement provides a lot of Python functions,
  86. # and it needs to be initialized before Jupyter for Jupyter to use those functions.
  87. AgentSkillsRequirement(),
  88. JupyterRequirement(),
  89. ]
  90. runtime_tools: list[RuntimeTool] = []
  91. system_message: str = get_system_message()
  92. in_context_example: str = f"Here is an example of how you can interact with the environment for task solving:\n{get_in_context_example()}\n\nNOW, LET'S START!"
  93. response_parser = CodeActSWEResponseParser()
  94. def __init__(
  95. self,
  96. llm: LLM,
  97. ) -> None:
  98. """
  99. Initializes a new instance of the CodeActAgent class.
  100. Parameters:
  101. - llm (LLM): The llm to be used by this agent
  102. """
  103. super().__init__(llm)
  104. self.reset()
  105. def reset(self) -> None:
  106. """
  107. Resets the CodeAct Agent.
  108. """
  109. super().reset()
  110. def step(self, state: State) -> Action:
  111. """
  112. Performs one step using the CodeAct Agent.
  113. This includes gathering info on previous steps and prompting the model to make a command to execute.
  114. Parameters:
  115. - state (State): used to get updated info and background commands
  116. Returns:
  117. - CmdRunAction(command) - bash command to run
  118. - IPythonRunCellAction(code) - IPython code to run
  119. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  120. - AgentFinishAction() - end the interaction
  121. """
  122. # if we're done, go back
  123. latest_user_message = state.history.get_last_user_message()
  124. if latest_user_message and latest_user_message.strip() == '/exit':
  125. return AgentFinishAction()
  126. # prepare what we want to send to the LLM
  127. messages: list[dict[str, str]] = self._get_messages(state)
  128. response = self.llm.completion(
  129. messages=messages,
  130. stop=[
  131. '</execute_ipython>',
  132. '</execute_bash>',
  133. ],
  134. temperature=0.0,
  135. )
  136. return self.response_parser.parse(response)
  137. def _get_messages(self, state: State) -> list[dict[str, str]]:
  138. messages = [
  139. {'role': 'system', 'content': self.system_message},
  140. {'role': 'user', 'content': self.in_context_example},
  141. ]
  142. for event in state.history.get_events():
  143. # create a regular message from an event
  144. message = (
  145. get_action_message(event)
  146. if isinstance(event, Action)
  147. else get_observation_message(event)
  148. )
  149. # add regular message
  150. if message:
  151. messages.append(message)
  152. # the latest user message is important:
  153. # we want to remind the agent of the environment constraints
  154. latest_user_message = next(
  155. (m for m in reversed(messages) if m['role'] == 'user'), None
  156. )
  157. # add a reminder to the prompt
  158. if latest_user_message:
  159. latest_user_message['content'] += (
  160. f'\n\nENVIRONMENT REMINDER: You have {state.max_iterations - state.iteration} turns left to complete the task.'
  161. )
  162. return messages