Repository navigation
Expand file tree
/
Copy pathagent.py
More file actions
364 lines (310 loc) · 16.1 KB
/
Copy pathagent.py
File metadata and controls
364 lines (310 loc) · 16.1 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
"""
agent.py - LLM incident-triage agents built on DevContext's data tools.
Three methods are exposed to eval.py:
llm_raw Baseline. One call, raw log tail + deploys + health pasted in.
No tools. Shows what the tool layer adds.
agent Investigator: a tool-calling loop over get_recent_errors,
get_recent_deploys, get_service_health, ending in a
structured submit_diagnosis call with quoted evidence.
agent_verified Investigator + Verifier: a second pass that checks the draft
against the tool outputs and may overturn it (e.g. a deploy
that is close in time but unrelated to the errors).
The agent deliberately does NOT get the rule-based diagnose() tool; otherwise
it would just echo the heuristic it is being compared against.
Provider-agnostic LLM client uses OpenAI-compatible endpoints configured via:
DEVCONTEXT_BASE_URL (required)
DEVCONTEXT_API_KEY (required)
DEVCONTEXT_MODEL (required)
Optional rate-pacing:
DEVCONTEXT_MIN_INTERVAL (seconds between calls, default 0)
Responses are cached on disk (.llm_cache/) keyed by base_url + model + prompt.
"""
import hashlib
import json
import os
import re
import time
from pathlib import Path
import tools
CACHE_DIR = Path(os.getenv("DEVCONTEXT_CACHE", ".llm_cache"))
TYPES = ["bad_deploy", "disk", "memory_leak", "downstream_dependency", "db_pool", "unclear"]
MAX_STEPS = 6
MAX_TOOL_CHARS = 3500
RAW_TAIL_LINES = 150
TAXONOMY = """Root-cause types:
- bad_deploy: a deploy's change (see its message and diff) explains the error signatures
- disk: disk exhaustion ("No space left on device", disk near 100%)
- memory_leak: heap/memory exhaustion or OOM kills
- downstream_dependency: an external/third-party API failing (5xx, unreachable)
- db_pool: database connection pool exhaustion or acquire timeouts
- unclear: evidence does not support any of the above"""
INVESTIGATOR_PROMPT = f"""You are an SRE triaging a production incident for one service.
Use the tools to gather evidence, then call submit_diagnosis exactly once.
{TAXONOMY}
Working rules:
- A deploy happening shortly before errors is NOT evidence by itself. Blame a deploy
only if its commit message/diff plausibly explains the specific error messages.
- Regressions can surface late: look at a wide window (minutes=120) and at older deploys.
- Benign warnings (slow query, retry succeeded, cache misses, GC pauses) are noise.
- A moderately elevated metric is not a cause unless the errors match it.
- Quote the log lines, metric values, or diff text that support your answer in `evidence`.
- suspect_commit must be the exact commit id from get_recent_deploys, or null."""
VERIFIER_PROMPT = f"""You are a skeptical reviewer of an incident diagnosis.
You get the investigator's draft and the raw tool outputs it saw.
{TAXONOMY}
Check:
1. Is every quoted piece of evidence actually present in the tool outputs?
2. If a deploy is blamed: does its message/diff plausibly cause the observed error
signatures? A deploy that is merely close in time but unrelated (docs, CSS, lint)
must be rejected, and the true cause chosen from the logs/health.
3. If a non-deploy cause is chosen: do the error signatures clearly match it?
Respond with JSON only:
{{"verdict": "accept" | "revise", "root_cause_type": "<type>", "suspect_commit": "<id or null>", "reason": "<one sentence>"}}
If you accept, repeat the draft's type and commit."""
TOOL_SCHEMAS = [
{"type": "function", "function": {
"name": "get_recent_errors",
"description": "ERROR/WARN log lines grouped by normalised signature, within the last N minutes of the log.",
"parameters": {"type": "object", "properties": {
"minutes": {"type": "integer", "description": "Window size in minutes (default 15)"}}}}},
{"type": "function", "function": {
"name": "get_recent_deploys",
"description": "Recent deployments, newest first: commit, timestamp, author, message, diff summary.",
"parameters": {"type": "object", "properties": {
"limit": {"type": "integer", "description": "Max deploys (default 5)"}}}}},
{"type": "function", "function": {
"name": "get_service_health",
"description": "Current CPU/memory/disk/DB-connection metrics with alert flags.",
"parameters": {"type": "object", "properties": {}}}},
{"type": "function", "function": {
"name": "submit_diagnosis",
"description": "Submit the final diagnosis. Call exactly once.",
"parameters": {"type": "object", "required": ["root_cause_type", "evidence"], "properties": {
"root_cause_type": {"type": "string", "enum": TYPES},
"suspect_commit": {"type": "string", "description": "Exact commit id, or empty string if no deploy is to blame"},
"evidence": {"type": "array", "items": {"type": "string"}}}}}},
]
# --------------------------------------------------------------------------
# LLM wrapper: caching, retries, usage accounting
# --------------------------------------------------------------------------
class DailyLimitError(RuntimeError):
"""The provider's per-day quota is exhausted; waiting a minute will not help."""
def _get_env_config():
missing = []
base_url = os.getenv("DEVCONTEXT_BASE_URL")
api_key = os.getenv("DEVCONTEXT_API_KEY")
model = os.getenv("DEVCONTEXT_MODEL")
if not base_url:
missing.append("DEVCONTEXT_BASE_URL")
if not api_key:
missing.append("DEVCONTEXT_API_KEY")
if not model:
missing.append("DEVCONTEXT_MODEL")
if missing:
if len(missing) == 1:
raise ValueError(f"Missing required environment variable: {missing[0]}")
raise ValueError(f"Missing required environment variables: {', '.join(missing)}")
return base_url, api_key, model
def _retry_wait(err, attempt):
headers = getattr(getattr(err, "response", None), "headers", None) or {}
retry_after = headers.get("retry-after") or headers.get("Retry-After")
if retry_after is not None:
try:
return max(1.0, float(retry_after))
except (TypeError, ValueError):
pass
msg = str(err)
m = re.search(r"(?:retry after|try again in)\s+([0-9.]+)\s*s?", msg, re.IGNORECASE)
if m:
try:
return max(1.0, float(m.group(1)))
except ValueError:
pass
return min(60.0, 5.0 * (2 ** attempt))
class LLM:
def __init__(self, client=None, model=None, base_url=None, run=0, min_interval=None):
if client is None:
env_base_url, env_api_key, env_model = _get_env_config()
from openai import OpenAI
self.base_url = base_url or env_base_url
self.model = model or env_model
self.client = OpenAI(base_url=self.base_url, api_key=env_api_key)
else:
self.client = client
self.model = model or os.getenv("DEVCONTEXT_MODEL") or "test-model"
self.base_url = base_url or os.getenv("DEVCONTEXT_BASE_URL") or "test-base-url"
self.run = run
self.min_interval = (
min_interval
if min_interval is not None
else float(os.getenv("DEVCONTEXT_MIN_INTERVAL", "0") or 0)
)
self.last_call_time = 0.0
self.calls = 0
self.tokens = 0
self.latency = 0.0
CACHE_DIR.mkdir(exist_ok=True)
def usage(self):
return {"calls": self.calls, "tokens": self.tokens, "latency_s": round(self.latency, 2)}
def chat(self, messages, tools=None, json_mode=False):
key = hashlib.sha256(json.dumps(
[self.base_url, self.model, self.run, messages, tools, json_mode], sort_keys=True).encode()).hexdigest()
cached = CACHE_DIR / f"{key}.json"
if cached.exists():
data = json.loads(cached.read_text(encoding="utf-8"))
self.calls += 1
self.tokens += data["tokens"]
return data["message"]
# Pacing: rate limit prevention
if self.min_interval > 0 and self.last_call_time > 0:
elapsed = time.perf_counter() - self.last_call_time
if elapsed < self.min_interval:
time.sleep(self.min_interval - elapsed)
kwargs = {"model": self.model, "messages": messages, "temperature": 0}
if tools:
kwargs.update(tools=tools, tool_choice="auto")
if json_mode:
kwargs["response_format"] = {"type": "json_object"}
last_err = None
for attempt in range(6):
try:
t0 = time.perf_counter()
resp = self.client.chat.completions.create(**kwargs)
self.latency += time.perf_counter() - t0
self.last_call_time = time.perf_counter()
break
except Exception as e: # rate limits and malformed tool calls are routine
last_err = e
status = getattr(e, "status_code", None)
if status is None and hasattr(e, "response") and hasattr(e.response, "status_code"):
status = e.response.status_code
text = str(e).lower()
is_429 = (status == 429) or ("429" in text) or ("rate limit" in text) or ("rate_limit" in text)
if is_429:
if any(k in text for k in ("daily", "day", "quota", "tpd")):
raise DailyLimitError(
f"Daily quota hit for {self.model}. Cached results are kept; rerun later "
f"or switch DEVCONTEXT_MODEL. Provider said: {e}") from e
wait = _retry_wait(e, attempt)
print(f" rate limited, waiting {wait:.0f}s (attempt {attempt + 1}/6)...", flush=True)
time.sleep(wait)
elif status == 400:
kwargs["temperature"] = 0.3 # nudge past a malformed tool call
else:
time.sleep(2)
else:
raise RuntimeError(f"LLM call failed after retries: {last_err}")
m = resp.choices[0].message
message = {"content": m.content or "", "tool_calls": [
{"id": tc.id, "type": "function",
"function": {"name": tc.function.name, "arguments": tc.function.arguments}}
for tc in (m.tool_calls or [])]}
used = getattr(resp.usage, "total_tokens", 0) or 0
self.calls += 1
self.tokens += used
cached.write_text(json.dumps({"message": message, "tokens": used}), encoding="utf-8")
return message
m = resp.choices[0].message
message = {"content": m.content or "", "tool_calls": [
{"id": tc.id, "type": "function",
"function": {"name": tc.function.name, "arguments": tc.function.arguments}}
for tc in (m.tool_calls or [])]}
used = getattr(resp.usage, "total_tokens", 0) or 0
self.calls += 1
self.tokens += used
cached.write_text(json.dumps({"message": message, "tokens": used}), encoding="utf-8")
return message
# --------------------------------------------------------------------------
# Helpers
# --------------------------------------------------------------------------
def _clip(obj) -> str:
text = json.dumps(obj, default=str)
return text if len(text) <= MAX_TOOL_CHARS else text[:MAX_TOOL_CHARS] + "...[truncated]"
def _normalise(d: dict) -> dict:
t = d.get("root_cause_type")
commit = d.get("suspect_commit")
ok = isinstance(commit, str) and commit.strip().lower() not in ("", "null", "none")
return {"root_cause_type": t if t in TYPES else "unclear",
"commit": commit.strip() if ok else None}
def _tool_runner(scenario_dir: Path, service: str):
def run(name, args):
if name == "get_recent_errors":
return tools.get_recent_errors(service, minutes=int(args.get("minutes", 15)),
data_dir=scenario_dir, log_path=_log_file(scenario_dir))
if name == "get_recent_deploys":
return tools.get_recent_deploys(service, limit=int(args.get("limit", 5)),
data_dir=scenario_dir)
if name == "get_service_health":
return tools.get_service_health(service, data_dir=scenario_dir)
return {"error": f"unknown tool {name}"}
return run
def _log_file(scenario_dir: Path):
logs = sorted(scenario_dir.glob("*.log"))
return logs[0] if logs else None
# --------------------------------------------------------------------------
# Investigator and verifier
# --------------------------------------------------------------------------
def investigate(llm: LLM, run_tool, service: str):
"""Tool-calling loop. Returns (draft_dict, transcript_of_tool_outputs)."""
messages = [{"role": "system", "content": INVESTIGATOR_PROMPT},
{"role": "user", "content": f"Service '{service}' is degraded. Find the root cause."}]
seen = []
for _ in range(MAX_STEPS):
msg = llm.chat(messages, tools=TOOL_SCHEMAS)
if not msg["tool_calls"]:
break
messages.append({"role": "assistant", "content": msg["content"], "tool_calls": msg["tool_calls"]})
for tc in msg["tool_calls"]:
name = tc["function"]["name"]
try:
args = json.loads(tc["function"]["arguments"] or "{}")
except json.JSONDecodeError:
args = {}
if name == "submit_diagnosis":
return args, "\n".join(seen)
out = _clip(run_tool(name, args))
seen.append(f"[{name} {json.dumps(args)}] {out}")
messages.append({"role": "tool", "tool_call_id": tc["id"], "content": out})
return {"root_cause_type": "unclear", "suspect_commit": None, "evidence": []}, "\n".join(seen)
def verify(llm: LLM, draft: dict, transcript: str) -> dict:
user = f"DRAFT:\n{json.dumps(draft)}\n\nTOOL OUTPUTS:\n{transcript}"
msg = llm.chat([{"role": "system", "content": VERIFIER_PROMPT},
{"role": "user", "content": user}], json_mode=True)
try:
v = json.loads(msg["content"])
except json.JSONDecodeError:
return draft # unparseable verifier output: keep the draft
if v.get("verdict") == "revise":
return {"root_cause_type": v.get("root_cause_type"), "suspect_commit": v.get("suspect_commit"),
"evidence": draft.get("evidence", [])}
return draft
def raw_baseline(llm: LLM, scenario_dir: Path, service: str) -> dict:
log = _log_file(scenario_dir).read_text(encoding="utf-8").splitlines()[-RAW_TAIL_LINES:]
deploys = (scenario_dir / "deploys.json").read_text(encoding="utf-8")
health = (scenario_dir / "health.json").read_text(encoding="utf-8")
prompt = (f"{TAXONOMY}\n\nService: {service}\n\nLAST {RAW_TAIL_LINES} LOG LINES:\n" + "\n".join(log)
+ f"\n\nDEPLOYS:\n{deploys}\n\nHEALTH:\n{health}\n\n"
'Respond with JSON only: {"root_cause_type": "<type>", "suspect_commit": "<id or null>"}')
msg = llm.chat([{"role": "user", "content": prompt}], json_mode=True)
try:
return json.loads(msg["content"])
except json.JSONDecodeError:
return {"root_cause_type": "unclear", "suspect_commit": None}
# --------------------------------------------------------------------------
# Entry points used by eval.py: (scenario_dir, service, run) -> dict
# --------------------------------------------------------------------------
def _finish(d, llm):
out = _normalise(d)
out["usage"] = llm.usage()
return out
def method_llm_raw(scenario_dir: Path, service: str, run: int = 0, client=None) -> dict:
llm = LLM(client=client, run=run)
return _finish(raw_baseline(llm, scenario_dir, service), llm)
def method_agent(scenario_dir: Path, service: str, run: int = 0, client=None) -> dict:
llm = LLM(client=client, run=run)
draft, _ = investigate(llm, _tool_runner(scenario_dir, service), service)
return _finish(draft, llm)
def method_agent_verified(scenario_dir: Path, service: str, run: int = 0, client=None) -> dict:
llm = LLM(client=client, run=run)
draft, transcript = investigate(llm, _tool_runner(scenario_dir, service), service)
return _finish(verify(llm, draft, transcript), llm)