File size: 1,943 Bytes
d0cd3f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83e07ca
 
 
 
 
 
 
 
d0cd3f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)