Skip to content

The agent that grows with you

refactor(mini_swe_runner): unify temperature helper with trajectory_compressor, compact literals and signatures

Teknium6d81b7e7e1aa
diff --git a/mini_swe_runner.py b/mini_swe_runner.py
index 7e9211ae6d5..fc7dc5099dc 100644
--- a/mini_swe_runner.py
+++ b/mini_swe_runner.py
@@ -21,20 +21,12 @@ from typing import List, Dict, Any, Optional
import fire
from dotenv import load_dotenv
from agent.tool_dispatch_helpers import make_tool_result_message
+from trajectory_compressor import _effective_temperature_for_model
# Load environment variables
load_dotenv()
-def _effective_temperature_for_model(
- model: str,
- base_url: Optional[str] = None,
-) -> Optional[float]:
- """Fixed temperature for models with strict sampling contracts, else None (omit the kwarg)."""
- from trajectory_compressor import _effective_temperature_for_model as _shared
- return _shared(model, None, base_url)
-
-
TERMINAL_TOOL_DEFINITION = {
"type": "function",
"function": {
@@ -65,18 +57,12 @@ TERMINAL_TOOL_DEFINITION = {
"parameters": {
"type": "object",
"properties": {
- "command": {
- "type": "string",
- "description": "The bash command to execute"
- },
- "timeout": {
- "type": "integer",
- "description": "Command timeout in seconds (default: 60)"
- }
+ "command": {"type": "string", "description": "The bash command to execute"},
+ "timeout": {"type": "integer", "description": "Command timeout in seconds (default: 60)"},
},
- "required": ["command"]
- }
- }
+ "required": ["command"],
+ },
+ },
}
SYSTEM_PROMPT = """You are an AI agent that can execute bash commands to complete tasks.
@@ -109,13 +95,7 @@ HERMES_SYSTEM_SUFFIX = (
_OPENROUTER_URL = "https://openrouter.ai/api/v1"
-def create_environment(
- env_type: str = "local",
- image: str = "python:3.11-slim",
- cwd: str = "/tmp",
- timeout: int = 60,
- **kwargs
-):
+def create_environment(env_type: str = "local", image: str = "python:3.11-slim", cwd: str = "/tmp", timeout: int = 60, **kwargs):
"""Create a Hermes execution environment (``local`` ignores ``image``/``kwargs``)."""
if env_type == "local":
from tools.environments.local import LocalEnvironment
@@ -148,26 +128,11 @@ def _gpt_content(msg: Dict[str, Any], content: str) -> str:
class MiniSWERunner:
"""Tool-calling agent loop over a Hermes execution environment, emitting Hermes trajectories."""
- def __init__(
- self,
- model: str = "anthropic/claude-sonnet-4.6",
- base_url: str = None,
- api_key: str = None,
- env_type: str = "local",
- image: str = "python:3.11-slim",
- cwd: str = "/tmp",
- max_iterations: int = 15,
- command_timeout: int = 60,
- verbose: bool = False,
- ):
- self.model = model
- self.max_iterations = max_iterations
- self.command_timeout = command_timeout
- self.verbose = verbose
- self.env_type = env_type
- self.image = image
- self.cwd = cwd
-
+ def __init__(self, model: str = "anthropic/claude-sonnet-4.6", base_url: str = None, api_key: str = None,
+ env_type: str = "local", image: str = "python:3.11-slim", cwd: str = "/tmp",
+ max_iterations: int = 15, command_timeout: int = 60, verbose: bool = False):
+ self.model, self.max_iterations, self.command_timeout, self.verbose = model, max_iterations, command_timeout, verbose
+ self.env_type, self.image, self.cwd = env_type, image, cwd
self.logger = logging.getLogger(__name__)
self.client = self._init_client(base_url, api_key)
self.env = None # created per-task
@@ -184,13 +149,8 @@ class MiniSWERunner:
"""Explicit api_key/base_url -> direct OpenAI client; otherwise the provider router."""
if api_key or base_url:
from openai import OpenAI
- return OpenAI(
- base_url=base_url or _OPENROUTER_URL,
- api_key=api_key or os.getenv(
- "OPENROUTER_API_KEY",
- os.getenv("ANTHROPIC_API_KEY",
- os.getenv("OPENAI_API_KEY", ""))),
- )
+ return OpenAI(base_url=base_url or _OPENROUTER_URL, api_key=api_key or os.getenv(
+ "OPENROUTER_API_KEY", os.getenv("ANTHROPIC_API_KEY", os.getenv("OPENAI_API_KEY", ""))))
from agent.auxiliary_client import resolve_provider_client
client, _ = resolve_provider_client("openrouter", model=self.model)
if client is None:
@@ -202,12 +162,7 @@ class MiniSWERunner:
def _create_env(self):
print(f"πŸ”§ Creating {self.env_type} environment...")
- self.env = create_environment(
- env_type=self.env_type,
- image=self.image,
- cwd=self.cwd,
- timeout=self.command_timeout
- )
+ self.env = create_environment(env_type=self.env_type, image=self.image, cwd=self.cwd, timeout=self.command_timeout)
print("βœ… Environment ready")
def _cleanup_env(self):
@@ -224,25 +179,16 @@ class MiniSWERunner:
self._create_env()
try:
result = self.env.execute(command, timeout=timeout or self.command_timeout)
- return {
- "output": result.get("output", ""),
- "exit_code": result.get("returncode", 0),
- "error": None
- }
+ return {"output": result.get("output", ""), "exit_code": result.get("returncode", 0), "error": None}
except Exception as e:
return {"output": "", "exit_code": -1, "error": str(e)}
def _format_tools_for_system_message(self) -> str:
- formatted_tools = [
- {
- "name": tool["function"]["name"],
- "description": tool["function"].get("description", ""),
- "parameters": tool["function"].get("parameters", {}),
- "required": None,
- }
- for tool in self.tools
- ]
- return json.dumps(formatted_tools, ensure_ascii=False)
+ return json.dumps([
+ {"name": t["function"]["name"], "description": t["function"].get("description", ""),
+ "parameters": t["function"].get("parameters", {}), "required": None}
+ for t in self.tools
+ ], ensure_ascii=False)
def _tool_response_turn(self, messages: List[Dict[str, Any]], i: int) -> tuple:
"""Fold the tool messages following assistant turn ``i`` into one ``tool`` value.
@@ -261,31 +207,18 @@ class MiniSWERunner:
except (json.JSONDecodeError, AttributeError):
pass
k = len(tool_responses)
- tool_responses.append(
- "<tool_response>\n"
- + json.dumps({
- "tool_call_id": tool_msg.get("tool_call_id", ""),
- "name": tool_calls[k]["function"]["name"] if k < len(tool_calls) else "unknown",
- "content": tool_content,
- }, ensure_ascii=False)
- + "\n</tool_response>"
- )
+ body = json.dumps({"tool_call_id": tool_msg.get("tool_call_id", ""),
+ "name": tool_calls[k]["function"]["name"] if k < len(tool_calls) else "unknown",
+ "content": tool_content}, ensure_ascii=False)
+ tool_responses.append(f"<tool_response>\n{body}\n</tool_response>")
j += 1
if not tool_responses:
return None, i
return "\n".join(tool_responses), j - 1
- def _convert_to_hermes_format(
- self,
- messages: List[Dict[str, Any]],
- user_query: str,
- ) -> List[Dict[str, Any]]:
+ def _convert_to_hermes_format(self, messages: List[Dict[str, Any]], user_query: str) -> List[Dict[str, Any]]:
"""Convert the OpenAI-style message list to the Hermes trajectory format used by batch_runner.py."""
- system_msg = (
- HERMES_SYSTEM_PREFIX
- + f"<tools>\n{self._format_tools_for_system_message()}\n</tools>\n"
- + HERMES_SYSTEM_SUFFIX
- )
+ system_msg = HERMES_SYSTEM_PREFIX + f"<tools>\n{self._format_tools_for_system_message()}\n</tools>\n" + HERMES_SYSTEM_SUFFIX
trajectory = [{"from": "system", "value": system_msg}, {"from": "human", "value": user_query}]
i = 1 # first user message already added
@@ -297,10 +230,7 @@ class MiniSWERunner:
for tool_call in msg["tool_calls"]:
if not tool_call or not isinstance(tool_call, dict):
continue
- tool_call_json = {
- "name": tool_call["function"]["name"],
- "arguments": _parse_json_args(tool_call["function"]["arguments"]),
- }
+ tool_call_json = {"name": tool_call["function"]["name"], "arguments": _parse_json_args(tool_call["function"]["arguments"])}
content += f"<tool_call>\n{json.dumps(tool_call_json, ensure_ascii=False)}\n</tool_call>\n"
trajectory.append({"from": "gpt", "value": _gpt_content(msg, content).rstrip()})
tool_value, i = self._tool_response_turn(messages, i)
@@ -316,16 +246,10 @@ class MiniSWERunner:
def _call_model(self, messages: List[Dict[str, Any]]):
"""One chat completion with the ephemeral system prompt; returns the message or None on API error."""
- api_kwargs = {
- "model": self.model,
- "messages": [{"role": "system", "content": SYSTEM_PROMPT}] + messages,
- "tools": self.tools,
- "timeout": 300.0,
- }
- fixed_temperature = _effective_temperature_for_model(
- self.model,
- str(getattr(self.client, "base_url", "") or ""),
- )
+ api_kwargs = {"model": self.model, "messages": [{"role": "system", "content": SYSTEM_PROMPT}] + messages,
+ "tools": self.tools, "timeout": 300.0}
+ # requested_temperature=None: only fixed model contracts (Kimi omit / Arcee 0.5) apply here.
+ fixed_temperature = _effective_temperature_for_model(self.model, None, str(getattr(self.client, "base_url", "") or ""))
if fixed_temperature is not None:
api_kwargs["temperature"] = fixed_temperature
try:
@@ -337,18 +261,10 @@ class MiniSWERunner:
def _run_tool_calls(self, assistant_message, messages: List[Dict[str, Any]]) -> bool:
"""Record the assistant turn, execute each terminal call, append results; True if the completion signal fired."""
print(f"πŸ”§ Tool calls: {len(assistant_message.tool_calls)}")
- messages.append({
- "role": "assistant",
- "content": assistant_message.content,
- "tool_calls": [
- {
- "id": tc.id,
- "type": tc.type,
- "function": {"name": tc.function.name, "arguments": tc.function.arguments},
- }
- for tc in assistant_message.tool_calls
- ]
- })
+ messages.append({"role": "assistant", "content": assistant_message.content, "tool_calls": [
+ {"id": tc.id, "type": tc.type, "function": {"name": tc.function.name, "arguments": tc.function.arguments}}
+ for tc in assistant_message.tool_calls
+ ]})
completed = False
for tc in assistant_message.tool_calls:
@@ -358,13 +274,7 @@ class MiniSWERunner:
print(f" πŸ“ž terminal: {command[:60]}...")
result = self._execute_command(command, timeout)
- result_json = json.dumps({
- "content": {
- "output": result["output"],
- "exit_code": result["exit_code"],
- "error": result["error"]
- }
- }, ensure_ascii=False)
+ result_json = json.dumps({"content": {"output": result["output"], "exit_code": result["exit_code"], "error": result["error"]}}, ensure_ascii=False)
if "MINI_SWE_AGENT_FINAL_OUTPUT" in result["output"]:
print(" βœ… Task completion signal detected!")
completed = True
@@ -413,18 +323,10 @@ class MiniSWERunner:
"conversations": self._convert_to_hermes_format(messages, task),
"completed": completed,
"api_calls": api_call_count,
- "metadata": {
- "model": self.model,
- "env_type": self.env_type,
- "timestamp": datetime.now().isoformat()
- }
+ "metadata": {"model": self.model, "env_type": self.env_type, "timestamp": datetime.now().isoformat()},
}
- def run_batch(
- self,
- prompts: List[str],
- output_file: str
- ) -> List[Dict[str, Any]]:
+ def run_batch(self, prompts: List[str], output_file: str) -> List[Dict[str, Any]]:
"""Run every prompt, appending each result to ``output_file`` as it finishes."""
results = []
@@ -442,13 +344,8 @@ class MiniSWERunner:
print(f"βœ… Task {i} completed (api_calls={result['api_calls']})")
except Exception as e:
self.logger.error("Error on task %s: %s", i, e)
- result = {
- "conversations": [],
- "completed": False,
- "api_calls": 0,
- "error": str(e),
- "metadata": {"timestamp": datetime.now().isoformat()}
- }
+ result = {"conversations": [], "completed": False, "api_calls": 0, "error": str(e),
+ "metadata": {"timestamp": datetime.now().isoformat()}}
results.append(result)
f.write(json.dumps(result, ensure_ascii=False) + "\n")
f.flush()
@@ -508,23 +405,11 @@ def main(
print("=" * 60)
# Configure root logging at the entry point (not in library __init__).
- logging.basicConfig(
- level=logging.DEBUG if verbose else logging.INFO,
- format='%(asctime)s - %(levelname)s - %(message)s',
- datefmt='%H:%M:%S'
- )
-
- runner = MiniSWERunner(
- model=model,
- base_url=base_url,
- api_key=api_key,
- env_type=env,
- image=image,
- cwd=cwd,
- max_iterations=max_iterations,
- command_timeout=timeout,
- verbose=verbose,
- )
+ logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO,
+ format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%H:%M:%S')
+
+ runner = MiniSWERunner(model=model, base_url=base_url, api_key=api_key, env_type=env, image=image, cwd=cwd,
+ max_iterations=max_iterations, command_timeout=timeout, verbose=verbose)
if task:
result = runner.run_task(task)