codeact_agent.py 22 KB

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