codeact_agent.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import re
  2. from typing import Mapping
  3. from agenthub.codeact_agent.prompt import EXAMPLES, SYSTEM_MESSAGE
  4. from opendevin.controller.agent import Agent
  5. from opendevin.controller.state.state import State
  6. from opendevin.core.logger import opendevin_logger as logger
  7. from opendevin.events.action import (
  8. Action,
  9. AgentFinishAction,
  10. CmdRunAction,
  11. IPythonRunCellAction,
  12. MessageAction,
  13. NullAction,
  14. )
  15. from opendevin.events.observation import (
  16. CmdOutputObservation,
  17. IPythonRunCellObservation,
  18. NullObservation,
  19. )
  20. from opendevin.llm.llm import LLM, completion_cost
  21. from opendevin.runtime.plugins import (
  22. JupyterRequirement,
  23. PluginRequirement,
  24. SWEAgentCommandsRequirement,
  25. )
  26. def parse_response(response) -> str:
  27. action = response.choices[0].message.content
  28. for lang in ['bash', 'ipython']:
  29. if f'<execute_{lang}>' in action and f'</execute_{lang}>' not in action:
  30. action += f'</execute_{lang}>'
  31. return action
  32. def truncate_observation(observation: str, max_chars: int = 10_000) -> str:
  33. """
  34. Truncate the middle of the observation if it is too long.
  35. """
  36. if len(observation) <= max_chars:
  37. return observation
  38. half = max_chars // 2
  39. return (
  40. observation[:half]
  41. + '\n[... Observation truncated due to length ...]\n'
  42. + observation[-half:]
  43. )
  44. def swe_agent_edit_hack(bash_command: str) -> str:
  45. """
  46. Hack to handle the SWE-agent edit command. The vanilla edit command will hang the SSHBox.
  47. REPLACE THIS:
  48. edit 683:693
  49. try:
  50. return list(urlsplit(url))
  51. except ValueError:
  52. raise ValidationError(self.error_messages['invalid'], code='invalid')
  53. end_of_edit
  54. WITH THIS:
  55. edit 683:693 <<EOF
  56. try:
  57. return list(urlsplit(url))
  58. except ValueError:
  59. raise ValidationError(self.error_messages['invalid'], code='invalid')s
  60. EOF
  61. """
  62. if 'edit' in bash_command:
  63. # edit\s(\d+):(\d+)([\s\S]*)end_of_edit
  64. # replace
  65. bash_command = re.sub(
  66. r'edit\s(\d+):(\d+)([\s\S]*)end_of_edit',
  67. r'edit \1:\2 <<EOF\3EOF',
  68. bash_command,
  69. )
  70. return bash_command
  71. class CodeActAgent(Agent):
  72. VERSION = '1.1'
  73. """
  74. The Code Act Agent is a minimalist agent.
  75. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  76. ### Overview
  77. 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).
  78. The conceptual idea is illustrated below. At each turn, the agent can:
  79. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  80. 2. **CodeAct**: Choose to perform the task by executing code
  81. - Execute any valid Linux `bash` command
  82. - 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.
  83. ![image](https://github.com/OpenDevin/OpenDevin/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  84. ### Plugin System
  85. To make the CodeAct agent more powerful with only access to `bash` action space, CodeAct agent leverages OpenDevin's plugin system:
  86. - [Jupyter plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/jupyter): for IPython execution via bash command
  87. - [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).
  88. ### Demo
  89. https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d69282d5f6ac
  90. *Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)*
  91. ### Work-in-progress & Next step
  92. [] Support web-browsing
  93. [] Complete the workflow for CodeAct agent to submit Github PRs
  94. """
  95. sandbox_plugins: list[PluginRequirement] = [
  96. JupyterRequirement(),
  97. SWEAgentCommandsRequirement(),
  98. ]
  99. SUPPORTED_ACTIONS = (
  100. CmdRunAction,
  101. IPythonRunCellAction,
  102. MessageAction,
  103. NullAction,
  104. )
  105. SUPPORTED_OBSERVATIONS = (
  106. CmdOutputObservation,
  107. IPythonRunCellObservation,
  108. NullObservation,
  109. )
  110. def __init__(
  111. self,
  112. llm: LLM,
  113. ) -> None:
  114. """
  115. Initializes a new instance of the CodeActAgent class.
  116. Parameters:
  117. - llm (LLM): The llm to be used by this agent
  118. """
  119. super().__init__(llm)
  120. self.messages: list[Mapping[str, str]] = []
  121. self.cost_accumulator = 0
  122. def step(self, state: State) -> Action:
  123. """
  124. Performs one step using the CodeAct Agent.
  125. This includes gathering info on previous steps and prompting the model to make a command to execute.
  126. Parameters:
  127. - state (State): used to get updated info and background commands
  128. Returns:
  129. - CmdRunAction(command) - bash command to run
  130. - IPythonRunCellAction(code) - IPython code to run
  131. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  132. - AgentFinishAction() - end the interaction
  133. """
  134. if len(self.messages) == 0:
  135. assert state.plan.main_goal, 'Expecting instruction to be set'
  136. self.messages = [
  137. {'role': 'system', 'content': SYSTEM_MESSAGE},
  138. {
  139. 'role': 'user',
  140. 'content': (
  141. f'Here is an example of how you can interact with the environment for task solving:\n{EXAMPLES}\n\n'
  142. f"NOW, LET'S START!\n\n{state.plan.main_goal}"
  143. ),
  144. },
  145. ]
  146. updated_info = state.updated_info
  147. if updated_info:
  148. for prev_action, obs in updated_info:
  149. assert isinstance(
  150. prev_action, self.SUPPORTED_ACTIONS
  151. ), f'{prev_action.__class__} is not supported (supported: {self.SUPPORTED_ACTIONS})'
  152. if (
  153. isinstance(prev_action, MessageAction)
  154. and prev_action.source == 'user'
  155. ):
  156. self.messages.append(
  157. {'role': 'user', 'content': prev_action.content}
  158. )
  159. if prev_action.content.strip() == '/exit':
  160. # User wants to exit
  161. return AgentFinishAction()
  162. # handle observations
  163. assert isinstance(
  164. obs, self.SUPPORTED_OBSERVATIONS
  165. ), f'{obs.__class__} is not supported (supported: {self.SUPPORTED_OBSERVATIONS})'
  166. if isinstance(obs, CmdOutputObservation):
  167. content = 'OBSERVATION:\n' + truncate_observation(obs.content)
  168. content += f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]]'
  169. self.messages.append({'role': 'user', 'content': content})
  170. elif isinstance(obs, IPythonRunCellObservation):
  171. content = 'OBSERVATION:\n' + obs.content
  172. # replace base64 images with a placeholder
  173. splitted = content.split('\n')
  174. for i, line in enumerate(splitted):
  175. if '![image](data:image/png;base64,' in line:
  176. splitted[i] = (
  177. '![image](data:image/png;base64, ...) already displayed to user'
  178. )
  179. content = '\n'.join(splitted)
  180. content = truncate_observation(content)
  181. self.messages.append({'role': 'user', 'content': content})
  182. elif isinstance(obs, NullObservation):
  183. pass
  184. else:
  185. raise NotImplementedError(
  186. f'Unknown observation type: {obs.__class__}'
  187. )
  188. response = self.llm.completion(
  189. messages=self.messages,
  190. stop=[
  191. '</execute_ipython>',
  192. '</execute_bash>',
  193. ],
  194. temperature=0.0,
  195. )
  196. cur_cost = completion_cost(completion_response=response)
  197. self.cost_accumulator += cur_cost
  198. logger.info(
  199. f'Cost: {cur_cost:.2f} USD | Accumulated Cost: {self.cost_accumulator:.2f} USD'
  200. )
  201. action_str: str = parse_response(response)
  202. state.num_of_chars += sum(
  203. len(message['content']) for message in self.messages
  204. ) + len(action_str)
  205. self.messages.append({'role': 'assistant', 'content': action_str})
  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. command_group = swe_agent_edit_hack(command_group)
  214. if command_group.strip() == 'exit':
  215. return AgentFinishAction()
  216. return CmdRunAction(command=command_group, thought=thought)
  217. elif python_code := re.search(
  218. r'<execute_ipython>(.*)</execute_ipython>', action_str, re.DOTALL
  219. ):
  220. # a code block was found
  221. code_group = python_code.group(1).strip()
  222. thought = action_str.replace(python_code.group(0), '').strip()
  223. return IPythonRunCellAction(code=code_group, thought=thought)
  224. else:
  225. # We assume the LLM is GOOD enough that when it returns pure natural language
  226. # it want to talk to the user
  227. return MessageAction(content=action_str, wait_for_response=True)
  228. def search_memory(self, query: str) -> list[str]:
  229. raise NotImplementedError('Implement this abstract method')