prompts.py
3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""提示词模板 API 路由"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.database import get_db
from app.schemas.prompt import (
PromptCreate, PromptUpdate, VALID_TEMPLATE_TYPES,
)
from app.services import prompt_service
from app.schemas.prompt import PromptCreate as PromptCreateValidator
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1/prompts", tags=["提示词模板"])
def _validate_template_type(template_type: str) -> None:
"""验证模板类型是否合法"""
if template_type not in VALID_TEMPLATE_TYPES:
valid_types = ", ".join(sorted(VALID_TEMPLATE_TYPES))
raise HTTPException(
status_code=422,
detail=f"无效的模板类型: {template_type},可选值: {valid_types}",
)
@router.post("", status_code=201)
async def create_prompt(data: PromptCreate, db: AsyncSession = Depends(get_db)):
"""新增提示词模板"""
try:
return await prompt_service.create_prompt(db, data)
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
@router.put("/{prompt_id}")
async def update_prompt(
prompt_id: str, data: PromptUpdate, db: AsyncSession = Depends(get_db)
):
"""编辑提示词模板"""
try:
result = await prompt_service.update_prompt(db, prompt_id, data)
if not result:
raise HTTPException(status_code=404, detail="模板不存在")
return result
except ValueError as e:
raise HTTPException(status_code=422, detail=str(e))
@router.get("/{prompt_id}")
async def get_prompt(prompt_id: str, db: AsyncSession = Depends(get_db)):
"""查询模板详情(含历史版本列表)"""
result = await prompt_service.get_prompt(db, prompt_id)
if not result:
raise HTTPException(status_code=404, detail="模板不存在")
return result
@router.delete("/{prompt_id}")
async def delete_prompt(prompt_id: str, db: AsyncSession = Depends(get_db)):
"""删除提示词模板(软删除)"""
try:
result = await prompt_service.delete_prompt(db, prompt_id)
if not result:
raise HTTPException(status_code=404, detail="模板不存在")
return {"status": "deleted", "id": prompt_id}
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
@router.get("")
async def list_prompts(
page: int = Query(1, ge=1, description="页码"),
page_size: int = Query(20, ge=1, le=100, description="每页条数"),
template_type: Optional[str] = Query(None, description="按模板类型筛选"),
title: Optional[str] = Query(None, description="按标题模糊搜索"),
status: Optional[str] = Query(None, description="按状态筛选:draft/published/archived"),
db: AsyncSession = Depends(get_db),
):
"""分页查询模板列表"""
return await prompt_service.list_prompts(
db=db, page=page, page_size=page_size,
template_type=template_type, title=title, status=status,
)