File size: 13,428 Bytes
7b7cab6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import tempfile
import zipfile
from typing import List, Optional

from fastapi import FastAPI, File, UploadFile, HTTPException, Query
from fastapi.responses import FileResponse, StreamingResponse

from llm_initialization import get_llm
from embedding import get_embeddings
from document_loaders import DocumentLoader
from text_splitter import TextSplitter
from vector_store import VectorStoreManager
from prompt_templates import PromptTemplates
from chat_management import ChatManagement
from retrieval_chain import RetrievalChain
from urllib.parse import quote_plus
from dotenv import load_dotenv
from pymongo import MongoClient

# Load environment variables
load_dotenv()
MONGO_PASSWORD = quote_plus(os.getenv("MONGO_PASSWORD"))
MONGO_DATABASE_NAME = os.getenv("DATABASE_NAME")
MONGO_COLLECTION_NAME = os.getenv("COLLECTION_NAME")
MONGO_CLUSTER_URL = os.getenv("CONNECTION_STRING")

app = FastAPI(title="VectorStore & Document Management API")

# Global variables (initialized on startup)
llm = None
embeddings = None
chat_manager = None
document_loader = None
text_splitter = None
vector_store_manager = None
vector_store = None
k = 3  # Number of documents to retrieve per query

# Global MongoDB collection to store retrieval chain configuration per chat session.
chat_chains_collection = None

# ----------------------- Startup Event -----------------------
@app.on_event("startup")
async def startup_event():
    global llm, embeddings, chat_manager, document_loader, text_splitter, vector_store_manager, vector_store, chat_chains_collection

    print("Starting up: Initializing components...")

    # Initialize LLM and embeddings
    llm = get_llm()
    print("LLM initialized.")
    embeddings = get_embeddings()
    print("Embeddings initialized.")

    # Setup chat management
    chat_manager = ChatManagement(
        cluster_url=MONGO_CLUSTER_URL,
        database_name=MONGO_DATABASE_NAME,
        collection_name=MONGO_COLLECTION_NAME,
    )
    print("Chat management initialized.")

    # Initialize document loader and text splitter
    document_loader = DocumentLoader()
    text_splitter = TextSplitter()
    print("Document loader and text splitter initialized.")

    # Initialize vector store manager and ensure vectorstore is set
    vector_store_manager = VectorStoreManager(embeddings)
    vector_store = vector_store_manager.vectorstore  # Now properly initialized
    print("Vector store initialized.")

    # Connect to MongoDB and get the collection.
    client = MongoClient(MONGO_CLUSTER_URL)
    db = client[MONGO_DATABASE_NAME]
    chat_chains_collection = db["chat_chains"]
    print("Chat chains collection initialized in MongoDB.")


# ----------------------- Root Endpoint -----------------------
@app.get("/")
def root():
    """
    Root endpoint that returns a welcome message.
    """
    return {"message": "Welcome to the VectorStore & Document Management API!"}


# ----------------------- New Chat Endpoint -----------------------
@app.post("/new_chat")
def new_chat():
    """
    Create a new chat session.
    """
    new_chat_id = chat_manager.create_new_chat()
    return {"chat_id": new_chat_id}


# ----------------------- Create Chain Endpoint -----------------------
@app.post("/create_chain")
def create_chain(
    chat_id: str = Query(..., description="Existing chat session ID"),
    template: str = Query(
        "quiz_solving",
        description="Select prompt template. Options: quiz_solving, assignment_solving, paper_solving, quiz_creation, assignment_creation, paper_creation",
    ),
):
    global chat_chains_collection  # Ensure we reference the global variable

    valid_templates = [
        "quiz_solving",
        "assignment_solving",
        "paper_solving",
        "quiz_creation",
        "assignment_creation",
        "paper_creation",
    ]
    if template not in valid_templates:
        raise HTTPException(status_code=400, detail="Invalid template selection.")

    # Upsert the configuration document for this chat session.
    chat_chains_collection.update_one(
        {"chat_id": chat_id}, {"$set": {"template": template}}, upsert=True
    )

    return {"message": "Retrieval chain configuration stored successfully.", "chat_id": chat_id, "template": template}


# ----------------------- Chat Endpoint -----------------------
@app.get("/chat")
def chat(query: str, chat_id: str = Query(..., description="Chat session ID created via /new_chat and configured via /create_chain")):
    """
    Process a chat query using the retrieval chain associated with the given chat_id.
    
    This endpoint uses the following code:
    
        try:
            stream_generator = retrieval_chain.stream_chat_response(
                query=query,
                chat_id=chat_id,
                get_chat_history=chat_manager.get_chat_history,
                initialize_chat_history=chat_manager.initialize_chat_history,
            )
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Error processing chat query: {str(e)}")
    
        return StreamingResponse(stream_generator, media_type="text/event-stream")
    
    It first retrieves the configuration from MongoDB, re-creates the chain, and then streams the response.
    """
    # Retrieve the chat configuration from MongoDB.
    config = chat_chains_collection.find_one({"chat_id": chat_id})
    if not config:
        raise HTTPException(status_code=400, detail="Chat configuration not found. Please create a chain using /create_chain.")

    template = config.get("template", "quiz_solving")
    if template == "quiz_solving":
        prompt = PromptTemplates.get_quiz_solving_prompt()
    elif template == "assignment_solving":
        prompt = PromptTemplates.get_assignment_solving_prompt()
    elif template == "paper_solving":
        prompt = PromptTemplates.get_paper_solving_prompt()
    elif template == "quiz_creation":
        prompt = PromptTemplates.get_quiz_creation_prompt()
    elif template == "assignment_creation":
        prompt = PromptTemplates.get_assignment_creation_prompt()
    elif template == "paper_creation":
        prompt = PromptTemplates.get_paper_creation_prompt()
    else:
        raise HTTPException(status_code=400, detail="Invalid chat configuration.")

    # Re-create the retrieval chain for this chat session.
    retrieval_chain = RetrievalChain(
        llm,
        vector_store.as_retriever(search_kwargs={"k": k}),
        prompt,
        verbose=True,
    )

    try:
        stream_generator = retrieval_chain.stream_chat_response(
            query=query,
            chat_id=chat_id,
            get_chat_history=chat_manager.get_chat_history,
            initialize_chat_history=chat_manager.initialize_chat_history,
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error processing chat query: {str(e)}")

    return StreamingResponse(stream_generator, media_type="text/event-stream")


# ----------------------- Add Document Endpoint -----------------------
from typing import Any, Optional

@app.post("/add_document")
async def add_document(
    file: Optional[Any] = File(None),
    wiki_query: Optional[str] = Query(None),
    wiki_url: Optional[str] = Query(None)
):
    """
    Upload a document OR load data from a Wikipedia query or URL.
    
    - If a file is provided, the document is loaded from the file.
    - If 'wiki_query' is provided, the Wikipedia page(s) are loaded using document_loader.wikipedia_query.
    - If 'wiki_url' is provided, the URL is loaded using document_loader.load_urls.
    
    The loaded document(s) are then split into chunks and added to the vector store.
    """
    # If file is provided but not as an UploadFile (e.g. an empty string), set it to None.
    if not isinstance(file, UploadFile):
        file = None

    # Ensure at least one input is provided.
    if file is None and wiki_query is None and wiki_url is None:
        raise HTTPException(status_code=400, detail="No document input provided (file, wiki_query, or wiki_url).")

    # Load document(s) based on input priority: file > wiki_query > wiki_url.
    if file is not None:
        with tempfile.NamedTemporaryFile(delete=False) as tmp:
            contents = await file.read()
            tmp.write(contents)
            tmp_filename = tmp.name

        ext = file.filename.split(".")[-1].lower()
        try:
            if ext == "pdf":
                documents = document_loader.load_pdf(tmp_filename)
            elif ext == "csv":
                documents = document_loader.load_csv(tmp_filename)
            elif ext in ["doc", "docx"]:
                documents = document_loader.load_doc(tmp_filename)
            elif ext in ["html", "htm"]:
                documents = document_loader.load_text_from_html(tmp_filename)
            elif ext in ["md", "markdown"]:
                documents = document_loader.load_markdown(tmp_filename)
            else:
                documents = document_loader.load_unstructured(tmp_filename)
        except Exception as e:
            os.remove(tmp_filename)
            raise HTTPException(status_code=400, detail=f"Error loading document from file: {str(e)}")
        os.remove(tmp_filename)
    elif wiki_query is not None:
        try:
            documents = document_loader.wikipedia_query(wiki_query)
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Error loading Wikipedia query: {str(e)}")
    elif wiki_url is not None:
        try:
            documents = document_loader.load_urls([wiki_url])
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Error loading URL: {str(e)}")

    try:
        chunks = text_splitter.split_documents(documents)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error splitting document: {str(e)}")

    try:
        ids = vector_store_manager.add_documents(chunks)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error indexing document chunks: {str(e)}")

    return {"message": f"Added {len(chunks)} document chunks.", "ids": ids}


# ----------------------- Delete Document Endpoint -----------------------
@app.post("/delete_document")
def delete_document(ids: List[str]):
    """
    Delete document(s) from the vector store using their IDs.
    """
    try:
        success = vector_store_manager.delete_documents(ids)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error deleting documents: {str(e)}")
    if not success:
        raise HTTPException(status_code=400, detail="Failed to delete documents.")
    return {"message": f"Deleted documents with IDs: {ids}"}


# ----------------------- Save Vectorstore Endpoint -----------------------
@app.get("/save_vectorstore")
def save_vectorstore():
    """
    Save the current vector store locally.
    If it is a directory, it will be zipped.
    Returns the file as a downloadable response.
    """
    try:
        save_result = vector_store_manager.save("faiss_index")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error saving vectorstore: {str(e)}")
    return FileResponse(
        path=save_result["file_path"],
        media_type=save_result["media_type"],
        filename=save_result["serve_filename"],
    )


# ----------------------- Load Vectorstore Endpoint -----------------------
@app.post("/load_vectorstore")
async def load_vectorstore(file: UploadFile = File(...)):
    """
    Load a vector store from an uploaded file (raw or zipped).
    This will replace the current vector store.
    """
    tmp_filename = None
    try:
        # Save the uploaded file content to a temporary file.
        with tempfile.NamedTemporaryFile(delete=False) as tmp:
            file_bytes = await file.read()  # await to get bytes
            tmp.write(file_bytes)
            tmp_filename = tmp.name

        instance, message = VectorStoreManager.load(tmp_filename, embeddings)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error loading vectorstore: {str(e)}")
    finally:
        if tmp_filename and os.path.exists(tmp_filename):
            os.remove(tmp_filename)
    global vector_store_manager
    vector_store_manager = instance
    return {"message": message}


# ----------------------- Merge Vectorstore Endpoint -----------------------
@app.post("/merge_vectorstore")
async def merge_vectorstore(file: UploadFile = File(...)):
    """
    Merge an uploaded vector store (raw or zipped) into the current vector store.
    """
    tmp_filename = None
    try:
        # Save the uploaded file content to a temporary file.
        with tempfile.NamedTemporaryFile(delete=False) as tmp:
            file_bytes = await file.read()  # Await the file.read() coroutine!
            tmp.write(file_bytes)
            tmp_filename = tmp.name

        # Pass the filename (a string) to the merge method.
        result = vector_store_manager.merge(tmp_filename, embeddings)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error merging vectorstore: {str(e)}")
    finally:
        if tmp_filename and os.path.exists(tmp_filename):
            os.remove(tmp_filename)
    return result


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