codeact_agent.py 9.3 KB

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