codeact_agent.py 11 KB

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