codeact_agent.py 11 KB

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