Files

118 lines
4.4 KiB
Python

"""渠道管理:CRUD + 测试 + Step Plan 预设"""
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from ...db.session import get_db
from ...db import repos
from ...models.entities import User, Channel
from ...api.routers.auth import current_user
from ...core.config import STEP_PRESET
from ...services.llm import LLMClient
router = APIRouter(prefix="/channels", tags=["channels"])
class ChannelIn(BaseModel):
name: str
base_url: str
api_key: str
models: dict = {}
visibility: str = "admin" # public / granted / admin
def _view(c: Channel) -> dict:
return {"id": c.id, "name": c.name, "base_url": c.base_url,
"models": c.models or {}, "owner_id": c.owner_id,
"visibility": c.visibility,
"has_key": bool(c.api_key_enc)}
@router.get("/preset")
async def preset():
return STEP_PRESET
@router.post("/preset/apply")
async def apply_preset(user: User = Depends(current_user), db=Depends(get_db)):
"""一键把 Step Plan 预设落成渠道(已有同名渠道则跳过)。"""
from ...core.config import settings
rows = await repos.ChannelRepo.visible_to(db, user)
for r in rows:
if r.name == STEP_PRESET["name"]:
return {"applied": False, "reason": "已存在同名渠道"}
c = Channel(name=STEP_PRESET["name"], base_url=STEP_PRESET["base_url"],
api_key_enc=settings.step_api_key or "", models=STEP_PRESET["models"],
owner_id=user.id if not user.is_admin else None, visibility="admin")
db.add(c)
await db.commit()
return {"applied": True, "channel": _view(c)}
@router.get("")
async def list_channels(user: User = Depends(current_user), db=Depends(get_db)):
rows = await repos.ChannelRepo.visible_to(db, user)
return {"channels": [_view(c) for c in rows]}
@router.post("")
async def create_channel(body: ChannelIn, user: User = Depends(current_user),
db=Depends(get_db)):
if not user.is_admin and (await repos.SettingRepo.get(db, "allow_byok")) != "true":
raise HTTPException(403, "本站不允许用户自定义 API 渠道")
c = Channel(name=body.name, base_url=body.base_url,
api_key_enc=body.api_key, # BYOK key 也走加密列(M2 加密开关接入后统一加密)
models=body.models, owner_id=None if user.is_admin else user.id,
visibility=body.visibility if user.is_admin else "admin")
db.add(c)
await db.commit()
return _view(c)
@router.patch("/{cid}")
async def update_channel(cid: int, body: ChannelIn, user: User = Depends(current_user),
db=Depends(get_db)):
c = await repos.ChannelRepo.can_use(db, user, cid)
if not c or (c.owner_id and c.owner_id != user.id and not user.is_admin):
raise HTTPException(403, "无权修改该渠道")
c.name, c.base_url, c.models = body.name, body.base_url, body.models
if body.api_key:
c.api_key_enc = body.api_key
if user.is_admin:
c.visibility = body.visibility
await db.commit()
return _view(c)
@router.delete("/{cid}")
async def delete_channel(cid: int, user: User = Depends(current_user),
db=Depends(get_db)):
c = await repos.ChannelRepo.can_use(db, user, cid)
if not c or (c.owner_id and c.owner_id != user.id and not user.is_admin):
raise HTTPException(403, "无权删除该渠道")
await db.delete(c)
await db.commit()
return {"ok": True}
@router.post("/{cid}/test")
async def test_channel(cid: int, user: User = Depends(current_user),
db=Depends(get_db)):
c = await repos.ChannelRepo.can_use(db, user, cid)
if not c:
raise HTTPException(403, "无权访问该渠道")
model = (c.models or {}).get("narrative") or "step-3.5-flash"
client = LLMClient(c.base_url, c.api_key_enc)
ok, msg = await client.ping(model)
return {"ok": ok, "message": msg, "model": model}
@router.get("/{cid}/grants")
async def list_grants(cid: int, user: User = Depends(current_user), db=Depends(get_db)):
from ...models.entities import ChannelGrant
from sqlalchemy import select
if not user.is_admin:
raise HTTPException(403, "需要管理员权限")
rows = (await db.execute(select(ChannelGrant).where(
ChannelGrant.channel_id == cid))).scalars().all()
return {"user_ids": [r.user_id for r in rows]}