Spaces:
Running
Running
File size: 22,330 Bytes
9a26894 cd61bf7 93b694c cd61bf7 9a26894 93b694c cd61bf7 bff9142 cd61bf7 7b9aed2 cd61bf7 9a26894 cd61bf7 9a26894 bff9142 9a26894 cd61bf7 9a26894 cd61bf7 9a26894 cd61bf7 9a26894 cd61bf7 9a26894 cd61bf7 78d05da cd61bf7 53b9e11 cd61bf7 53b9e11 9a26894 bff9142 9a26894 cd61bf7 9a26894 d9eef76 9a26894 cd61bf7 9a26894 6b3e0ab 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b cd34c6f 560824b | 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 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import select
from typing import List, Optional
from uuid import UUID
from pydantic import BaseModel
import io
from app.core.database import get_session
from app.services.embeddings import get_embedding_service
from app.services.vector_store import get_vector_store
from app.services.ai_memory_manager import get_memory_manager
from app.models.knowledge import KnowledgeBase
from app.models import User
from app.models.tenant import Tenant
from app.api.deps import get_current_user
from app.core.logging import get_logger
logger = get_logger(__name__)
router = APIRouter(prefix="/knowledge", tags=["Knowledge Base"])
class KnowledgeInput(BaseModel):
"""Input for adding knowledge."""
content: str
source_type: str = "manual"
category: Optional[str] = None
tags: Optional[str] = None
class KnowledgeBatchInput(BaseModel):
"""Input for batch knowledge upload."""
chunks: List[str]
source_type: str = "manual"
source_file: Optional[str] = None
category: Optional[str] = None
class SearchQuery(BaseModel):
"""Search query."""
query: str
top_k: int = 5
category: Optional[str] = None
@router.post("/add")
async def add_knowledge(
data: KnowledgeInput,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Add single knowledge chunk to RAG (tenant-isolated)."""
# Use authenticated user's tenant_id (prevents tenant isolation breach)
tenant_id = current_user.tenant_id
vector_store = get_vector_store()
kb_entry = await vector_store.add_knowledge(
session=session,
tenant_id=tenant_id,
content=data.content,
source_type=data.source_type,
category=data.category,
tags=data.tags
)
# SIGNAL: Invalidate AI Memory
tenant = await session.get(Tenant, tenant_id)
if tenant:
await get_memory_manager().invalidate_memory(session, tenant)
return {
"ok": True,
"id": str(kb_entry.id),
"message": "Knowledge added successfully"
}
@router.post("/add-batch")
async def add_knowledge_batch(
data: KnowledgeBatchInput,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Add multiple knowledge chunks efficiently (tenant-isolated)."""
# Use authenticated user's tenant_id (prevents tenant isolation breach)
tenant_id = current_user.tenant_id
vector_store = get_vector_store()
kb_entries = await vector_store.add_knowledge_batch(
session=session,
tenant_id=tenant_id,
chunks=data.chunks,
source_type=data.source_type,
source_file=data.source_file,
category=data.category
)
await get_vector_store().add_documents(documents=kb_entries)
# SIGNAL: Invalidate AI Memory
await get_memory_manager().invalidate_memory(session, current_user.tenant_id)
return {
"ok": True,
"count": len(kb_entries),
"message": f"Added {len(kb_entries)} knowledge chunks"
}
@router.post("/search")
async def search_knowledge(
query: SearchQuery,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Search knowledge base using semantic similarity (tenant-isolated)."""
# Use authenticated user's tenant_id (prevents tenant isolation breach)
tenant_id = current_user.tenant_id
vector_store = get_vector_store()
results = await vector_store.semantic_search(
session=session,
tenant_id=tenant_id,
query=query.query,
top_k=query.top_k,
category=query.category
)
return {
"ok": True,
"count": len(results),
"results": results
}
@router.get("/list")
async def list_knowledge(
category: Optional[str] = None,
skip: int = 0,
limit: int = 50,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""List knowledge entries for authenticated user's tenant."""
# Use authenticated user's tenant_id (prevents tenant isolation breach)
tenant_id = current_user.tenant_id
stmt = select(KnowledgeBase).where(
KnowledgeBase.tenant_id == tenant_id,
KnowledgeBase.is_active == True
)
if category:
stmt = stmt.where(KnowledgeBase.category == category)
stmt = stmt.order_by(KnowledgeBase.created_at.desc())
stmt = stmt.offset(skip).limit(limit)
result = await session.execute(stmt)
entries = result.scalars().all()
return {
"ok": True,
"count": len(entries),
"entries": [
{
"id": str(entry.id),
"content": entry.content_chunk[:200] + "..." if len(entry.content_chunk) > 200 else entry.content_chunk,
"full_content": entry.content_chunk, # Full content for editing
"category": entry.category,
"source_type": entry.source_type,
"tags": entry.tags,
"created_at": entry.created_at.isoformat()
}
for entry in entries
]
}
@router.post("/upload")
async def upload_file(
file: UploadFile = File(...),
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Upload file (PDF or TXT) and extract knowledge (tenant-isolated)."""
# Use authenticated user's tenant_id (prevents tenant isolation breach)
tenant_id = current_user.tenant_id
try:
content = await file.read()
# Validate file is not empty
if len(content) == 0:
raise HTTPException(status_code=400, detail="Загруженный файл пустой. Пожалуйста, выберите файл с содержимым.")
# Check if it's actually a PDF by magic bytes
if file.filename.endswith('.pdf'):
if not content.startswith(b'%PDF'):
raise HTTPException(
status_code=400,
detail="К сожалению, этот PDF-файл повреждён или имеет нестандартный формат. Рекомендуем сохранить документ как текстовый файл (.txt) и загрузить заново."
)
text = ""
# Extract text based on file type
if file.filename.endswith('.txt'):
text = content.decode('utf-8')
elif file.filename.endswith('.pdf'):
# Try multiple PDF parsing methods
try:
from PyPDF2 import PdfReader
pdf_file = io.BytesIO(content)
reader = PdfReader(pdf_file)
text = "\n".join([page.extract_text() for page in reader.pages])
except Exception as pypdf_error:
# Fallback to pdfplumber if PyPDF2 fails
try:
import pdfplumber
pdf_file = io.BytesIO(content)
with pdfplumber.open(pdf_file) as pdf:
text = "\n".join([page.extract_text() or "" for page in pdf.pages])
except ImportError:
raise HTTPException(
status_code=400,
detail="Не удалось прочитать PDF-файл. Пожалуйста, сохраните документ как текстовый файл (.txt) и загрузите заново."
)
except Exception as plumber_error:
raise HTTPException(
status_code=400,
detail="Не удалось извлечь текст из PDF. Рекомендуем скопировать содержимое и сохранить как текстовый файл (.txt)."
)
else:
raise HTTPException(status_code=400, detail="Поддерживаются только файлы форматов PDF и TXT. Пожалуйста, выберите файл с расширением .pdf или .txt")
if not text.strip():
raise HTTPException(status_code=400, detail="Не удалось извлечь текст из файла. Убедитесь, что документ содержит текстовую информацию.")
# Split into chunks (simple splitting by paragraphs)
chunks = [chunk.strip() for chunk in text.split('\n\n') if chunk.strip() and len(chunk.strip()) > 50]
if not chunks:
# Fallback: treat entire text as one chunk
chunks = [text]
logger.info(f"📄 File upload: {file.filename} split into {len(chunks)} chunks for tenant {tenant_id}")
# Add to vector store
vector_store = get_vector_store()
knowledge_entries = await vector_store.add_knowledge_batch(
session=session,
tenant_id=tenant_id,
chunks=chunks,
source_type="file_upload",
source_file=file.filename,
category="uploaded_docs"
)
logger.info(f"✅ File upload complete: {len(knowledge_entries)} entries created in knowledge_base")
# SIGNAL: Invalidate AI Memory
tenant = await session.get(Tenant, tenant_id)
if tenant:
await get_memory_manager().invalidate_memory(session, tenant)
return {
"ok": True,
"chunks_created": len(knowledge_entries),
"filename": file.filename,
"message": f"Successfully uploaded and processed {file.filename}"
}
except Exception as e:
logger.error(
"Failed to upload file",
filename=file.filename,
error=str(e),
exc_info=True
)
raise
@router.delete("/{knowledge_id}")
async def delete_knowledge(
knowledge_id: UUID,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Delete (soft delete) a knowledge entry (tenant-isolated)."""
# Use authenticated user's tenant_id (prevents tenant isolation breach)
tenant_id = current_user.tenant_id
stmt = select(KnowledgeBase).where(
KnowledgeBase.tenant_id == tenant_id,
KnowledgeBase.id == knowledge_id
)
result = await session.execute(stmt)
knowledge = result.scalar_one_or_none()
if not knowledge:
raise HTTPException(status_code=404, detail="Knowledge not found")
knowledge.is_active = False
session.add(knowledge)
await session.commit()
# SIGNAL: Invalidate AI Memory
tenant = await session.get(Tenant, tenant_id)
if tenant:
await get_memory_manager().invalidate_memory(session, tenant)
return {
"ok": True,
"message": "Knowledge deleted"
}
class KnowledgeUpdate(BaseModel):
"""Input for updating knowledge."""
content: Optional[str] = None
category: Optional[str] = None
@router.put("/{knowledge_id}")
async def update_knowledge(
knowledge_id: UUID,
data: KnowledgeUpdate,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Update a knowledge entry (tenant-isolated)."""
tenant_id = current_user.tenant_id
stmt = select(KnowledgeBase).where(
KnowledgeBase.tenant_id == tenant_id,
KnowledgeBase.id == knowledge_id
)
result = await session.execute(stmt)
knowledge = result.scalar_one_or_none()
if not knowledge:
raise HTTPException(status_code=404, detail="Knowledge not found")
# Update fields
if data.content is not None:
knowledge.content_chunk = data.content
if data.category is not None:
knowledge.category = data.category
session.add(knowledge)
await session.commit()
# SIGNAL: Invalidate AI Memory
tenant = await session.get(Tenant, tenant_id)
if tenant:
await get_memory_manager().invalidate_memory(session, tenant)
return {
"ok": True,
"id": str(knowledge.id),
"message": "Knowledge updated"
}
# ============================================================================
# PAYMENT METHODS API
# ============================================================================
class PaymentMethodInput(BaseModel):
"""Input for creating/updating payment method."""
name: str
payment_type: str = "requisites" # requisites, link, qr_code, image
requisites_text: Optional[str] = None
payment_link: Optional[str] = None
image_url: Optional[str] = None
send_condition: str = "on_request" # on_request, after_agreement, always
ai_instruction: Optional[str] = None
sort_order: int = 0
@router.get("/payment-methods")
async def list_payment_methods(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""List all payment methods for tenant."""
from app.models.knowledge import PaymentMethod
stmt = select(PaymentMethod).where(
PaymentMethod.tenant_id == current_user.tenant_id,
PaymentMethod.is_active == True
).order_by(PaymentMethod.sort_order)
result = await session.execute(stmt)
methods = result.scalars().all()
return [
{
"id": str(m.id),
"name": m.name,
"payment_type": m.payment_type,
"requisites_text": m.requisites_text,
"payment_link": m.payment_link,
"image_url": m.image_url,
"send_condition": m.send_condition,
"ai_instruction": m.ai_instruction,
"sort_order": m.sort_order
}
for m in methods
]
@router.post("/payment-methods")
async def create_payment_method(
data: PaymentMethodInput,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Create new payment method."""
from app.models.knowledge import PaymentMethod
method = PaymentMethod(
tenant_id=current_user.tenant_id,
name=data.name,
payment_type=data.payment_type,
requisites_text=data.requisites_text,
payment_link=data.payment_link,
image_url=data.image_url,
send_condition=data.send_condition,
ai_instruction=data.ai_instruction,
sort_order=data.sort_order
)
session.add(method)
await session.commit()
await session.refresh(method)
return {"ok": True, "id": str(method.id)}
@router.patch("/payment-methods/{method_id}")
async def update_payment_method(
method_id: UUID,
data: PaymentMethodInput,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Update payment method."""
from app.models.knowledge import PaymentMethod
stmt = select(PaymentMethod).where(
PaymentMethod.id == method_id,
PaymentMethod.tenant_id == current_user.tenant_id
)
result = await session.execute(stmt)
method = result.scalar_one_or_none()
if not method:
raise HTTPException(status_code=404, detail="Payment method not found")
method.name = data.name
method.payment_type = data.payment_type
method.requisites_text = data.requisites_text
method.payment_link = data.payment_link
method.image_url = data.image_url
method.send_condition = data.send_condition
method.ai_instruction = data.ai_instruction
method.sort_order = data.sort_order
await session.commit()
return {"ok": True, "id": str(method.id)}
@router.delete("/payment-methods/{method_id}")
async def delete_payment_method(
method_id: UUID,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Delete payment method (soft delete)."""
from app.models.knowledge import PaymentMethod
stmt = select(PaymentMethod).where(
PaymentMethod.id == method_id,
PaymentMethod.tenant_id == current_user.tenant_id
)
result = await session.execute(stmt)
method = result.scalar_one_or_none()
if not method:
raise HTTPException(status_code=404, detail="Payment method not found")
method.is_active = False
await session.commit()
return {"ok": True}
# ============================================================================
# KNOWLEDGE FILES API
# ============================================================================
class KnowledgeFileInput(BaseModel):
"""Input for creating/updating knowledge file.
Universal content delivery:
- on_request: when client asks
- by_day: on specific day of course/program
- by_stage: when lead reaches funnel stage
- by_event: on specific event (purchase, signup)
- ai_decides: AI determines based on instruction
- manual: operator only
"""
name: str
file_type: str = "document" # document, image, video, link, qr, audio
file_url: Optional[str] = None
external_link: Optional[str] = None
thumbnail_url: Optional[str] = None
description: Optional[str] = None
# Flexible send conditions
send_condition: str = "on_request"
trigger_day: Optional[int] = None # For by_day: Day 1, 2, 3...
trigger_stage_id: Optional[str] = None # For by_stage: UUID of SalesStage
trigger_event: Optional[str] = None # For by_event: purchase, booking, signup
# Legacy fields (still supported)
trigger_keywords: Optional[str] = None
trigger_stage: Optional[str] = None # Legacy stage name
ai_instruction: Optional[str] = None
sort_order: int = 0
@router.get("/files")
async def list_knowledge_files(
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""List all knowledge files for tenant."""
from app.models.knowledge import KnowledgeFile
stmt = select(KnowledgeFile).where(
KnowledgeFile.tenant_id == current_user.tenant_id,
KnowledgeFile.is_active == True
).order_by(KnowledgeFile.sort_order)
result = await session.execute(stmt)
files = result.scalars().all()
return [
{
"id": str(f.id),
"name": f.name,
"file_type": f.file_type,
"file_url": f.file_url,
"external_link": f.external_link,
"thumbnail_url": f.thumbnail_url,
"description": f.description,
"send_condition": f.send_condition,
"trigger_day": f.trigger_day,
"trigger_stage_id": str(f.trigger_stage_id) if f.trigger_stage_id else None,
"trigger_event": f.trigger_event,
"trigger_keywords": f.trigger_keywords,
"trigger_stage": f.trigger_stage,
"ai_instruction": f.ai_instruction,
"sort_order": f.sort_order
}
for f in files
]
@router.post("/files")
async def create_knowledge_file(
data: KnowledgeFileInput,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Create new knowledge file."""
from app.models.knowledge import KnowledgeFile
file = KnowledgeFile(
tenant_id=current_user.tenant_id,
name=data.name,
file_type=data.file_type,
file_url=data.file_url,
external_link=data.external_link,
thumbnail_url=data.thumbnail_url,
description=data.description,
send_condition=data.send_condition,
trigger_day=data.trigger_day,
trigger_stage_id=UUID(data.trigger_stage_id) if data.trigger_stage_id else None,
trigger_event=data.trigger_event,
trigger_keywords=data.trigger_keywords,
trigger_stage=data.trigger_stage,
ai_instruction=data.ai_instruction,
sort_order=data.sort_order
)
session.add(file)
await session.commit()
await session.refresh(file)
return {"ok": True, "id": str(file.id)}
@router.patch("/files/{file_id}")
async def update_knowledge_file(
file_id: UUID,
data: KnowledgeFileInput,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Update knowledge file."""
from app.models.knowledge import KnowledgeFile
stmt = select(KnowledgeFile).where(
KnowledgeFile.id == file_id,
KnowledgeFile.tenant_id == current_user.tenant_id
)
result = await session.execute(stmt)
file = result.scalar_one_or_none()
if not file:
raise HTTPException(status_code=404, detail="Knowledge file not found")
file.name = data.name
file.file_type = data.file_type
file.file_url = data.file_url
file.external_link = data.external_link
file.thumbnail_url = data.thumbnail_url
file.description = data.description
file.send_condition = data.send_condition
file.trigger_day = data.trigger_day
file.trigger_stage_id = UUID(data.trigger_stage_id) if data.trigger_stage_id else None
file.trigger_event = data.trigger_event
file.trigger_keywords = data.trigger_keywords
file.trigger_stage = data.trigger_stage
file.ai_instruction = data.ai_instruction
file.sort_order = data.sort_order
await session.commit()
return {"ok": True, "id": str(file.id)}
@router.delete("/files/{file_id}")
async def delete_knowledge_file(
file_id: UUID,
current_user: User = Depends(get_current_user),
session = Depends(get_session)
):
"""Delete knowledge file (soft delete)."""
from app.models.knowledge import KnowledgeFile
stmt = select(KnowledgeFile).where(
KnowledgeFile.id == file_id,
KnowledgeFile.tenant_id == current_user.tenant_id
)
result = await session.execute(stmt)
file = result.scalar_one_or_none()
if not file:
raise HTTPException(status_code=404, detail="Knowledge file not found")
file.is_active = False
await session.commit()
return {"ok": True}
|