codeact_agent.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. import json
  2. import os
  3. from collections import deque
  4. from itertools import islice
  5. from litellm import ModelResponse
  6. import openhands.agenthub.codeact_agent.function_calling as codeact_function_calling
  7. from openhands.agenthub.codeact_agent.action_parser import CodeActResponseParser
  8. from openhands.controller.agent import Agent
  9. from openhands.controller.state.state import State
  10. from openhands.core.config import AgentConfig
  11. from openhands.core.logger import openhands_logger as logger
  12. from openhands.core.message import ImageContent, Message, TextContent
  13. from openhands.events.action import (
  14. Action,
  15. AgentDelegateAction,
  16. AgentFinishAction,
  17. CmdRunAction,
  18. FileEditAction,
  19. IPythonRunCellAction,
  20. MessageAction,
  21. )
  22. from openhands.events.observation import (
  23. AgentDelegateObservation,
  24. CmdOutputObservation,
  25. FileEditObservation,
  26. IPythonRunCellObservation,
  27. UserRejectObservation,
  28. )
  29. from openhands.events.observation.error import ErrorObservation
  30. from openhands.events.observation.observation import Observation
  31. from openhands.events.serialization.event import truncate_content
  32. from openhands.llm.llm import LLM
  33. from openhands.runtime.plugins import (
  34. AgentSkillsRequirement,
  35. JupyterRequirement,
  36. PluginRequirement,
  37. )
  38. from openhands.utils.microagent import MicroAgent
  39. from openhands.utils.prompt import PromptManager
  40. class CodeActAgent(Agent):
  41. VERSION = '2.1'
  42. """
  43. The Code Act Agent is a minimalist agent.
  44. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  45. ### Overview
  46. 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).
  47. The conceptual idea is illustrated below. At each turn, the agent can:
  48. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  49. 2. **CodeAct**: Choose to perform the task by executing code
  50. - Execute any valid Linux `bash` command
  51. - 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.
  52. ![image](https://github.com/All-Hands-AI/OpenHands/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  53. """
  54. sandbox_plugins: list[PluginRequirement] = [
  55. # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since
  56. # AgentSkillsRequirement provides a lot of Python functions,
  57. # and it needs to be initialized before Jupyter for Jupyter to use those functions.
  58. AgentSkillsRequirement(),
  59. JupyterRequirement(),
  60. ]
  61. obs_prefix = 'OBSERVATION:\n'
  62. def __init__(
  63. self,
  64. llm: LLM,
  65. config: AgentConfig,
  66. ) -> None:
  67. """Initializes a new instance of the CodeActAgent class.
  68. Parameters:
  69. - llm (LLM): The llm to be used by this agent
  70. """
  71. super().__init__(llm, config)
  72. self.reset()
  73. self.micro_agent = (
  74. MicroAgent(
  75. os.path.join(
  76. os.path.dirname(__file__), 'micro', f'{config.micro_agent_name}.md'
  77. )
  78. )
  79. if config.micro_agent_name
  80. else None
  81. )
  82. self.function_calling_active = self.config.function_calling
  83. if self.function_calling_active and not self.llm.is_function_calling_active():
  84. logger.warning(
  85. f'Function calling not supported for model {self.llm.config.model}. '
  86. 'Disabling function calling.'
  87. )
  88. self.function_calling_active = False
  89. if self.function_calling_active:
  90. # Function calling mode
  91. self.tools = codeact_function_calling.get_tools(
  92. codeact_enable_browsing_delegate=self.config.codeact_enable_browsing_delegate,
  93. codeact_enable_jupyter=self.config.codeact_enable_jupyter,
  94. codeact_enable_llm_editor=self.config.codeact_enable_llm_editor,
  95. )
  96. logger.info(
  97. f'TOOLS loaded for CodeActAgent: {json.dumps(self.tools, indent=2)}'
  98. )
  99. self.system_prompt = codeact_function_calling.SYSTEM_PROMPT
  100. self.initial_user_message = None
  101. else:
  102. # Non-function-calling mode
  103. self.action_parser = CodeActResponseParser()
  104. self.prompt_manager = PromptManager(
  105. prompt_dir=os.path.join(os.path.dirname(__file__)),
  106. agent_skills_docs=AgentSkillsRequirement.documentation,
  107. micro_agent=self.micro_agent,
  108. )
  109. self.system_prompt = self.prompt_manager.system_message
  110. self.initial_user_message = self.prompt_manager.initial_user_message
  111. self.pending_actions: deque[Action] = deque()
  112. def get_action_message(
  113. self,
  114. action: Action,
  115. pending_tool_call_action_messages: dict[str, Message],
  116. ) -> list[Message]:
  117. """Converts an action into a message format that can be sent to the LLM.
  118. This method handles different types of actions and formats them appropriately:
  119. 1. For tool-based actions (AgentDelegate, CmdRun, IPythonRunCell, FileEdit) and agent-sourced AgentFinish:
  120. - In function calling mode: Stores the LLM's response in pending_tool_call_action_messages
  121. - In non-function calling mode: Creates a message with the action string
  122. 2. For MessageActions: Creates a message with the text content and optional image content
  123. Args:
  124. action (Action): The action to convert. Can be one of:
  125. - AgentDelegateAction: For delegating tasks to other agents
  126. - CmdRunAction: For executing bash commands
  127. - IPythonRunCellAction: For running IPython code
  128. - FileEditAction: For editing files
  129. - AgentFinishAction: For ending the interaction
  130. - MessageAction: For sending messages
  131. pending_tool_call_action_messages (dict[str, Message]): Dictionary mapping response IDs
  132. to their corresponding messages. Used in function calling mode to track tool calls
  133. that are waiting for their results.
  134. Returns:
  135. list[Message]: A list containing the formatted message(s) for the action.
  136. May be empty if the action is handled as a tool call in function calling mode.
  137. Note:
  138. In function calling mode, tool-based actions are stored in pending_tool_call_action_messages
  139. rather than being returned immediately. They will be processed later when all corresponding
  140. tool call results are available.
  141. """
  142. # create a regular message from an event
  143. if isinstance(
  144. action,
  145. (
  146. AgentDelegateAction,
  147. CmdRunAction,
  148. IPythonRunCellAction,
  149. FileEditAction,
  150. ),
  151. ) or (isinstance(action, AgentFinishAction) and action.source == 'agent'):
  152. if self.function_calling_active:
  153. tool_metadata = action.tool_call_metadata
  154. assert tool_metadata is not None, (
  155. 'Tool call metadata should NOT be None when function calling is enabled. Action: '
  156. + str(action)
  157. )
  158. llm_response: ModelResponse = tool_metadata.model_response
  159. assistant_msg = llm_response.choices[0].message
  160. # Add the LLM message (assistant) that initiated the tool calls
  161. # (overwrites any previous message with the same response_id)
  162. pending_tool_call_action_messages[llm_response.id] = Message(
  163. role=assistant_msg.role,
  164. # tool call content SHOULD BE a string
  165. content=[TextContent(text=assistant_msg.content)]
  166. if assistant_msg.content is not None
  167. else [],
  168. tool_calls=assistant_msg.tool_calls,
  169. )
  170. return []
  171. else:
  172. content = [TextContent(text=self.action_parser.action_to_str(action))]
  173. return [
  174. Message(
  175. role='user' if action.source == 'user' else 'assistant',
  176. content=content,
  177. )
  178. ]
  179. elif isinstance(action, MessageAction):
  180. role = 'user' if action.source == 'user' else 'assistant'
  181. content = [TextContent(text=action.content)]
  182. if self.llm.vision_is_active() and action.images_urls:
  183. content.append(ImageContent(image_urls=action.images_urls))
  184. return [
  185. Message(
  186. role=role,
  187. content=content,
  188. )
  189. ]
  190. return []
  191. def get_observation_message(
  192. self,
  193. obs: Observation,
  194. tool_call_id_to_message: dict[str, Message],
  195. ) -> list[Message]:
  196. """Converts an observation into a message format that can be sent to the LLM.
  197. This method handles different types of observations and formats them appropriately:
  198. - CmdOutputObservation: Formats command execution results with exit codes
  199. - IPythonRunCellObservation: Formats IPython cell execution results, replacing base64 images
  200. - FileEditObservation: Formats file editing results
  201. - AgentDelegateObservation: Formats results from delegated agent tasks
  202. - ErrorObservation: Formats error messages from failed actions
  203. - UserRejectObservation: Formats user rejection messages
  204. In function calling mode, observations with tool_call_metadata are stored in
  205. tool_call_id_to_message for later processing instead of being returned immediately.
  206. Args:
  207. obs (Observation): The observation to convert
  208. tool_call_id_to_message (dict[str, Message]): Dictionary mapping tool call IDs
  209. to their corresponding messages (used in function calling mode)
  210. Returns:
  211. list[Message]: A list containing the formatted message(s) for the observation.
  212. May be empty if the observation is handled as a tool response in function calling mode.
  213. Raises:
  214. ValueError: If the observation type is unknown
  215. """
  216. message: Message
  217. max_message_chars = self.llm.config.max_message_chars
  218. obs_prefix = 'OBSERVATION:\n'
  219. if isinstance(obs, CmdOutputObservation):
  220. text = obs_prefix + truncate_content(
  221. obs.content + obs.interpreter_details, max_message_chars
  222. )
  223. text += f'\n[Command finished with exit code {obs.exit_code}]'
  224. message = Message(role='user', content=[TextContent(text=text)])
  225. elif isinstance(obs, IPythonRunCellObservation):
  226. text = obs_prefix + obs.content
  227. # replace base64 images with a placeholder
  228. splitted = text.split('\n')
  229. for i, line in enumerate(splitted):
  230. if '![image](data:image/png;base64,' in line:
  231. splitted[i] = (
  232. '![image](data:image/png;base64, ...) already displayed to user'
  233. )
  234. text = '\n'.join(splitted)
  235. text = truncate_content(text, max_message_chars)
  236. message = Message(role='user', content=[TextContent(text=text)])
  237. elif isinstance(obs, FileEditObservation):
  238. text = obs_prefix + truncate_content(str(obs), max_message_chars)
  239. message = Message(role='user', content=[TextContent(text=text)])
  240. elif isinstance(obs, AgentDelegateObservation):
  241. text = obs_prefix + truncate_content(
  242. obs.outputs['content'] if 'content' in obs.outputs else '',
  243. max_message_chars,
  244. )
  245. message = Message(role='user', content=[TextContent(text=text)])
  246. elif isinstance(obs, ErrorObservation):
  247. text = obs_prefix + truncate_content(obs.content, max_message_chars)
  248. text += '\n[Error occurred in processing last action]'
  249. message = Message(role='user', content=[TextContent(text=text)])
  250. elif isinstance(obs, UserRejectObservation):
  251. text = 'OBSERVATION:\n' + truncate_content(obs.content, max_message_chars)
  252. text += '\n[Last action has been rejected by the user]'
  253. message = Message(role='user', content=[TextContent(text=text)])
  254. else:
  255. # If an observation message is not returned, it will cause an error
  256. # when the LLM tries to return the next message
  257. raise ValueError(f'Unknown observation type: {type(obs)}')
  258. if self.function_calling_active:
  259. # Update the message as tool response properly
  260. if (tool_call_metadata := obs.tool_call_metadata) is not None:
  261. tool_call_id_to_message[tool_call_metadata.tool_call_id] = Message(
  262. role='tool',
  263. content=message.content,
  264. tool_call_id=tool_call_metadata.tool_call_id,
  265. name=tool_call_metadata.function_name,
  266. )
  267. # No need to return the observation message
  268. # because it will be added by get_action_message when all the corresponding
  269. # tool calls in the SAME request are processed
  270. return []
  271. return [message]
  272. def reset(self) -> None:
  273. """Resets the CodeAct Agent."""
  274. super().reset()
  275. def step(self, state: State) -> Action:
  276. """Performs one step using the CodeAct Agent.
  277. This includes gathering info on previous steps and prompting the model to make a command to execute.
  278. Parameters:
  279. - state (State): used to get updated info
  280. Returns:
  281. - CmdRunAction(command) - bash command to run
  282. - IPythonRunCellAction(code) - IPython code to run
  283. - AgentDelegateAction(agent, inputs) - delegate action for (sub)task
  284. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  285. - AgentFinishAction() - end the interaction
  286. """
  287. # Continue with pending actions if any
  288. if self.pending_actions:
  289. return self.pending_actions.popleft()
  290. # if we're done, go back
  291. latest_user_message = state.history.get_last_user_message()
  292. if latest_user_message and latest_user_message.strip() == '/exit':
  293. return AgentFinishAction()
  294. # prepare what we want to send to the LLM
  295. messages = self._get_messages(state)
  296. params: dict = {
  297. 'messages': self.llm.format_messages_for_llm(messages),
  298. }
  299. if self.function_calling_active:
  300. params['tools'] = self.tools
  301. else:
  302. params['stop'] = [
  303. '</execute_ipython>',
  304. '</execute_bash>',
  305. '</execute_browse>',
  306. '</file_edit>',
  307. ]
  308. response = self.llm.completion(**params)
  309. if self.function_calling_active:
  310. actions = codeact_function_calling.response_to_actions(response)
  311. for action in actions:
  312. self.pending_actions.append(action)
  313. return self.pending_actions.popleft()
  314. else:
  315. return self.action_parser.parse(response)
  316. def _get_messages(self, state: State) -> list[Message]:
  317. """Constructs the message history for the LLM conversation.
  318. This method builds a structured conversation history by processing events from the state
  319. and formatting them into messages that the LLM can understand. It handles both regular
  320. message flow and function-calling scenarios.
  321. The method performs the following steps:
  322. 1. Initializes with system prompt and optional initial user message
  323. 2. Processes events (Actions and Observations) into messages
  324. 3. Handles tool calls and their responses in function-calling mode
  325. 4. Manages message role alternation (user/assistant/tool)
  326. 5. Applies caching for specific LLM providers (e.g., Anthropic)
  327. 6. Adds environment reminders for non-function-calling mode
  328. Args:
  329. state (State): The current state object containing conversation history and other metadata
  330. Returns:
  331. list[Message]: A list of formatted messages ready for LLM consumption, including:
  332. - System message with prompt
  333. - Initial user message (if configured)
  334. - Action messages (from both user and assistant)
  335. - Observation messages (including tool responses)
  336. - Environment reminders (in non-function-calling mode)
  337. Note:
  338. - In function-calling mode, tool calls and their responses are carefully tracked
  339. to maintain proper conversation flow
  340. - Messages from the same role are combined to prevent consecutive same-role messages
  341. - For Anthropic models, specific messages are cached according to their documentation
  342. """
  343. messages: list[Message] = [
  344. Message(
  345. role='system',
  346. content=[
  347. TextContent(
  348. text=self.system_prompt,
  349. cache_prompt=self.llm.is_caching_prompt_active(), # Cache system prompt
  350. )
  351. ],
  352. )
  353. ]
  354. if self.initial_user_message:
  355. messages.append(
  356. Message(
  357. role='user',
  358. content=[TextContent(text=self.initial_user_message)],
  359. )
  360. )
  361. pending_tool_call_action_messages: dict[str, Message] = {}
  362. tool_call_id_to_message: dict[str, Message] = {}
  363. events = list(state.history.get_events())
  364. for event in events:
  365. # create a regular message from an event
  366. if isinstance(event, Action):
  367. messages_to_add = self.get_action_message(
  368. action=event,
  369. pending_tool_call_action_messages=pending_tool_call_action_messages,
  370. )
  371. elif isinstance(event, Observation):
  372. messages_to_add = self.get_observation_message(
  373. obs=event,
  374. tool_call_id_to_message=tool_call_id_to_message,
  375. )
  376. else:
  377. raise ValueError(f'Unknown event type: {type(event)}')
  378. # Check pending tool call action messages and see if they are complete
  379. _response_ids_to_remove = []
  380. for (
  381. response_id,
  382. pending_message,
  383. ) in pending_tool_call_action_messages.items():
  384. assert pending_message.tool_calls is not None, (
  385. 'Tool calls should NOT be None when function calling is enabled & the message is considered pending tool call. '
  386. f'Pending message: {pending_message}'
  387. )
  388. if all(
  389. tool_call.id in tool_call_id_to_message
  390. for tool_call in pending_message.tool_calls
  391. ):
  392. # If complete:
  393. # -- 1. Add the message that **initiated** the tool calls
  394. messages_to_add.append(pending_message)
  395. # -- 2. Add the tool calls **results***
  396. for tool_call in pending_message.tool_calls:
  397. messages_to_add.append(tool_call_id_to_message[tool_call.id])
  398. tool_call_id_to_message.pop(tool_call.id)
  399. _response_ids_to_remove.append(response_id)
  400. # Cleanup the processed pending tool messages
  401. for response_id in _response_ids_to_remove:
  402. pending_tool_call_action_messages.pop(response_id)
  403. for message in messages_to_add:
  404. # add regular message
  405. if message:
  406. # handle error if the message is the SAME role as the previous message
  407. # litellm.exceptions.BadRequestError: litellm.BadRequestError: OpenAIException - Error code: 400 - {'detail': 'Only supports u/a/u/a/u...'}
  408. # there shouldn't be two consecutive messages from the same role
  409. # NOTE: we shouldn't combine tool messages because each of them has a different tool_call_id
  410. if (
  411. messages
  412. and messages[-1].role == message.role
  413. and message.role != 'tool'
  414. ):
  415. messages[-1].content.extend(message.content)
  416. else:
  417. messages.append(message)
  418. if self.llm.is_caching_prompt_active():
  419. # NOTE: this is only needed for anthropic
  420. # following logic here:
  421. # https://github.com/anthropics/anthropic-quickstarts/blob/8f734fd08c425c6ec91ddd613af04ff87d70c5a0/computer-use-demo/computer_use_demo/loop.py#L241-L262
  422. breakpoints_remaining = 3 # remaining 1 for system/tool
  423. for message in reversed(messages):
  424. if message.role == 'user' or message.role == 'tool':
  425. if breakpoints_remaining > 0:
  426. message.content[
  427. -1
  428. ].cache_prompt = True # Last item inside the message content
  429. breakpoints_remaining -= 1
  430. else:
  431. break
  432. if not self.function_calling_active:
  433. # The latest user message is important:
  434. # we want to remind the agent of the environment constraints
  435. latest_user_message = next(
  436. islice(
  437. (
  438. m
  439. for m in reversed(messages)
  440. if m.role == 'user'
  441. and any(isinstance(c, TextContent) for c in m.content)
  442. ),
  443. 1,
  444. ),
  445. None,
  446. )
  447. # do not add this for function calling
  448. if latest_user_message:
  449. 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>.'
  450. latest_user_message.content.append(TextContent(text=reminder_text))
  451. return messages