-
Notifications
You must be signed in to change notification settings - Fork 324
Expand file tree
/
Copy pathbase.py
More file actions
57 lines (45 loc) · 1.62 KB
/
Copy pathbase.py
File metadata and controls
57 lines (45 loc) · 1.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""Abstract LLM backend interface."""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class LLMResult:
"""Return type for :meth:`LLMBackend.generate` / :meth:`generate_with_usage`.
``input_tokens`` / ``output_tokens`` / ``total_tokens`` are ``0`` when the
backend can't report usage (e.g. mocks in unit tests). ``total_tokens``
should reflect the provider total when available; otherwise callers may use
``input_tokens + output_tokens``.
"""
text: str
input_tokens: int = 0
output_tokens: int = 0
total_tokens: int = 0
class LLMBackend(ABC):
"""Abstract interface for LLM backends."""
@abstractmethod
def generate(
self,
prompt: str,
temperature: float = 0.0,
max_tokens: int | None = None,
) -> LLMResult:
"""Generate text given a prompt; includes usage when the backend provides it."""
...
def generate_with_usage(
self,
prompt: str,
temperature: float = 0.0,
max_tokens: int | None = None,
) -> LLMResult:
"""Generate text and report token usage.
Default impl delegates to :meth:`generate` (same fields as usage-aware
backends).
"""
return self.generate(prompt, temperature, max_tokens)
@property
def model_id(self) -> str:
"""Return the backend's model identifier, or ``"unknown"``.
Default impl reads ``self._model_id`` if present so existing
subclasses work without modification.
"""
return getattr(self, "_model_id", "unknown")