SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Web: Refactor state into one runConfig with use-immer (#350)
Kilian Lieretb699b5011fa6
diff --git a/sweagent/api/server.py b/sweagent/api/server.pyindex d8df6778..6d1c493d 100644--- a/sweagent/api/server.py+++ b/sweagent/api/server.py@@ -7,6 +7,7 @@ except ImportError as e:)raise RuntimeError(msg) from efrom contextlib import redirect_stderr, redirect_stdout+import copyimport jsonimport osfrom pathlib import Path@@ -21,7 +22,7 @@ import yamlfrom sweagent import CONFIG_DIR, PACKAGE_DIRfrom sweagent.agent.agents import AgentArgumentsfrom sweagent.agent.models import ModelArguments-from sweagent.api.utils import ThreadWithExc+from sweagent.api.utils import ThreadWithExc, AttrDictfrom sweagent.environment.swe_env import EnvironmentArgumentsfrom sweagent.api.hooks import EnvUpdateHook, WebUpdate, MainUpdateHook, AgentUpdateHookimport sweagent.environment.utils as env_utils@@ -102,10 +103,16 @@ def handle_connect():print("Client connected")-def write_env_yaml(data: Dict[str, Any]) -> str:+def write_env_yaml(data) -> str:+ data: Any = AttrDict(copy.deepcopy(dict(data)))+ if not data.install_command_active:+ data.install = ""+ del data.install_command_active+ data.pip_packages = [p.strip() for p in data.pip_packages.split("\n") if p.strip()]path = Path(tempfile.NamedTemporaryFile(delete=False, suffix=".yml").name)+ # Make sure that the file is deleted when the program exitsatexit.register(path.unlink)- path.write_text(yaml.dump(data))+ path.write_text(yaml.dump(dict(data)))return str(path)@@ -122,20 +129,23 @@ def run():thread.stop()wu = WebUpdate(socketio)wu.up_agent("Starting the run")- data_path = request.args["data_path"]- repo_path = request.args["repo_path"]- model_name = request.args["model"]- environment = json.loads(request.args["environment"])+ # Use Any type to silence annoying false positives from mypy+ run: Any = AttrDict.from_nested_dicts(json.loads(request.args["runConfig"]))+ print(run)+ data_path: str = run.environment.data_path+ repo_path: str = run.environment.repo_path+ model_name: str = run.agent.model.model_nameenvironment_setup = ""- if environment["config_type"] == "manual":- if not environment["install_command_active"]:- environment["install"] = ""- environment_setup = str(write_env_yaml(environment))- elif environment["config_type"] == "script_path":- environment_setup = environment["script_path"]+ environment_input_type = run.environment.environment_setup.input_type+ if environment_input_type == "manual":+ environment_setup = str(write_env_yaml(run.environment.environment_setup.manual))+ elif environment_input_type == "script_path":+ environment_setup = run.environment.environment_setup.script_path["script_path"]+ else:+ raise ValueError(f"Unknown input type: {environment_input_type}")if not environment_setup.strip():environment_setup = None- test_run = request.args["test_run"].lower() == "true"+ test_run: bool = run.extra.test_runif test_run:model_name = "instant_empty_submit"defaults = ScriptArguments(diff --git a/sweagent/api/utils.py b/sweagent/api/utils.pyindex ec3bd9e4..3dc76c84 100644--- a/sweagent/api/utils.py+++ b/sweagent/api/utils.py@@ -104,3 +104,39 @@ _ANSI_ESCAPE = re.compile(def strip_ansi_sequences(string: str) -> str:return _ANSI_ESCAPE.sub("", string)+++class AttrDict(dict):+ """ Dictionary subclass whose entries can be accessed by attributes (as well+ as normally).++ Author: https://stackoverflow.com/users/355230/martineau+ Posted June 26, 2016+ Post: https://stackoverflow.com/questions/38034377/++ >>> obj = AttrDict()+ >>> obj['test'] = 'hi'+ >>> print obj.test+ hi+ >>> del obj.test+ >>> obj.test = 'bye'+ >>> print obj['test']+ bye+ >>> print len(obj)+ 1+ >>> obj.clear()+ >>> print len(obj)+ 0+ """+ def __init__(self, *args, **kwargs):+ super(AttrDict, self).__init__(*args, **kwargs)+ self.__dict__ = self++ @classmethod+ def from_nested_dicts(cls, data):+ """ Construct nested AttrDicts from nested dictionaries. """+ if not isinstance(data, dict):+ return data+ else:+ return cls({key: cls.from_nested_dicts(data[key]) for key in data})+diff --git a/sweagent/frontend/package-lock.json b/sweagent/frontend/package-lock.jsonindex 02547a71..40866963 100644--- a/sweagent/frontend/package-lock.json+++ b/sweagent/frontend/package-lock.json@@ -23,6 +23,7 @@"react-scripts": "5.0.1","react-syntax-highlighter": "^15.5.0","socket.io-client": "^4.7.5",+ "use-immer": "^0.9.0","web-vitals": "^2.1.4"}},@@ -20211,6 +20212,15 @@"requires-port": "^1.0.0"}},+ "node_modules/use-immer": {+ "version": "0.9.0",+ "resolved": "https://registry.npmjs.org/use-immer/-/use-immer-0.9.0.tgz",+ "integrity": "sha512-/L+enLi0nvuZ6j4WlyK0US9/ECUtV5v9RUbtxnn5+WbtaXYUaOBoKHDNL9I5AETdurQ4rIFIj/s+Z5X80ATyKw==",+ "peerDependencies": {+ "immer": ">=2.0.0",+ "react": "^16.8.0 || ^17.0.1 || ^18.0.0"+ }+ },"node_modules/util-deprecate": {"version": "1.0.2","resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",diff --git a/sweagent/frontend/package.json b/sweagent/frontend/package.jsonindex f556eeaf..0c9de5b2 100644--- a/sweagent/frontend/package.json+++ b/sweagent/frontend/package.json@@ -18,7 +18,8 @@"react-scripts": "5.0.1","react-syntax-highlighter": "^15.5.0","socket.io-client": "^4.7.5",- "web-vitals": "^2.1.4"+ "web-vitals": "^2.1.4",+ "use-immer": "^0.9.0"},"scripts": {"start": "react-scripts start",diff --git a/sweagent/frontend/src/Run.js b/sweagent/frontend/src/Run.jsindex 33a3988f..1701a2e4 100644--- a/sweagent/frontend/src/Run.js+++ b/sweagent/frontend/src/Run.js@@ -6,6 +6,7 @@ import AgentFeed from "./components/panels/AgentFeed";import EnvFeed from "./components/panels/EnvFeed";import LogPanel from "./components/panels/LogPanel";import LRunControl from "./components/controls/LRunControl";+import { useImmer } from "use-immer";const url = ""; // Will get this from .env// Connect to Socket.io@@ -15,19 +16,35 @@ function Run() {const [isConnected, setIsConnected] = useState(socket.connected);const [errorBanner, setErrorBanner] = useState("");- const [dataPath, setDataPath] = useState(- "https://github.com/marshmallow-code/marshmallow/issues/1359",- );- const [repoPath, setRepoPath] = useState("");- const [model, setModel] = useState("gpt4");- const envConfigDefault = {- python: "3.10",- config_type: "manual",- install: "pip install --editable .",- install_command_active: true,+ const runConfigDefault = {+ agent: {+ model: {+ model_name: "gpt4",+ },+ },+ environment: {+ data_path: "",+ repo_path: "",+ environment_setup: {+ input_type: "manual",+ manual: {+ python: "3.10",+ config_type: "manual",+ install: "pip install --editable .",+ install_command_active: true,+ pip_packages: "",+ },+ script_path: {+ script_path: "",+ },+ },+ },+ extra: {+ test_run: false,+ },};- const [envConfig, setEnvConfig] = useState(envConfigDefault);- const [testRun, setTestRun] = useState(false);+ const [runConfig, setRunConfig] = useImmer(runConfigDefault);+const [agentFeed, setAgentFeed] = useState([]);const [envFeed, setEnvFeed] = useState([]);const [highlightedStep, setHighlightedStep] = useState(null);@@ -119,13 +136,7 @@ function Run() {setErrorBanner("");try {await axios.get(`/run`, {- params: {- data_path: dataPath,- test_run: testRun,- repo_path: repoPath,- model: model,- environment: JSON.stringify(envConfig),- },+ params: { runConfig: JSON.stringify(runConfig) },});} catch (error) {console.error("Error:", error);@@ -257,16 +268,11 @@ function Run() {isConnected={isConnected}handleStop={handleStop}handleSubmit={handleSubmit}- setDataPath={setDataPath}- setTestRun={setTestRun}- setRepoPath={setRepoPath}- testRun={testRun}- setModel={setModel}tabKey={tabKey}setTabKey={setTabKey}- envConfig={envConfig}- setEnvConfig={setEnvConfig}- envConfigDefault={envConfigDefault}+ runConfig={runConfig}+ setRunConfig={setRunConfig}+ runConfigDefault={runConfigDefault}/><div id="demo"><hr />diff --git a/sweagent/frontend/src/components/controls/LRunControl.js b/sweagent/frontend/src/components/controls/LRunControl.jsindex e283c3b5..3e5cd899 100644--- a/sweagent/frontend/src/components/controls/LRunControl.js+++ b/sweagent/frontend/src/components/controls/LRunControl.js@@ -11,20 +11,14 @@ function LRunControl({isConnected,handleStop,handleSubmit,- setDataPath,- setTestRun,- testRun,- setRepoPath,- setModel,tabKey,setTabKey,- envConfig,- setEnvConfig,- envConfigDefault,+ runConfig,+ setRunConfig,+ runConfigDefault,}) {// ps = problem statementconst [psType, setPsType] = useState("gh");- const [envInputType, setEnvInputType] = useState("manual");const defaultInstallCommand = "pip install --editable .";const defaultPS =@@ -47,7 +41,11 @@ function LRunControl({<inputtype="text"className="form-control"- onChange={(e) => setDataPath(e.target.value)}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.environment.data_path = e.target.value;+ })+ }placeholder={"Example: " + defaultPS}defaultValue=""/>@@ -63,7 +61,11 @@ function LRunControl({<inputtype="text"className="form-control"- onChange={(e) => setDataPath(e.target.value)}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.environment.data_path = e.target.value;+ })+ }placeholder="/path/to/your/local/file.md"defaultValue=""/>@@ -74,7 +76,11 @@ function LRunControl({return (<textareaclassName="form-control"- onChange={(e) => setDataPath("text://" + e.target.value)}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.environment.data_path = "text://" + e.target.value;+ })+ }rows="5"placeholder="Enter problem statement"/>@@ -85,21 +91,22 @@ function LRunControl({function getEnvInput() {// Get environment configuration input controls based on the// "Environment type" dropdown menu.- if (envInputType === "conda") {- return (- <div className="input-group mb-3">- <span className="input-group-text">Conda environment</span>- <input- type="text"- className="form-control"- onChange={(e) =>- setEnvConfig({ ...envConfig, packages: e.target.value })- }- placeholder="/path/to/conda_env.yml"- />- </div>- );- }+ // if (envInputType === "conda") {+ // return (+ // <div className="input-group mb-3">+ // <span className="input-group-text">Conda environment</span>+ // <input+ // type="text"+ // className="form-control"+ // onChange={(e) =>+ // setRunConfig(draft => {draft.environment.environment_setup.packages = e.target.value})+ // }+ // placeholder="/path/to/conda_env.yml"+ // />+ // </div>+ // );+ // }+ const envInputType = runConfig.environment.environment_setup.input_type;if (envInputType === "script_path") {return (<div>@@ -109,7 +116,10 @@ function LRunControl({type="text"className="form-control"onChange={(e) =>- setEnvConfig({ ...envConfig, script_path: e.target.value })+ setRunConfig((draft) => {+ draft.environment.environment_setup.script_path.script_path =+ e.target.value;+ })}placeholder="/path/to/setup.sh"defaultValue=""@@ -132,12 +142,16 @@ function LRunControl({type="text"className="form-control"onChange={(e) =>- setEnvConfig({- ...envConfig,- python: e.target.value || envConfigDefault["python"],+ setRunConfig((draft) => {+ draft.environment.environment_setup.manual.python =+ e.target.value ||+ runConfigDefault.environment.environment_setup.manual+ .python;})}- placeholder={envConfigDefault["python"]}+ placeholder={+ runConfigDefault.environment.environment_setup.manual.python+ }defaultValue=""/></div>@@ -149,9 +163,9 @@ function LRunControl({aria-label="Run installation command"defaultChecked={true}onChange={(e) =>- setEnvConfig({- ...envConfig,- install_command_active: e.target.value,+ setRunConfig((draft) => {+ draft.environment.environment_setup.manual.install_command_active =+ e.target.checked;})}/>@@ -163,9 +177,9 @@ function LRunControl({aria-label="Text input with checkbox"placeholder={defaultInstallCommand}onChange={(e) =>- setEnvConfig({- ...envConfig,- install: e.target.value || defaultInstallCommand,+ setRunConfig((draft) => {+ draft.environment.environment_setup.manual.install =+ e.target.value;})}/>@@ -174,7 +188,10 @@ function LRunControl({<textareaclassName="form-control"onChange={(e) =>- setEnvConfig({ ...envConfig, pip_packages: e.target.value })+ setRunConfig((draft) => {+ draft.environment.environment_setup.manual.pip_packages =+ e.target.value;+ })}rows="5"placeholder="pip installable packages list, one per line (i.e., requirements.txt)."@@ -184,25 +201,6 @@ function LRunControl({}}- function handleEnvInputTypeUpdate(value) {- // Handle a change in how the user wants to configure the environment.- // We need to make sure that we clear out config items that aren't "active" anymore- // For example, if we switch from conda to manual, we should clear out conda env path- setEnvInputType(value);- if (value === "conda") {- setEnvConfig({ packages: "", config_type: "conda" });- } else if (value === "manual") {- setEnvConfig({- python: envConfigDefault["python"],- config_type: "manual",- install: "pip install --editable .",- install_command_active: true,- });- } else if (value === "script_path") {- setEnvConfig({ script_path: "", config_type: "script_path" });- }- }-function onTabClicked(keyClicked) {/* Handle clicks on the tabs of the control/setting groups */if (keyClicked === tabKey) {@@ -244,7 +242,11 @@ function LRunControl({type="text"className="form-control"placeholder="Optional when using GitHub issue as problem source."- onChange={(e) => setRepoPath(e.target.value)}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.environment.repo_path = e.target.value;+ })+ }defaultValue=""/></div>@@ -258,7 +260,11 @@ function LRunControl({type="text"className="form-control"placeholder="gpt4"- onChange={(e) => setModel(e.target.value || "gpt4")}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.agent.model.model_name = e.target.value || "gpt4";+ })+ }/></div><div className="alert alert-info" role="alert">@@ -282,8 +288,15 @@ function LRunControl({<selectclassName="form-select"aria-label="Select problem statement type"- onChange={(e) => handleEnvInputTypeUpdate(e.target.value)}- defaultValue={envInputType}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.environment.environment_setup.input_type =+ e.target.value;+ })+ }+ defaultValue={+ runConfigDefault.environment.environment_setup.input_type+ }><option value="manual">Python version and packages</option><option value="script_path">Path to shell script</option>@@ -300,8 +313,12 @@ function LRunControl({type="switch"id="custom-switch"label="Test run (dummy agent without LM queries)"- checked={testRun}- onChange={(e) => setTestRun(e.target.checked)}+ checked={runConfig.extra.test_run}+ onChange={(e) =>+ setRunConfig((draft) => {+ draft.extra.test_run = e.target.checked;+ })+ }/></div></Tab>