codeact_agent.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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(str(obs.outputs), max_message_chars)
  136. return Message(role='user', content=[TextContent(text=text)])
  137. elif isinstance(obs, ErrorObservation):
  138. text = obs_prefix + truncate_content(obs.content, max_message_chars)
  139. text += '\n[Error occurred in processing last action]'
  140. return Message(role='user', content=[TextContent(text=text)])
  141. elif isinstance(obs, UserRejectObservation):
  142. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  143. text += '\n[Last action has been rejected by the user]'
  144. return Message(role='user', content=[TextContent(text=text)])
  145. else:
  146. # If an observation message is not returned, it will cause an error
  147. # when the LLM tries to return the next message
  148. raise ValueError(f'Unknown observation type: {type(obs)}')
  149. def reset(self) -> None:
  150. """Resets the CodeAct Agent."""
  151. super().reset()
  152. def step(self, state: State) -> Action:
  153. """Performs one step using the CodeAct Agent.
  154. This includes gathering info on previous steps and prompting the model to make a command to execute.
  155. Parameters:
  156. - state (State): used to get updated info
  157. Returns:
  158. - CmdRunAction(command) - bash command to run
  159. - IPythonRunCellAction(code) - IPython code to run
  160. - AgentDelegateAction(agent, inputs) - delegate action for (sub)task
  161. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  162. - AgentFinishAction() - end the interaction
  163. """
  164. # if we're done, go back
  165. latest_user_message = state.history.get_last_user_message()
  166. if latest_user_message and latest_user_message.strip() == '/exit':
  167. return AgentFinishAction()
  168. # prepare what we want to send to the LLM
  169. messages = self._get_messages(state)
  170. params = {
  171. 'messages': self.llm.format_messages_for_llm(messages),
  172. 'stop': [
  173. '</execute_ipython>',
  174. '</execute_bash>',
  175. '</execute_browse>',
  176. ],
  177. 'temperature': 0.0,
  178. }
  179. if self.llm.is_caching_prompt_active():
  180. params['extra_headers'] = {
  181. 'anthropic-beta': 'prompt-caching-2024-07-31',
  182. }
  183. try:
  184. response = self.llm.completion(**params)
  185. except Exception:
  186. return AgentFinishAction(
  187. thought='Agent encountered an error while processing the last action. Please try again.'
  188. )
  189. return self.action_parser.parse(response)
  190. def _get_messages(self, state: State) -> list[Message]:
  191. messages: list[Message] = [
  192. Message(
  193. role='system',
  194. content=[
  195. TextContent(
  196. text=self.prompt_manager.system_message,
  197. cache_prompt=self.llm.is_caching_prompt_active(), # Cache system prompt
  198. )
  199. ],
  200. ),
  201. Message(
  202. role='user',
  203. content=[
  204. TextContent(
  205. text=self.prompt_manager.initial_user_message,
  206. cache_prompt=self.llm.is_caching_prompt_active(), # if the user asks the same query,
  207. )
  208. ],
  209. ),
  210. ]
  211. for event in state.history.get_events():
  212. # create a regular message from an event
  213. if isinstance(event, Action):
  214. message = self.get_action_message(event)
  215. elif isinstance(event, Observation):
  216. message = self.get_observation_message(event)
  217. else:
  218. raise ValueError(f'Unknown event type: {type(event)}')
  219. # add regular message
  220. if message:
  221. # handle error if the message is the SAME role as the previous message
  222. # litellm.exceptions.BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - {'detail': 'Only supports u/a/u/a/u...'}
  223. # there shouldn't be two consecutive messages from the same role
  224. if messages and messages[-1].role == message.role:
  225. messages[-1].content.extend(message.content)
  226. else:
  227. messages.append(message)
  228. # Add caching to the last 2 user messages
  229. if self.llm.is_caching_prompt_active():
  230. user_turns_processed = 0
  231. for message in reversed(messages):
  232. if message.role == 'user' and user_turns_processed < 2:
  233. message.content[
  234. -1
  235. ].cache_prompt = True # Last item inside the message content
  236. user_turns_processed += 1
  237. # The latest user message is important:
  238. # we want to remind the agent of the environment constraints
  239. latest_user_message = next(
  240. islice(
  241. (
  242. m
  243. for m in reversed(messages)
  244. if m.role == 'user'
  245. and any(isinstance(c, TextContent) for c in m.content)
  246. ),
  247. 1,
  248. ),
  249. None,
  250. )
  251. if latest_user_message:
  252. 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>.'
  253. latest_user_message.content.append(TextContent(text=reminder_text))
  254. return messages