68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
from fastapi import APIRouter, Depends, HTTPException, Query
|
|
from sqlalchemy.orm import Session
|
|
from app.core.db import get_db
|
|
from app.models import AIModel
|
|
from app.schemas.ai_model import AIModelOut, AIModelCreate, AIModelUpdate
|
|
from typing import List, Optional
|
|
|
|
router = APIRouter(prefix="/ai-models", tags=["ai-models"])
|
|
|
|
|
|
@router.get("", response_model=List[AIModelOut])
|
|
def list_ai_models(
|
|
model_type: Optional[str] = Query(None, pattern="^(asr|llm)$"),
|
|
db: Session = Depends(get_db)
|
|
):
|
|
query = db.query(AIModel)
|
|
if model_type:
|
|
query = query.filter(AIModel.model_type == model_type)
|
|
return query.order_by(AIModel.created_at.desc()).all()
|
|
|
|
|
|
@router.post("", response_model=AIModelOut)
|
|
def create_ai_model(payload: AIModelCreate, db: Session = Depends(get_db)):
|
|
# Logic: If set as default, unset others of same type
|
|
if payload.is_default:
|
|
db.query(AIModel).filter(AIModel.model_type == payload.model_type).update({"is_default": False})
|
|
|
|
item = AIModel(**payload.model_dump())
|
|
db.add(item)
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.put("/{model_id}", response_model=AIModelOut)
|
|
def update_ai_model(model_id: int, payload: AIModelUpdate, db: Session = Depends(get_db)):
|
|
item = db.query(AIModel).filter(AIModel.model_id == model_id).first()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Model not found")
|
|
|
|
update_data = payload.model_dump(exclude_unset=True)
|
|
|
|
if update_data.get("is_default"):
|
|
# Unset others
|
|
target_type = update_data.get("model_type", item.model_type)
|
|
db.query(AIModel).filter(AIModel.model_type == target_type).update({"is_default": False})
|
|
|
|
for k, v in update_data.items():
|
|
setattr(item, k, v)
|
|
|
|
db.commit()
|
|
db.refresh(item)
|
|
return item
|
|
|
|
|
|
@router.delete("/{model_id}")
|
|
def delete_ai_model(model_id: int, db: Session = Depends(get_db)):
|
|
item = db.query(AIModel).filter(AIModel.model_id == model_id).first()
|
|
if not item:
|
|
raise HTTPException(status_code=404, detail="Model not found")
|
|
|
|
if item.is_default:
|
|
raise HTTPException(status_code=400, detail="Cannot delete default model")
|
|
|
|
db.delete(item)
|
|
db.commit()
|
|
return {"status": "ok"}
|