codeact_agent.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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.core.logger import opendevin_logger as logger
  12. from opendevin.events.action import (
  13. Action,
  14. AgentFinishAction,
  15. BrowseInteractiveAction,
  16. CmdRunAction,
  17. IPythonRunCellAction,
  18. MessageAction,
  19. )
  20. from opendevin.events.observation import (
  21. BrowserOutputObservation,
  22. CmdOutputObservation,
  23. IPythonRunCellObservation,
  24. )
  25. from opendevin.llm.llm import LLM
  26. from opendevin.runtime.plugins import (
  27. JupyterRequirement,
  28. PluginRequirement,
  29. SWEAgentCommandsRequirement,
  30. )
  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 truncate_observation(observation: str, max_chars: int = 10_000) -> str:
  39. """
  40. Truncate the middle of the observation if it is too long.
  41. """
  42. if len(observation) <= max_chars:
  43. return observation
  44. half = max_chars // 2
  45. return (
  46. observation[:half]
  47. + '\n[... Observation truncated due to length ...]\n'
  48. + observation[-half:]
  49. )
  50. def swe_agent_edit_hack(bash_command: str) -> str:
  51. """
  52. Hack to handle the SWE-agent edit command. The vanilla edit command will hang the SSHBox.
  53. REPLACE THIS:
  54. edit 683:693
  55. try:
  56. return list(urlsplit(url))
  57. except ValueError:
  58. raise ValidationError(self.error_messages['invalid'], code='invalid')
  59. end_of_edit
  60. WITH THIS:
  61. edit 683:693 <<EOF
  62. try:
  63. return list(urlsplit(url))
  64. except ValueError:
  65. raise ValidationError(self.error_messages['invalid'], code='invalid')
  66. EOF
  67. """
  68. if 'edit' in bash_command:
  69. # edit\s(\d+):(\d+)([\s\S]*)end_of_edit
  70. # replace
  71. bash_command = re.sub(
  72. r'edit\s(\d+):(\d+)([\s\S]*?)end_of_edit',
  73. r'edit \1:\2 <<EOF\3EOF',
  74. bash_command,
  75. )
  76. return bash_command
  77. class CodeActAgent(Agent):
  78. VERSION = '1.3'
  79. """
  80. The Code Act Agent is a minimalist agent.
  81. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  82. ### Overview
  83. 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).
  84. The conceptual idea is illustrated below. At each turn, the agent can:
  85. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  86. 2. **CodeAct**: Choose to perform the task by executing code
  87. - Execute any valid Linux `bash` command
  88. - 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.
  89. ![image](https://github.com/OpenDevin/OpenDevin/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  90. ### Plugin System
  91. To make the CodeAct agent more powerful with only access to `bash` action space, CodeAct agent leverages OpenDevin's plugin system:
  92. - [Jupyter plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/jupyter): for IPython execution via bash command
  93. - [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).
  94. ### Demo
  95. https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d69282d5f6ac
  96. *Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)*
  97. ### Work-in-progress & Next step
  98. [] Support web-browsing
  99. [] Complete the workflow for CodeAct agent to submit Github PRs
  100. """
  101. sandbox_plugins: list[PluginRequirement] = [
  102. JupyterRequirement(),
  103. SWEAgentCommandsRequirement(),
  104. ]
  105. system_message: str = (
  106. f'{SYSTEM_PREFIX}\n{GITHUB_MESSAGE}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  107. if ENABLE_GITHUB
  108. else f'{SYSTEM_PREFIX}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  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.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': self.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. - BrowseInteractiveAction(browsergym_command) - BrowserGym commands to run
  144. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  145. - AgentFinishAction() - end the interaction
  146. """
  147. updated_info = state.updated_info
  148. if updated_info:
  149. for prev_action, obs in updated_info:
  150. if (
  151. isinstance(prev_action, MessageAction)
  152. and prev_action.source == 'user'
  153. ):
  154. self.messages.append(
  155. {'role': 'user', 'content': prev_action.content}
  156. )
  157. if prev_action.content.strip() == '/exit':
  158. # User wants to exit
  159. return AgentFinishAction()
  160. if isinstance(obs, CmdOutputObservation):
  161. content = 'OBSERVATION:\n' + truncate_observation(obs.content)
  162. content += f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]]'
  163. self.messages.append({'role': 'user', 'content': content})
  164. elif isinstance(obs, IPythonRunCellObservation):
  165. content = 'OBSERVATION:\n' + obs.content
  166. # replace base64 images with a placeholder
  167. splitted = content.split('\n')
  168. for i, line in enumerate(splitted):
  169. if '![image](data:image/png;base64,' in line:
  170. splitted[i] = (
  171. '![image](data:image/png;base64, ...) already displayed to user'
  172. )
  173. content = '\n'.join(splitted)
  174. content = truncate_observation(content)
  175. self.messages.append({'role': 'user', 'content': content})
  176. elif isinstance(obs, BrowserOutputObservation):
  177. content = 'OBSERVATION:\n' + truncate_observation(obs.content)
  178. self.messages.append({'role': 'user', 'content': content})
  179. latest_user_message = [m for m in self.messages if m['role'] == 'user'][-1]
  180. if latest_user_message:
  181. latest_user_message['content'] += (
  182. f'\n\nENVIRONMENT REMINDER: You have {state.max_iterations - state.iteration} turns left to complete the task.'
  183. )
  184. response = self.llm.completion(
  185. messages=self.messages,
  186. stop=[
  187. '</execute_ipython>',
  188. '</execute_bash>',
  189. '</execute_browse>',
  190. ],
  191. temperature=0.0,
  192. )
  193. self.log_cost(response)
  194. action_str: str = parse_response(response)
  195. state.num_of_chars += sum(
  196. len(message['content']) for message in self.messages
  197. ) + len(action_str)
  198. self.messages.append({'role': 'assistant', 'content': action_str})
  199. if finish_command := re.search(r'<finish>.*</finish>', action_str, re.DOTALL):
  200. thought = action_str.replace(finish_command.group(0), '').strip()
  201. return AgentFinishAction(thought=thought)
  202. if bash_command := re.search(
  203. r'<execute_bash>(.*)</execute_bash>', action_str, re.DOTALL
  204. ):
  205. # remove the command from the action string to get thought
  206. thought = action_str.replace(bash_command.group(0), '').strip()
  207. # a command was found
  208. command_group = bash_command.group(1).strip()
  209. command_group = swe_agent_edit_hack(command_group)
  210. if command_group.strip() == 'exit':
  211. return AgentFinishAction()
  212. return CmdRunAction(command=command_group, thought=thought)
  213. elif python_code := re.search(
  214. r'<execute_ipython>(.*)</execute_ipython>', action_str, re.DOTALL
  215. ):
  216. # a code block was found
  217. code_group = python_code.group(1).strip()
  218. thought = action_str.replace(python_code.group(0), '').strip()
  219. return IPythonRunCellAction(code=code_group, thought=thought)
  220. elif browse_command := re.search(
  221. r'<execute_browse>(.*)</execute_browse>', action_str, re.DOTALL
  222. ):
  223. # BrowserGym actions was found
  224. browse_actions = browse_command.group(1).strip()
  225. thought = action_str.replace(browse_command.group(0), '').strip()
  226. return BrowseInteractiveAction(
  227. browser_actions=browse_actions, thought=thought
  228. )
  229. else:
  230. # We assume the LLM is GOOD enough that when it returns pure natural language
  231. # it want to talk to the user
  232. return MessageAction(content=action_str, wait_for_response=True)
  233. def search_memory(self, query: str) -> list[str]:
  234. raise NotImplementedError('Implement this abstract method')
  235. def log_cost(self, response):
  236. try:
  237. cur_cost = self.llm.completion_cost(response)
  238. except Exception:
  239. cur_cost = 0
  240. self.cost_accumulator += cur_cost
  241. logger.info(
  242. 'Cost: %.2f USD | Accumulated Cost: %.2f USD',
  243. cur_cost,
  244. self.cost_accumulator,
  245. )