"""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 read_secret(env_name, file_path): """The API key from a file (first line) or an environment variable. The key itself is never recorded; only where it came from.""" if file_path: with open(os.path.expanduser(file_path)) as f: return f.readline().strip() return os.environ.get(env_name, "") 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, extra=None, key_env=None, key_file=None, **_): self.model, self.max_tokens, self.temperature, self.timeout = model, max_tokens, temperature, timeout self.extra = dict(extra or {}) self.url = (base_url or "https://api.anthropic.com") + "/v1/messages" self.key_source = key_file or key_env or "ANTHROPIC_API_KEY" self.secret = read_secret(key_env or "ANTHROPIC_API_KEY", key_file) if not self.secret: raise SystemExit(f"no API key ({self.key_source})") def params(self): return {"max_tokens": self.max_tokens, "temperature": self.temperature, "extra": self.extra, "key_source": self.key_source} 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 body.update(self.extra) r = _post(self.url, {"x-api-key": self.secret, "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: """`extra` is merged into every request body (for example {"reasoning_effort": "medium"}) and recorded. OpenAI's own endpoint takes `max_completion_tokens`; other servers take `max_tokens` unless `token_param` says otherwise. The API key is read from the environment variable named by `key_env` (default OPENAI_API_KEY).""" name = "openai" def __init__(self, model, max_tokens=8192, temperature=None, base_url=None, timeout=600, extra=None, key_env=None, key_file=None, token_param=None, **_): self.model, self.max_tokens, self.temperature, self.timeout = model, max_tokens, temperature, timeout self.base = (base_url or "https://api.openai.com/v1").rstrip("/") self.url = self.base + "/chat/completions" self.key_env = key_env or "OPENAI_API_KEY" self.secret = read_secret(self.key_env, key_file) self.key_source = key_file or self.key_env self.extra = dict(extra or {}) self.token_param = token_param or ("max_completion_tokens" if "api.openai.com" in self.base else "max_tokens") def params(self): return {"max_tokens": self.max_tokens, "token_param": self.token_param, "temperature": self.temperature, "extra": self.extra, "key_source": self.key_source} 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, self.token_param: 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 body.update(self.extra) headers = {"authorization": "Bearer " + self.secret} if self.secret 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)