LLM-Port mit Schritt-Profilen #47
No files matched your search
@@ -0,0 +1,11 @@
|
||||
"""Step profiles: which kind of model a step needs."""
|
||||
|
||||
from enum import StrEnum
|
||||
|
||||
|
||||
class StepProfile(StrEnum):
|
||||
"""Named by task; a new profile is a new member."""
|
||||
|
||||
ANALYSE = "analyse"
|
||||
WRITE = "write"
|
||||
CLASSIFY = "classify"
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Port for LLM calls."""
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Protocol
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
from chemenu.domain.step_profile import StepProfile
|
||||
|
||||
_STEP_NAME = re.compile(r"[a-z0-9-]+")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LlmRequest:
|
||||
"""One call; `step` names the step and later becomes part of a file path."""
|
||||
|
||||
step: str # e.g. "note-inventory"; [a-z0-9-]+, else ValueError
|
||||
profile: StepProfile
|
||||
prompt: str
|
||||
output_model: type[BaseModel]
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if _STEP_NAME.fullmatch(self.step) is None:
|
||||
raise ValueError(f"invalid step name: {self.step!r}")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Usage:
|
||||
"""Token consumption of one call."""
|
||||
|
||||
input_tokens: int
|
||||
output_tokens: int
|
||||
cache_read_tokens: int = 0
|
||||
cache_write_tokens: int = 0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LlmResponse:
|
||||
"""Answer of a call."""
|
||||
|
||||
text: str # raw, not parsed
|
||||
model: str # as reported by the provider
|
||||
usage: Usage
|
||||
|
||||
|
||||
class LlmPort(Protocol):
|
||||
"""Calls a model; implementations are called from several threads."""
|
||||
|
||||
def complete(self, request: LlmRequest) -> LlmResponse: ...
|
||||
|
||||
|
||||
class LlmError(Exception):
|
||||
"""Base of all LLM errors; carries the usage, as far as known."""
|
||||
|
||||
usage: Usage | None
|
||||
|
||||
def __init__(self, message: str, usage: Usage | None = None) -> None:
|
||||
super().__init__(message)
|
||||
self.usage = usage
|
||||
|
||||
|
||||
class ProfileNotConfiguredError(LlmError):
|
||||
"""The requested profile has no model configured."""
|
||||
|
||||
|
||||
class MissingApiKeyError(LlmError):
|
||||
"""The API key for the provider is not available."""
|
||||
|
||||
|
||||
class MissingRecordingError(LlmError):
|
||||
"""Replay mode found no recorded answer for the request."""
|
||||
|
||||
|
||||
class RefusedError(LlmError):
|
||||
"""The model refused to answer."""
|
||||
|
||||
|
||||
class TruncatedError(LlmError):
|
||||
"""The answer was cut off, for example at the token limit."""
|
||||
|
||||
|
||||
class ModelMismatchError(LlmError):
|
||||
"""The provider answered with a different model than configured."""
|
||||
|
||||
|
||||
class LlmTimeoutError(LlmError):
|
||||
"""The call exceeded its time limit."""
|
||||
|
||||
|
||||
class ProviderError(LlmError):
|
||||
"""The provider failed in any other way."""
|
||||
@@ -0,0 +1,10 @@
|
||||
from chemenu.domain.step_profile import StepProfile
|
||||
|
||||
|
||||
def test_profile_values() -> None:
|
||||
assert {p.name: p.value for p in StepProfile} == {
|
||||
"ANALYSE": "analyse",
|
||||
"WRITE": "write",
|
||||
"CLASSIFY": "classify",
|
||||
}
|
||||
assert StepProfile("write") is StepProfile.WRITE
|
||||
@@ -0,0 +1,53 @@
|
||||
import pytest
|
||||
from pydantic import BaseModel
|
||||
|
||||
from chemenu.domain.step_profile import StepProfile
|
||||
from chemenu.ports import llm
|
||||
from chemenu.ports.llm import LlmError, LlmRequest, Usage
|
||||
|
||||
|
||||
class _Out(BaseModel):
|
||||
x: int
|
||||
|
||||
|
||||
def _request(step: str) -> LlmRequest:
|
||||
return LlmRequest(step=step, profile=StepProfile.ANALYSE, prompt="p", output_model=_Out)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("step", ["", "Note", "note_inventory", "../x", "a/b", "note-inventory\n"])
|
||||
def test_invalid_step_name_is_rejected(step: str) -> None:
|
||||
with pytest.raises(ValueError, match="invalid step name"):
|
||||
_request(step)
|
||||
|
||||
|
||||
def test_valid_step_name_is_accepted() -> None:
|
||||
assert _request("note-inventory2").step == "note-inventory2"
|
||||
|
||||
|
||||
def test_error_carries_usage() -> None:
|
||||
usage = Usage(input_tokens=3, output_tokens=4)
|
||||
error = llm.TruncatedError("cut off", usage)
|
||||
assert error.usage == usage
|
||||
assert str(error) == "cut off"
|
||||
assert LlmError("plain").usage is None
|
||||
assert usage.cache_read_tokens == 0
|
||||
assert usage.cache_write_tokens == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"name",
|
||||
[
|
||||
"ProfileNotConfiguredError",
|
||||
"MissingApiKeyError",
|
||||
"MissingRecordingError",
|
||||
"RefusedError",
|
||||
"TruncatedError",
|
||||
"ModelMismatchError",
|
||||
"LlmTimeoutError",
|
||||
"ProviderError",
|
||||
],
|
||||
)
|
||||
def test_all_errors_are_llm_errors(name: str) -> None:
|
||||
cls = getattr(llm, name)
|
||||
assert issubclass(cls, LlmError)
|
||||
assert str(cls("msg")) == "msg"
|
||||
Reference in new issue
Block a user