125 lines
3.5 KiB
Python
125 lines
3.5 KiB
Python
import os
|
|
from fastapi import FastAPI, Request, Form, HTTPException
|
|
from fastapi.templating import Jinja2Templates
|
|
from fastapi.responses import HTMLResponse
|
|
from contextlib import asynccontextmanager
|
|
from loguru import logger
|
|
import uvicorn
|
|
|
|
from rag_service import rag_service
|
|
from models import QuestionRequest, QuestionResponse, HealthResponse
|
|
|
|
|
|
# Template configuration
|
|
templates = Jinja2Templates(directory=os.environ["TEMPLATES_DIR"])
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Application lifespan handler."""
|
|
try:
|
|
logger.info("Starting application...")
|
|
logger.info("Initializing RAG system...")
|
|
await rag_service.initialize()
|
|
logger.success("Application started successfully")
|
|
except Exception as e:
|
|
logger.error(f"Failed to initialize RAG system: {e}")
|
|
# Don't exit - allow the app to run for diagnostics
|
|
|
|
yield # Application runs here
|
|
|
|
logger.info("Shutting down application...")
|
|
|
|
|
|
# Create FastAPI app
|
|
app = FastAPI(
|
|
title="Pre-historic Knowledge Assistant",
|
|
description="A RAG-based knowledge assistant",
|
|
version="1.0.0",
|
|
lifespan=lifespan
|
|
)
|
|
|
|
|
|
# Web interface routes
|
|
@app.get("/", response_class=HTMLResponse)
|
|
async def home(request: Request):
|
|
"""Render the main page."""
|
|
return templates.TemplateResponse(
|
|
"index.html", {"request": request}
|
|
)
|
|
|
|
|
|
@app.post("/ask", response_class=HTMLResponse)
|
|
async def ask_question(request: Request, question: str = Form(...)):
|
|
"""Process a question and return the response."""
|
|
if not rag_service.is_initialized():
|
|
return templates.TemplateResponse(
|
|
"index.html",
|
|
{
|
|
"request": request,
|
|
"error": "RAG system not available. Please restart the server."
|
|
}
|
|
)
|
|
|
|
try:
|
|
response = await rag_service.query(question)
|
|
|
|
return templates.TemplateResponse(
|
|
"index.html",
|
|
{
|
|
"request": request,
|
|
"question": question,
|
|
"answer": response
|
|
}
|
|
)
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error processing question: {e}")
|
|
return templates.TemplateResponse(
|
|
"index.html",
|
|
{
|
|
"request": request,
|
|
"question": question,
|
|
"error": f"Error: {str(e)}"
|
|
}
|
|
)
|
|
|
|
|
|
# API routes
|
|
@app.post("/api/ask", response_model=QuestionResponse)
|
|
async def ask_question_api(request: QuestionRequest):
|
|
"""API endpoint for question processing."""
|
|
if not rag_service.is_initialized():
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail="RAG system not available"
|
|
)
|
|
|
|
try:
|
|
response = await rag_service.query(
|
|
request.question,
|
|
mode=request.mode,
|
|
response_type=request.response_type
|
|
)
|
|
return QuestionResponse(question=request.question, answer=response)
|
|
except Exception as e:
|
|
logger.error(f"Error processing question: {e}")
|
|
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
|
|
@app.get("/api/health", response_model=HealthResponse)
|
|
async def health_check():
|
|
"""Health check endpoint."""
|
|
return HealthResponse(
|
|
status="healthy" if rag_service.is_initialized() else "unhealthy",
|
|
rag_initialized=rag_service.is_initialized()
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run(
|
|
"gui.app:app",
|
|
host="0.0.0.0",
|
|
port=int(os.environ["WEBUI_PORT"]),
|
|
reload=True
|
|
) |