File size: 5,125 Bytes
b4f2238 | 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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | """
LLM 后端基础定义
定义 LLM 后端的统一接口和数据类.
Requirements: 1.1, 1.5
"""
from collections.abc import AsyncIterator, Iterator
from dataclasses import dataclass, field
from typing import Any, Protocol, runtime_checkable
@dataclass
class LLMResponse:
"""
LLM 响应数据类
统一所有后端的响应格式,便于调用方处理.
Attributes:
content: 生成的文本内容
model: 使用的模型名称
prompt_tokens: 输入 token 数
completion_tokens: 输出 token 数
total_tokens: 总 token 数
duration_ms: 调用耗时(毫秒)
backend: 使用的后端标识 (siliconflow/ollama/openai_compatible)
Requirements: 1.1, 1.5
"""
content: str
model: str
prompt_tokens: int
completion_tokens: int
total_tokens: int
duration_ms: float
backend: str = ""
@dataclass
class LLMUsage:
prompt_tokens: int = 0
completion_tokens: int = 0
total_tokens: int = 0
@dataclass
class LLMStreamChunk:
content: str = ""
usage: LLMUsage | None = None
model: str = ""
backend: str = ""
@dataclass
class BackendConfig:
"""
后端配置数据类
定义 LLM 后端的配置参数.
Attributes:
name: 后端名称 (siliconflow/ollama/openai_compatible)
enabled: 是否启用
priority: 降级优先级,数字越小优先级越高
default_model: 默认模型名称
base_url: API 基础 URL
api_key: API 密钥
timeout: 请求超时时间(秒)
extra_options: 额外配置选项
"""
name: str
enabled: bool
priority: int
default_model: str
base_url: str | None = None
api_key: str | None = None
timeout: int = 60
embedding_model: str | None = None
extra_options: dict[str, Any] = field(default_factory=dict)
@runtime_checkable
class ILLMBackend(Protocol):
"""
LLM 后端接口协议
定义所有 LLM 后端必须实现的方法.使用 Protocol 实现结构化子类型,
无需显式继承即可满足接口约束.
Requirements: 1.1, 1.5
"""
def chat(
self,
messages: list[dict[str, str]],
model: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
**kwargs: Any,
) -> LLMResponse:
"""
同步聊天接口
Args:
messages: 消息列表,格式为 [{"role": "user", "content": "..."}]
model: 模型名称,None 时使用默认模型
temperature: 温度参数,控制输出随机性
max_tokens: 最大输出 token 数
**kwargs: 后端特定参数
Returns:
LLMResponse: 统一格式的响应对象
Raises:
LLMNetworkError: 网络连接失败
LLMAPIError: API 返回错误
LLMAuthenticationError: 认证失败
LLMTimeoutError: 请求超时
"""
...
async def achat(
self,
messages: list[dict[str, str]],
model: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
**kwargs: Any,
) -> LLMResponse:
"""
异步聊天接口
Args:
messages: 消息列表,格式为 [{"role": "user", "content": "..."}]
model: 模型名称,None 时使用默认模型
temperature: 温度参数,控制输出随机性
max_tokens: 最大输出 token 数
**kwargs: 后端特定参数
Returns:
LLMResponse: 统一格式的响应对象
Raises:
LLMNetworkError: 网络连接失败
LLMAPIError: API 返回错误
LLMAuthenticationError: 认证失败
LLMTimeoutError: 请求超时
"""
...
def stream(
self,
messages: list[dict[str, str]],
model: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
**kwargs: Any,
) -> Iterator[LLMStreamChunk]: ...
async def astream(
self,
messages: list[dict[str, str]],
model: str | None = None,
temperature: float = 0.7,
max_tokens: int | None = None,
**kwargs: Any,
) -> AsyncIterator[LLMStreamChunk]: ...
def get_default_model(self) -> str:
"""
获取默认模型名称
Returns:
str: 后端的默认模型名称
"""
...
def get_default_embedding_model(self) -> str:
"""获取默认向量模型名称。"""
...
def embed_texts(
self,
texts: list[str],
model: str | None = None,
**kwargs: Any,
) -> list[list[float]]:
"""向量化文本列表。"""
...
def is_available(self) -> bool:
"""
检查后端是否可用
检查后端的配置是否完整(如 API Key 是否存在),
以及服务是否可达.
Returns:
bool: True 表示后端可用,False 表示不可用
"""
...
|