Files
Story-extractor/backend/app/api/settings.py
2026-04-24 16:02:16 +08:00

71 lines
2.7 KiB
Python

from typing import Annotated
from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.database import get_db
from app.models.config import Config
from app.schemas.schemas import SettingsOut, SettingsUpdate
from app.services.llm_client import llm_client
from app.config import settings
router = APIRouter(prefix="/settings", tags=["系统设置"])
async def _get_config_value(db: AsyncSession, key: str, default: str = "") -> str:
"""获取配置值"""
result = await db.execute(select(Config).where(Config.key == key))
config = result.scalar_one_or_none()
return config.value if config else default
@router.get("", response_model=SettingsOut)
async def get_settings(db: Annotated[AsyncSession, Depends(get_db)]):
"""获取系统配置"""
return SettingsOut(
llm_provider=await _get_config_value(db, "llm_provider", settings.LLM_PROVIDER),
llm_model=await _get_config_value(db, "llm_model", settings.LLM_MODEL),
llm_base_url=await _get_config_value(db, "llm_base_url", settings.LLM_BASE_URL),
llm_api_key=await _get_config_value(db, "llm_api_key", "****"),
segment_max_lines=int(await _get_config_value(db, "segment_max_lines", str(settings.SEGMENT_MAX_LINES))),
story_min_lines=int(await _get_config_value(db, "story_min_lines", str(settings.STORY_MIN_LINES))),
confidence_threshold=float(await _get_config_value(db, "confidence_threshold", str(settings.CONFIDENCE_THRESHOLD))),
temperature=float(await _get_config_value(db, "temperature", str(settings.TEMPERATURE))),
)
@router.put("")
async def update_settings(data: SettingsUpdate, db: Annotated[AsyncSession, Depends(get_db)]):
"""更新系统配置"""
updates = data.model_dump(exclude_none=True)
for key, value in updates.items():
# API Key 脱敏处理
if key == "llm_api_key" and value == "****":
continue
existing = await db.execute(select(Config).where(Config.key == key))
config = existing.scalar_one_or_none()
if config:
config.value = str(value)
else:
db.add(Config(key=key, value=str(value)))
await db.commit()
# 更新 LLM 客户端配置
if "llm_base_url" in updates:
llm_client.update_config(base_url=updates["llm_base_url"])
if "llm_api_key" in updates:
llm_client.update_config(api_key=updates["llm_api_key"])
if "llm_model" in updates:
llm_client.update_config(model=updates["llm_model"])
return {"message": "配置已保存"}
@router.post("/test-llm")
async def test_llm():
"""测试 LLM 连接"""
result = await llm_client.test_connection()
return result