codeact_swe_agent.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 AgentConfig
  11. from opendevin.core.message import ImageContent, Message, TextContent
  12. from opendevin.events.action import (
  13. Action,
  14. AgentFinishAction,
  15. CmdRunAction,
  16. IPythonRunCellAction,
  17. MessageAction,
  18. )
  19. from opendevin.events.observation import (
  20. CmdOutputObservation,
  21. IPythonRunCellObservation,
  22. )
  23. from opendevin.events.observation.error import ErrorObservation
  24. from opendevin.events.observation.observation import Observation
  25. from opendevin.events.serialization.event import truncate_content
  26. from opendevin.llm.llm import LLM
  27. from opendevin.runtime.plugins import (
  28. AgentSkillsRequirement,
  29. JupyterRequirement,
  30. PluginRequirement,
  31. )
  32. from opendevin.runtime.tools import RuntimeTool
  33. def get_system_message() -> str:
  34. return f'{SYSTEM_PREFIX}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  35. def get_in_context_example() -> str:
  36. return SWE_EXAMPLE
  37. class CodeActSWEAgent(Agent):
  38. VERSION = '1.6'
  39. """
  40. 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.
  41. It is intended use is **solving Github issues**.
  42. It removes web-browsing and Github capability from the original CodeAct agent to avoid confusion to the agent.
  43. """
  44. sandbox_plugins: list[PluginRequirement] = [
  45. # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since
  46. # AgentSkillsRequirement provides a lot of Python functions,
  47. # and it needs to be initialized before Jupyter for Jupyter to use those functions.
  48. AgentSkillsRequirement(),
  49. JupyterRequirement(),
  50. ]
  51. runtime_tools: list[RuntimeTool] = []
  52. system_message: str = get_system_message()
  53. 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!"
  54. response_parser = CodeActSWEResponseParser()
  55. def __init__(
  56. self,
  57. llm: LLM,
  58. config: AgentConfig,
  59. ) -> None:
  60. """Initializes a new instance of the CodeActSWEAgent class.
  61. Parameters:
  62. - llm (LLM): The llm to be used by this agent
  63. """
  64. super().__init__(llm, config)
  65. self.reset()
  66. def action_to_str(self, action: Action) -> str:
  67. if isinstance(action, CmdRunAction):
  68. return (
  69. f'{action.thought}\n<execute_bash>\n{action.command}\n</execute_bash>'
  70. )
  71. elif isinstance(action, IPythonRunCellAction):
  72. return f'{action.thought}\n<execute_ipython>\n{action.code}\n</execute_ipython>'
  73. elif isinstance(action, MessageAction):
  74. return action.content
  75. return ''
  76. def get_action_message(self, action: Action) -> Message | None:
  77. if (
  78. isinstance(action, CmdRunAction)
  79. or isinstance(action, IPythonRunCellAction)
  80. or isinstance(action, MessageAction)
  81. ):
  82. content = [TextContent(text=self.action_to_str(action))]
  83. if isinstance(action, MessageAction) and action.images_urls:
  84. content.append(ImageContent(image_urls=action.images_urls))
  85. return Message(
  86. role='user' if action.source == 'user' else 'assistant', content=content
  87. )
  88. return None
  89. def get_observation_message(self, obs: Observation) -> Message | None:
  90. max_message_chars = self.llm.config.max_message_chars
  91. if isinstance(obs, CmdOutputObservation):
  92. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  93. text += (
  94. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]'
  95. )
  96. return Message(role='user', content=[TextContent(text=text)])
  97. elif isinstance(obs, IPythonRunCellObservation):
  98. text = 'OBSERVATION:\n' + obs.content
  99. # replace base64 images with a placeholder
  100. splitted = text.split('\n')
  101. for i, line in enumerate(splitted):
  102. if '![image](data:image/png;base64,' in line:
  103. splitted[i] = (
  104. '![image](data:image/png;base64, ...) already displayed to user'
  105. )
  106. text = '\n'.join(splitted)
  107. text = truncate_content(text, max_message_chars)
  108. return Message(role='user', content=[TextContent(text=text)])
  109. elif isinstance(obs, ErrorObservation):
  110. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  111. text += '\n[Error occurred in processing last action]'
  112. return Message(role='user', content=[TextContent(text=text)])
  113. else:
  114. # If an observation message is not returned, it will cause an error
  115. # when the LLM tries to return the next message
  116. raise ValueError(f'Unknown observation type: {type(obs)}')
  117. def reset(self) -> None:
  118. """Resets the CodeAct Agent."""
  119. super().reset()
  120. def step(self, state: State) -> Action:
  121. """Performs one step using the CodeAct Agent.
  122. This includes gathering info on previous steps and prompting the model to make a command to execute.
  123. Parameters:
  124. - state (State): used to get updated info and background commands
  125. Returns:
  126. - CmdRunAction(command) - bash command to run
  127. - IPythonRunCellAction(code) - IPython code to run
  128. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  129. - AgentFinishAction() - end the interaction
  130. """
  131. # if we're done, go back
  132. latest_user_message = state.history.get_last_user_message()
  133. if latest_user_message and latest_user_message.strip() == '/exit':
  134. return AgentFinishAction()
  135. # prepare what we want to send to the LLM
  136. messages: list[Message] = self._get_messages(state)
  137. response = self.llm.completion(
  138. messages=[message.model_dump() for message in messages],
  139. stop=[
  140. '</execute_ipython>',
  141. '</execute_bash>',
  142. ],
  143. temperature=0.0,
  144. )
  145. return self.response_parser.parse(response)
  146. def _get_messages(self, state: State) -> list[Message]:
  147. messages: list[Message] = [
  148. Message(role='system', content=[TextContent(text=self.system_message)]),
  149. Message(role='user', content=[TextContent(text=self.in_context_example)]),
  150. ]
  151. for event in state.history.get_events():
  152. # create a regular message from an event
  153. if isinstance(event, Action):
  154. message = self.get_action_message(event)
  155. elif isinstance(event, Observation):
  156. message = self.get_observation_message(event)
  157. else:
  158. raise ValueError(f'Unknown event type: {type(event)}')
  159. # add regular message
  160. if message:
  161. # handle error if the message is the SAME role as the previous message
  162. # litellm.exceptions.BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - {'detail': 'Only supports u/a/u/a/u...'}
  163. # there should not have two consecutive messages from the same role
  164. if messages and messages[-1].role == message.role:
  165. messages[-1].content.extend(message.content)
  166. else:
  167. messages.append(message)
  168. # the latest user message is important:
  169. # we want to remind the agent of the environment constraints
  170. latest_user_message = next(
  171. (m for m in reversed(messages) if m.role == 'user'), None
  172. )
  173. # Get the last user text inside content
  174. if latest_user_message:
  175. latest_user_message_text = next(
  176. (
  177. t
  178. for t in reversed(latest_user_message.content)
  179. if isinstance(t, TextContent)
  180. )
  181. )
  182. # add a reminder to the prompt
  183. reminder_text = f'\n\nENVIRONMENT REMINDER: You have {state.max_iterations - state.iteration} turns left to complete the task. When finished reply with <finish></finish>.'
  184. if latest_user_message_text:
  185. latest_user_message_text.text = (
  186. latest_user_message_text.text + reminder_text
  187. )
  188. else:
  189. latest_user_message_text = TextContent(text=reminder_text)
  190. latest_user_message.content.append(latest_user_message_text)
  191. return messages