tools/eval (stdlib Python): one agent loop, system prompt and tool set (list/read/write/edit files, run, finish) for every language; language profiles for aji_air, rust, zig carry only toolchain invocation, docs location and command classification; bubblewrap sandbox without network, read-only toolchain and /docs; providers: Anthropic Messages, OpenAI-compatible (incl. local servers), scripted; run record per protocol §28 (hashes, versions, limits, hardware, seed, all events, patches, commands, final repository, first-generation snapshot, evaluator verdicts, cost); metrics §14-§17; resumable matrix plans; report (VSR, repair cycles, context, cost per correct solution); classify (§27 categories, caught-by, smoke-test causes). docs/evaluation/harness.md (task format for the private benchmark repository, evaluator contract, record schema); dev-tasks/dev-echo (harness development task, no benchmark family); smoke plan shape for the owner's E-S choice (binary/stream parser, bounded pipeline); self-tests in CI
210 lines
9.1 KiB
Python
210 lines
9.1 KiB
Python
"""Model providers behind one interface.
|
|
|
|
reply = provider.complete(system, messages, tools)
|
|
|
|
`messages` and the reply use one neutral shape:
|
|
{"role": "user"|"assistant", "content": [block, ...]}
|
|
block: {"type": "text", "text": ...}
|
|
| {"type": "tool_call", "id": ..., "name": ..., "input": {...}}
|
|
| {"type": "tool_result", "id": ..., "output": ..., "is_error": bool}
|
|
The reply adds "usage": {"input": n, "output": n, "cached_input": n} and
|
|
"stop": "tool_use"|"end"|"max_tokens".
|
|
|
|
anthropic Anthropic Messages API (ANTHROPIC_API_KEY)
|
|
openai OpenAI-compatible chat completions (OPENAI_API_KEY, base URL);
|
|
also local servers (vLLM, llama.cpp, Ollama) via --base-url
|
|
scripted replays a JSON list of assistant turns (harness tests)
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
|
|
class ProviderError(Exception):
|
|
pass
|
|
|
|
|
|
def _post(url, headers, body, timeout, retries=4):
|
|
data = json.dumps(body).encode()
|
|
for attempt in range(retries + 1):
|
|
req = urllib.request.Request(url, data=data, headers={"content-type": "application/json", **headers})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return json.loads(r.read())
|
|
except urllib.error.HTTPError as e:
|
|
detail = e.read().decode(errors="replace")[:500]
|
|
if e.code in (429, 500, 502, 503, 529) and attempt < retries:
|
|
time.sleep(2 ** attempt * 5)
|
|
continue
|
|
raise ProviderError(f"HTTP {e.code}: {detail}")
|
|
except (urllib.error.URLError, TimeoutError) as e:
|
|
if attempt < retries:
|
|
time.sleep(2 ** attempt * 5)
|
|
continue
|
|
raise ProviderError(str(e))
|
|
|
|
|
|
class Anthropic:
|
|
name = "anthropic"
|
|
|
|
def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=600):
|
|
self.model, self.max_tokens, self.temperature, self.timeout = model, max_tokens, temperature, timeout
|
|
self.url = (base_url or "https://api.anthropic.com") + "/v1/messages"
|
|
self.key = os.environ.get("ANTHROPIC_API_KEY")
|
|
if not self.key:
|
|
raise SystemExit("ANTHROPIC_API_KEY is not set")
|
|
|
|
def params(self):
|
|
return {"max_tokens": self.max_tokens, "temperature": self.temperature}
|
|
|
|
def complete(self, system, messages, tools):
|
|
msgs = []
|
|
for m in messages:
|
|
blocks = []
|
|
for b in m["content"]:
|
|
if b["type"] == "text":
|
|
blocks.append({"type": "text", "text": b["text"]})
|
|
elif b["type"] == "tool_call":
|
|
blocks.append({"type": "tool_use", "id": b["id"], "name": b["name"], "input": b["input"]})
|
|
elif b["type"] == "tool_result":
|
|
blocks.append({"type": "tool_result", "tool_use_id": b["id"], "content": b["output"], "is_error": b["is_error"]})
|
|
msgs.append({"role": m["role"], "content": blocks})
|
|
body = {
|
|
"model": self.model,
|
|
"max_tokens": self.max_tokens,
|
|
"system": [{"type": "text", "text": system, "cache_control": {"type": "ephemeral"}}],
|
|
"messages": msgs,
|
|
"tools": [{"name": t["name"], "description": t["description"], "input_schema": t["parameters"]} for t in tools],
|
|
}
|
|
if self.temperature is not None:
|
|
body["temperature"] = self.temperature
|
|
r = _post(self.url, {"x-api-key": self.key, "anthropic-version": "2023-06-01"}, body, self.timeout)
|
|
content = []
|
|
for b in r.get("content", []):
|
|
if b["type"] == "text":
|
|
content.append({"type": "text", "text": b["text"]})
|
|
elif b["type"] == "tool_use":
|
|
content.append({"type": "tool_call", "id": b["id"], "name": b["name"], "input": b["input"]})
|
|
u = r.get("usage", {})
|
|
stop = {"tool_use": "tool_use", "max_tokens": "max_tokens"}.get(r.get("stop_reason"), "end")
|
|
return {
|
|
"role": "assistant",
|
|
"content": content,
|
|
"stop": stop,
|
|
"model": r.get("model", self.model),
|
|
"usage": {
|
|
"input": u.get("input_tokens", 0) + u.get("cache_read_input_tokens", 0) + u.get("cache_creation_input_tokens", 0),
|
|
"output": u.get("output_tokens", 0),
|
|
"cached_input": u.get("cache_read_input_tokens", 0),
|
|
},
|
|
}
|
|
|
|
|
|
class OpenAICompatible:
|
|
name = "openai"
|
|
|
|
def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=600):
|
|
self.model, self.max_tokens, self.temperature, self.timeout = model, max_tokens, temperature, timeout
|
|
self.url = (base_url or "https://api.openai.com/v1").rstrip("/") + "/chat/completions"
|
|
self.key = os.environ.get("OPENAI_API_KEY", "")
|
|
|
|
def params(self):
|
|
return {"max_tokens": self.max_tokens, "temperature": self.temperature}
|
|
|
|
def complete(self, system, messages, tools):
|
|
msgs = [{"role": "system", "content": system}]
|
|
for m in messages:
|
|
texts = [b["text"] for b in m["content"] if b["type"] == "text"]
|
|
calls = [b for b in m["content"] if b["type"] == "tool_call"]
|
|
results = [b for b in m["content"] if b["type"] == "tool_result"]
|
|
if m["role"] == "assistant":
|
|
msg = {"role": "assistant", "content": "\n".join(texts) or None}
|
|
if calls:
|
|
msg["tool_calls"] = [{"id": c["id"], "type": "function", "function": {"name": c["name"], "arguments": json.dumps(c["input"])}} for c in calls]
|
|
msgs.append(msg)
|
|
else:
|
|
for r in results:
|
|
msgs.append({"role": "tool", "tool_call_id": r["id"], "content": r["output"]})
|
|
if texts:
|
|
msgs.append({"role": "user", "content": "\n".join(texts)})
|
|
body = {
|
|
"model": self.model,
|
|
"max_tokens": self.max_tokens,
|
|
"messages": msgs,
|
|
"tools": [{"type": "function", "function": {"name": t["name"], "description": t["description"], "parameters": t["parameters"]}} for t in tools],
|
|
}
|
|
if self.temperature is not None:
|
|
body["temperature"] = self.temperature
|
|
headers = {"authorization": f"Bearer {self.key}"} if self.key else {}
|
|
r = _post(self.url, headers, body, self.timeout)
|
|
choice = r["choices"][0]
|
|
msg = choice["message"]
|
|
content = []
|
|
if msg.get("content"):
|
|
content.append({"type": "text", "text": msg["content"]})
|
|
for c in msg.get("tool_calls") or []:
|
|
try:
|
|
args = json.loads(c["function"]["arguments"] or "{}")
|
|
except json.JSONDecodeError:
|
|
args = {"_unparsable_arguments": c["function"]["arguments"]}
|
|
content.append({"type": "tool_call", "id": c["id"], "name": c["function"]["name"], "input": args})
|
|
u = r.get("usage") or {}
|
|
details = u.get("prompt_tokens_details") or {}
|
|
stop = "tool_use" if msg.get("tool_calls") else ("max_tokens" if choice.get("finish_reason") == "length" else "end")
|
|
return {
|
|
"role": "assistant",
|
|
"content": content,
|
|
"stop": stop,
|
|
"model": r.get("model", self.model),
|
|
"usage": {"input": u.get("prompt_tokens", 0), "output": u.get("completion_tokens", 0), "cached_input": details.get("cached_tokens", 0)},
|
|
}
|
|
|
|
|
|
class Scripted:
|
|
"""Replays assistant turns from a JSON file: a list of lists of blocks
|
|
(`{"text": ...}` or `{"tool": name, "input": {...}}`). Usage is counted
|
|
as characters / 4 so accounting paths are exercised."""
|
|
|
|
name = "scripted"
|
|
|
|
def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=0):
|
|
self.model = model
|
|
with open(model) as f:
|
|
self.turns = json.load(f)
|
|
self.i = 0
|
|
|
|
def params(self):
|
|
return {}
|
|
|
|
def complete(self, system, messages, tools):
|
|
if self.i >= len(self.turns):
|
|
return {"role": "assistant", "content": [{"type": "text", "text": "done"}], "stop": "end", "model": "scripted", "usage": {"input": 0, "output": 0, "cached_input": 0}}
|
|
turn = self.turns[self.i]
|
|
self.i += 1
|
|
content = []
|
|
for n, b in enumerate(turn):
|
|
if "tool" in b:
|
|
content.append({"type": "tool_call", "id": f"call_{self.i}_{n}", "name": b["tool"], "input": b["input"]})
|
|
else:
|
|
content.append({"type": "text", "text": b["text"]})
|
|
prompt_chars = len(system) + len(json.dumps(messages))
|
|
return {
|
|
"role": "assistant",
|
|
"content": content,
|
|
"stop": "tool_use" if any(b["type"] == "tool_call" for b in content) else "end",
|
|
"model": "scripted",
|
|
"usage": {"input": prompt_chars // 4, "output": len(json.dumps(turn)) // 4, "cached_input": 0},
|
|
}
|
|
|
|
|
|
PROVIDERS = {"anthropic": Anthropic, "openai": OpenAICompatible, "scripted": Scripted}
|
|
|
|
|
|
def make(name, model, **kw):
|
|
if name not in PROVIDERS:
|
|
raise SystemExit(f"unknown provider {name!r}; available: {', '.join(PROVIDERS)}")
|
|
return PROVIDERS[name](model, **kw)
|