Files
chemenu-ng/tests/adapters/test_llm_factory.py
T
torbenandClaude Sonnet 5.5 88b8361ef3 Add build_llm factory for the LLM port
Builds providers and router from configuration; the caller passes env,
a missing key fails only on call.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-04 06:56:48 +01:00

79 lines
2.5 KiB
Python

import json
from pathlib import Path
import pytest
from pydantic import BaseModel
from chemenu.adapters.llm.config import LlmConfig
from chemenu.adapters.llm.factory import build_llm
from chemenu.adapters.llm.recorded import request_key
from chemenu.domain.step_profile import StepProfile
from chemenu.ports.llm import LlmRequest, MissingApiKeyError, ModelMismatchError
class _Out(BaseModel):
x: int
def _config(directory: Path) -> LlmConfig:
raw = {
"providers": {
"anthropic": {"kind": "anthropic", "api_key_env": "TEST_KEY"},
"replay": {"kind": "recorded", "directory": str(directory)},
},
"profiles": {
"analyse": {
"provider": "replay",
"model": "claude-x",
"effort": "high",
"max_tokens": 1000,
"timeout_seconds": 60,
},
"classify": {
"provider": "anthropic",
"model": "claude-y",
"effort": "low",
"max_tokens": 1000,
"timeout_seconds": 60,
},
},
}
return LlmConfig.model_validate(raw)
def _request(profile: StepProfile) -> LlmRequest:
return LlmRequest(step="s", profile=profile, prompt="p", output_model=_Out)
def _record(directory: Path, request: LlmRequest, model: str) -> None:
folder = directory / request.step
folder.mkdir()
key = request_key(request)
(folder / f"{key}.json").write_text('{"x": 1}')
meta = {"model": model, "usage": {"input_tokens": 1, "output_tokens": 2}}
(folder / f"{key}.meta.json").write_text(json.dumps(meta))
def test_build_llm(tmp_path: Path) -> None:
request = _request(StepProfile.ANALYSE)
_record(tmp_path, request, "claude-x")
# the Anthropic provider is built with a key, without any network call
port = build_llm(_config(tmp_path), {"TEST_KEY": "k"})
assert port.complete(request).text == '{"x": 1}'
def test_missing_env_fails_on_call(tmp_path: Path) -> None:
port = build_llm(_config(tmp_path), {})
with pytest.raises(MissingApiKeyError):
port.complete(_request(StepProfile.CLASSIFY))
def test_recording_from_other_model_raises(tmp_path: Path) -> None:
request = _request(StepProfile.ANALYSE)
_record(tmp_path, request, "claude-old")
port = build_llm(_config(tmp_path), {})
with pytest.raises(ModelMismatchError, match=r"claude-x.*claude-old") as info:
port.complete(request)
assert info.value.usage is not None
assert info.value.usage.output_tokens == 2