codeact_agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import re
  2. from agenthub.codeact_agent.prompt import EXAMPLES, SYSTEM_MESSAGE
  3. from opendevin.controller.agent import Agent
  4. from opendevin.controller.state.state import State
  5. from opendevin.core.logger import opendevin_logger as logger
  6. from opendevin.events.action import (
  7. Action,
  8. AgentFinishAction,
  9. CmdRunAction,
  10. IPythonRunCellAction,
  11. MessageAction,
  12. NullAction,
  13. )
  14. from opendevin.events.observation import (
  15. CmdOutputObservation,
  16. IPythonRunCellObservation,
  17. NullObservation,
  18. )
  19. from opendevin.llm.llm import LLM
  20. from opendevin.runtime.plugins import (
  21. JupyterRequirement,
  22. PluginRequirement,
  23. SWEAgentCommandsRequirement,
  24. )
  25. def parse_response(response) -> str:
  26. action = response.choices[0].message.content
  27. for lang in ['bash', 'ipython']:
  28. if f'<execute_{lang}>' in action and f'</execute_{lang}>' not in action:
  29. action += f'</execute_{lang}>'
  30. return action
  31. def truncate_observation(observation: str, max_chars: int = 10_000) -> str:
  32. """
  33. Truncate the middle of the observation if it is too long.
  34. """
  35. if len(observation) <= max_chars:
  36. return observation
  37. half = max_chars // 2
  38. return (
  39. observation[:half]
  40. + '\n[... Observation truncated due to length ...]\n'
  41. + observation[-half:]
  42. )
  43. def swe_agent_edit_hack(bash_command: str) -> str:
  44. """
  45. Hack to handle the SWE-agent edit command. The vanilla edit command will hang the SSHBox.
  46. REPLACE THIS:
  47. edit 683:693
  48. try:
  49. return list(urlsplit(url))
  50. except ValueError:
  51. raise ValidationError(self.error_messages['invalid'], code='invalid')
  52. end_of_edit
  53. WITH THIS:
  54. edit 683:693 <<EOF
  55. try:
  56. return list(urlsplit(url))
  57. except ValueError:
  58. raise ValidationError(self.error_messages['invalid'], code='invalid')
  59. EOF
  60. """
  61. if 'edit' in bash_command:
  62. # edit\s(\d+):(\d+)([\s\S]*)end_of_edit
  63. # replace
  64. bash_command = re.sub(
  65. r'edit\s(\d+):(\d+)([\s\S]*?)end_of_edit',
  66. r'edit \1:\2 <<EOF\3EOF',
  67. bash_command,
  68. )
  69. return bash_command
  70. class CodeActAgent(Agent):
  71. VERSION = '1.1'
  72. """
  73. The Code Act Agent is a minimalist agent.
  74. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  75. ### Overview
  76. 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).
  77. The conceptual idea is illustrated below. At each turn, the agent can:
  78. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  79. 2. **CodeAct**: Choose to perform the task by executing code
  80. - Execute any valid Linux `bash` command
  81. - 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.
  82. ![image](https://github.com/OpenDevin/OpenDevin/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  83. ### Plugin System
  84. To make the CodeAct agent more powerful with only access to `bash` action space, CodeAct agent leverages OpenDevin's plugin system:
  85. - [Jupyter plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/jupyter): for IPython execution via bash command
  86. - [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).
  87. ### Demo
  88. https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d69282d5f6ac
  89. *Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)*
  90. ### Work-in-progress & Next step
  91. [] Support web-browsing
  92. [] Complete the workflow for CodeAct agent to submit Github PRs
  93. """
  94. sandbox_plugins: list[PluginRequirement] = [
  95. JupyterRequirement(),
  96. SWEAgentCommandsRequirement(),
  97. ]
  98. SUPPORTED_ACTIONS = (
  99. CmdRunAction,
  100. IPythonRunCellAction,
  101. MessageAction,
  102. NullAction,
  103. )
  104. SUPPORTED_OBSERVATIONS = (
  105. CmdOutputObservation,
  106. IPythonRunCellObservation,
  107. NullObservation,
  108. )
  109. messages: list[dict] = []
  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.reset()
  121. def reset(self) -> None:
  122. """
  123. Resets the CodeAct Agent.
  124. """
  125. super().reset()
  126. self.messages: list[dict[str, str]] = [
  127. {'role': 'system', 'content': SYSTEM_MESSAGE},
  128. {
  129. 'role': 'user',
  130. 'content': f"Here is an example of how you can interact with the environment for task solving:\n{EXAMPLES}\n\nNOW, LET'S START!",
  131. },
  132. ]
  133. self.cost_accumulator = 0
  134. def step(self, state: State) -> Action:
  135. """
  136. Performs one step using the CodeAct Agent.
  137. This includes gathering info on previous steps and prompting the model to make a command to execute.
  138. Parameters:
  139. - state (State): used to get updated info and background commands
  140. Returns:
  141. - CmdRunAction(command) - bash command to run
  142. - IPythonRunCellAction(code) - IPython code to run
  143. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  144. - AgentFinishAction() - end the interaction
  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. latest_user_message = [m for m in self.messages if m['role'] == 'user'][-1]
  189. if latest_user_message:
  190. latest_user_message['content'] += (
  191. f'\n\nENVIRONMENT REMINDER: You have {state.max_iterations - state.iteration - 1} turns left to complete the task.'
  192. )
  193. response = self.llm.completion(
  194. messages=self.messages,
  195. stop=[
  196. '</execute_ipython>',
  197. '</execute_bash>',
  198. ],
  199. temperature=0.0,
  200. )
  201. self.log_cost(response)
  202. action_str: str = parse_response(response)
  203. state.num_of_chars += sum(
  204. len(message['content']) for message in self.messages
  205. ) + len(action_str)
  206. self.messages.append({'role': 'assistant', 'content': action_str})
  207. if finish_command := re.search(r'<finish>.*</finish>', action_str, re.DOTALL):
  208. thought = action_str.replace(finish_command.group(0), '').strip()
  209. return AgentFinishAction(thought=thought)
  210. if bash_command := re.search(
  211. r'<execute_bash>(.*)</execute_bash>', action_str, re.DOTALL
  212. ):
  213. # remove the command from the action string to get thought
  214. thought = action_str.replace(bash_command.group(0), '').strip()
  215. # a command was found
  216. command_group = bash_command.group(1).strip()
  217. command_group = swe_agent_edit_hack(command_group)
  218. if command_group.strip() == 'exit':
  219. return AgentFinishAction()
  220. return CmdRunAction(command=command_group, thought=thought)
  221. elif python_code := re.search(
  222. r'<execute_ipython>(.*)</execute_ipython>', action_str, re.DOTALL
  223. ):
  224. # a code block was found
  225. code_group = python_code.group(1).strip()
  226. thought = action_str.replace(python_code.group(0), '').strip()
  227. return IPythonRunCellAction(code=code_group, thought=thought)
  228. else:
  229. # We assume the LLM is GOOD enough that when it returns pure natural language
  230. # it want to talk to the user
  231. return MessageAction(content=action_str, wait_for_response=True)
  232. def search_memory(self, query: str) -> list[str]:
  233. raise NotImplementedError('Implement this abstract method')
  234. def log_cost(self, response):
  235. cur_cost = self.llm.completion_cost(response)
  236. self.cost_accumulator += cur_cost
  237. logger.info(
  238. 'Cost: %.2f USD | Accumulated Cost: %.2f USD',
  239. cur_cost,
  240. self.cost_accumulator,
  241. )