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 openhands.controller.agent import Agent
  9. from openhands.controller.state.state import State
  10. from openhands.core.config import AgentConfig
  11. from openhands.core.message import ImageContent, Message, TextContent
  12. from openhands.events.action import (
  13. Action,
  14. AgentFinishAction,
  15. CmdRunAction,
  16. IPythonRunCellAction,
  17. MessageAction,
  18. )
  19. from openhands.events.observation import (
  20. CmdOutputObservation,
  21. IPythonRunCellObservation,
  22. )
  23. from openhands.events.observation.error import ErrorObservation
  24. from openhands.events.observation.observation import Observation
  25. from openhands.events.serialization.event import truncate_content
  26. from openhands.llm.llm import LLM
  27. from openhands.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 OpenHands.
  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 (
  82. self.llm.vision_is_active()
  83. and isinstance(action, MessageAction)
  84. and action.images_urls
  85. ):
  86. content.append(ImageContent(image_urls=action.images_urls))
  87. return Message(
  88. role='user' if action.source == 'user' else 'assistant', content=content
  89. )
  90. return None
  91. def get_observation_message(self, obs: Observation) -> Message | None:
  92. max_message_chars = self.llm.config.max_message_chars
  93. if isinstance(obs, CmdOutputObservation):
  94. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  95. text += (
  96. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]'
  97. )
  98. return Message(role='user', content=[TextContent(text=text)])
  99. elif isinstance(obs, IPythonRunCellObservation):
  100. text = 'OBSERVATION:\n' + obs.content
  101. # replace base64 images with a placeholder
  102. splitted = text.split('\n')
  103. for i, line in enumerate(splitted):
  104. if '![image](data:image/png;base64,' in line:
  105. splitted[i] = (
  106. '![image](data:image/png;base64, ...) already displayed to user'
  107. )
  108. text = '\n'.join(splitted)
  109. text = truncate_content(text, max_message_chars)
  110. return Message(role='user', content=[TextContent(text=text)])
  111. elif isinstance(obs, ErrorObservation):
  112. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  113. text += '\n[Error occurred in processing last action]'
  114. return Message(role='user', content=[TextContent(text=text)])
  115. else:
  116. # If an observation message is not returned, it will cause an error
  117. # when the LLM tries to return the next message
  118. raise ValueError(f'Unknown observation type: {type(obs)}')
  119. def reset(self) -> None:
  120. """Resets the CodeAct Agent."""
  121. super().reset()
  122. def step(self, state: State) -> Action:
  123. """Performs one step using the CodeAct Agent.
  124. This includes gathering info on previous steps and prompting the model to make a command to execute.
  125. Parameters:
  126. - state (State): used to get updated info and background commands
  127. Returns:
  128. - CmdRunAction(command) - bash command to run
  129. - IPythonRunCellAction(code) - IPython code to run
  130. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  131. - AgentFinishAction() - end the interaction
  132. """
  133. # if we're done, go back
  134. latest_user_message = state.history.get_last_user_message()
  135. if latest_user_message and latest_user_message.strip() == '/exit':
  136. return AgentFinishAction()
  137. # prepare what we want to send to the LLM
  138. messages: list[Message] = self._get_messages(state)
  139. response = self.llm.completion(
  140. messages=self.llm.format_messages_for_llm(messages),
  141. stop=[
  142. '</execute_ipython>',
  143. '</execute_bash>',
  144. ],
  145. )
  146. return self.response_parser.parse(response)
  147. def _get_messages(self, state: State) -> list[Message]:
  148. messages: list[Message] = [
  149. Message(role='system', content=[TextContent(text=self.system_message)]),
  150. Message(role='user', content=[TextContent(text=self.in_context_example)]),
  151. ]
  152. for event in state.history.get_events():
  153. # create a regular message from an event
  154. if isinstance(event, Action):
  155. message = self.get_action_message(event)
  156. elif isinstance(event, Observation):
  157. message = self.get_observation_message(event)
  158. else:
  159. raise ValueError(f'Unknown event type: {type(event)}')
  160. # add regular message
  161. if message:
  162. # handle error if the message is the SAME role as the previous message
  163. # litellm.exceptions.BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - {'detail': 'Only supports u/a/u/a/u...'}
  164. # there should not have two consecutive messages from the same role
  165. if messages and messages[-1].role == message.role:
  166. messages[-1].content.extend(message.content)
  167. else:
  168. messages.append(message)
  169. # the latest user message is important:
  170. # we want to remind the agent of the environment constraints
  171. latest_user_message = next(
  172. (m for m in reversed(messages) if m.role == 'user'), None
  173. )
  174. # Get the last user text inside content
  175. if latest_user_message:
  176. latest_user_message_text = next(
  177. (
  178. t
  179. for t in reversed(latest_user_message.content)
  180. if isinstance(t, TextContent)
  181. )
  182. )
  183. # add a reminder to the prompt
  184. 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>.'
  185. if latest_user_message_text:
  186. latest_user_message_text.text = (
  187. latest_user_message_text.text + reminder_text
  188. )
  189. else:
  190. latest_user_message_text = TextContent(text=reminder_text)
  191. latest_user_message.content.append(latest_user_message_text)
  192. return messages