TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
16.9 kB
"""Step 5a: one LLM call whose reply is a validated Pydantic object, cached on disk.
llm = LLM.load()
answer, usage = llm.generate(prompt, Answer, check=answer_rules)
Owner decisions (5a):
- Claude Haiku via the anthropic SDK (a fast, modest model, so the retrieval design
shows; the benchmark that chose it is in config.py). The model name is pinned in .env.
- Every reply is validated with Pydantic (plus an optional `check` for rules a schema
can't express). An invalid reply is re-asked ONCE, with the reply and the error put
back into the conversation ("reask").
- Transient API errors (429, 5xx, connection) are retried with exponential backoff,
counted apart from reasks. Anything else fails at once.
- Only validated replies are cached (.cache/llm, one JSON file per request), so a rerun
costs nothing and returns the same text: Haiku 5.5 takes no temperature, so a fresh
call can word things differently, and the hand grades are keyed on the answer text.
- Calls run one at a time (latency_ms stays the latency of one question).
- A failure raises LLMError carrying the usage already spent (an error row must not
look free).
No eval or ingest import: Systems A, B, C and the deployed app all use this module.
"""
import hashlib
import json
import os
import time
import uuid
from collections.abc import Callable
from dataclasses import asdict, dataclass, fields
from pathlib import Path
from typing import Any
import anthropic
from pydantic import BaseModel, ValidationError
from coveragecheck import config
REASK = (
"Your reply was rejected: {error}\n"
"Reply again with only the corrected JSON object, following the original instructions."
)
@dataclass
class Usage:
"""What answering cost. calls = API replies received; reasks = calls made because a
reply was invalid; api_retries = transient errors retried; llm_ms = wall time of
the whole generate() (calls, backoff waits); cache_hits = 1 when the reply came from
the cache.
On a cache hit, tokens, calls, reasks and llm_ms are those of the ORIGINAL call (what
this answer cost to produce, and how long the model took), so a rerun reports the
same cost and an honest LLM time. api_retries is NOT replayed: nothing was retried
on the rerun, and a past 529 says nothing about the answer (5a audit).
replayed_ms = llm_ms of a cache hit, 0 for a live call: the time a run's clock did
NOT see. A field of its own so sums stay right (5b audit): one cached 2 s call plus
two live 5 s calls must replay 2 s, not the summed llm_ms of 7 s."""
tokens_in: int = 0
tokens_out: int = 0
calls: int = 0
reasks: int = 0
api_retries: int = 0
cache_hits: int = 0
llm_ms: float = 0.0
replayed_ms: float = 0.0
def __add__(self, other: "Usage") -> "Usage":
"""Field-wise sum, for a system that makes several calls per question (C)."""
return Usage(*(getattr(self, f.name) + getattr(other, f.name) for f in fields(self)))
# Why a call failed, so the eval can count each cause without parsing messages (5a audit):
# "api": an API error (non-transient, or transient beyond the retries);
# "refusal": the model declined; "stopped": it stopped for another reason a reask can't
# fix (e.g. model_context_window_exceeded); "truncated": the last reply hit max_tokens;
# "invalid": the last reply failed validation or check.
FAILURE_KINDS = ("api", "refusal", "stopped", "truncated", "invalid")
class LLMError(Exception):
"""The call failed. kind is one of FAILURE_KINDS; usage holds what was spent before
failing, so the eval row can still count it."""
def __init__(self, message: str, usage: Usage, kind: str):
if kind not in FAILURE_KINDS:
raise ValueError(f"unknown failure kind {kind!r}")
super().__init__(message)
self.usage, self.kind = usage, kind
def api_schema(model: type[BaseModel], drop: frozenset[str] = config.LLM_UNSUPPORTED_SCHEMA_KEYS):
"""The model's JSON schema as sent to the API:
- without the keywords the API rejects (measured: minimum / maximum on numbers);
Pydantic still enforces them on the reply. Names under "properties" are field
names, not keywords, so a field called "minimum" is kept.
- with EVERY property required, defaults included. Measured (5b, 63 questions):
Answer.citations has a default, so it wasn't required, and constrained decoding
let Haiku leave the key out: 9 answers had no citations even after the reask.
Required, the model must write the field (an empty list is still allowed)."""
def clean(node: Any, field_names: bool = False) -> Any:
if isinstance(node, dict):
out = {
key: clean(value, field_names=key == "properties" and not field_names)
for key, value in node.items()
if field_names or key not in drop
}
if not field_names and isinstance(out.get("properties"), dict):
out["required"] = list(out["properties"])
return out
if isinstance(node, list):
return [clean(value) for value in node]
return node
return clean(model.model_json_schema())
def is_transient(error: Exception) -> bool:
"""Worth retrying. The same rules as the SDK's own retry (anthropic 2.12
_should_retry; we turn the SDK's retries off only to count them): the server's
x-should-retry header wins when present; otherwise no connection or a timeout,
408 request timeout, 409 lock timeout, 429 rate limit, or any 5xx (529 overloaded
included). Other 4xx mean the request itself is wrong, so a retry can't help."""
if isinstance(error, anthropic.APIConnectionError): # includes APITimeoutError
return True
if isinstance(error, anthropic.APIStatusError):
header = error.response.headers.get("x-should-retry")
if header in ("true", "false"):
return header == "true"
return error.status_code in (408, 409, 429) or error.status_code >= 500
return False
def backoff(attempt: int, base: float, cap: float, error: Exception | None = None) -> float:
"""Seconds to wait before retry number attempt+1: base, 2*base, 4*base ..., but at
least the server's retry-after (seconds) when it sends one; capped either way, so
one question can't stall a run for minutes."""
wait = base * 2**attempt
response = getattr(error, "response", None)
if response is not None:
try:
wait = max(wait, float(response.headers.get("retry-after", "")))
except ValueError:
pass # absent, or an HTTP date: keep the exponential wait
return min(cap, wait)
def request_key(request: dict) -> str:
"""The cache key: a hash of everything that shapes the reply (model, effort, token
limit, system prompt, prompt, schema). Sorted keys, so dict order can't change it."""
canonical = json.dumps(request, sort_keys=True, ensure_ascii=False)
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
def error_text(error: Exception) -> str:
"""A short, model-readable reason a reply was rejected: one line per Pydantic error
(field path + message, no docs URL), or the check's own message."""
if isinstance(error, ValidationError):
return "; ".join(
f"{'.'.join(map(str, e['loc'])) or 'reply'}: {e['msg']}" for e in error.errors()
)
return str(error)
def validate[T: BaseModel](text: str, schema: type[T], check: Callable[[T], None] | None) -> T:
"""Parse and validate a reply. check raises ValueError for rules the schema can't
express (e.g. 5b's "an answer must cite something"). ValidationError is itself a
ValueError, so callers catch one type."""
parsed = schema.model_validate_json(text)
if check is not None:
check(parsed)
return parsed
def reply_text(message: Any) -> str:
"""The text of a reply (structured output puts the JSON in text blocks)."""
return "".join(block.text for block in message.content if block.type == "text")
class DiskCache:
"""One JSON file per request key. A cache must never break a run: a missing or
unreadable file is a miss, and a failed write is skipped (the valid reply, already
paid for, is still returned). Writes go through a temp file and a rename, so an
interrupted write never leaves half a file behind."""
def __init__(self, directory: Path):
self.directory = directory
def get(self, key: str) -> dict | None:
try:
return json.loads((self.directory / f"{key}.json").read_text(encoding="utf-8"))
except (OSError, ValueError):
return None
def put(self, key: str, record: dict) -> bool:
"""Save the record; False if it couldn't be saved. The temp name is unique per
write: measured (5a audit), 4 processes writing one key through a shared
<key>.tmp raised 157-190 OSErrors each on Windows (a file in use can't be
replaced). A lost write only costs a later cache miss."""
tmp = self.directory / f"{key}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
try:
self.directory.mkdir(parents=True, exist_ok=True)
tmp.write_text(json.dumps(record, ensure_ascii=False, indent=1), encoding="utf-8")
tmp.replace(self.directory / f"{key}.json")
return True
except OSError:
tmp.unlink(missing_ok=True)
return False
class LLM:
"""A pinned model with its settings, a client and a cache. Build it once per process
(LLM.load()) and reuse it: the client keeps its connection open between calls."""
def __init__(
self,
client: Any,
model: str,
cache: DiskCache | None,
effort: str,
max_tokens: int,
max_reasks: int,
api_retries: int,
retry_base_s: float,
retry_max_s: float,
sleep: Callable[[float], None] = time.sleep,
clock: Callable[[], float] = time.perf_counter,
):
self.client, self.model, self.cache = client, model, cache
self.effort, self.max_tokens = effort, max_tokens
self.max_reasks, self.api_retries = max_reasks, api_retries
self.retry_base_s, self.retry_max_s = retry_base_s, retry_max_s
self.sleep, self.clock = sleep, clock
@classmethod
def load(cls) -> "LLM":
"""The real client with the config settings, passed explicitly (defaults bound at
import would ignore a patched config). The SDK's own retries are off
(max_retries=0): generate() retries itself, so it can count them."""
model = config.llm_model() # also loads ANTHROPIC_API_KEY from .env
client = anthropic.Anthropic(max_retries=0, timeout=config.LLM_TIMEOUT_S)
return cls(
client,
model,
DiskCache(config.LLM_CACHE_DIR),
effort=config.LLM_EFFORT,
max_tokens=config.LLM_MAX_TOKENS,
max_reasks=config.LLM_MAX_REASKS,
api_retries=config.LLM_API_RETRIES,
retry_base_s=config.LLM_RETRY_BASE_S,
retry_max_s=config.LLM_RETRY_MAX_S,
)
@property
def settings(self) -> dict:
"""What a run records about the LLM (it changes the answers or their latency)."""
return {
"llm_model": self.model,
"llm_effort": self.effort,
"llm_max_tokens": self.max_tokens,
"llm_max_reasks": self.max_reasks,
"llm_api_retries": self.api_retries,
"llm_cache": self.cache is not None,
"llm_concurrency": 1,
}
def request(self, prompt: str, schema: type[BaseModel], system: str | None) -> dict:
"""The API request for the first attempt; also what the cache key hashes."""
request = {
"model": self.model,
"max_tokens": self.max_tokens,
"messages": [{"role": "user", "content": prompt}],
"output_config": {
"effort": self.effort,
"format": {"type": "json_schema", "schema": api_schema(schema)},
},
}
if system is not None:
request["system"] = system
return request
def generate[T: BaseModel](
self,
prompt: str,
schema: type[T],
*,
system: str | None = None,
check: Callable[[T], None] | None = None,
) -> tuple[T, Usage]:
"""Ask once; return the validated reply and its usage. A cached reply is used
if it still passes validation and check (a check made stricter later turns an
old cached reply into a miss, and the new reply overwrites it). An invalid or
cut-off reply is re-asked up to max_reasks times with the reason; a refusal, any
other unexpected stop, or an API error fails at once. Raises LLMError (with
usage and kind) on failure; only a valid reply is cached."""
request = self.request(prompt, schema, system)
key = request_key(request)
cached = self.cache.get(key) if self.cache else None
if cached is not None:
try:
parsed = validate(cached["text"], schema, check)
original = cached["usage"]
replay = original | {
"api_retries": 0,
"cache_hits": 1,
"replayed_ms": original.get("llm_ms", 0.0),
}
return parsed, Usage(**replay)
except (ValueError, KeyError, TypeError, AttributeError):
pass # stale or damaged entry: call the model and overwrite it
usage, start = Usage(), self.clock()
try:
return self.ask(request, key, schema, check, usage, start)
except LLMError as failure: # a failure took time too
failure.usage.llm_ms = (self.clock() - start) * 1000
raise
def ask(self, request, key, schema, check, usage: Usage, start: float):
"""generate()'s uncached path: the call, the reask loop and the cache write."""
messages, error, kind = list(request["messages"]), "", "invalid"
for attempt in range(self.max_reasks + 1):
if attempt:
usage.reasks += 1
message = self.create(request | {"messages": messages}, usage)
usage.calls += 1
usage.tokens_in += message.usage.input_tokens
usage.tokens_out += message.usage.output_tokens # includes thinking tokens
stop = message.stop_reason
if stop == "refusal":
raise LLMError("the model refused to answer", usage, "refusal")
if stop not in ("end_turn", "stop_sequence", "max_tokens"):
# e.g. model_context_window_exceeded: the same prompt would stop again
raise LLMError(f"the model stopped early: {stop}", usage, "stopped")
text = reply_text(message)
if stop == "max_tokens":
error = f"the reply was cut off at {self.max_tokens} tokens; answer more briefly"
kind = "truncated"
else:
try:
parsed = validate(text, schema, check)
except ValueError as invalid:
error, kind = error_text(invalid), "invalid"
else:
usage.llm_ms = (self.clock() - start) * 1000 # set before the record
if self.cache:
record = {"model": message.model, "text": text, "usage": asdict(usage)}
self.cache.put(key, record)
return parsed, usage
messages = messages + [
{"role": "assistant", "content": text or "(empty reply)"},
{"role": "user", "content": REASK.format(error=error)},
]
raise LLMError(f"{kind} reply after {self.max_reasks} reask(s): {error}", usage, kind)
def create(self, params: dict, usage: Usage) -> Any:
"""One API request, retrying transient errors with backoff (counted in usage).
Any other API error, or a transient one that outlasts the retries, raises
LLMError(kind="api") with the usage so far."""
for attempt in range(self.api_retries + 1):
try:
return self.client.messages.create(**params)
except anthropic.APIError as error:
if not is_transient(error) or attempt == self.api_retries:
message = f"{type(error).__name__}: {error}"
raise LLMError(message, usage, "api") from error
usage.api_retries += 1
self.sleep(backoff(attempt, self.retry_base_s, self.retry_max_s, error))
raise AssertionError("unreachable") # the loop always returns or raises