codeact_agent.py 12 KB

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