codeact_agent.py 11 KB

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