codeact_agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. UserRejectObservation,
  20. )
  21. from openhands.events.observation.error import ErrorObservation
  22. from openhands.events.observation.observation import Observation
  23. from openhands.events.serialization.event import truncate_content
  24. from openhands.llm.llm import LLM
  25. from openhands.runtime.plugins import (
  26. AgentSkillsRequirement,
  27. JupyterRequirement,
  28. PluginRequirement,
  29. )
  30. from openhands.utils.microagent import MicroAgent
  31. from openhands.utils.prompt import PromptManager
  32. class CodeActAgent(Agent):
  33. VERSION = '1.9'
  34. """
  35. The Code Act Agent is a minimalist agent.
  36. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  37. ### Overview
  38. 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).
  39. The conceptual idea is illustrated below. At each turn, the agent can:
  40. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  41. 2. **CodeAct**: Choose to perform the task by executing code
  42. - Execute any valid Linux `bash` command
  43. - 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.
  44. ![image](https://github.com/All-Hands-AI/OpenHands/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  45. """
  46. sandbox_plugins: list[PluginRequirement] = [
  47. # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since
  48. # AgentSkillsRequirement provides a lot of Python functions,
  49. # and it needs to be initialized before Jupyter for Jupyter to use those functions.
  50. AgentSkillsRequirement(),
  51. JupyterRequirement(),
  52. ]
  53. action_parser = CodeActResponseParser()
  54. def __init__(
  55. self,
  56. llm: LLM,
  57. config: AgentConfig,
  58. ) -> None:
  59. """Initializes a new instance of the CodeActAgent class.
  60. Parameters:
  61. - llm (LLM): The llm to be used by this agent
  62. """
  63. super().__init__(llm, config)
  64. self.reset()
  65. self.micro_agent = (
  66. MicroAgent(
  67. os.path.join(
  68. os.path.dirname(__file__), 'micro', f'{config.micro_agent_name}.md'
  69. )
  70. )
  71. if config.micro_agent_name
  72. else None
  73. )
  74. self.prompt_manager = PromptManager(
  75. prompt_dir=os.path.join(os.path.dirname(__file__)),
  76. agent_skills_docs=AgentSkillsRequirement.documentation,
  77. micro_agent=self.micro_agent,
  78. )
  79. def action_to_str(self, action: Action) -> str:
  80. if isinstance(action, CmdRunAction):
  81. return (
  82. f'{action.thought}\n<execute_bash>\n{action.command}\n</execute_bash>'
  83. )
  84. elif isinstance(action, IPythonRunCellAction):
  85. return f'{action.thought}\n<execute_ipython>\n{action.code}\n</execute_ipython>'
  86. elif isinstance(action, AgentDelegateAction):
  87. return f'{action.thought}\n<execute_browse>\n{action.inputs["task"]}\n</execute_browse>'
  88. elif isinstance(action, MessageAction):
  89. return action.content
  90. elif isinstance(action, AgentFinishAction) and action.source == 'agent':
  91. return action.thought
  92. return ''
  93. def get_action_message(self, action: Action) -> Message | None:
  94. if (
  95. isinstance(action, AgentDelegateAction)
  96. or isinstance(action, CmdRunAction)
  97. or isinstance(action, IPythonRunCellAction)
  98. or isinstance(action, MessageAction)
  99. or (isinstance(action, AgentFinishAction) and action.source == 'agent')
  100. ):
  101. content = [TextContent(text=self.action_to_str(action))]
  102. if isinstance(action, MessageAction) and action.images_urls:
  103. content.append(ImageContent(image_urls=action.images_urls))
  104. return Message(
  105. role='user' if action.source == 'user' else 'assistant', content=content
  106. )
  107. return None
  108. def get_observation_message(self, obs: Observation) -> Message | None:
  109. max_message_chars = self.llm.config.max_message_chars
  110. if isinstance(obs, CmdOutputObservation):
  111. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  112. text += (
  113. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]'
  114. )
  115. return Message(role='user', content=[TextContent(text=text)])
  116. elif isinstance(obs, IPythonRunCellObservation):
  117. text = 'OBSERVATION:\n' + obs.content
  118. # replace base64 images with a placeholder
  119. splitted = text.split('\n')
  120. for i, line in enumerate(splitted):
  121. if '![image](data:image/png;base64,' in line:
  122. splitted[i] = (
  123. '![image](data:image/png;base64, ...) already displayed to user'
  124. )
  125. text = '\n'.join(splitted)
  126. text = truncate_content(text, max_message_chars)
  127. return Message(role='user', content=[TextContent(text=text)])
  128. elif isinstance(obs, AgentDelegateObservation):
  129. text = 'OBSERVATION:\n' + truncate_content(
  130. str(obs.outputs), max_message_chars
  131. )
  132. return Message(role='user', content=[TextContent(text=text)])
  133. elif isinstance(obs, ErrorObservation):
  134. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  135. text += '\n[Error occurred in processing last action]'
  136. return Message(role='user', content=[TextContent(text=text)])
  137. elif isinstance(obs, UserRejectObservation):
  138. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  139. text += '\n[Last action has been rejected by the user]'
  140. return Message(role='user', content=[TextContent(text=text)])
  141. else:
  142. # If an observation message is not returned, it will cause an error
  143. # when the LLM tries to return the next message
  144. raise ValueError(f'Unknown observation type: {type(obs)}')
  145. def reset(self) -> None:
  146. """Resets the CodeAct Agent."""
  147. super().reset()
  148. def step(self, state: State) -> Action:
  149. """Performs one step using the CodeAct Agent.
  150. This includes gathering info on previous steps and prompting the model to make a command to execute.
  151. Parameters:
  152. - state (State): used to get updated info
  153. Returns:
  154. - CmdRunAction(command) - bash command to run
  155. - IPythonRunCellAction(code) - IPython code to run
  156. - AgentDelegateAction(agent, inputs) - delegate action for (sub)task
  157. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  158. - AgentFinishAction() - end the interaction
  159. """
  160. # if we're done, go back
  161. latest_user_message = state.history.get_last_user_message()
  162. if latest_user_message and latest_user_message.strip() == '/exit':
  163. return AgentFinishAction()
  164. # prepare what we want to send to the LLM
  165. messages = self._get_messages(state)
  166. params = {
  167. 'messages': [message.model_dump() for message in messages],
  168. 'stop': [
  169. '</execute_ipython>',
  170. '</execute_bash>',
  171. '</execute_browse>',
  172. ],
  173. 'temperature': 0.0,
  174. }
  175. if self.llm.supports_prompt_caching:
  176. params['extra_headers'] = {
  177. 'anthropic-beta': 'prompt-caching-2024-07-31',
  178. }
  179. try:
  180. response = self.llm.completion(**params)
  181. except Exception:
  182. return AgentFinishAction(
  183. thought='Agent encountered an error while processing the last action. Please try again.'
  184. )
  185. return self.action_parser.parse(response)
  186. def _get_messages(self, state: State) -> list[Message]:
  187. messages: list[Message] = [
  188. Message(
  189. role='system',
  190. content=[
  191. TextContent(
  192. text=self.prompt_manager.system_message,
  193. cache_prompt=self.llm.supports_prompt_caching, # Cache system prompt
  194. )
  195. ],
  196. ),
  197. Message(
  198. role='user',
  199. content=[
  200. TextContent(
  201. text=self.prompt_manager.initial_user_message,
  202. cache_prompt=self.llm.supports_prompt_caching, # if the user asks the same query,
  203. )
  204. ],
  205. ),
  206. ]
  207. for event in state.history.get_events():
  208. # create a regular message from an event
  209. if isinstance(event, Action):
  210. message = self.get_action_message(event)
  211. elif isinstance(event, Observation):
  212. message = self.get_observation_message(event)
  213. else:
  214. raise ValueError(f'Unknown event type: {type(event)}')
  215. # add regular message
  216. if message:
  217. # handle error if the message is the SAME role as the previous message
  218. # litellm.exceptions.BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - {'detail': 'Only supports u/a/u/a/u...'}
  219. # there should not have two consecutive messages from the same role
  220. if messages and messages[-1].role == message.role:
  221. messages[-1].content.extend(message.content)
  222. else:
  223. messages.append(message)
  224. # Add caching to the last 2 user messages
  225. if self.llm.supports_prompt_caching:
  226. user_turns_processed = 0
  227. for message in reversed(messages):
  228. if message.role == 'user' and user_turns_processed < 2:
  229. message.content[
  230. -1
  231. ].cache_prompt = True # Last item inside the message content
  232. user_turns_processed += 1
  233. # the latest user message is important:
  234. # we want to remind the agent of the environment constraints
  235. latest_user_message = next(
  236. (
  237. m
  238. for m in reversed(messages)
  239. if m.role == 'user'
  240. and any(isinstance(c, TextContent) for c in m.content)
  241. ),
  242. None,
  243. )
  244. if latest_user_message:
  245. 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>.'
  246. latest_user_message.content.append(TextContent(text=reminder_text))
  247. return messages