Spaces:
Sleeping
Sleeping
Update backend/main.py
Browse files1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import osimport tempfileimport shutilfrom typing import List, Dict, Anyfrom fastapi import FastAPI, UploadFile, File, Form, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom aimakerspace.text_utils import CharacterTextSplitter, TextFileLoader, PDFLoaderfrom aimakerspace.openai_utils.prompts import (UserRolePrompt,SystemRolePrompt,AssistantRolePrompt,)from aimakerspace.openai_utils.embedding import EmbeddingModelfrom aimakerspace.vectordatabase import VectorDatabasefrom aimakerspace.openai_utils.chatmodel import ChatOpenAIapp = FastAPI()# Add CORS middlewareapp.add_middleware(CORSMiddleware,allow_origins=["*"], # In production, replace with your frontend URLallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Initialize componentstext_splitter = CharacterTextSplitter()vector_db = Nonechat_openai = ChatOpenAI(model_name="gpt-3.5-turbo")system_template = """\Use the following context to answer a users question. If you cannot find the answer in the context, say you don't know the answer."""system_role_prompt = SystemRolePrompt(system_template)user_prompt_template = """\Context:{context}Question:{question}"""user_role_prompt = UserRolePrompt(user_prompt_template)class QuestionRequest(BaseModel):question: strclass QuestionResponse(BaseModel):response: strcontext: List[tuple]def process_file(file_path: str, file_name: str):print(f"Processing file: {file_name}")# Create appropriate loaderif file_name.lower().endswith('.pdf'):loader = PDFLoader(file_path)else:loader = TextFileLoader(file_path)# Load and process the documentsdocuments = loader.load_documents()texts = text_splitter.split_texts(documents)return textsclass RetrievalAugmentedQAPipeline:def __init__(self, llm: ChatOpenAI, vector_db_retriever: VectorDatabase) -> None:self.llm = llmself.vector_db_retriever = vector_db_retrieverasync def run_pipeline(self, user_query: str):context_list = self.vector_db_retriever.search_by_text(user_query, k=4)context_prompt = ""for context in context_list:context_prompt += context[0] + "\n"formatted_system_prompt = system_role_prompt.create_message()formatted_user_prompt = user_role_prompt.create_message(question=user_query, context=context_prompt)# Remove await since run is not an async methodresponse = self.llm.run([formatted_system_prompt, formatted_user_prompt])return {"response": response, "context": context_list}@app.post("/upload")async def upload_file(file: UploadFile = File(...)):global vector_db# Validate file typeif not file.filename.lower().endswith(('.txt', '.pdf')):raise HTTPException(status_code=400, detail="Only .txt and .pdf files are allowed")# Create a temporary filesuffix = f".{file.filename.split('.')[-1]}"with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as temp_file:# Copy the uploaded file content to the temporary filecontent = await file.read()with open(temp_file.name, "wb") as f:f.write(content)try:# Process the filetexts = process_file(temp_file.name, file.filename)print(f"Processing {len(texts)} text chunks")# Create a vector storevector_db = VectorDatabase()vector_db = await vector_db.abuild_from_list(texts)return {"message": f"File {file.filename} processed successfully", "chunks": len(texts)}finally:# Clean up the temporary filetry:os.unlink(temp_file.name)except Exception as e:print(f"Error cleaning up temporary file: {e}")@app.post("/ask", response_model=QuestionResponse)async def ask_question(request: QuestionRequest):global vector_dbif vector_db is None:raise HTTPException(status_code=400, detail="Please upload a file first")# Create a chainretrieval_augmented_qa_pipeline = RetrievalAugmentedQAPipeline(vector_db_retriever=vector_db,llm=chat_openai)# Run the pipelineresult = await retrieval_augmented_qa_pipeline.run_pipeline(request.question)return QuestionResponse(response=result["response"],context=result["context"])@app.get("/health")async def health_check():return {"status": "healthy"}
backend/main.py+144-1