-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathagent.py
More file actions
191 lines (156 loc) · 5.4 KB
/
agent.py
File metadata and controls
191 lines (156 loc) · 5.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/env python3
"""
SuperAgent for Term Challenge - Entry Point (SDK 3.0 Compatible).
This agent accepts --instruction from the validator and runs autonomously.
Uses Chutes API for LLM calls instead of term_sdk.
Installation:
pip install . # via pyproject.toml
pip install -r requirements.txt # via requirements.txt
Usage:
python agent.py --instruction "Your task description here..."
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path
# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent))
# Auto-install dependencies if missing
def ensure_dependencies():
"""Install dependencies if not present."""
try:
import httpx
import pydantic
except ImportError:
print("[setup] Installing dependencies...", file=sys.stderr)
agent_dir = Path(__file__).parent
req_file = agent_dir / "requirements.txt"
if req_file.exists():
subprocess.run(
[sys.executable, "-m", "pip", "install", "-r", str(req_file), "-q"], check=True
)
else:
subprocess.run(
[sys.executable, "-m", "pip", "install", str(agent_dir), "-q"], check=True
)
print("[setup] Dependencies installed", file=sys.stderr)
ensure_dependencies()
from src.config.defaults import CONFIG
from src.core.loop import run_agent_loop
from src.llm.client import CostLimitExceeded, LLMClient
from src.output.jsonl import ErrorEvent, emit
from src.tools.registry import ToolRegistry
class AgentContext:
"""Minimal context for agent execution (replaces term_sdk.AgentContext)."""
def __init__(self, instruction: str, cwd: str = None):
self.instruction = instruction
self.cwd = cwd or os.getcwd()
self.step = 0
self.is_done = False
self.history = []
self._start_time = time.time()
@property
def elapsed_secs(self) -> float:
return time.time() - self._start_time
def shell(self, cmd: str, timeout: int = 120) -> "ShellResult":
"""Execute a shell command."""
self.step += 1
try:
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
timeout=timeout,
cwd=self.cwd,
)
output = result.stdout + result.stderr
exit_code = result.returncode
except subprocess.TimeoutExpired:
output = "[TIMEOUT]"
exit_code = -1
except Exception as e:
output = f"[ERROR] {e}"
exit_code = -1
shell_result = ShellResult(output=output, exit_code=exit_code)
self.history.append(
{
"step": self.step,
"command": cmd,
"output": output[:1000],
"exit_code": exit_code,
}
)
return shell_result
def done(self):
"""Mark task as complete."""
self.is_done = True
def log(self, msg: str):
"""Log a message."""
timestamp = time.strftime("%H:%M:%S")
print(f"[{timestamp}] [ctx] {msg}", file=sys.stderr, flush=True)
class ShellResult:
"""Result from shell command."""
def __init__(self, output: str, exit_code: int):
self.output = output
self.stdout = output
self.stderr = ""
self.exit_code = exit_code
def has(self, text: str) -> bool:
return text in self.output
def _log(msg: str):
"""Log to stderr."""
timestamp = time.strftime("%H:%M:%S")
print(f"[{timestamp}] [superagent] {msg}", file=sys.stderr, flush=True)
def main():
parser = argparse.ArgumentParser(description="SuperAgent for Term Challenge SDK 3.0")
parser.add_argument("--instruction", required=True, help="Task instruction from validator")
args = parser.parse_args()
_log("=" * 60)
_log("SuperAgent Starting (SDK 3.0 - Chutes API)")
_log("=" * 60)
_log(f"Model: {CONFIG['model']}")
_log(f"Reasoning effort: {CONFIG.get('reasoning_effort', 'default')}")
_log(f"Instruction: {args.instruction[:200]}...")
_log("-" * 60)
# Initialize components
start_time = time.time()
llm = LLMClient(
model=CONFIG["model"],
temperature=CONFIG.get("temperature"),
max_tokens=CONFIG.get("max_tokens", 16384),
)
tools = ToolRegistry()
ctx = AgentContext(instruction=args.instruction)
_log("Components initialized")
try:
run_agent_loop(
llm=llm,
tools=tools,
ctx=ctx,
config=CONFIG,
)
except CostLimitExceeded as e:
_log(f"Cost limit exceeded: {e}")
emit(ErrorEvent(message=f"Cost limit exceeded: {e}"))
except Exception as e:
_log(f"Fatal error: {e}")
emit(ErrorEvent(message=str(e)))
raise
finally:
elapsed = time.time() - start_time
try:
stats = llm.get_stats()
_log(f"Total tokens: {stats.get('total_tokens', 0)}")
_log(f"Total cost: ${stats.get('total_cost', 0):.4f}")
_log(f"Requests: {stats.get('request_count', 0)}")
except Exception as e:
_log(f"Stats error: {e}")
_log(f"Elapsed: {elapsed:.1f}s")
_log("Agent finished")
_log("=" * 60)
if __name__ == "__main__":
main()