codeact_swe_agent.py 8.2 KB

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