mirror of
https://github.com/OpenHands/OpenHands.git
synced 2025-12-26 05:48:36 +08:00
* initialize plugin definition * initialize plugin definition * simplify mixin * further improve plugin mixin * add cache dir for pip * support clean up cache * add script for setup jupyter and execution server * integrate JupyterRequirement to ssh_box * source bashrc at the end of plugin load * add execute_cli that accept code via stdin * make JUPYTER_EXEC_SERVER_PORT configurable via env var * increase background cmd sleep time * Update opendevin/sandbox/plugins/mixin.py Co-authored-by: Robert Brennan <accounts@rbren.io> * add mixin to base class * make jupyter requirement a dataclass * source plugins only when >0 requirements * add `sandbox_plugins` for each agent & have controller take care of it * update build.sh to make logs available in /opendevin/logs * switch to use config for lib and cache dir * Add SANDBOX_WORKSPACE_DIR into config * Add SANDBOX_WORKSPACE_DIR into config * fix occurence of /workspace * fix permission issue with /workspace * use python to implement execute_cli to avoid stdin escape issue * add IPythonRunCellAction and get it working * wait until jupyter is avaialble * support plugin via copying instead of mounting * add agent talk action * support follow-up user language feedback * add __str__ for action to be printed better * only print PLAN at the beginning * wip: update codeact agent * get rid the initial messate * update codeact agent to handle null action; add thought to bash * dispatch thought for RUN action as well * fix weird behavior of pxssh where the output would not flush correctly * make ssh box can handle exit_code properly as well * add initial version of swe-agent plugin; * rename swe cursors * split setup script into two and create two requirements * print SWE-agent command documentation * update swe-agent to default to no custom docs * add initial version of swe-agent plugin; * rename swe cursors * split setup script into two and create two requirements * print SWE-agent command documentation * update swe-agent to default to no custom docs * update dockerfile with dependency from swe-agent * make env setup a separate script for .bashrc source * add wip prompt * fix mount_dir for ssh_box * update prompt * fix mount_dir for ssh_box * default to use host network * default to use host network * move prompt to a separate file * fix swe-tool plugins; add missing _split_string * remove hostname from sshbox * update the prompt with edit functionality * fix swe-tool plugins; add missing _split_string * add awaiting into status bar * fix the bug of additional send event * remove some print action * move logic to config.py * remove debugging comments * make host network as default * make WORKSPACE_MOUNT_PATH as abspath * implement execute_cli via file cp * Revert "implement execute_cli via file cp" This reverts commit 06f0155bc17d1f99097e71b83b2143f6e8092654. * add codeact dependencies to default container * add IPythonRunCellObservation * add back cache dir and default to /tmp * make USE_HOST_NETWORK a bool * revert use host network to false * add temporarily fix for IPython RUN action * preliminary implementation of CodeActAgent's jupyter * update node module * update prompt * revert USE_HOST_NETWORK to true since it is not affecting anything * attempt to fix lint * remove newline * update prompt * Refactor browser style. (#1358) * delete useless assets and css class. * add waiting for page loaded (networkidle with 3s timeout) * Add integration test framework with mock llm (#1301) * Add integration test framework with mock llm * Fix MonologueAgent and PlannerAgent tests * Remove adhoc logging * Use existing logs * Fix SWEAgent and PlannerAgent * Check-in test log files * conftest: look up under test name folder only * Add docstring to conftest * Finish dev doc * Avoid non-determinism * Remove dependency on llm embedding model * Init embedding model only for MonologueAgent * Add adhoc fix for sandbox discrepancy * Test ssh and exec sandboxes * CI: fix missing sandbox type * conftest: Remove hack * Reword comment for TODO * Revert "refactor(frontend): Terminal (#1315)" (#1360) This reverts commit 27246aca7e0f3d399740db466f31026c891a5374. * revert USE_HOST_NETWORK to true since it is not affecting anything * attempt to fix lint * handle IsADirectory errors (#1365) * update to 0.4.0 (#1362) Co-authored-by: Jim Su <jimsu@protonmail.com> * feat(frontend): multiple design changes (#1370) * fix/improve terminal hook (#1371) * Revert "update node module" This reverts commit 459b1031e722529ddc00ca475b88245bf52edeaa. * support SyntaxHighlighter and markdown for jupyter visualization * fix jupyter execution server * make jupyter active * improve the display of markdown and raw text * get base64 image display for react * add `thought` to most action class * fix unit tests for current action abstraction * support user exit * update test cases with the latest action format (added 'thought') * fix integration test for CodeActAGent by mocking stdin * only mock stdin for tests with user_responses.log * remove -exec integration test for CodeActAgent since it is not supported * remove specific stop word * fix comments * improve clarity of prompt * attempt to fix lint * attempt to fix lint yet agiain * fix py lint * fix integration tests * sandbox might failed in chown due to mounting, but it won't be fatal * update debug instruction for sshbox * fix typo * get RUN_AS_DEVIN and network=host working with app sandbox * get RUN_AS_DEVIN and network=host working with app sandbox * attempt to fix the workspace base permission * sandbox might failed in chown due to mounting, but it won't be fatal * update sshbox instruction * remove default user id since it will be passed in the instruction * revert permission fix since it should be resolved by correct SANDBOX_USER_ID * the permission issue can be fixed by simply provide correct env var * remove log * set sandbox user id to getuid by default * move logging to initializer * make the uid consistent across host, app container, and sandbox * remove hostname as it causes sudo issue * fix permission of entrypoint script * make the uvicron app run as host user uid for jupyter plugin * add warning message * fix frontend lint * update dev md for instruction of running unit tests * add back unit tests * revert back to the original sandbox implementation to fix testcases * revert use host network * get docker socket gid and usermod instead of chmod 777 * allow unit test workflow to find docker.sock * make sandbox test working via patch * fix arg parser that's broken for some reason * try to fix app build disk space issue * fix integration test * Revert "fix arg parser that's broken for some reason" This reverts commit 6cc89611337bb74555fd16b4be78681fb7e36573. * update Development.md * cleanup intergration tests & add exception for CodeAct+execbox * fix config * implement user_message action * fix doc * fix event dict error * fix frontend lint * revert accidentally changes to integration tests * revert accidentally changes to integration tests --------- Co-authored-by: Robert Brennan <accounts@rbren.io> Co-authored-by: Leo <ifuryst@gmail.com> Co-authored-by: Boxuan Li <liboxuan@connect.hku.hk> Co-authored-by: Jim Su <jimsu@protonmail.com> Co-authored-by: Alex Bäuerle <alex@a13x.io> Co-authored-by: sp.wack <83104063+amanape@users.noreply.github.com> Co-authored-by: Robert Brennan <contact@rbren.io>
171 lines
6.5 KiB
Python
171 lines
6.5 KiB
Python
import re
|
|
from typing import List, Mapping
|
|
|
|
from agenthub.codeact_agent.prompt import EXAMPLES, SYSTEM_MESSAGE
|
|
from opendevin.action import (
|
|
Action,
|
|
AgentEchoAction,
|
|
AgentFinishAction,
|
|
AgentTalkAction,
|
|
CmdRunAction,
|
|
IPythonRunCellAction,
|
|
NullAction,
|
|
)
|
|
from opendevin.agent import Agent
|
|
from opendevin.llm.llm import LLM
|
|
from opendevin.observation import (
|
|
AgentMessageObservation,
|
|
CmdOutputObservation,
|
|
IPythonRunCellObservation,
|
|
UserMessageObservation,
|
|
)
|
|
from opendevin.sandbox.plugins import (
|
|
JupyterRequirement,
|
|
PluginRequirement,
|
|
SWEAgentCommandsRequirement,
|
|
)
|
|
from opendevin.state import State
|
|
|
|
|
|
def parse_response(response) -> str:
|
|
action = response.choices[0].message.content
|
|
for lang in ['bash', 'ipython']:
|
|
if f'<execute_{lang}>' in action and f'</execute_{lang}>' not in action:
|
|
action += f'</execute_{lang}>'
|
|
return action
|
|
|
|
|
|
class CodeActAgent(Agent):
|
|
"""
|
|
The Code Act Agent is a minimalist agent.
|
|
The agent works by passing the model a list of action-observation pairs and prompting the model to take the next step.
|
|
"""
|
|
|
|
sandbox_plugins: List[PluginRequirement] = [JupyterRequirement(), SWEAgentCommandsRequirement()]
|
|
SUPPORTED_ACTIONS = (
|
|
CmdRunAction,
|
|
IPythonRunCellAction,
|
|
AgentEchoAction,
|
|
AgentTalkAction,
|
|
NullAction
|
|
)
|
|
SUPPORTED_OBSERVATIONS = (
|
|
AgentMessageObservation,
|
|
UserMessageObservation,
|
|
CmdOutputObservation,
|
|
IPythonRunCellObservation
|
|
)
|
|
|
|
def __init__(
|
|
self,
|
|
llm: LLM,
|
|
) -> None:
|
|
"""
|
|
Initializes a new instance of the CodeActAgent class.
|
|
|
|
Parameters:
|
|
- llm (LLM): The llm to be used by this agent
|
|
"""
|
|
super().__init__(llm)
|
|
self.messages: List[Mapping[str, str]] = []
|
|
|
|
def step(self, state: State) -> Action:
|
|
"""
|
|
Performs one step using the Code Act Agent.
|
|
This includes gathering info on previous steps and prompting the model to make a command to execute.
|
|
|
|
Parameters:
|
|
- state (State): used to get updated info and background commands
|
|
|
|
Returns:
|
|
- CmdRunAction(command) - command action to run
|
|
- AgentEchoAction(content=INVALID_INPUT_MESSAGE) - invalid command output
|
|
|
|
Raises:
|
|
- NotImplementedError - for actions other than CmdOutputObservation or AgentMessageObservation
|
|
"""
|
|
|
|
if len(self.messages) == 0:
|
|
assert state.plan.main_goal, 'Expecting instruction to be set'
|
|
self.messages = [
|
|
{'role': 'system', 'content': SYSTEM_MESSAGE},
|
|
{
|
|
'role': 'user',
|
|
'content': (
|
|
f'Here is an example of how you can interact with the environment for task solving:\n{EXAMPLES}\n\n'
|
|
f"NOW, LET'S START!\n\n{state.plan.main_goal}"
|
|
)
|
|
},
|
|
]
|
|
updated_info = state.updated_info
|
|
if updated_info:
|
|
for prev_action, obs in updated_info:
|
|
assert isinstance(
|
|
prev_action, self.SUPPORTED_ACTIONS
|
|
), f'{prev_action.__class__} is not supported (supported: {self.SUPPORTED_ACTIONS})'
|
|
# prev_action is already added to self.messages when returned
|
|
|
|
# handle observations
|
|
assert isinstance(
|
|
obs, self.SUPPORTED_OBSERVATIONS
|
|
), f'{obs.__class__} is not supported (supported: {self.SUPPORTED_OBSERVATIONS})'
|
|
if isinstance(obs, (AgentMessageObservation, UserMessageObservation)):
|
|
self.messages.append(
|
|
{'role': 'user', 'content': obs.content})
|
|
|
|
# User wants to exit
|
|
if obs.content.strip() == '/exit':
|
|
return AgentFinishAction()
|
|
elif isinstance(obs, CmdOutputObservation):
|
|
content = 'OBSERVATION:\n' + obs.content
|
|
content += f'\n[Command {obs.command_id} finished with exit code {obs.exit_code}]]'
|
|
self.messages.append({'role': 'user', 'content': content})
|
|
elif isinstance(obs, IPythonRunCellObservation):
|
|
content = 'OBSERVATION:\n' + obs.content
|
|
# replace base64 images with a placeholder
|
|
splited = content.split('\n')
|
|
for i, line in enumerate(splited):
|
|
if ' already displayed to user'
|
|
content = '\n'.join(splited)
|
|
self.messages.append({'role': 'user', 'content': content})
|
|
else:
|
|
raise NotImplementedError(
|
|
f'Unknown observation type: {obs.__class__}'
|
|
)
|
|
|
|
response = self.llm.completion(
|
|
messages=self.messages,
|
|
stop=[
|
|
'</execute_ipython>',
|
|
'</execute_bash>',
|
|
],
|
|
temperature=0.0
|
|
)
|
|
action_str: str = parse_response(response)
|
|
state.num_of_chars += sum(
|
|
len(message['content']) for message in self.messages
|
|
) + len(action_str)
|
|
self.messages.append({'role': 'assistant', 'content': action_str})
|
|
|
|
if bash_command := re.search(r'<execute_bash>(.*)</execute_bash>', action_str, re.DOTALL):
|
|
# remove the command from the action string to get thought
|
|
thought = action_str.replace(bash_command.group(0), '').strip()
|
|
# a command was found
|
|
command_group = bash_command.group(1).strip()
|
|
if command_group.strip() == 'exit':
|
|
return AgentFinishAction()
|
|
return CmdRunAction(command=command_group, thought=thought)
|
|
elif python_code := re.search(r'<execute_ipython>(.*)</execute_ipython>', action_str, re.DOTALL):
|
|
# a code block was found
|
|
code_group = python_code.group(1).strip()
|
|
thought = action_str.replace(python_code.group(0), '').strip()
|
|
return IPythonRunCellAction(code=code_group, thought=thought)
|
|
else:
|
|
# We assume the LLM is GOOD enough that when it returns pure natural language
|
|
# it want to talk to the user
|
|
return AgentTalkAction(content=action_str)
|
|
|
|
def search_memory(self, query: str) -> List[str]:
|
|
raise NotImplementedError('Implement this abstract method')
|