Files
life-echo/api/app/features/conversation/router.py
2026-03-19 14:36:40 +08:00

107 lines
3.5 KiB
Python

"""
对话 feature — conversations 路由
"""
from app.core.logging import get_logger
from fastapi import APIRouter, Depends, HTTPException
from app.core.dependencies import get_current_user
from app.features.conversation.deps import get_conversation_service
from app.features.conversation.service import ConversationService
from app.features.user.models import User
router = APIRouter(
prefix="/api/conversations",
tags=["conversations"],
responses={
401: {"description": "认证失败"},
403: {"description": "权限不足"},
404: {"description": "资源不存在"},
429: {"description": "配额已用尽"},
},
)
logger = get_logger(__name__)
@router.get("")
async def get_conversations(
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""获取当前用户的所有对话列表(需要认证)"""
return await service.list_for_user(current_user.id)
@router.post("")
async def create_conversation(
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""创建新对话(需要认证)。对话轮数在每次发送消息时校验。"""
return await service.create(current_user.id)
@router.get("/{conversation_id}")
async def get_conversation(
conversation_id: str,
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""获取对话详情(需要认证,只能访问自己的对话)"""
return await service.get_one(conversation_id, current_user.id)
@router.post("/{conversation_id}/end")
async def end_conversation(
conversation_id: str,
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""结束对话(需要认证,只能结束自己的对话)"""
return await service.end(conversation_id, current_user.id)
@router.delete("/{conversation_id}")
async def delete_conversation(
conversation_id: str,
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""删除对话(需要认证,只能删除自己的对话)"""
await service.delete(conversation_id, current_user.id)
return {"message": "对话已删除"}
@router.get("/{conversation_id}/messages")
async def get_messages(
conversation_id: str,
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""获取对话的消息列表(需要认证,只能访问自己的对话)"""
return await service.get_messages(conversation_id, current_user.id)
@router.post("/{conversation_id}/organize")
async def organize_conversation(
conversation_id: str,
current_user: User = Depends(get_current_user),
service: ConversationService = Depends(get_conversation_service),
):
"""
整理对话内容成章节(需要认证,只能整理自己的对话)
手动触发对话整理,将对话中的内容整理成回忆录章节
"""
try:
return await service.organize(
conversation_id,
current_user.id,
current_user.subscription_type,
)
except HTTPException:
raise
except Exception as e:
logger.exception("提交整理任务失败: %s", e)
raise HTTPException(status_code=500, detail=f"提交整理任务失败: {str(e)}")