π OpenHands: AI-Driven Development
Additions to agent docs (#3434)
Engel Nyst84a814c4473a
diff --git a/agenthub/README.md b/agenthub/README.mdindex cb2a09b1f0..76d738e005 100644--- a/agenthub/README.md+++ b/agenthub/README.md@@ -17,12 +17,30 @@ See the [LiteLLM docs for `self.llm.completion`](https://docs.litellm.ai/docs/co## State-The `state` contains:--- A history of actions taken by the agent, as well as any observations (e.g. file content, command output) from those actions-- A list of actions/observations that have happened since the most recent step-- A [`root_task`](https://github.com/OpenDevin/OpenDevin/blob/main/opendevin/controller/state/task.py), which contains a plan of action- - The agent can add and modify subtasks through the `AddTaskAction` and `ModifyTaskAction`+The `state` represents the running state of an agent in the OpenDevin system. The class handles saving and restoring the agent session. It is serialized in a pickle.++The State object stores information about:++* Multi-agent state / delegates:+ * the 'root task' (conversation between the agent and the user)+ * the subtask (conversation between an agent and the user or another agent)+ * global and local iterations+ * delegate levels for multi-agent interactions+ * almost stuck state+* Running state of an agent:+ * current agent state (e.g., LOADING, RUNNING, PAUSED)+ * traffic control state for rate limiting+ * confirmation mode+ * the last error encountered+* History:+ * start and end IDs for events in agent's history. This allows to retrieve the actions taken by the agent, and observations (e.g. file content, command output) from the current or past sessions.+* Metrics:+ * global metrics for the current task+ * local metrics for the current subtask+* Extra data:+ * additional task-specific data++The agent can add and modify subtasks through the `AddTaskAction` and `ModifyTaskAction`## Actions@@ -40,7 +58,10 @@ Here is a list of available Actions, which can be returned by `agent.step()`:- [`AgentFinishAction`](../opendevin/events/action/agent.py) - Stops the control loop, allowing the user to enter a new task- [`MessageAction`](../opendevin/events/action/message.py) - Represents a message from an agent or the user-You can use `action.to_dict()` and `action_from_dict` to serialize and deserialize actions.+To serialize and deserialize an action, you can use:+- `action.to_dict()` to serialize the action to a dictionary to be sent to the UI, including a user-friendly string representation of the message+- `action.to_memory()` to serialize the action to a dictionary to be sent to the LLM. It may include raw information, such as the underlying exceptions that occurred during the action execution.+- `action_from_dict(action_dict)` to deserialize the action from a dictionary.## Observations@@ -70,3 +91,52 @@ def step(self, state: "State") -> "Action"`step` moves the agent forward one step towards its goal. This probably meanssending a prompt to the LLM, then parsing the response into an `Action`.++## Agent Delegation++OpenDevin is a multi-agentic system. Agents can delegate tasks to other agents, whether+prompted by the user, or when the agent decides to ask another agent for help. For example,+the `CodeActAgent` might delegate to the `BrowsingAgent` to answer questions that involve browsing+the web. The Delegator Agent forwards tasks to micro-agents, such as 'RepoStudyAgent' to study a repo,+or 'VerifierAgent' to verify a task completion.++### Understanding the terminology++A `task` is an end-to-end conversation between OpenDevin (the whole system) and the user,+which might involve one or more inputs from the user. It starts with an initial input+(typically a task statement) from the user, and ends with either an `AgentFinishAction`+initiated by the agent, a stop initiated by the user, or an error.++A `subtask` is an end-to-end conversation between an agent and the user, or+another agent. If a `task` is conducted by a single agent, then it's also a `subtask`+itself. Otherwise, a `task` consists of multiple `subtasks`, each executed by+one agent.++For example, considering a task from the user: `tell me how many GitHub stars+OpenDevin repo has`. Let's assume the default agent is CodeActAgent.++```+-- TASK STARTS (SUBTASK 0 STARTS) --++DELEGATE_LEVEL 0, ITERATION 0, LOCAL_ITERATION 0+CodeActAgent: I should request help from BrowsingAgent++-- DELEGATE STARTS (SUBTASK 1 STARTS) --++DELEGATE_LEVEL 1, ITERATION 1, LOCAL_ITERATION 0+BrowsingAgent: Let me find the answer on GitHub++DELEGATE_LEVEL 1, ITERATION 2, LOCAL_ITERATION 1+BrowsingAgent: I found the answer, let me convey the result and finish++-- DELEGATE ENDS (SUBTASK 1 ENDS) --++DELEGATE_LEVEL 0, ITERATION 3, LOCAL_ITERATION 1+CodeActAgent: I got the answer from BrowsingAgent, let me convey the result+and finish++-- TASK ENDS (SUBTASK 0 ENDS) --+```++Note how ITERATION counter is shared across agents, while LOCAL_ITERATION+is local to each subtask.diff --git a/opendevin/controller/agent_controller.py b/opendevin/controller/agent_controller.pyindex b668192043..ff7330cec2 100644--- a/opendevin/controller/agent_controller.py+++ b/opendevin/controller/agent_controller.py@@ -116,6 +116,7 @@ class AgentController:self.agent_task = asyncio.create_task(self._start_step_loop())async def close(self):+ """Closes the agent controller, canceling any ongoing tasks and unsubscribing from the event stream."""if self.agent_task is not None:self.agent_task.cancel()await self.set_agent_state_to(AgentState.STOPPED)@@ -130,7 +131,7 @@ class AgentController:self.state.local_metrics = self.agent.llm.metricsasync def report_error(self, message: str, exception: Exception | None = None):- """This error will be reported to the user and sent to the LLM next step, in the hope it can self-correct.+ """Reports an error to the user and sends the exception to the LLM next step, in the hope it can self-correct.This method should be called for a particular type of errors, which have:- a user-friendly message, which will be shown in the chat box. This should not be a raw exception message.@@ -142,6 +143,8 @@ class AgentController:self.event_stream.add_event(ErrorObservation(message), EventSource.AGENT)async def _start_step_loop(self):+ """The main loop for the agent's step-by-step execution."""+logger.info(f'[Agent Controller {self.id}] Starting step loop...')while True:try:@@ -162,6 +165,11 @@ class AgentController:await asyncio.sleep(0.1)async def on_event(self, event: Event):+ """Callback from the event stream. Notifies the controller of incoming events.++ Args:+ event (Event): The incoming event to process.+ """if isinstance(event, ChangeAgentStateAction):await self.set_agent_state_to(event.agent_state) # type: ignoreelif isinstance(event, MessageAction):@@ -212,10 +220,17 @@ class AgentController:logger.info(event, extra={'msg_type': 'OBSERVATION'})def reset_task(self):+ """Resets the agent's task."""+self.almost_stuck = 0self.agent.reset()async def set_agent_state_to(self, new_state: AgentState):+ """Updates the agent's state and handles side effects. Can emit events to the event stream.++ Args:+ new_state (AgentState): The new state to set for the agent.+ """logger.debug(f'[Agent Controller {self.id}] Setting agent({self.agent.name}) state from {self.state.agent_state} to {new_state}')@@ -256,10 +271,29 @@ class AgentController:self.state.resume_state = Nonedef get_agent_state(self):- """Returns the current state of the agent task."""+ """Returns the current state of the agent.++ Returns:+ AgentState: The current state of the agent.+ """return self.state.agent_stateasync def start_delegate(self, action: AgentDelegateAction):+ """Start a delegate agent to handle a subtask.++ OpenDevin is a multi-agentic system. A `task` is a conversation between+ OpenDevin (the whole system) and the user, which might involve one or more inputs+ from the user. It starts with an initial input (typically a task statement) from+ the user, and ends with either an `AgentFinishAction` initiated by the agent, a+ stop initiated by the user, or an error.++ A `subtask` is a conversation between an agent and the user, or another agent. If a `task`+ is conducted by a single agent, then it's also a `subtask`. Otherwise, a `task` consists of+ multiple `subtasks`, each executed by one agent.++ Args:+ action (AgentDelegateAction): The action containing information about the delegate agent to start.+ """agent_cls: Type[Agent] = Agent.get_cls(action.agent)agent_config = self.agent_configs.get(action.agent, self.agent.config)llm_config = self.agent_to_llm_config.get(action.agent, self.agent.llm.config)@@ -292,6 +326,7 @@ class AgentController:await self.delegate.set_agent_state_to(AgentState.RUNNING)async def _step(self) -> None:+ """Executes a single step of the parent or delegate agent. Detects stuck agents and limits on the number of iterations and the task budget."""if self.get_agent_state() != AgentState.RUNNING:await asyncio.sleep(1)return@@ -438,6 +473,11 @@ class AgentController:await self.set_agent_state_to(AgentState.ERROR)def get_state(self):+ """Returns the current running state object.++ Returns:+ State: The current state object.+ """return self.statedef set_initial_state(@@ -446,6 +486,13 @@ class AgentController:max_iterations: int,confirmation_mode: bool = False,):+ """Sets the initial state for the agent, either from the previous session, or from a parent agent, or by creating a new one.++ Args:+ state: The state to initialize with, or None to create a new state.+ max_iterations: The maximum number of iterations allowed for the task.+ confirmation_mode: Whether to enable confirmation mode.+ """# state from the previous session, state from a parent agent, or a new state# note that this is called twice when restoring a previous session, first with state=Noneif state is None:@@ -478,6 +525,11 @@ class AgentController:self.state.history.end_id = self.state.end_iddef _is_stuck(self):+ """Checks if the agent or its delegate is stuck in a loop.++ Returns:+ bool: True if the agent is stuck, False otherwise.+ """# check if delegate stuckif self.delegate and self.delegate._is_stuck():return Truediff --git a/opendevin/controller/state/state.py b/opendevin/controller/state/state.pyindex 372a667679..f82895ecde 100644--- a/opendevin/controller/state/state.py+++ b/opendevin/controller/state/state.py@@ -38,48 +38,35 @@ RESUMABLE_STATES = [@dataclassclass State:"""- OpenDevin is a multi-agentic system.-- A `task` is an end-to-end conversation between OpenDevin (the whole sytem) and the- user, which might involve one or more inputs from the user. It starts with- an initial input (typically a task statement) from the user, and ends with either- a `AgentFinishAction` initiated by the agent, or an error.-- A `subtask` is an end-to-end conversation between an agent and the user, or- another agent. If a `task` is conducted by a single agent, then it's also a `subtask`- itself. Otherwise, a `task` consists of multiple `subtasks`, each executed by- one agent.-- A `State` is a mutable object associated with a `subtask`. It includes several- mutable and immutable fields, among which `iteration` is shared across- subtasks.-- For example, considering a task from the user: `tell me how many GitHub stars- OpenDevin repo has`. Let's assume the default agent is CodeActAgent.-- -- TASK STARTS (SUBTASK 0 STARTS) ---- DELEGATE_LEVEL 0, ITERATION 0, LOCAL_ITERATION 0- CodeActAgent: I should request help from BrowsingAgent-- -- DELEGATE STARTS (SUBTASK 1 STARTS) ---- DELEGATE_LEVEL 1, ITERATION 1, LOCAL_ITERATION 0- BrowsingAgent: Let me find the answer on GitHub-- DELEGATE_LEVEL 1, ITERATION 2, LOCAL_ITERATION 1- BrowsingAgent: I found the answer, let me convey the result and finish-- -- DELEGATE ENDS (SUBTASK 1 ENDS) ---- DELEGATE_LEVEL 0, ITERATION 3, LOCAL_ITERATION 1- CodeActAgent: I got the answer from BrowsingAgent, let me convey the result- and finish-- -- TASK ENDS (SUBTASK 0 ENDS) ---- Note how ITERATION counter is shared across agents, while LOCAL_ITERATION- is local to each subtask.+ Represents the running state of an agent in the OpenDevin system, saving data of its operation and memory.++ - Multi-agent/delegate state:+ - store the task (conversation between the agent and the user)+ - the subtask (conversation between an agent and the user or another agent)+ - global and local iterations+ - delegate levels for multi-agent interactions+ - almost stuck state++ - Running state of an agent:+ - current agent state (e.g., LOADING, RUNNING, PAUSED)+ - traffic control state for rate limiting+ - confirmation mode+ - the last error encountered++ - Data for saving and restoring the agent:+ - save to and restore from a session+ - serialize with pickle and base64++ - Save / restore data about message history+ - start and end IDs for events in agent's history+ - summaries and delegate summaries++ - Metrics:+ - global metrics for the current task+ - local metrics for the current subtask++ - Extra data:+ - additional task-specific data"""root_task: RootTask = field(default_factory=RootTask)