File size: 10,876 Bytes
1d10b0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
"""FastAPI backend service for RAG application."""
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional, Dict
import uvicorn
from datetime import datetime
import os

from config import settings
from dataset_loader import RAGBenchLoader
from vector_store import ChromaDBManager
from llm_client import GroqLLMClient, RAGPipeline
from trace_evaluator import TRACEEvaluator

# Initialize FastAPI app
app = FastAPI(
    title="RAG Capstone API",
    description="API for RAG system with TRACE evaluation",
    version="1.0.0"
)

# Add CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global state
rag_pipeline: Optional[RAGPipeline] = None
vector_store: Optional[ChromaDBManager] = None
current_collection: Optional[str] = None


# Request/Response models
class DatasetLoadRequest(BaseModel):
    """Request model for loading dataset."""
    dataset_name: str = Field(..., description="Name of the dataset")
    num_samples: int = Field(50, description="Number of samples to load")
    chunking_strategy: str = Field("hybrid", description="Chunking strategy")
    chunk_size: int = Field(512, description="Size of chunks")
    overlap: int = Field(50, description="Overlap between chunks")
    embedding_model: str = Field(..., description="Embedding model name")
    llm_model: str = Field("llama-3.1-8b-instant", description="LLM model name")
    groq_api_key: str = Field(..., description="Groq API key")


class QueryRequest(BaseModel):
    """Request model for querying."""
    query: str = Field(..., description="User query")
    n_results: int = Field(5, description="Number of documents to retrieve")
    max_tokens: int = Field(1024, description="Maximum tokens to generate")
    temperature: float = Field(0.7, description="Sampling temperature")


class QueryResponse(BaseModel):
    """Response model for query."""
    query: str
    response: str
    retrieved_documents: List[Dict]
    timestamp: str


class EvaluationRequest(BaseModel):
    """Request model for evaluation."""
    num_samples: int = Field(10, description="Number of test samples")


class CollectionInfo(BaseModel):
    """Collection information model."""
    name: str
    count: int
    metadata: Dict


# API endpoints
@app.get("/")
async def root():
    """Root endpoint."""
    return {
        "message": "RAG Capstone API",
        "version": "1.0.0",
        "docs": "/docs"
    }


@app.get("/health")
async def health_check():
    """Health check endpoint."""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat()
    }


@app.get("/datasets")
async def list_datasets():
    """List available datasets."""
    return {
        "datasets": settings.ragbench_datasets
    }


@app.get("/models/embedding")
async def list_embedding_models():
    """List available embedding models."""
    return {
        "embedding_models": settings.embedding_models
    }


@app.get("/models/llm")
async def list_llm_models():
    """List available LLM models."""
    return {
        "llm_models": settings.llm_models
    }


@app.get("/chunking-strategies")
async def list_chunking_strategies():
    """List available chunking strategies."""
    return {
        "chunking_strategies": settings.chunking_strategies
    }


@app.get("/collections")
async def list_collections():
    """List all vector store collections."""
    global vector_store
    
    if not vector_store:
        vector_store = ChromaDBManager(settings.chroma_persist_directory)
    
    collections = vector_store.list_collections()
    
    return {
        "collections": collections,
        "count": len(collections)
    }


@app.get("/collections/{collection_name}")
async def get_collection_info(collection_name: str):
    """Get information about a specific collection."""
    global vector_store
    
    if not vector_store:
        vector_store = ChromaDBManager(settings.chroma_persist_directory)
    
    try:
        stats = vector_store.get_collection_stats(collection_name)
        return stats
    except Exception as e:
        raise HTTPException(status_code=404, detail=f"Collection not found: {str(e)}")


@app.post("/load-dataset")
async def load_dataset(request: DatasetLoadRequest, background_tasks: BackgroundTasks):
    """Load dataset and create vector collection."""
    global rag_pipeline, vector_store, current_collection
    
    try:
        # Initialize dataset loader
        loader = RAGBenchLoader()
        
        # Load dataset
        dataset = loader.load_dataset(
            request.dataset_name,
            split="train",
            max_samples=request.num_samples
        )
        
        if not dataset:
            raise HTTPException(status_code=400, detail="Failed to load dataset")
        
        # Initialize vector store
        vector_store = ChromaDBManager(settings.chroma_persist_directory)
        
        # Create collection name
        collection_name = f"{request.dataset_name}_{request.chunking_strategy}_{request.embedding_model.split('/')[-1]}"
        collection_name = collection_name.replace("-", "_").replace(".", "_")
        
        # Load data into collection
        vector_store.load_dataset_into_collection(
            collection_name=collection_name,
            embedding_model_name=request.embedding_model,
            chunking_strategy=request.chunking_strategy,
            dataset_data=dataset,
            chunk_size=request.chunk_size,
            overlap=request.overlap
        )
        
        # Initialize LLM client
        llm_client = GroqLLMClient(
            api_key=request.groq_api_key,
            model_name=request.llm_model,
            max_rpm=settings.groq_rpm_limit,
            rate_limit_delay=settings.rate_limit_delay
        )
        
        # Create RAG pipeline
        rag_pipeline = RAGPipeline(llm_client, vector_store)
        current_collection = collection_name
        
        return {
            "status": "success",
            "collection_name": collection_name,
            "num_documents": len(dataset),
            "message": f"Collection '{collection_name}' created successfully"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error loading dataset: {str(e)}")


@app.post("/query", response_model=QueryResponse)
async def query_rag(request: QueryRequest):
    """Query the RAG system."""
    global rag_pipeline
    
    if not rag_pipeline:
        raise HTTPException(
            status_code=400,
            detail="RAG pipeline not initialized. Load a dataset first."
        )
    
    try:
        result = rag_pipeline.query(
            query=request.query,
            n_results=request.n_results,
            max_tokens=request.max_tokens,
            temperature=request.temperature
        )
        
        result["timestamp"] = datetime.now().isoformat()
        
        return result
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error processing query: {str(e)}")


@app.get("/chat-history")
async def get_chat_history():
    """Get chat history."""
    global rag_pipeline
    
    if not rag_pipeline:
        raise HTTPException(
            status_code=400,
            detail="RAG pipeline not initialized. Load a dataset first."
        )
    
    return {
        "history": rag_pipeline.get_chat_history()
    }


@app.delete("/chat-history")
async def clear_chat_history():
    """Clear chat history."""
    global rag_pipeline
    
    if not rag_pipeline:
        raise HTTPException(
            status_code=400,
            detail="RAG pipeline not initialized. Load a dataset first."
        )
    
    rag_pipeline.clear_history()
    
    return {
        "status": "success",
        "message": "Chat history cleared"
    }


@app.post("/evaluate")
async def run_evaluation(request: EvaluationRequest):
    """Run TRACE evaluation."""
    global rag_pipeline, current_collection
    
    if not rag_pipeline:
        raise HTTPException(
            status_code=400,
            detail="RAG pipeline not initialized. Load a dataset first."
        )
    
    try:
        # Get dataset name from collection metadata
        collection_metadata = vector_store.current_collection.metadata
        dataset_name = current_collection.split("_")[0] if current_collection else "hotpotqa"
        
        # Get test data
        loader = RAGBenchLoader()
        test_data = loader.get_test_data(dataset_name, request.num_samples)
        
        # Prepare test cases
        test_cases = []
        
        for sample in test_data:
            result = rag_pipeline.query(sample["question"], n_results=5)
            
            test_cases.append({
                "query": sample["question"],
                "response": result["response"],
                "retrieved_documents": [doc["document"] for doc in result["retrieved_documents"]],
                "ground_truth": sample.get("answer", "")
            })
        
        # Run evaluation
        evaluator = TRACEEvaluator()
        results = evaluator.evaluate_batch(test_cases)
        
        return {
            "status": "success",
            "results": results
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error during evaluation: {str(e)}")


@app.delete("/collections/{collection_name}")
async def delete_collection(collection_name: str):
    """Delete a collection."""
    global vector_store
    
    if not vector_store:
        vector_store = ChromaDBManager(settings.chroma_persist_directory)
    
    try:
        vector_store.delete_collection(collection_name)
        return {
            "status": "success",
            "message": f"Collection '{collection_name}' deleted"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error deleting collection: {str(e)}")


@app.get("/current-collection")
async def get_current_collection():
    """Get current collection information."""
    global current_collection, vector_store
    
    if not current_collection:
        return {
            "collection": None,
            "message": "No collection loaded"
        }
    
    try:
        stats = vector_store.get_collection_stats(current_collection)
        return {
            "collection": current_collection,
            "stats": stats
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error getting collection info: {str(e)}")


if __name__ == "__main__":
    uvicorn.run(
        "api:app",
        host="0.0.0.0",
        port=8000,
        reload=True
    )