Add recorded LLM provider replaying answers from files

Key is a hash of step, prompt and output schema, so recordings
survive profile changes. Broken recordings raise MissingRecordingError
with the path of the affected file.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
torbenandClaude Sonnet 5.5 committed 2026-12-04 22:06:58 +01:00
1 parent 65f0714a3b
commit 276756e4af
2 files changed
+210

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
"""Replay of recorded answers from files, without network."""
import hashlib
import json
from pathlib import Path
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from chemenu.adapters.llm.config import ModelTarget
from chemenu.ports.llm import LlmRequest, LlmResponse, MissingRecordingError, Usage
_STRICT = ConfigDict(strict=True, extra="forbid", frozen=True)
class _UsageMeta(BaseModel):
model_config = _STRICT
input_tokens: int = Field(ge=0)
output_tokens: int = Field(ge=0)
cache_read_tokens: int = Field(default=0, ge=0)
cache_write_tokens: int = Field(default=0, ge=0)
class _Meta(BaseModel):
model_config = _STRICT
model: str
usage: _UsageMeta
def request_key(request: LlmRequest) -> str:
"""Key of a recording; depends on step, prompt and output schema, not on the profile."""
canonical = json.dumps(
{
"step": request.step,
"prompt": request.prompt,
"schema": request.output_model.model_json_schema(),
},
sort_keys=True,
separators=(",", ":"),
)
return hashlib.sha256(canonical.encode("ascii")).hexdigest()[:16]
def _read_text(path: Path) -> str:
try:
# Bytes, not read_text: line endings must stay as recorded.
return path.read_bytes().decode("utf-8")
except OSError as error:
raise MissingRecordingError(f"recording not readable: {path}") from error
except UnicodeDecodeError as error:
raise MissingRecordingError(f"recording is not UTF-8: {path}") from error
class RecordedProvider:
"""Implements `Provider`; reads `<directory>/<step>/<key>.json` and `<key>.meta.json`."""
def __init__(self, directory: Path) -> None:
self._directory = directory
def complete(self, request: LlmRequest, target: ModelTarget) -> LlmResponse:
base = self._directory / request.step
key = request_key(request)
raw_path = base / f"{key}.json"
meta_path = base / f"{key}.meta.json"
text = _read_text(raw_path)
meta_text = _read_text(meta_path)
try:
meta = _Meta.model_validate_json(meta_text)
except ValidationError as error:
raise MissingRecordingError(f"invalid recording metadata: {meta_path}") from error
return LlmResponse(
text=text,
model=meta.model,
usage=Usage(
input_tokens=meta.usage.input_tokens,
output_tokens=meta.usage.output_tokens,
cache_read_tokens=meta.usage.cache_read_tokens,
cache_write_tokens=meta.usage.cache_write_tokens,
),
)