Skip to content

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]

Feat: Allow human to jump in agent run

Kilian Lieret42691d956937
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 7ae25090..4f3e97d6 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -24,6 +24,7 @@ from sweagent.agent.hooks.abstract import AbstractAgentHook, CombinedAgentHook
from sweagent.agent.models import (
AbstractModel,
HumanModel,
+ HumanModelConfig,
HumanThoughtModel,
InstanceStats,
ModelConfig,
@@ -1072,6 +1073,8 @@ class DefaultAgent(AbstractAgent):
except KeyboardInterrupt:
raise
+ except EOFError:
+ raise
# Errors that cause requery
@@ -1240,8 +1243,19 @@ class DefaultAgent(AbstractAgent):
self._chook.on_run_start()
step_output = StepOutput()
while not step_output.done:
- step_output = self.step()
- self.save_trajectory()
+ try:
+ step_output = self.step()
+ self.save_trajectory()
+ except KeyboardInterrupt:
+ if not isinstance(self.model, HumanModel):
+ self.human_step_in()
+ continue
+ raise
+ except EOFError:
+ # Can only happen if we have a human model, so switch back
+ self.logger.info("Detected ^D - switching back to AI mode")
+ self.human_step_out()
+ continue
self._chook.on_run_done(trajectory=self.trajectory, info=self.info)
self.logger.info("Trajectory saved to %s", self.traj_path)
@@ -1250,3 +1264,31 @@ class DefaultAgent(AbstractAgent):
# be the best submission instead of the last one, etc.), so we get it from the traj file
data = self.get_trajectory_data()
return AgentRunResult(info=data["info"], trajectory=data["trajectory"])
+
+ def human_step_in(self) -> None:
+ """Replace the current model with a HumanModel instance.
+ This allows for human intervention during agent execution.
+ """
+ self._original_model = self.model
+ self._original_parser = self.tools.config.parse_function
+
+ human_config = HumanModelConfig(name="human", catch_eof=False)
+ self.model = get_model(human_config, self.tools.config)
+ self.tools.config.parse_function = ActionOnlyParser()
+
+ self.logger.info("Switched to human mode. Agent will now accept human input. Press ^D to switch back.")
+
+ def human_step_out(self) -> None:
+ """Switch back to the original model from human mode.
+ This is called when ^D is pressed in human mode.
+ """
+ if not hasattr(self, "_original_model") or self._original_model is None:
+ self.logger.info("No previous model to switch back to. Remaining in current mode.")
+ return
+
+ self.model = self._original_model
+ self.tools.config.parse_function = self._original_parser
+ self._original_model = None
+ self._original_parser = None
+
+ self.logger.info("Switched back to AI model mode.")
diff --git a/sweagent/agent/models.py b/sweagent/agent/models.py
index 81015167..11d29edf 100644
--- a/sweagent/agent/models.py
+++ b/sweagent/agent/models.py
@@ -223,6 +223,8 @@ class HumanModelConfig(GenericAPIModelConfig):
)
total_cost_limit: float = Field(default=0.0, description="Cost limit for all instances (tasks).")
cost_per_call: float = 0.0
+ catch_eof: bool = True
+ """Whether to catch EOF and return 'exit' when ^D is pressed. Set to False when used in human_step_in mode."""
model_config = ConfigDict(extra="forbid")
@@ -412,8 +414,12 @@ class HumanModel(AbstractModel):
print("^C (exit with ^D)")
out.append(self.query(history, action_prompt))
except EOFError:
- print("\nGoodbye!")
- out.append({"message": "exit"})
+ if self.config.catch_eof:
+ print("\nGoodbye!")
+ out.append({"message": "exit"})
+ else:
+ # Re-raise EOFError when catch_eof is disabled
+ raise
if n is None:
return out[0]
return out
@@ -773,6 +779,7 @@ class LiteLLMModel(AbstractModel):
litellm.exceptions.AuthenticationError,
ContentPolicyViolationError,
ModelConfigurationError,
+ KeyboardInterrupt,
)
),
before_sleep=retry_warning,