codeact_agent.py 11 KB

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