codeact_agent.py 9.0 KB

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