273 lines
10 KiB
Python
273 lines
10 KiB
Python
"""
|
|||
|
|
模型配置存储层
|
||
|
|
==============
|
||
|
|
|
||
|
|
【功能说明】模型偏好配置的持久化(SQLite),支持增删改查。
|
||
|
|
【技术选型理由】与 ProjectStore/TaskStore 同库同哲学(决策点 5 接口抽象 + SQLite)。
|
||
|
|
【安全设计】API key 不入库,只存 provider_key 引用。
|
||
|
|
【实现思路】ModelConfigStore 抽象 + SqliteModelConfigStore 实现,含默认数据初始化。
|
||
|
|
"""
|
||
|
|
|
||
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import sqlite3
|
||
|
|
import uuid
|
||
|
|
from abc import ABC, abstractmethod
|
||
|
|
from datetime import datetime
|
||
|
|
from pathlib import Path
|
||
|
|
from typing import Optional
|
||
|
|
|
||
|
|
from app.schemas.model_config import ModelConfig, ModelConfigCreate, ModelConfigUpdate
|
||
|
|
from app.store.sqlite_util import open_connection
|
||
|
|
|
||
|
|
# 默认模型配置(首次启动自动初始化,用户可增删改)
|
||
|
|
DEFAULT_MODELS = [
|
||
|
|
{
|
||
|
|
"display_name": "GLM-5.3 — 强模型(代码/推理)",
|
||
|
|
"model_id": "glm-5.3",
|
||
|
|
"provider_key": "ccswitch",
|
||
|
|
"model_role": "strong",
|
||
|
|
"is_enabled": True,
|
||
|
|
"sort_order": 10,
|
||
|
|
"description": "via ccswitch,代码与推理能力强",
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"display_name": "GLM-5.3-Flash — 轻量快速",
|
||
|
|
"model_id": "glm-5.3-flash",
|
||
|
|
"provider_key": "ccswitch",
|
||
|
|
"model_role": "weak",
|
||
|
|
"is_enabled": True,
|
||
|
|
"sort_order": 20,
|
||
|
|
"description": "via ccswitch,速度快、成本低",
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"display_name": "Mimo-v2.6-Pro — 小米强模型",
|
||
|
|
"model_id": "mimo-v2.6-pro",
|
||
|
|
"provider_key": "ccswitch",
|
||
|
|
"model_role": "strong",
|
||
|
|
"is_enabled": True,
|
||
|
|
"sort_order": 30,
|
||
|
|
"description": "via ccswitch",
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"display_name": "DeepSeek-v4-Pro",
|
||
|
|
"model_id": "deepseek-v4-pro",
|
||
|
|
"provider_key": "ccswitch",
|
||
|
|
"model_role": "strong",
|
||
|
|
"is_enabled": True,
|
||
|
|
"sort_order": 40,
|
||
|
|
"description": "via ccswitch",
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"display_name": "MiniMax-Latest",
|
||
|
|
"model_id": "minimax-latest",
|
||
|
|
"provider_key": "ccswitch",
|
||
|
|
"model_role": "general",
|
||
|
|
"is_enabled": True,
|
||
|
|
"sort_order": 50,
|
||
|
|
"description": "via ccswitch",
|
||
|
|
},
|
||
|
|
]
|
||
|
|
|
||
|
|
|
||
|
|
class ModelConfigStore(ABC):
|
||
|
|
"""模型配置存储抽象接口"""
|
||
|
|
|
||
|
|
@abstractmethod
|
||
|
|
def create(self, payload: ModelConfigCreate) -> ModelConfig: ...
|
||
|
|
|
||
|
|
@abstractmethod
|
||
|
|
def get(self, config_id: str) -> Optional[ModelConfig]: ...
|
||
|
|
|
||
|
|
@abstractmethod
|
||
|
|
def list_all(self, only_enabled: bool = False) -> list[ModelConfig]: ...
|
||
|
|
|
||
|
|
@abstractmethod
|
||
|
|
def update(
|
||
|
|
self, config_id: str, payload: ModelConfigUpdate
|
||
|
|
) -> Optional[ModelConfig]: ...
|
||
|
|
|
||
|
|
@abstractmethod
|
||
|
|
def delete(self, config_id: str) -> bool: ...
|
||
|
|
|
||
|
|
|
||
|
|
class SqliteModelConfigStore(ModelConfigStore):
|
||
|
|
"""ModelConfigStore 的 SQLite 实现"""
|
||
|
|
|
||
|
|
def __init__(self, db_path: Path) -> None:
|
||
|
|
self._db_path = Path(db_path)
|
||
|
|
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||
|
|
self._init_schema()
|
||
|
|
self._seed_defaults()
|
||
|
|
|
||
|
|
def _connect(self):
|
||
|
|
"""
|
||
|
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
||
|
|
|
||
|
|
【修复】原先 `with sqlite3.connect(...)` 只提交不关闭,连接泄漏到 GC。
|
||
|
|
改为委托 app.store.sqlite_util.open_connection,语义不变、额外保证 close。
|
||
|
|
"""
|
||
|
|
return open_connection(self._db_path)
|
||
|
|
|
||
|
|
def _init_schema(self) -> None:
|
||
|
|
ddl = """
|
||
|
|
CREATE TABLE IF NOT EXISTS model_config (
|
||
|
|
id TEXT PRIMARY KEY,
|
||
|
|
display_name TEXT NOT NULL,
|
||
|
|
model_id TEXT NOT NULL,
|
||
|
|
provider_key TEXT NOT NULL DEFAULT 'ccswitch',
|
||
|
|
model_role TEXT NOT NULL DEFAULT 'general',
|
||
|
|
is_enabled INTEGER NOT NULL DEFAULT 1,
|
||
|
|
sort_order INTEGER NOT NULL DEFAULT 0,
|
||
|
|
fallback_order INTEGER NOT NULL DEFAULT 999,
|
||
|
|
description TEXT DEFAULT '',
|
||
|
|
created_at TEXT NOT NULL,
|
||
|
|
updated_at TEXT NOT NULL
|
||
|
|
);
|
||
|
|
"""
|
||
|
|
with self._connect() as conn:
|
||
|
|
conn.execute(ddl)
|
||
|
|
conn.commit()
|
||
|
|
# 兼容旧表:补 fallback_order 列(幂等)
|
||
|
|
try:
|
||
|
|
conn.execute(
|
||
|
|
"ALTER TABLE model_config ADD COLUMN fallback_order INTEGER NOT NULL DEFAULT 999"
|
||
|
|
)
|
||
|
|
conn.commit()
|
||
|
|
except Exception:
|
||
|
|
pass # 列已存在
|
||
|
|
# 数据迁移:fallback_order 全为 999 的旧数据按 sort_order 重排为 1,2,3...
|
||
|
|
try:
|
||
|
|
all_999 = conn.execute(
|
||
|
|
"SELECT COUNT(*) FROM model_config WHERE fallback_order != 999"
|
||
|
|
).fetchone()[0]
|
||
|
|
total = conn.execute("SELECT COUNT(*) FROM model_config").fetchone()[0]
|
||
|
|
if total > 0 and all_999 == 0:
|
||
|
|
rows = conn.execute(
|
||
|
|
"SELECT id FROM model_config ORDER BY sort_order ASC, created_at ASC"
|
||
|
|
).fetchall()
|
||
|
|
for i, row in enumerate(rows, start=1):
|
||
|
|
conn.execute(
|
||
|
|
"UPDATE model_config SET fallback_order = ? WHERE id = ?",
|
||
|
|
(i, row["id"]),
|
||
|
|
)
|
||
|
|
conn.commit()
|
||
|
|
except Exception:
|
||
|
|
pass
|
||
|
|
|
||
|
|
def _seed_defaults(self) -> None:
|
||
|
|
"""首次启动初始化默认模型配置(幂等:已有数据则跳过)。"""
|
||
|
|
with self._connect() as conn:
|
||
|
|
count = conn.execute("SELECT COUNT(*) FROM model_config").fetchone()[0]
|
||
|
|
if count > 0:
|
||
|
|
return
|
||
|
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
|
|
for idx, item in enumerate(DEFAULT_MODELS):
|
||
|
|
conn.execute(
|
||
|
|
"""INSERT INTO model_config
|
||
|
|
(id, display_name, model_id, provider_key, model_role,
|
||
|
|
is_enabled, sort_order, fallback_order, description, created_at, updated_at)
|
||
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||
|
|
(
|
||
|
|
f"model_{uuid.uuid4().hex[:12]}",
|
||
|
|
item["display_name"],
|
||
|
|
item["model_id"],
|
||
|
|
item["provider_key"],
|
||
|
|
item["model_role"],
|
||
|
|
1 if item["is_enabled"] else 0,
|
||
|
|
item["sort_order"],
|
||
|
|
idx + 1, # 默认降级链顺序按初始化顺序
|
||
|
|
item["description"],
|
||
|
|
now,
|
||
|
|
now,
|
||
|
|
),
|
||
|
|
)
|
||
|
|
conn.commit()
|
||
|
|
|
||
|
|
@staticmethod
|
||
|
|
def _row_to_entity(row: sqlite3.Row) -> ModelConfig:
|
||
|
|
return ModelConfig(
|
||
|
|
id=row["id"],
|
||
|
|
display_name=row["display_name"],
|
||
|
|
model_id=row["model_id"],
|
||
|
|
provider_key=row["provider_key"],
|
||
|
|
model_role=row["model_role"],
|
||
|
|
is_enabled=bool(row["is_enabled"]),
|
||
|
|
sort_order=row["sort_order"],
|
||
|
|
fallback_order=row["fallback_order"] if "fallback_order" in row.keys() else 999,
|
||
|
|
description=row["description"] or "",
|
||
|
|
created_at=datetime.fromisoformat(row["created_at"]),
|
||
|
|
updated_at=datetime.fromisoformat(row["updated_at"]),
|
||
|
|
)
|
||
|
|
|
||
|
|
def create(self, payload: ModelConfigCreate) -> ModelConfig:
|
||
|
|
config_id = f"model_{uuid.uuid4().hex[:12]}"
|
||
|
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
|
|
with self._connect() as conn:
|
||
|
|
conn.execute(
|
||
|
|
"""INSERT INTO model_config
|
||
|
|
(id, display_name, model_id, provider_key, model_role,
|
||
|
|
is_enabled, sort_order, fallback_order, description, created_at, updated_at)
|
||
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||
|
|
(
|
||
|
|
config_id,
|
||
|
|
payload.display_name,
|
||
|
|
payload.model_id,
|
||
|
|
payload.provider_key,
|
||
|
|
payload.model_role,
|
||
|
|
1 if payload.is_enabled else 0,
|
||
|
|
payload.sort_order,
|
||
|
|
payload.fallback_order,
|
||
|
|
payload.description,
|
||
|
|
now,
|
||
|
|
now,
|
||
|
|
),
|
||
|
|
)
|
||
|
|
conn.commit()
|
||
|
|
created = self.get(config_id)
|
||
|
|
if created is None:
|
||
|
|
raise RuntimeError(f"模型配置创建后回读失败:{config_id}")
|
||
|
|
return created
|
||
|
|
|
||
|
|
def get(self, config_id: str) -> Optional[ModelConfig]:
|
||
|
|
with self._connect() as conn:
|
||
|
|
row = conn.execute(
|
||
|
|
"SELECT * FROM model_config WHERE id = ?", (config_id,)
|
||
|
|
).fetchone()
|
||
|
|
return self._row_to_entity(row) if row else None
|
||
|
|
|
||
|
|
def list_all(self, only_enabled: bool = False) -> list[ModelConfig]:
|
||
|
|
sql = "SELECT * FROM model_config"
|
||
|
|
if only_enabled:
|
||
|
|
sql += " WHERE is_enabled = 1"
|
||
|
|
sql += " ORDER BY sort_order ASC, created_at ASC"
|
||
|
|
with self._connect() as conn:
|
||
|
|
rows = conn.execute(sql).fetchall()
|
||
|
|
return [self._row_to_entity(r) for r in rows]
|
||
|
|
|
||
|
|
def update(
|
||
|
|
self, config_id: str, payload: ModelConfigUpdate
|
||
|
|
) -> Optional[ModelConfig]:
|
||
|
|
existing = self.get(config_id)
|
||
|
|
if existing is None:
|
||
|
|
return None
|
||
|
|
changes = payload.model_dump(exclude_none=True)
|
||
|
|
if not changes:
|
||
|
|
return existing
|
||
|
|
# is_enabled 转 SQLite 整数
|
||
|
|
if "is_enabled" in changes:
|
||
|
|
changes["is_enabled"] = 1 if changes["is_enabled"] else 0
|
||
|
|
changes["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
||
|
|
set_clause = ", ".join(f"{k} = ?" for k in changes)
|
||
|
|
values = list(changes.values()) + [config_id]
|
||
|
|
with self._connect() as conn:
|
||
|
|
conn.execute(f"UPDATE model_config SET {set_clause} WHERE id = ?", values)
|
||
|
|
conn.commit()
|
||
|
|
return self.get(config_id)
|
||
|
|
|
||
|
|
def delete(self, config_id: str) -> bool:
|
||
|
|
with self._connect() as conn:
|
||
|
|
cursor = conn.execute("DELETE FROM model_config WHERE id = ?", (config_id,))
|
||
|
|
conn.commit()
|
||
|
|
return cursor.rowcount > 0
|