File size: 11,843 Bytes
5c1ff2b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 | 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
|