codeact_agent.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. from agenthub.codeact_agent.action_parser import CodeActResponseParser
  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. CmdRunAction,
  16. IPythonRunCellAction,
  17. MessageAction,
  18. )
  19. from opendevin.events.observation import (
  20. AgentDelegateObservation,
  21. CmdOutputObservation,
  22. IPythonRunCellObservation,
  23. )
  24. from opendevin.events.serialization.event import truncate_content
  25. from opendevin.llm.llm import LLM
  26. from opendevin.runtime.plugins import (
  27. AgentSkillsRequirement,
  28. JupyterRequirement,
  29. PluginRequirement,
  30. )
  31. from opendevin.runtime.tools import RuntimeTool
  32. ENABLE_GITHUB = True
  33. def action_to_str(action: Action) -> str:
  34. if isinstance(action, CmdRunAction):
  35. return f'{action.thought}\n<execute_bash>\n{action.command}\n</execute_bash>'
  36. elif isinstance(action, IPythonRunCellAction):
  37. return f'{action.thought}\n<execute_ipython>\n{action.code}\n</execute_ipython>'
  38. elif isinstance(action, AgentDelegateAction):
  39. return f'{action.thought}\n<execute_browse>\n{action.inputs["task"]}\n</execute_browse>'
  40. elif isinstance(action, MessageAction):
  41. return action.content
  42. return ''
  43. def get_action_message(action: Action) -> dict[str, str] | None:
  44. if (
  45. isinstance(action, AgentDelegateAction)
  46. or isinstance(action, CmdRunAction)
  47. or isinstance(action, IPythonRunCellAction)
  48. or isinstance(action, MessageAction)
  49. ):
  50. return {
  51. 'role': 'user' if action.source == 'user' else 'assistant',
  52. 'content': action_to_str(action),
  53. }
  54. return None
  55. def get_observation_message(obs) -> dict[str, str] | None:
  56. if isinstance(obs, CmdOutputObservation):
  57. content = 'OBSERVATION:\n' + truncate_content(obs.content)
  58. content += (
  59. f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]'
  60. )
  61. return {'role': 'user', 'content': content}
  62. elif isinstance(obs, IPythonRunCellObservation):
  63. content = 'OBSERVATION:\n' + obs.content
  64. # replace base64 images with a placeholder
  65. splitted = content.split('\n')
  66. for i, line in enumerate(splitted):
  67. if '![image](data:image/png;base64,' in line:
  68. splitted[i] = (
  69. '![image](data:image/png;base64, ...) already displayed to user'
  70. )
  71. content = '\n'.join(splitted)
  72. content = truncate_content(content)
  73. return {'role': 'user', 'content': content}
  74. elif isinstance(obs, AgentDelegateObservation):
  75. content = 'OBSERVATION:\n' + truncate_content(str(obs.outputs))
  76. return {'role': 'user', 'content': content}
  77. return None
  78. # FIXME: We can tweak these two settings to create MicroAgents specialized toward different area
  79. def get_system_message() -> str:
  80. if ENABLE_GITHUB:
  81. return f'{SYSTEM_PREFIX}\n{GITHUB_MESSAGE}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  82. else:
  83. return f'{SYSTEM_PREFIX}\n\n{COMMAND_DOCS}\n\n{SYSTEM_SUFFIX}'
  84. def get_in_context_example() -> str:
  85. return EXAMPLES
  86. class CodeActAgent(Agent):
  87. VERSION = '1.6'
  88. """
  89. The Code Act Agent is a minimalist agent.
  90. The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
  91. ### Overview
  92. 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).
  93. The conceptual idea is illustrated below. At each turn, the agent can:
  94. 1. **Converse**: Communicate with humans in natural language to ask for clarification, confirmation, etc.
  95. 2. **CodeAct**: Choose to perform the task by executing code
  96. - Execute any valid Linux `bash` command
  97. - 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.
  98. ![image](https://github.com/OpenDevin/OpenDevin/assets/38853559/92b622e3-72ad-4a61-8f41-8c040b6d5fb3)
  99. ### Plugin System
  100. To make the CodeAct agent more powerful with only access to `bash` action space, CodeAct agent leverages OpenDevin's plugin system:
  101. - [Jupyter plugin](https://github.com/OpenDevin/OpenDevin/tree/main/opendevin/runtime/plugins/jupyter): for IPython execution via bash command
  102. - [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).
  103. ### Demo
  104. https://github.com/OpenDevin/OpenDevin/assets/38853559/f592a192-e86c-4f48-ad31-d69282d5f6ac
  105. *Example of CodeActAgent with `gpt-4-turbo-2024-04-09` performing a data science task (linear regression)*
  106. ### Work-in-progress & Next step
  107. [] Support web-browsing
  108. [] Complete the workflow for CodeAct agent to submit Github PRs
  109. """
  110. sandbox_plugins: list[PluginRequirement] = [
  111. # NOTE: AgentSkillsRequirement need to go before JupyterRequirement, since
  112. # AgentSkillsRequirement provides a lot of Python functions
  113. # and it need to be initialized before Jupyter for Jupyter to use those functions.
  114. AgentSkillsRequirement(),
  115. JupyterRequirement(),
  116. ]
  117. runtime_tools: list[RuntimeTool] = [RuntimeTool.BROWSER]
  118. system_message: str = get_system_message()
  119. 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!"
  120. action_parser = CodeActResponseParser()
  121. def __init__(
  122. self,
  123. llm: LLM,
  124. ) -> None:
  125. """
  126. Initializes a new instance of the CodeActAgent class.
  127. Parameters:
  128. - llm (LLM): The llm to be used by this agent
  129. """
  130. super().__init__(llm)
  131. self.reset()
  132. def reset(self) -> None:
  133. """
  134. Resets the CodeAct Agent.
  135. """
  136. super().reset()
  137. def step(self, state: State) -> Action:
  138. """
  139. Performs one step using the CodeAct Agent.
  140. This includes gathering info on previous steps and prompting the model to make a command to execute.
  141. Parameters:
  142. - state (State): used to get updated info and background commands
  143. Returns:
  144. - CmdRunAction(command) - bash command to run
  145. - IPythonRunCellAction(code) - IPython code to run
  146. - AgentDelegateAction(agent, inputs) - delegate action for (sub)task
  147. - MessageAction(content) - Message action to run (e.g. ask for clarification)
  148. - AgentFinishAction() - end the interaction
  149. """
  150. messages: list[dict[str, str]] = [
  151. {'role': 'system', 'content': self.system_message},
  152. {'role': 'user', 'content': self.in_context_example},
  153. ]
  154. for prev_action, obs in state.history:
  155. action_message = get_action_message(prev_action)
  156. if action_message:
  157. messages.append(action_message)
  158. obs_message = get_observation_message(obs)
  159. if obs_message:
  160. messages.append(obs_message)
  161. latest_user_message = [m for m in messages if m['role'] == 'user'][-1]
  162. if latest_user_message:
  163. if latest_user_message['content'].strip() == '/exit':
  164. return AgentFinishAction()
  165. latest_user_message['content'] += (
  166. f'\n\nENVIRONMENT REMINDER: You have {state.max_iterations - state.iteration} turns left to complete the task.'
  167. )
  168. response = self.llm.completion(
  169. messages=messages,
  170. stop=[
  171. '</execute_ipython>',
  172. '</execute_bash>',
  173. '</execute_browse>',
  174. ],
  175. temperature=0.0,
  176. )
  177. return self.action_parser.parse(response)
  178. def search_memory(self, query: str) -> list[str]:
  179. raise NotImplementedError('Implement this abstract method')