codeact_agent.py 23 KB

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