codeact_agent.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. import re
  2. from typing import List, Mapping
  3. from opendevin.agent import Agent
  4. from opendevin.state import State
  5. from opendevin.action import (
  6. Action,
  7. CmdRunAction,
  8. AgentEchoAction,
  9. AgentFinishAction,
  10. )
  11. from opendevin.observation import (
  12. CmdOutputObservation,
  13. AgentMessageObservation,
  14. )
  15. from opendevin.llm.llm import LLM
  16. SYSTEM_MESSAGE = """You are a helpful assistant. You will be provided access (as root) to a bash shell to complete user-provided tasks.
  17. You will be able to execute commands in the bash shell, interact with the file system, install packages, and receive the output of your commands.
  18. DO NOT provide code in ```triple backticks```. Instead, you should execute bash command on behalf of the user by wrapping them with <execute> and </execute>.
  19. For example:
  20. You can list the files in the current directory by executing the following command:
  21. <execute>ls</execute>
  22. You can also install packages using pip:
  23. <execute> pip install numpy </execute>
  24. You can also write a block of code to a file:
  25. <execute>
  26. echo "import math
  27. print(math.pi)" > math.py
  28. </execute>
  29. When you are done, execute "exit" to close the shell and end the conversation.
  30. """
  31. INVALID_INPUT_MESSAGE = (
  32. "I don't understand your input. \n"
  33. "If you want to execute command, please use <execute> YOUR_COMMAND_HERE </execute>.\n"
  34. "If you already completed the task, please exit the shell by generating: <execute> exit </execute>."
  35. )
  36. def parse_response(response) -> str:
  37. action = response.choices[0].message.content
  38. if "<execute>" in action and "</execute>" not in action:
  39. action += "</execute>"
  40. return action
  41. class CodeActAgent(Agent):
  42. def __init__(
  43. self,
  44. llm: LLM,
  45. ) -> None:
  46. """
  47. Initializes a new instance of the CodeActAgent class.
  48. Parameters:
  49. - instruction (str): The instruction for the agent to execute.
  50. - max_steps (int): The maximum number of steps to run the agent.
  51. """
  52. super().__init__(llm)
  53. self.messages: List[Mapping[str, str]] = []
  54. def step(self, state: State) -> Action:
  55. if len(self.messages) == 0:
  56. assert state.plan.main_goal, "Expecting instruction to be set"
  57. self.messages = [
  58. {"role": "system", "content": SYSTEM_MESSAGE},
  59. {"role": "user", "content": state.plan.main_goal},
  60. ]
  61. updated_info = state.updated_info
  62. if updated_info:
  63. for prev_action, obs in updated_info:
  64. assert isinstance(prev_action, (CmdRunAction, AgentEchoAction)), "Expecting CmdRunAction or AgentEchoAction for Action"
  65. if isinstance(obs, AgentMessageObservation): # warning message from itself
  66. self.messages.append({"role": "user", "content": obs.content})
  67. elif isinstance(obs, CmdOutputObservation):
  68. content = "OBSERVATION:\n" + obs.content
  69. content += f"\n[Command {obs.command_id} finished with exit code {obs.exit_code}]]"
  70. self.messages.append({"role": "user", "content": content})
  71. else:
  72. raise NotImplementedError(f"Unknown observation type: {obs.__class__}")
  73. response = self.llm.completion(
  74. messages=self.messages,
  75. stop=["</execute>"],
  76. temperature=0.0,
  77. seed=42,
  78. )
  79. action_str: str = parse_response(response)
  80. self.messages.append({"role": "assistant", "content": action_str})
  81. command = re.search(r"<execute>(.*)</execute>", action_str, re.DOTALL)
  82. if command is not None:
  83. # a command was found
  84. command_group = command.group(1)
  85. if command_group.strip() == "exit":
  86. return AgentFinishAction()
  87. return CmdRunAction(command = command_group)
  88. # # execute the code
  89. # # TODO: does exit_code get loaded into Message?
  90. # exit_code, observation = self.env.execute(command_group)
  91. # self._history.append(Message(Role.ASSISTANT, observation))
  92. else:
  93. # we could provide a error message for the model to continue similar to
  94. # https://github.com/xingyaoww/mint-bench/blob/main/mint/envs/general_env.py#L18-L23
  95. # observation = INVALID_INPUT_MESSAGE
  96. # self._history.append(Message(Role.ASSISTANT, observation))
  97. return AgentEchoAction(content=INVALID_INPUT_MESSAGE) # warning message to itself
  98. def search_memory(self, query: str) -> List[str]:
  99. raise NotImplementedError("Implement this abstract method")