codeact_agent.py 11 KB

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