67 lines
2.1 KiB
Python
67 lines
2.1 KiB
Python
from fastapi import APIRouter, HTTPException, Request, status
|
|
|
|
from schemas import (
|
|
CreateSessionRequest,
|
|
CreateSessionResponse,
|
|
SendMessageRequest,
|
|
SendMessageResponse,
|
|
SessionHistoryResponse,
|
|
)
|
|
from service import ChatProviderError, ChatService
|
|
from storage import SessionNotFoundError, SessionStorageError
|
|
|
|
|
|
router = APIRouter(prefix="/sessions", tags=["sessions"])
|
|
|
|
|
|
def get_chat_service(request: Request) -> ChatService:
|
|
return request.app.state.chat_service
|
|
|
|
|
|
@router.post(
|
|
"",
|
|
response_model=CreateSessionResponse,
|
|
status_code=status.HTTP_201_CREATED,
|
|
)
|
|
async def create_session(
|
|
request: Request,
|
|
body: CreateSessionRequest | None = None,
|
|
) -> CreateSessionResponse:
|
|
try:
|
|
return await get_chat_service(request).create_session(
|
|
body.system_prompt if body is not None else None
|
|
)
|
|
except SessionStorageError as exc:
|
|
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
|
|
|
|
|
@router.post("/{session_id}/messages", response_model=SendMessageResponse)
|
|
async def send_message(
|
|
session_id: str,
|
|
body: SendMessageRequest,
|
|
request: Request,
|
|
) -> SendMessageResponse:
|
|
try:
|
|
return await get_chat_service(request).generate_response(
|
|
session_id, body.content
|
|
)
|
|
except SessionNotFoundError as exc:
|
|
raise HTTPException(status_code=404, detail="session not found") from exc
|
|
except ChatProviderError as exc:
|
|
raise HTTPException(status_code=502, detail=str(exc)) from exc
|
|
except SessionStorageError as exc:
|
|
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
|
|
|
|
|
@router.get("/{session_id}/messages", response_model=SessionHistoryResponse)
|
|
async def get_session_history(
|
|
session_id: str,
|
|
request: Request,
|
|
) -> SessionHistoryResponse:
|
|
try:
|
|
return await get_chat_service(request).get_session_history(session_id)
|
|
except SessionNotFoundError as exc:
|
|
raise HTTPException(status_code=404, detail="session not found") from exc
|
|
except SessionStorageError as exc:
|
|
raise HTTPException(status_code=500, detail=str(exc)) from exc
|