Files
chat-bot/api/prompt.py
lychang 64ce30fdfd init
2025-08-26 09:35:29 +08:00

58 lines
1.9 KiB
Python

from typing import Dict
from fastapi import HTTPException
from api.base import app
from extension.standard import db_manager
@app.get("/api/prompts", response_model=Dict)
async def get_prompts(page: int = 1, per_page: int = 5):
result = db_manager.prompts.get_all(page=page, per_page=per_page)
return {
'items': [{
'id': row[0],
'name': row[1],
'content': '\n'.join(row[2].split('\n')[:2]) + ('\n' if len(row[2].split('\n')) > 2 else ''),
'created_at': row[3]
} for row in result['items']],
'pagination': {
'total': result['total'],
'page': result['page'],
'per_page': result['per_page'],
'total_pages': result['total_pages']
}
}
@app.post("/api/prompts", response_model=Dict)
async def create_prompt(data: Dict):
content = data.get('content')
if not content:
raise HTTPException(status_code=400, detail='内容不能为空')
prompt_id = db_manager.prompts.create(name=data.get('name', ''), content=content)
return {'id': prompt_id}
@app.get("/api/prompts/{prompt_id}", response_model=Dict)
async def get_prompt(prompt_id: int):
prompt = db_manager.prompts.get_by_id(prompt_id)
if prompt:
return dict(prompt)
raise HTTPException(status_code=404, detail='Prompt not found')
@app.put("/api/prompts/{prompt_id}", response_model=Dict)
async def update_prompt(prompt_id: int, data: Dict):
name = data.get('name', '')
content = data.get('content')
if not content:
raise HTTPException(status_code=400, detail='内容不能为空')
db_manager.prompts.update(prompt_id, name=name, content=content)
return {'message': 'Prompt updated'}
@app.delete("/api/prompts/{prompt_id}", response_model=Dict)
async def delete_prompt(prompt_id: int):
db_manager.prompts.delete(prompt_id)
return {'message': 'Prompt deleted'}