codeact_swe_agent.py 8.8 KB

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