LLM-Port mit Schritt-Profilen #47

Merged
torben merged 10 commits from 17-llm-port into main 2026-12-04 21:54:44 +00:00
2 changed files with 210 additions and 0 deletions
Showing only changes of commit 276756e4af - Show all commits

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,
),
)
+129
View File
@@ -0,0 +1,129 @@
import json
from pathlib import Path
import pytest
from pydantic import BaseModel
from chemenu.adapters.llm.config import ModelTarget
from chemenu.adapters.llm.recorded import RecordedProvider, request_key
from chemenu.domain.step_profile import StepProfile
from chemenu.ports.llm import LlmRequest, MissingRecordingError, Usage
_TARGET = ModelTarget(
provider="r", model="claude-x", effort="high", max_tokens=1000, timeout_seconds=60
)
_META = '{"model": "m", "usage": {"input_tokens": 1, "output_tokens": 1}}'
class _Out(BaseModel):
x: int
class _Other(BaseModel):
y: str
def _request(
step: str = "s",
prompt: str = "SECRET",
output_model: type[BaseModel] = _Out,
profile: StepProfile = StepProfile.ANALYSE,
) -> LlmRequest:
return LlmRequest(step=step, profile=profile, prompt=prompt, output_model=output_model)
def _write(directory: Path, request: LlmRequest, raw: bytes, meta: str | None) -> tuple[Path, Path]:
key = request_key(request)
folder = directory / request.step
folder.mkdir(parents=True, exist_ok=True)
raw_path = folder / f"{key}.json"
meta_path = folder / f"{key}.meta.json"
raw_path.write_bytes(raw)
if meta is not None:
meta_path.write_bytes(meta.encode())
return raw_path, meta_path
def test_returns_raw_text_model_and_usage(tmp_path: Path) -> None:
request = _request(prompt="Größe\r\nZeile")
text = '{ "x":1 }\r\nÄöü\n'
meta = {"model": "claude-x", "usage": {"input_tokens": 3, "output_tokens": 5}}
_write(tmp_path, request, text.encode(), json.dumps(meta))
response = RecordedProvider(tmp_path).complete(request, _TARGET)
assert response.text == text
assert response.model == "claude-x"
assert response.usage == Usage(3, 5, 0, 0)
def test_cache_fields_are_read(tmp_path: Path) -> None:
request = _request()
usage = {
"input_tokens": 1,
"output_tokens": 2,
"cache_read_tokens": 3,
"cache_write_tokens": 4,
}
_write(tmp_path, request, b"raw", json.dumps({"model": "m", "usage": usage}))
response = RecordedProvider(tmp_path).complete(request, _TARGET)
assert response.usage == Usage(1, 2, 3, 4)
def test_missing_recording_names_path(tmp_path: Path) -> None:
request = _request()
provider = RecordedProvider(tmp_path)
raw_path, meta_path = _write(tmp_path, request, b"raw", None)
with pytest.raises(MissingRecordingError) as meta_info:
provider.complete(request, _TARGET)
assert str(meta_path) in str(meta_info.value)
assert "SECRET" not in str(meta_info.value)
raw_path.unlink()
meta_path.write_text(_META)
with pytest.raises(MissingRecordingError) as raw_info:
provider.complete(request, _TARGET)
assert str(raw_path) in str(raw_info.value)
def test_non_utf8_recording_raises(tmp_path: Path) -> None:
request = _request()
raw_path, _ = _write(tmp_path, request, b"\xff\xfe", _META)
with pytest.raises(MissingRecordingError) as info:
RecordedProvider(tmp_path).complete(request, _TARGET)
assert str(raw_path) in str(info.value)
def test_key_changes_with_prompt_and_schema() -> None:
base = request_key(_request())
assert request_key(_request(prompt="other")) != base
assert request_key(_request(output_model=_Other)) != base
assert request_key(_request(step="t")) != base
def test_key_ignores_profile() -> None:
assert request_key(_request(profile=StepProfile.ANALYSE)) == request_key(
_request(profile=StepProfile.WRITE)
)
def test_key_is_stable() -> None:
assert request_key(_request()) == "f27cdc9af61eba8c"
@pytest.mark.parametrize(
"meta",
[
"not json",
"{}",
'{"model": "m"}',
'{"model": "m", "usage": {"input_tokens": -1, "output_tokens": 1}}',
'{"model": "m", "usage": {"input_tokens": 1, "output_tokens": 1, "cache_read_tokens": -1}}',
'{"model": "m", "usage": {"input_tokens": "3", "output_tokens": 1}}',
'{"model": "m", "usage": {"input_tokens": 1, "output_tokens": 1}, "extra": 1}',
],
)
def test_invalid_meta_raises(tmp_path: Path, meta: str) -> None:
request = _request()
_, meta_path = _write(tmp_path, request, b"raw", meta)
with pytest.raises(MissingRecordingError) as info:
RecordedProvider(tmp_path).complete(request, _TARGET)
assert str(meta_path) in str(info.value)