codeact_agent.py 8.6 KB

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