creativesar/face
0
1from fastapi import APIRouter, HTTPException, Depends2from pydantic import BaseModel3from typing import List, Optional4import logging5import os6from dotenv import load_dotenv7 8# Load environment variables9load_dotenv()10 11# Import services12from services.optimized_openrouter_rag_service import OptimizedOpenRouterRAGService13from services.qdrant_service import QdrantService14from services.openrouter_service import OpenRouterService15 16# Configure logging17logging.basicConfig(level=logging.INFO)18logger = logging.getLogger(__name__)19 20# Load environment variables21load_dotenv()22 23# Initialize services with OpenRouter24openrouter_service = OpenRouterService()25qdrant_service = QdrantService()26rag_service = OptimizedOpenRouterRAGService(openrouter_service, qdrant_service)27 28router = APIRouter()29 30class ChatQuery(BaseModel):31 query: str32 user_id: Optional[str] = None33 session_id: Optional[str] = None34 35class ChatResponse(BaseModel):36 answer: str37 sources: List[dict]38 query_embedding: Optional[List[float]] = None39 40class ContentIndexRequest(BaseModel):41 content: str42 chapter_id: str43 section_title: str44 source_url: str45 46@router.post("/query", response_model=ChatResponse)47async def query_chat(query_data: ChatQuery):48 """49 Process a chat query using RAG (Retrieval Augmented Generation)50 """51 try:52 logger.info(f"Processing query: {query_data.query}")53 54 # Use RAG service to get response55 result = await rag_service.process_query(56 query=query_data.query,57 user_id=query_data.user_id58 )59 60 return ChatResponse(61 answer=result["answer"],62 sources=result["sources"],63 query_embedding=result.get("query_embedding")64 )65 except Exception as e:66 logger.error(f"Error processing query: {str(e)}")67 raise HTTPException(status_code=500, detail=str(e))68 69@router.post("/index-content")70async def index_content(content_data: ContentIndexRequest):71 """72 Index content for RAG retrieval73 """74 try:75 logger.info(f"Indexing content for chapter: {content_data.chapter_id}")76 77 # Index the content using the RAG service78 result = await rag_service.index_content(79 content=content_data.content,80 chapter_id=content_data.chapter_id,81 section_title=content_data.section_title,82 source_url=content_data.source_url83 )84 85 return {"success": True, "document_id": result["document_id"]}86 except Exception as e:87 logger.error(f"Error indexing content: {str(e)}")88 raise HTTPException(status_code=500, detail=str(e))89 90@router.get("/test-connection")91async def test_connection():92 """93 Test connection to all services94 """95 try:96 # Test OpenRouter connection97 openrouter_status = await openrouter_service.test_connection()98 99 # Test Qdrant connection100 qdrant_status = await qdrant_service.test_connection()101 102 return {103 "openrouter": openrouter_status,104 "qdrant": qdrant_status,105 "overall": openrouter_status and qdrant_status106 }107 except Exception as e:108 logger.error(f"Error testing connections: {str(e)}")109 raise HTTPException(status_code=500, detail=str(e))