codeact_swe_agent.py 8.7 KB

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