codeact_agent.py 12 KB

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