222 lines
8.3 KiB
Python
222 lines
8.3 KiB
Python
"""
|
||||
|
|
Provider 服务通道存储
|
|||
|
|
====================
|
|||
|
|
|
|||
|
|
【功能说明】
|
|||
|
|
管理多个 AI 模型服务通道(GLM/DeepSeek/Mimo 等平台)的地址与密钥。
|
|||
|
|
实现 ccswitch 的核心能力:统一管理多平台、按 model_id 路由。
|
|||
|
|
|
|||
|
|
【技术选型理由】
|
|||
|
|
1. 每个 Provider = 一个平台(base_url + api_key);
|
|||
|
|
2. 模型管理的 provider_key 引用 Provider 的 name;
|
|||
|
|
3. 模型路由按 provider_key 查 Provider 连接配置 → 直连调用。
|
|||
|
|
|
|||
|
|
【安全设计】API key 加密存储,前端返回脱敏值。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
import base64
|
|||
|
|
import logging
|
|||
|
|
import sqlite3
|
|||
|
|
import uuid
|
|||
|
|
from datetime import datetime
|
|||
|
|
from pathlib import Path
|
|||
|
|
from typing import Optional
|
|||
|
|
|
|||
|
|
from app.store.sqlite_util import open_connection
|
|||
|
|
|
|||
|
|
logger = logging.getLogger("agent.provider")
|
|||
|
|
|
|||
|
|
# 简易加密(与 db_connection_store 同款)
|
|||
|
|
_XOR_KEY = b"agent_provider_key_2026"
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _encrypt(text: str) -> str:
|
|||
|
|
if not text:
|
|||
|
|
return ""
|
|||
|
|
data = text.encode("utf-8")
|
|||
|
|
encrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(data))
|
|||
|
|
return base64.b64encode(encrypted).decode("ascii")
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _decrypt(token: str) -> str:
|
|||
|
|
if not token:
|
|||
|
|
return ""
|
|||
|
|
try:
|
|||
|
|
encrypted = base64.b64decode(token.encode("ascii"))
|
|||
|
|
decrypted = bytes(b ^ _XOR_KEY[i % len(_XOR_KEY)] for i, b in enumerate(encrypted))
|
|||
|
|
return decrypted.decode("utf-8")
|
|||
|
|
except Exception: # noqa: BLE001
|
|||
|
|
return ""
|
|||
|
|
|
|||
|
|
|
|||
|
|
class ProviderStore:
|
|||
|
|
"""Provider 存储(SQLite)"""
|
|||
|
|
|
|||
|
|
def __init__(self, db_path: Path) -> None:
|
|||
|
|
self._db_path = Path(db_path)
|
|||
|
|
self._init_schema()
|
|||
|
|
self._seed_ccswitch()
|
|||
|
|
|
|||
|
|
def _conn(self):
|
|||
|
|
"""
|
|||
|
|
获取一个短连接(用完自动提交/回滚并关闭)。
|
|||
|
|
|
|||
|
|
【修复】原先只返回裸 sqlite3 连接、用完从不 close,连接泄漏到 GC
|
|||
|
|
(Windows 文件锁 / 句柄增长)。改为委托 app.store.sqlite_util.open_connection,
|
|||
|
|
提交/回滚语义不变,额外保证 close。
|
|||
|
|
"""
|
|||
|
|
return open_connection(self._db_path)
|
|||
|
|
|
|||
|
|
def _init_schema(self) -> None:
|
|||
|
|
ddl = """
|
|||
|
|
CREATE TABLE IF NOT EXISTS provider (
|
|||
|
|
id TEXT PRIMARY KEY,
|
|||
|
|
name TEXT NOT NULL UNIQUE,
|
|||
|
|
base_url TEXT NOT NULL,
|
|||
|
|
api_key TEXT NOT NULL DEFAULT '',
|
|||
|
|
description TEXT DEFAULT '',
|
|||
|
|
is_enabled INTEGER DEFAULT 1,
|
|||
|
|
created_at TEXT NOT NULL,
|
|||
|
|
updated_at TEXT NOT NULL
|
|||
|
|
);
|
|||
|
|
"""
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
conn.execute(ddl)
|
|||
|
|
conn.commit()
|
|||
|
|
|
|||
|
|
def _seed_ccswitch(self) -> None:
|
|||
|
|
"""首次初始化:把 .env 里的 ccswitch 配置导入为默认 Provider(向后兼容)。"""
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
count = conn.execute("SELECT COUNT(*) FROM provider").fetchone()[0]
|
|||
|
|
if count > 0:
|
|||
|
|
return
|
|||
|
|
try:
|
|||
|
|
from app.config.settings import load_settings
|
|||
|
|
|
|||
|
|
s = load_settings()
|
|||
|
|
if s.ccswitch_api_key and s.ccswitch_base_url:
|
|||
|
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
|||
|
|
conn.execute(
|
|||
|
|
"INSERT INTO provider (id, name, base_url, api_key, description, is_enabled, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?)",
|
|||
|
|
(
|
|||
|
|
f"prov_{uuid.uuid4().hex[:8]}",
|
|||
|
|
"ccswitch",
|
|||
|
|
s.ccswitch_base_url,
|
|||
|
|
_encrypt(s.ccswitch_api_key),
|
|||
|
|
"ccswitch 本地代理(兼容旧配置)",
|
|||
|
|
1,
|
|||
|
|
now,
|
|||
|
|
now,
|
|||
|
|
),
|
|||
|
|
)
|
|||
|
|
conn.commit()
|
|||
|
|
logger.info("已导入 ccswitch 为默认 Provider")
|
|||
|
|
except Exception as exc: # noqa: BLE001
|
|||
|
|
logger.warning("导入 ccswitch 失败:%s", exc)
|
|||
|
|
|
|||
|
|
def _row_to_dict(self, row: sqlite3.Row, mask_key: bool = False) -> dict:
|
|||
|
|
key = row["api_key"] or ""
|
|||
|
|
# 本地工具不脱敏,直接返回解密后的真实密钥(便于用户查看/编辑)
|
|||
|
|
display_key = _decrypt(key)
|
|||
|
|
return {
|
|||
|
|
"id": row["id"],
|
|||
|
|
"name": row["name"],
|
|||
|
|
"base_url": row["base_url"],
|
|||
|
|
"api_key": display_key,
|
|||
|
|
"description": row["description"] or "",
|
|||
|
|
"is_enabled": bool(row["is_enabled"]),
|
|||
|
|
"created_at": row["created_at"],
|
|||
|
|
"updated_at": row["updated_at"],
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def list_all(self, only_enabled: bool = False) -> list[dict]:
|
|||
|
|
sql = "SELECT * FROM provider"
|
|||
|
|
if only_enabled:
|
|||
|
|
sql += " WHERE is_enabled = 1"
|
|||
|
|
sql += " ORDER BY created_at"
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
rows = conn.execute(sql).fetchall()
|
|||
|
|
return [self._row_to_dict(r) for r in rows]
|
|||
|
|
|
|||
|
|
def get(self, provider_id: str) -> Optional[dict]:
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
row = conn.execute("SELECT * FROM provider WHERE id = ?", (provider_id,)).fetchone()
|
|||
|
|
return self._row_to_dict(row) if row else None
|
|||
|
|
|
|||
|
|
def get_by_name(self, name: str) -> Optional[dict]:
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
row = conn.execute("SELECT * FROM provider WHERE name = ?", (name,)).fetchone()
|
|||
|
|
return self._row_to_dict(row) if row else None
|
|||
|
|
|
|||
|
|
def get_with_key(self, name: str) -> Optional[dict]:
|
|||
|
|
"""获取含真实 api_key 的连接信息(供模型路由用,不暴露给前端)。"""
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
row = conn.execute("SELECT * FROM provider WHERE name = ?", (name,)).fetchone()
|
|||
|
|
return self._row_with_real_key(row) if row else None
|
|||
|
|
|
|||
|
|
def get_with_key_by_id(self, provider_id: str) -> Optional[dict]:
|
|||
|
|
"""按 ID 获取含真实 api_key 的连接信息(供测试连接用)。"""
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
row = conn.execute("SELECT * FROM provider WHERE id = ?", (provider_id,)).fetchone()
|
|||
|
|
return self._row_with_real_key(row) if row else None
|
|||
|
|
|
|||
|
|
@staticmethod
|
|||
|
|
def _row_with_real_key(row: sqlite3.Row) -> dict:
|
|||
|
|
return {
|
|||
|
|
"id": row["id"],
|
|||
|
|
"name": row["name"],
|
|||
|
|
"base_url": row["base_url"],
|
|||
|
|
"api_key": _decrypt(row["api_key"] or ""),
|
|||
|
|
"is_enabled": bool(row["is_enabled"]),
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
def create(self, name: str, base_url: str, api_key: str = "", description: str = "") -> dict:
|
|||
|
|
pid = f"prov_{uuid.uuid4().hex[:8]}"
|
|||
|
|
now = datetime.now().astimezone().isoformat(timespec="seconds")
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
conn.execute(
|
|||
|
|
"INSERT INTO provider (id, name, base_url, api_key, description, is_enabled, created_at, updated_at) VALUES (?,?,?,?,?,1,?,?)",
|
|||
|
|
(pid, name, base_url, _encrypt(api_key), description, now, now),
|
|||
|
|
)
|
|||
|
|
conn.commit()
|
|||
|
|
return self.get(pid)
|
|||
|
|
|
|||
|
|
def update(self, provider_id: str, **kwargs) -> Optional[dict]:
|
|||
|
|
allowed = {"name", "base_url", "api_key", "description", "is_enabled"}
|
|||
|
|
updates = {k: v for k, v in kwargs.items() if k in allowed and v is not None}
|
|||
|
|
if not updates:
|
|||
|
|
return self.get(provider_id)
|
|||
|
|
if "api_key" in updates:
|
|||
|
|
updates["api_key"] = _encrypt(updates["api_key"])
|
|||
|
|
if "is_enabled" in updates:
|
|||
|
|
updates["is_enabled"] = 1 if updates["is_enabled"] else 0
|
|||
|
|
updates["updated_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
|
|||
|
|
set_clause = ", ".join(f"{k} = ?" for k in updates)
|
|||
|
|
values = list(updates.values()) + [provider_id]
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
conn.execute(f"UPDATE provider SET {set_clause} WHERE id = ?", values)
|
|||
|
|
conn.commit()
|
|||
|
|
return self.get(provider_id)
|
|||
|
|
|
|||
|
|
def delete(self, provider_id: str) -> bool:
|
|||
|
|
with self._conn() as conn:
|
|||
|
|
cursor = conn.execute("DELETE FROM provider WHERE id = ?", (provider_id,))
|
|||
|
|
conn.commit()
|
|||
|
|
return cursor.rowcount > 0
|
|||
|
|
|
|||
|
|
|
|||
|
|
# 全局单例
|
|||
|
|
_store: ProviderStore | None = None
|
|||
|
|
|
|||
|
|
|
|||
|
|
def get_provider_store() -> ProviderStore:
|
|||
|
|
global _store
|
|||
|
|
if _store is None:
|
|||
|
|
from app.config.settings import load_settings
|
|||
|
|
|
|||
|
|
s = load_settings()
|
|||
|
|
_store = ProviderStore(s.sqlite_db_path)
|
|||
|
|
return _store
|