Agentic_RAG / main.py
fansa34's picture
fixedd main 2
83e07ca
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import os
from pathlib import Path
# Import your existing agent functions
from agent_direct_llm_sections import configure_settings, create_agent_instance
app = FastAPI()
# Request model
class QueryRequest(BaseModel):
question: str
# Global agent variable
agent = None
@app.on_event("startup")
async def startup_event():
"""Initialize the agent when API starts"""
global agent
try:
# Check if required files exist
if not Path("./data/section_files").is_dir():
raise Exception("Section files directory not found")
# Check environment variable
if not os.getenv("GOOGLE_API_KEY"):
raise Exception("GOOGLE_API_KEY not set")
# Initialize agent
configure_settings()
agent = create_agent_instance()
print("βœ… Agent initialized successfully!")
except Exception as e:
print(f"❌ Failed to initialize agent: {e}")
agent = None
@app.get("/")
async def root():
return {"message": "Agentic RAG API is running. Use POST /ask."}
@app.post("/ask")
async def ask_question(request: QueryRequest):
"""Send a question and get an answer"""
if agent is None:
raise HTTPException(status_code=503, detail="Agent not initialized")
if not request.question.strip():
raise HTTPException(status_code=400, detail="Question cannot be empty")
try:
# Get response from agent
response = agent.chat(request.question)
return {"answer": str(response.response)}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
if __name__ == "__main__":
import uvicorn
# Use port 7860 for Hugging Face Spaces
port = int(os.environ.get("PORT", 7860))
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=False)