codeact_agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import re
  2. from agenthub.codeact_agent.prompt import (
  3. COMMAND_DOCS,
  4. EXAMPLES,
  5. GITHUB_MESSAGE,
  6. SYSTEM_PREFIX,
  7. SYSTEM_SUFFIX,
  8. )
  9. from opendevin.controller.agent import Agent
  10. from opendevin.controller.state.state import State
  11. from opendevin.events.action import (
  12. Action,
  13. AgentFinishAction,
  14. BrowseInteractiveAction,
  15. CmdRunAction,
  16. IPythonRunCellAction,
  17. MessageAction,
  18. )
  19. from opendevin.events.observation import (
  20. BrowserOutputObservation,
  21. CmdOutputObservation,
  22. IPythonRunCellObservation,
  23. )
  24. from opendevin.llm.llm import LLM
  25. from opendevin.runtime.plugins import (
  26. AgentSkillsRequirement,
  27. JupyterRequirement,
  28. PluginRequirement,
  29. )
  30. from opendevin.runtime.tools import RuntimeTool
  31. ENABLE_GITHUB = True
  32. def parse_response(response) -> str:
  33. action = response.choices[0].message.content
  34. for lang in ['bash', 'ipython', 'browse']:
  35. if f'<execute_{lang}>' in action and f'</execute_{lang}>' not in action:
  36. action += f'</execute_{lang}>'
  37. return action
  38. def action_to_str(action: Action) -> str:
  39. if isinstance(action, CmdRunAction):
  40. return f'{action.thought}\n<execute_bash>\n{action.command}\n</execute_bash>'
  41. elif isinstance(action, IPythonRunCellAction):
  42. return f'{action.thought}\n<execute_ipython>\n{action.code}\n</execute_ipython>'
  43. elif isinstance(action, BrowseInteractiveAction):
  44. return f'{action.thought}\n<execute_browse>\n{action.browser_actions}\n</execute_browse>'
  45. elif isinstance(action, MessageAction):
  46. return action.content
  47. return ''
  48. def get_action_message(action: Action) -> dict[str, str] | None:
  49. if (
  50. isinstance(action, BrowseInteractiveAction)
  51. or isinstance(action, CmdRunAction)
  52. or isinstance(action, IPythonRunCellAction)
  53. or isinstance(action, MessageAction)
  54. ):
  55. return {
  56. 'role': 'user' if action.source == 'user' else 'assistant',
  57. 'content': action_to_str(action),
  58. }
  59. return None
  60. def get_observation_message(obs) -> dict[str, str] | None:
  61. if isinstance(obs, CmdOutputObservation):
  62. content = 'OBSERVATION:\n' + truncate_observation(obs.content)
  63. content += (
  64. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]]'
  65. )
  66. return {'role': 'user', 'content': content}
  67. elif isinstance(obs, IPythonRunCellObservation):
  68. content = 'OBSERVATION:\n' + obs.content
  69. # replace base64 images with a placeholder
  70. splitted = content.split('\n')
  71. for i, line in enumerate(splitted):
  72. if '![image](data:image/png;base64,' in line:
  73. splitted[i] = (
  74. '![image](data:image/png;base64, ...) already displayed to user'
  75. )
  76. content = '\n'.join(splitted)
  77. content = truncate_observation(content)
  78. return {'role': 'user', 'content': content}
  79. elif isinstance(obs, BrowserOutputObservation):
  80. content = 'OBSERVATION:\n' + truncate_observation(obs.content)
  81. return {'role': 'user', 'content': content}
  82. return None
  83. def truncate_observation(observation: str, max_chars: int = 10_000) -> str:
  84. """
  85. Truncate the middle of the observation if it is too long.
  86. """
  87. if len(observation) <= max_chars:
  88. return observation
  89. half = max_chars // 2
  90. return (
  91. observation[:half]
  92. + '\n[... Observation truncated due to length ...]\n'
  93. + observation[-half:]
  94. )
  95. # FIXME: We can tweak these two settings to create MicroAgents specialized toward different area
  96. def get_system_message() -> str:
  97. if ENABLE_GITHUB:
  98. return f'{SYSTEM_PREFIX}\n{GITHUB_MESSAGE}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  99. else:
  100. return f'{SYSTEM_PREFIX}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  101. def get_in_context_example() -> str:
  102. return EXAMPLES
  103. class CodeActAgent(Agent):
  104. VERSION = '1.5'
  105. """
  106. The Code Act Agent is a minimalist agent.
  107. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  108. ### Overview
  109. This agent implements the CodeAct idea ([paper](https://arxiv.org/abs/2402.13463), [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).
  110. The conceptual idea is illustrated below. At each turn, the agent can:
  111. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  112. 2. **CodeAct**: Choose to perform the task by executing code
  113. - Execute any valid Linux `bash` command
  114. - 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.
  115. ![image](https://github.com/OpenDevin/OpenDevin/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  116. ### Plugin System
  117. To make the CodeAct agent more powerful with only access to `bash` action space, CodeAct agent leverages OpenDevin's plugin system:
  118. - [Jupyter plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/jupyter): for IPython execution via bash command
  119. - [SWE-agent tool plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/swe_agent_commands): Powerful bash command line tools for software development tasks introduced by [swe-agent](https://github.com/princeton-nlp/swe-agent).
  120. ### Demo
  121. https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d69282d5f6ac
  122. *Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)*
  123. ### Work-in-progress & Next step
  124. [] Support web-browsing
  125. [] Complete the workflow for CodeAct agent to submit Github PRs
  126. """
  127. sandbox_plugins: list[PluginRequirement] = [
  128. # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since
  129. # AgentSkillsRequirement provides a lot of Python functions
  130. # and it need to be initialized before Jupyter for Jupyter to use those functions.
  131. AgentSkillsRequirement(),
  132. JupyterRequirement(),
  133. ]
  134. runtime_tools: list[RuntimeTool] = [RuntimeTool.BROWSER]
  135. jupyter_kernel_init_code: str = 'from agentskills import *'
  136. system_message: str = get_system_message()
  137. in_context_example: str = f"Here is an example of how you can interact with the environment for task solving:\n{get_in_context_example()}\n\nNOW, LET'S START!"
  138. def __init__(
  139. self,
  140. llm: LLM,
  141. ) -> None:
  142. """
  143. Initializes a new instance of the CodeActAgent class.
  144. Parameters:
  145. - llm (LLM): The llm to be used by this agent
  146. """
  147. super().__init__(llm)
  148. self.reset()
  149. def reset(self) -> None:
  150. """
  151. Resets the CodeAct Agent.
  152. """
  153. super().reset()
  154. def step(self, state: State) -> Action:
  155. """
  156. Performs one step using the CodeAct Agent.
  157. This includes gathering info on previous steps and prompting the model to make a command to execute.
  158. Parameters:
  159. - state (State): used to get updated info and background commands
  160. Returns:
  161. - CmdRunAction(command) - bash command to run
  162. - IPythonRunCellAction(code) - IPython code to run
  163. - BrowseInteractiveAction(browsergym_command) - BrowserGym commands to run
  164. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  165. - AgentFinishAction() - end the interaction
  166. """
  167. messages: list[dict[str, str]] = [
  168. {'role': 'system', 'content': self.system_message},
  169. {'role': 'user', 'content': self.in_context_example},
  170. ]
  171. for prev_action, obs in state.history:
  172. action_message = get_action_message(prev_action)
  173. if action_message:
  174. messages.append(action_message)
  175. obs_message = get_observation_message(obs)
  176. if obs_message:
  177. messages.append(obs_message)
  178. latest_user_message = [m for m in messages if m['role'] == 'user'][-1]
  179. if latest_user_message:
  180. if latest_user_message['content'].strip() == '/exit':
  181. return AgentFinishAction()
  182. latest_user_message['content'] += (
  183. f'\n\nENVIRONMENT REMINDER: You have {state.max_iterations - state.iteration} turns left to complete the task.'
  184. )
  185. response = self.llm.do_completion(
  186. messages=messages,
  187. stop=[
  188. '</execute_ipython>',
  189. '</execute_bash>',
  190. '</execute_browse>',
  191. ],
  192. temperature=0.0,
  193. )
  194. action_str: str = parse_response(response)
  195. state.num_of_chars += sum(
  196. len(message['content']) for message in messages
  197. ) + len(action_str)
  198. if finish_command := re.search(r'<finish>.*</finish>', action_str, re.DOTALL):
  199. thought = action_str.replace(finish_command.group(0), '').strip()
  200. return AgentFinishAction(thought=thought)
  201. if bash_command := re.search(
  202. r'<execute_bash>(.*?)</execute_bash>', action_str, re.DOTALL
  203. ):
  204. # remove the command from the action string to get thought
  205. thought = action_str.replace(bash_command.group(0), '').strip()
  206. # a command was found
  207. command_group = bash_command.group(1).strip()
  208. if command_group.strip() == 'exit':
  209. return AgentFinishAction()
  210. return CmdRunAction(command=command_group, thought=thought)
  211. elif python_code := re.search(
  212. r'<execute_ipython>(.*?)</execute_ipython>', action_str, re.DOTALL
  213. ):
  214. # a code block was found
  215. code_group = python_code.group(1).strip()
  216. thought = action_str.replace(python_code.group(0), '').strip()
  217. return IPythonRunCellAction(
  218. code=code_group,
  219. thought=thought,
  220. kernel_init_code=self.jupyter_kernel_init_code,
  221. )
  222. elif browse_command := re.search(
  223. r'<execute_browse>(.*)</execute_browse>', action_str, re.DOTALL
  224. ):
  225. # BrowserGym actions was found
  226. browse_actions = browse_command.group(1).strip()
  227. thought = action_str.replace(browse_command.group(0), '').strip()
  228. return BrowseInteractiveAction(
  229. browser_actions=browse_actions, thought=thought
  230. )
  231. else:
  232. # We assume the LLM is GOOD enough that when it returns pure natural language
  233. # it want to talk to the user
  234. return MessageAction(content=action_str, wait_for_response=True)
  235. def search_memory(self, query: str) -> list[str]:
  236. raise NotImplementedError('Implement this abstract method')