from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File, Form from fastapi.responses import StreamingResponse from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from typing import List, Optional from app.database import get_db from app.schemas.bot import BotCreate, BotResponse, BotUpdate, DocumentCreate, DocumentResponse from app.services.auth import get_current_user from app.services.rag import process_uploaded_file, process_file_content from app.models.bot import Bot, Document from app.models.user import User import aiofiles import os router = APIRouter(prefix="/bots", tags=["bots"]) @router.get("/", response_model=List[BotResponse]) async def get_bots( current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): result = await db.execute(select(Bot).where(Bot.owner_id == current_user.id)) bots = result.scalars().all() return bots @router.get("/{bot_id}", response_model=BotResponse) async def get_bot( bot_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): result = await db.execute(select(Bot).where(Bot.id == 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") return bot @router.post("/", response_model=BotResponse, status_code=status.HTTP_201_CREATED) async def create_bot( bot_data: BotCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): new_bot = Bot(**bot_data.model_dump(), owner_id=current_user.id) db.add(new_bot) await db.flush() await db.refresh(new_bot) return new_bot @router.put("/{bot_id}", response_model=BotResponse) async def update_bot( bot_id: str, bot_data: BotUpdate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): result = await db.execute(select(Bot).where(Bot.id == 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") update_data = bot_data.model_dump(exclude_unset=True) for field, value in update_data.items(): setattr(bot, field, value) await db.flush() await db.refresh(bot) return bot @router.delete("/{bot_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_bot( bot_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): result = await db.execute(select(Bot).where(Bot.id == 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") await db.delete(bot) await db.flush() return None @router.post("/{bot_id}/documents", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED) async def upload_document( bot_id: str, doc_data: DocumentCreate, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): # Verify bot exists and belongs to user result = await db.execute(select(Bot).where(Bot.id == 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") new_doc = Document(**doc_data.model_dump()) db.add(new_doc) await db.flush() await db.refresh(new_doc) return new_doc @router.post("/{bot_id}/documents/upload", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED) async def upload_document_file( bot_id: str, file: UploadFile = File(...), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """Upload a file (PDF, DOCX, TXT) and process it for RAG""" # Verify bot exists and belongs to user result = await db.execute(select(Bot).where(Bot.id == 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") # Read file content content = await file.read() # Process file file_type, extracted_text, chunks = await process_uploaded_file(content, file.filename) # Create document record new_doc = Document( bot_id=bot_id, name=file.filename, content=extracted_text, file_type=file_type, chunks=chunks # Store chunks for retrieval ) db.add(new_doc) await db.flush() await db.refresh(new_doc) return new_doc @router.post("/{bot_id}/documents/text", response_model=DocumentResponse, status_code=status.HTTP_201_CREATED) async def upload_text_document( bot_id: str, name: str = Form(...), text: str = Form(...), current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """Upload plain text content""" # Verify bot exists and belongs to user result = await db.execute(select(Bot).where(Bot.id == 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") # Process text extracted_text, chunks = await process_file_content(text, "txt") # Create document record new_doc = Document( bot_id=bot_id, name=name, content=extracted_text, file_type="txt", chunks=chunks ) db.add(new_doc) await db.flush() await db.refresh(new_doc) return new_doc @router.post("/{bot_id}/playground") async def test_bot( bot_id: str, request: dict, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """Test bot response with current settings (Playground)""" from app.services.rag import build_system_prompt, retrieve_relevant_documents, process_chat_message user_message = request.get("message", "") test_context = request.get("context", []) # Optional test context # Verify bot exists result = await db.execute(select(Bot).where(Bot.id == 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") # Build system prompt system_prompt = build_system_prompt(bot) # Get relevant documents if test_context: relevant_chunks = test_context else: relevant_chunks = await retrieve_relevant_documents(bot, user_message, db) # Generate response response_text = await process_chat_message(bot, ChatRequest(bot_id=bot_id, message=user_message, session_id="playground"), db ) return { "system_prompt": system_prompt, "relevant_chunks": relevant_chunks, "user_message": user_message, "response": response_text } @router.get("/{bot_id}/conversations") async def get_conversations( bot_id: str, limit: int = 50, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """Get all conversations for a bot""" # Verify bot exists result = await db.execute(select(Bot).where(Bot.id == 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") # Get conversations from app.models.bot import Conversation result = await db.execute( select(Conversation) .where(Conversation.bot_id == bot_id) .order_by(Conversation.updated_at.desc()) .limit(limit) ) conversations = result.scalars().all() return conversations @router.post("/{bot_id}/conversations/{conversation_id}/operator") async def request_operator( bot_id: str, conversation_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """Mark conversation as requiring human operator and send notification""" from app.services.telegram import get_telegram_service from app.services.webhook import webhook_service # Verify bot and conversation result = await db.execute(select(Bot).where(Bot.id == 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") result = await db.execute( select(Conversation) .where(Conversation.id == conversation_id, Conversation.bot_id == bot_id) ) conversation = result.scalar_one_or_none() if not conversation: raise HTTPException(status_code=404, detail="Conversation not found") # Update conversation status conversation.lead_status = "operator_requested" await db.flush() # Send Telegram notification if configured if bot.telegram_bot_token and bot.telegram_chat_id and bot.notify_on_operator_request: telegram_service = get_telegram_service(bot.telegram_bot_token) await telegram_service.send_conversation_alert( chat_id=bot.telegram_chat_id, bot_name=bot.name, session_id=conversation.session_id, message_count=0 ) # Send webhook if configured if bot.webhook_url: await webhook_service.send_webhook(bot.webhook_url, { "event": "operator_requested", "bot_id": bot_id, "bot_name": bot.name, "conversation_id": conversation_id, "session_id": conversation.session_id, "lead_name": conversation.lead_name, "lead_phone": conversation.lead_phone, "lead_email": conversation.lead_email }) return {"success": True, "message": "Оператор уведомлен"} @router.get("/{bot_id}/conversations/{conversation_id}") async def get_conversation( bot_id: str, conversation_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): """Get specific conversation with messages""" # Verify bot exists result = await db.execute(select(Bot).where(Bot.id == 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") # Get conversation from app.models.bot import Conversation, Message result = await db.execute( select(Conversation) .where(Conversation.id == conversation_id, Conversation.bot_id == bot_id) ) conversation = result.scalar_one_or_none() if not conversation: raise HTTPException(status_code=404, detail="Conversation not found") # Get messages result = await db.execute( select(Message) .where(Message.conversation_id == conversation_id) .order_by(Message.created_at) ) messages = result.scalars().all() return { "conversation": conversation, "messages": messages } @router.get("/{bot_id}/documents", response_model=List[DocumentResponse]) async def get_documents( bot_id: str, current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db) ): # Verify bot exists and belongs to user result = await db.execute(select(Bot).where(Bot.id == 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") result = await db.execute(select(Document).where(Document.bot_id == bot_id)) documents = result.scalars().all() return documents