File size: 6,071 Bytes
97f9138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, HttpUrl
from typing import Optional
import uuid
import logging
from src.database import db
from src.queue_manager import queue_manager
from src.vector_store import vector_store
from src.embeddings import embedding_service
from groq import Groq
from src.config import config

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="RAG System API", version="1.0.0")

class IngestURLRequest(BaseModel):
    url: HttpUrl

class QueryRequest(BaseModel):
    question: str
    top_k: Optional[int] = None

class IngestURLResponse(BaseModel):
    url_id: str
    url: str
    status: str
    message: str

class StatusResponse(BaseModel):
    url_id: str
    url: str
    status: str
    created_at: str
    updated_at: str
    completed_at: Optional[str] = None
    chunk_count: int
    error_message: Optional[str] = None

class QueryResponse(BaseModel):
    question: str
    answer: str
    sources: list

@app.on_event("startup")
async def startup_event():
    logger.info("Starting RAG System API...")
    logger.info(f"Database path: {config.DATABASE_PATH}")
    logger.info(f"Redis: {config.REDIS_HOST}:{config.REDIS_PORT}")
    logger.info(f"Qdrant: {config.QDRANT_HOST}:{config.QDRANT_PORT}")

@app.get("/")
async def root():
    return {
        "message": "RAG System API",
        "version": "1.0.0",
        "endpoints": {
            "ingest": "POST /ingest-url",
            "query": "POST /query",
            "status": "GET /status/{url_id}"
        }
    }

@app.post("/ingest-url", response_model=IngestURLResponse, status_code=202)
async def ingest_url(request: IngestURLRequest):
    try:
        url = str(request.url)
        url_id = str(uuid.uuid4())
        
        db.create_url_record(url_id, url)
        
        job_data = {
            "url_id": url_id,
            "url": url
        }
        queue_manager.enqueue(job_data)
        
        logger.info(f"Enqueued URL for processing: {url} (ID: {url_id})")
        
        return IngestURLResponse(
            url_id=url_id,
            url=url,
            status="pending",
            message="URL has been queued for processing"
        )
    
    except Exception as e:
        logger.error(f"Error enqueueing URL: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error processing request: {str(e)}")

@app.get("/status/{url_id}", response_model=StatusResponse)
async def get_status(url_id: str):
    record = db.get_url_record(url_id)
    
    if not record:
        raise HTTPException(status_code=404, detail="URL ID not found")
    
    return StatusResponse(
        url_id=record["id"],
        url=record["url"],
        status=record["status"],
        created_at=record["created_at"],
        updated_at=record["updated_at"],
        completed_at=record.get("completed_at"),
        chunk_count=record.get("chunk_count", 0),
        error_message=record.get("error_message")
    )

@app.post("/query", response_model=QueryResponse)
async def query_knowledge_base(request: QueryRequest):
    try:
        if not config.GROQ_API_KEY:
            raise HTTPException(
                status_code=500,
                detail="GROQ_API_KEY not configured. Please set it in your .env file"
            )
        
        question = request.question
        top_k = request.top_k or config.TOP_K_RESULTS
        
        query_embedding = embedding_service.embed_text(question)
        
        search_results = vector_store.search(query_embedding, top_k=top_k)
        
        if not search_results:
            return QueryResponse(
                question=question,
                answer="I don't have enough information in my knowledge base to answer this question. Please ingest relevant URLs first.",
                sources=[]
            )
        
        context_parts = []
        sources = []
        for i, result in enumerate(search_results):
            context_parts.append(f"[Source {i+1}]: {result['text']}")
            sources.append({
                "url": result["url"],
                "score": result["score"],
                "text_snippet": result["text"][:200] + "..." if len(result["text"]) > 200 else result["text"]
            })
        
        context = "\n\n".join(context_parts)
        
        system_prompt = """You are a helpful AI assistant that answers questions based solely on the provided context. 
Your responses must be:
1. Grounded in the provided sources
2. Accurate and factual
3. Clear and concise
4. If the context doesn't contain relevant information, say so explicitly."""

        user_prompt = f"""Context from knowledge base:

{context}

Question: {question}

Please provide a clear, grounded answer based only on the information in the context above. If the context doesn't contain enough information to answer the question, please say so."""

        groq_client = Groq(api_key=config.GROQ_API_KEY)
        
        chat_completion = groq_client.chat.completions.create(
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            model="llama-3.3-70b-versatile",
            temperature=0.3,
            max_tokens=1024
        )
        
        answer = chat_completion.choices[0].message.content
        
        logger.info(f"Query processed: {question[:100]}...")
        
        return QueryResponse(
            question=question,
            answer=answer,
            sources=sources
        )
    
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error processing query: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error processing query: {str(e)}")

@app.get("/health")
async def health_check():
    redis_ok = queue_manager.ping()
    
    return {
        "status": "healthy",
        "redis_connected": redis_ok,
        "queue_length": queue_manager.get_queue_length() if redis_ok else None
    }