Files

166 lines
5.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""商业化预留 v1 API:API Key 认证 + 限流 + 用量账本。
设计原则:
- /v1/* 稳定契约:只加字段不改语义,向前兼容
- key 只存 sha256;明文只返回一次
- scope 分级:chat / full;rate_limit 按 key 限流
- 用量落 usage_logs,将来接计费系统零改造
"""
import hashlib
import secrets
import time
import datetime as dt
from collections import defaultdict, deque
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from sqlalchemy import select
from ..db.session import get_db
from ..db import repos
from ..models.entities import ApiKey, UsageLog, User, Message
from ..api.routers.auth import current_user
from ..api.routers.chat import (_dec, _enc, _own_session, _key, build_context,
_channel_for)
router = APIRouter(prefix="/v1", tags=["v1-commercial"])
# ---------- API Key 认证 ----------
def _hash_key(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
async def api_key_auth(request: Request, db=Depends(get_db)) -> tuple[User, ApiKey]:
raw = request.headers.get("X-API-Key", "")
if not raw:
raise HTTPException(401, "缺少 X-API-Key")
row = (await db.execute(select(ApiKey).where(
ApiKey.key_hash == _hash_key(raw), ApiKey.revoked == False))).scalar_one_or_none()
if not row:
raise HTTPException(401, "API Key 无效或已吊销")
user = await db.get(User, row.user_id)
if not user or not user.is_active:
raise HTTPException(401, "账户无效")
return user, row
# ---------- 限流(滑动窗口,进程内;多实例部署换 Redis) ----------
_buckets: dict[int, deque] = defaultdict(deque)
def check_rate_limit(key_row: ApiKey):
b = _buckets[key_row.id]
now = time.time()
while b and b[0] < now - 60:
b.popleft()
if len(b) >= key_row.rate_limit:
raise HTTPException(429, f"超过限流 {key_row.rate_limit}/min")
b.append(now)
async def log_usage(db, user: User, key_row: ApiKey, endpoint: str):
db.add(UsageLog(user_id=user.id, api_key_id=key_row.id,
endpoint=endpoint, cost_units=1))
key_row.last_used_at = dt.datetime.utcnow()
await db.commit()
# ---------- Key 管理(JWT 鉴权) ----------
class KeyIn(BaseModel):
name: str = "default"
scope: str = "chat" # chat / full
rate_limit: int = 60
@router.post("/keys")
async def create_key(body: KeyIn, user: User = Depends(current_user),
db=Depends(get_db)):
raw = "omk_" + secrets.token_urlsafe(24)
row = ApiKey(user_id=user.id, key_hash=_hash_key(raw),
name=body.name, scope=body.scope, rate_limit=body.rate_limit)
db.add(row)
await db.commit()
return {"key": raw, "id": row.id, "notice": "明文仅此一次,请立即保存"}
@router.get("/keys")
async def list_keys(user: User = Depends(current_user), db=Depends(get_db)):
rows = (await db.execute(select(ApiKey).where(
ApiKey.user_id == user.id, ApiKey.revoked == False))).scalars().all()
return {"keys": [{"id": k.id, "name": k.name, "scope": k.scope,
"rate_limit": k.rate_limit,
"last_used": str(k.last_used_at or "")} for k in rows]}
@router.delete("/keys/{kid}")
async def revoke_key(kid: int, user: User = Depends(current_user), db=Depends(get_db)):
row = await db.get(ApiKey, kid)
if not row or row.user_id != user.id:
raise HTTPException(404, "不存在")
row.revoked = True
await db.commit()
return {"ok": True}
@router.get("/usage")
async def my_usage(user: User = Depends(current_user), db=Depends(get_db)):
rows = (await db.execute(select(UsageLog).where(
UsageLog.user_id == user.id).order_by(UsageLog.id.desc()).limit(500))).scalars().all()
by_ep = {}
for r in rows:
by_ep[r.endpoint] = by_ep.get(r.endpoint, 0) + 1
return {"recent_calls": len(rows), "by_endpoint": by_ep}
# ---------- v1 稳定接口 ----------
@router.get("/ping")
async def ping():
"""健康检查,无鉴权"""
return {"ok": True, "service": "open-maopaoya", "version": "v1"}
@router.get("/characters")
async def v1_characters(pair: tuple = Depends(api_key_auth), db=Depends(get_db)):
user, key_row = pair
if key_row.scope != "full":
raise HTTPException(403, "scope 不足,需要 full")
from ..db.repos import dec
rows = await repos.CharacterRepo.list_for(db, user.id)
await log_usage(db, user, key_row, "/v1/characters")
k = _key(user)
return {"data": [{"id": c.id, "name": c.name,
"persona": dec(k, c.persona), "voice": c.voice} for c in rows]}
class V1ChatIn(BaseModel):
session_id: int
content: str
@router.post("/chat")
async def v1_chat(body: V1ChatIn, pair: tuple = Depends(api_key_auth),
db=Depends(get_db)):
"""以 API Key 驱动一次对话(走用户自己的渠道配置)"""
user, key_row = pair
check_rate_limit(key_row)
s = await _own_session(db, user, body.session_id)
db.add(Message(session_id=s.id, user_id=user.id, role="user",
content_enc=_enc(user, body.content)))
await db.commit()
history = await repos.MessageRepo.history(db, user.id, s.id, limit=80)
msgs = await build_context(db, user, s, history)
client, models = await _channel_for(db, user, s)
reply = await client.chat(models.get("narrative") or "step-3.5-flash", msgs)
db.add(Message(session_id=s.id, user_id=user.id, role="assistant",
content_enc=_enc(user, reply)))
await log_usage(db, user, key_row, "/v1/chat")
await db.commit()
return {"reply": reply, "session_id": s.id}