codeact_agent.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import os
  2. from agenthub.codeact_agent.action_parser import CodeActResponseParser
  3. from openhands.controller.agent import Agent
  4. from openhands.controller.state.state import State
  5. from openhands.core.config import AgentConfig
  6. from openhands.core.message import ImageContent, Message, TextContent
  7. from openhands.events.action import (
  8. Action,
  9. AgentDelegateAction,
  10. AgentFinishAction,
  11. CmdRunAction,
  12. IPythonRunCellAction,
  13. MessageAction,
  14. )
  15. from openhands.events.observation import (
  16. AgentDelegateObservation,
  17. CmdOutputObservation,
  18. IPythonRunCellObservation,
  19. )
  20. from openhands.events.observation.error import ErrorObservation
  21. from openhands.events.observation.observation import Observation
  22. from openhands.events.serialization.event import truncate_content
  23. from openhands.llm.llm import LLM
  24. from openhands.runtime.plugins import (
  25. AgentSkillsRequirement,
  26. JupyterRequirement,
  27. PluginRequirement,
  28. )
  29. from openhands.utils.prompt import PromptManager
  30. class CodeActAgent(Agent):
  31. VERSION = '1.9'
  32. """
  33. The Code Act Agent is a minimalist agent.
  34. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  35. ### Overview
  36. This agent implements the CodeAct idea ([paper](https://arxiv.org/abs/2402.01030), [tweet](https://twitter.com/xingyaow_/status/1754556835703751087)) that consolidates LLM agents’ **act**ions into a unified **code** action space for both *simplicity* and *performance* (see paper for more details).
  37. The conceptual idea is illustrated below. At each turn, the agent can:
  38. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  39. 2. **CodeAct**: Choose to perform the task by executing code
  40. - Execute any valid Linux `bash` command
  41. - Execute any valid `Python` code with [an interactive Python interpreter](https://ipython.org/). This is simulated through `bash` command, see plugin system below for more details.
  42. ![image](https://github.com/All-Hands-AI/OpenHands/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  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. action_parser = CodeActResponseParser()
  52. def __init__(
  53. self,
  54. llm: LLM,
  55. config: AgentConfig,
  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, config)
  62. self.reset()
  63. self.prompt_manager = PromptManager(
  64. prompt_dir=os.path.join(os.path.dirname(__file__)),
  65. agent_skills_docs=AgentSkillsRequirement.documentation,
  66. micro_agent_name=None, # TODO: implement micro-agent
  67. )
  68. def action_to_str(self, action: Action) -> str:
  69. if isinstance(action, CmdRunAction):
  70. return (
  71. f'{action.thought}\n<execute_bash>\n{action.command}\n</execute_bash>'
  72. )
  73. elif isinstance(action, IPythonRunCellAction):
  74. return f'{action.thought}\n<execute_ipython>\n{action.code}\n</execute_ipython>'
  75. elif isinstance(action, AgentDelegateAction):
  76. return f'{action.thought}\n<execute_browse>\n{action.inputs["task"]}\n</execute_browse>'
  77. elif isinstance(action, MessageAction):
  78. return action.content
  79. elif isinstance(action, AgentFinishAction) and action.source == 'agent':
  80. return action.thought
  81. return ''
  82. def get_action_message(self, action: Action) -> Message | None:
  83. if (
  84. isinstance(action, AgentDelegateAction)
  85. or isinstance(action, CmdRunAction)
  86. or isinstance(action, IPythonRunCellAction)
  87. or isinstance(action, MessageAction)
  88. or (isinstance(action, AgentFinishAction) and action.source == 'agent')
  89. ):
  90. content = [TextContent(text=self.action_to_str(action))]
  91. if isinstance(action, MessageAction) and action.images_urls:
  92. content.append(ImageContent(image_urls=action.images_urls))
  93. return Message(
  94. role='user' if action.source == 'user' else 'assistant', content=content
  95. )
  96. return None
  97. def get_observation_message(self, obs: Observation) -> Message | None:
  98. max_message_chars = self.llm.config.max_message_chars
  99. if isinstance(obs, CmdOutputObservation):
  100. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  101. text += (
  102. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]'
  103. )
  104. return Message(role='user', content=[TextContent(text=text)])
  105. elif isinstance(obs, IPythonRunCellObservation):
  106. text = 'OBSERVATION:\n' + obs.content
  107. # replace base64 images with a placeholder
  108. splitted = text.split('\n')
  109. for i, line in enumerate(splitted):
  110. if '![image](data:image/png;base64,' in line:
  111. splitted[i] = (
  112. '![image](data:image/png;base64, ...) already displayed to user'
  113. )
  114. text = '\n'.join(splitted)
  115. text = truncate_content(text, max_message_chars)
  116. return Message(role='user', content=[TextContent(text=text)])
  117. elif isinstance(obs, AgentDelegateObservation):
  118. text = 'OBSERVATION:\n' + truncate_content(
  119. str(obs.outputs), max_message_chars
  120. )
  121. return Message(role='user', content=[TextContent(text=text)])
  122. elif isinstance(obs, ErrorObservation):
  123. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  124. text += '\n[Error occurred in processing last action]'
  125. return Message(role='user', content=[TextContent(text=text)])
  126. else:
  127. # If an observation message is not returned, it will cause an error
  128. # when the LLM tries to return the next message
  129. raise ValueError(f'Unknown observation type: {type(obs)}')
  130. def reset(self) -> None:
  131. """Resets the CodeAct Agent."""
  132. super().reset()
  133. def step(self, state: State) -> Action:
  134. """Performs one step using the CodeAct Agent.
  135. This includes gathering info on previous steps and prompting the model to make a command to execute.
  136. Parameters:
  137. - state (State): used to get updated info
  138. Returns:
  139. - CmdRunAction(command) - bash command to run
  140. - IPythonRunCellAction(code) - IPython code to run
  141. - AgentDelegateAction(agent, inputs) - delegate action for (sub)task
  142. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  143. - AgentFinishAction() - end the interaction
  144. """
  145. # if we're done, go back
  146. latest_user_message = state.history.get_last_user_message()
  147. if latest_user_message and latest_user_message.strip() == '/exit':
  148. return AgentFinishAction()
  149. # prepare what we want to send to the LLM
  150. messages = self._get_messages(state)
  151. response = self.llm.completion(
  152. messages=[message.model_dump() for message in messages],
  153. stop=[
  154. '</execute_ipython>',
  155. '</execute_bash>',
  156. '</execute_browse>',
  157. ],
  158. temperature=0.0,
  159. )
  160. return self.action_parser.parse(response)
  161. def _get_messages(self, state: State) -> list[Message]:
  162. messages: list[Message] = [
  163. Message(
  164. role='system',
  165. content=[TextContent(text=self.prompt_manager.system_message)],
  166. ),
  167. Message(
  168. role='user',
  169. content=[TextContent(text=self.prompt_manager.initial_user_message)],
  170. ),
  171. ]
  172. for event in state.history.get_events():
  173. # create a regular message from an event
  174. if isinstance(event, Action):
  175. message = self.get_action_message(event)
  176. elif isinstance(event, Observation):
  177. message = self.get_observation_message(event)
  178. else:
  179. raise ValueError(f'Unknown event type: {type(event)}')
  180. # add regular message
  181. if message:
  182. # handle error if the message is the SAME role as the previous message
  183. # litellm.exceptions.BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - {'detail': 'Only supports u/a/u/a/u...'}
  184. # there should not have two consecutive messages from the same role
  185. if messages and messages[-1].role == message.role:
  186. messages[-1].content.extend(message.content)
  187. else:
  188. messages.append(message)
  189. # the latest user message is important:
  190. # we want to remind the agent of the environment constraints
  191. latest_user_message = next(
  192. (
  193. m
  194. for m in reversed(messages)
  195. if m.role == 'user'
  196. and any(isinstance(c, TextContent) for c in m.content)
  197. ),
  198. None,
  199. )
  200. # Get the last user text inside content
  201. if latest_user_message:
  202. latest_user_message_text = next(
  203. (
  204. t
  205. for t in reversed(latest_user_message.content)
  206. if isinstance(t, TextContent)
  207. )
  208. )
  209. # add a reminder to the prompt
  210. 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>.'
  211. if latest_user_message_text:
  212. latest_user_message_text.text = (
  213. latest_user_message_text.text + reminder_text
  214. )
  215. else:
  216. latest_user_message_text = TextContent(text=reminder_text)
  217. latest_user_message.content.append(latest_user_message_text)
  218. return messages