codeact_agent.py 9.0 KB

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