Spaces:
Runtime error

File size: 10,763 Bytes
2ec5a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, HttpUrl
from typing import List, Optional
import requests
from bs4 import BeautifulSoup
from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.documents import Document
from groq import Groq
import tempfile
import os
import uuid

# Initialize FastAPI app
app = FastAPI(
    title="RAG Chatbot API",
    description="FastAPI-based RAG chatbot with PDF and web scraping support",
    version="1.0.0"
)

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

# In-memory storage for vector databases and chat sessions
sessions = {}

# Pydantic models
class ChatRequest(BaseModel):
    session_id: str
    message: str
    api_key: str
    model: str = "llama-3.1-8b-instant"

class ChatResponse(BaseModel):
    session_id: str
    question: str
    answer: str

class WebScrapingRequest(BaseModel):
    url: HttpUrl
    session_id: Optional[str] = None

class SessionResponse(BaseModel):
    session_id: str
    message: str
    num_chunks: int
    rag_type: str

class SessionInfo(BaseModel):
    session_id: str
    rag_type: Optional[str]
    chat_history: List[dict]
    has_vector_db: bool

# Helper functions
def load_embeddings():
    """Load HuggingFace embeddings model"""
    return HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")

def process_pdf(file_path: str):
    """Process PDF file"""
    try:
        loader = PyPDFLoader(file_path)
        docs = loader.load()
        return docs
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error processing PDF: {str(e)}")

def create_vector_db(documents, embeddings):
    """Create FAISS vector database from documents"""
    try:
        text_splitter = CharacterTextSplitter(
            chunk_size=1000,
            chunk_overlap=200
        )
        chunks = text_splitter.split_documents(documents)
        vector_db = FAISS.from_documents(chunks, embeddings)
        return vector_db, len(chunks)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error creating vector database: {str(e)}")

def scrape_website(url: str):
    """Scrape website content"""
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, "html.parser")
        
        texts = []
        for tag in soup.find_all(["p", "li", "a", "td", "h1", "h2", "h3"]):
            text = tag.get_text(strip=True)
            if text and len(text) > 30:
                texts.append(text)
        
        full_text = "\n".join(texts)
        
        document = Document(
            page_content=full_text,
            metadata={"source": url}
        )
        
        return [document]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error scraping website: {str(e)}")

def generate_response(message: str, vector_db, api_key: str, model: str):
    """Generate chatbot response using RAG"""
    try:
        # Retrieve relevant chunks
        result = vector_db.similarity_search(message, k=3)
        context = []
        for i in result:
            context.append(f"Chunk: {i.page_content}")
        
        # Create Groq client
        client = Groq(api_key=api_key)
        
        prompt = """

You are a smart chatbot. You need to respond to user questions only by referring to the data present within the below knowledge base.

Don't give any reference to the chunk which you are referring to. Just return a well-structured response as the answer to the user question.

"""
        
        finalprompt = f"{prompt}\n\nKnowledge Base: {context}"
        
        completion = client.chat.completions.create(
            model=model,
            messages=[
                {
                    "role": "system",
                    "content": finalprompt
                },
                {
                    "role": "user",
                    "content": message
                }
            ],
            temperature=0,
            max_completion_tokens=1024
        )
        
        return completion.choices[0].message.content
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error generating response: {str(e)}")

# API Endpoints
@app.get("/")
async def root():
    return {
        "message": "RAG Chatbot API",
        "version": "1.0.0",
        "endpoints": {
            "POST /session/create": "Create a new session",
            "POST /upload/pdf": "Upload and process PDF",
            "POST /scrape/web": "Scrape website content",
            "POST /chat": "Send a chat message",
            "GET /session/{session_id}": "Get session info",
            "DELETE /session/{session_id}": "Delete a session"
        }
    }

@app.post("/session/create")
async def create_session():
    """Create a new chat session"""
    session_id = str(uuid.uuid4())
    sessions[session_id] = {
        "vector_db": None,
        "chat_history": [],
        "rag_type": None
    }
    return {"session_id": session_id, "message": "Session created successfully"}

@app.post("/upload/pdf", response_model=SessionResponse)
async def upload_pdf(

    file: UploadFile = File(...),

    session_id: Optional[str] = Form(None)

):
    """Upload and process a PDF file"""
    # Create session if not provided
    if not session_id:
        session_id = str(uuid.uuid4())
        sessions[session_id] = {
            "vector_db": None,
            "chat_history": [],
            "rag_type": None
        }
    
    if session_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")
    
    # Validate file type
    if not file.filename.endswith('.pdf'):
        raise HTTPException(status_code=400, detail="Only PDF files are supported")
    
    # Save uploaded file temporarily
    with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
        content = await file.read()
        tmp_file.write(content)
        tmp_path = tmp_file.name
    
    try:
        # Load embeddings
        embeddings = load_embeddings()
        
        # Process PDF
        docs = process_pdf(tmp_path)
        
        # Create vector database
        vector_db, num_chunks = create_vector_db(docs, embeddings)
        
        # Store in session
        sessions[session_id]["vector_db"] = vector_db
        sessions[session_id]["rag_type"] = "PDF"
        sessions[session_id]["chat_history"] = []
        
        return SessionResponse(
            session_id=session_id,
            message="PDF processed successfully",
            num_chunks=num_chunks,
            rag_type="PDF"
        )
    finally:
        # Clean up temp file
        os.unlink(tmp_path)

@app.post("/scrape/web", response_model=SessionResponse)
async def scrape_web(request: WebScrapingRequest):
    """Scrape website and create vector database"""
    # Create session if not provided
    session_id = request.session_id or str(uuid.uuid4())
    
    if session_id not in sessions:
        sessions[session_id] = {
            "vector_db": None,
            "chat_history": [],
            "rag_type": None
        }
    
    # Load embeddings
    embeddings = load_embeddings()
    
    # Scrape website
    documents = scrape_website(str(request.url))
    
    # Create vector database
    vector_db, num_chunks = create_vector_db(documents, embeddings)
    
    # Store in session
    sessions[session_id]["vector_db"] = vector_db
    sessions[session_id]["rag_type"] = "Web"
    sessions[session_id]["chat_history"] = []
    
    return SessionResponse(
        session_id=session_id,
        message="Website scraped successfully",
        num_chunks=num_chunks,
        rag_type="Web"
    )

@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
    """Send a chat message and get a response"""
    if request.session_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")
    
    session = sessions[request.session_id]
    
    if session["vector_db"] is None:
        raise HTTPException(
            status_code=400,
            detail="No knowledge base loaded. Please upload a PDF or scrape a website first."
        )
    
    # Generate response
    answer = generate_response(
        request.message,
        session["vector_db"],
        request.api_key,
        request.model
    )
    
    # Store in chat history
    chat_entry = {
        "question": request.message,
        "answer": answer
    }
    session["chat_history"].append(chat_entry)
    
    return ChatResponse(
        session_id=request.session_id,
        question=request.message,
        answer=answer
    )

@app.get("/session/{session_id}", response_model=SessionInfo)
async def get_session(session_id: str):
    """Get session information"""
    if session_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")
    
    session = sessions[session_id]
    
    return SessionInfo(
        session_id=session_id,
        rag_type=session["rag_type"],
        chat_history=session["chat_history"],
        has_vector_db=session["vector_db"] is not None
    )

@app.delete("/session/{session_id}")
async def delete_session(session_id: str):
    """Delete a session"""
    if session_id not in sessions:
        raise HTTPException(status_code=404, detail="Session not found")
    
    del sessions[session_id]
    return {"message": "Session deleted successfully"}

@app.get("/sessions")
async def list_sessions():
    """List all active sessions"""
    session_list = []
    for session_id, data in sessions.items():
        session_list.append({
            "session_id": session_id,
            "rag_type": data["rag_type"],
            "has_vector_db": data["vector_db"] is not None,
            "chat_count": len(data["chat_history"])
        })
    return {"sessions": session_list}

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