README / fastapi-backend /app /api /documents.py
TonyMoralist's picture
Upload 55 files
5c1ff2b verified
Raw History Blame Contribute Delete
1.92 kB
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.database import get_db
from app.schemas.message import ChatRequest, ChatResponse
from app.services.auth import get_current_user
from app.services.rag import process_chat_message, process_chat_message_stream
from app.models.bot import Bot
router = APIRouter(prefix="/chat", tags=["chat"])
@router.post("/message", response_model=ChatResponse)
async def chat_message(
request: ChatRequest,
current_user = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
result = await db.execute(select(Bot).where(Bot.id == request.bot_id, Bot.owner_id == current_user.id))
bot = result.scalar_one_or_none()
if not bot:
raise HTTPException(status_code=404, detail="Bot not found")
if not bot.is_active:
raise HTTPException(status_code=400, detail="Bot is not active")
response_text = await process_chat_message(bot, request, db)
return ChatResponse(
response=response_text,
session_id=request.session_id,
conversation_id=""
)
@router.post("/stream")
async def chat_stream(
request: ChatRequest,
current_user = Depends(get_current_user),
db: AsyncSession = Depends(get_db)
):
result = await db.execute(select(Bot).where(Bot.id == request.bot_id, Bot.owner_id == current_user.id))
bot = result.scalar_one_or_none()
if not bot:
raise HTTPException(status_code=404, detail="Bot not found")
if not bot.is_active:
raise HTTPException(status_code=400, detail="Bot is not active")
async def generate():
async for chunk in process_chat_message_stream(bot, request, db):
yield chunk
return StreamingResponse(generate(), media_type="text/event-stream")