Please fix my code: import os import logging import time import psutil import asyncio…
- User
Please fix my code:
import os import logging import time import psutil import asyncio import uuid import pickle import torch import numpy as np from typing import Optional, Dict from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect from pydantic import BaseModel from fastapi.middleware.cors import CORSMiddleware from langchain_core.prompts import PromptTemplate from langchain_community.llms import Ollama from transformers import AutoTokenizer from sentence_transformers import SentenceTransformer import faiss
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
Initialize the FastAPI app
app = FastAPI()
Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
app.add_middleware( CORSMiddleware, allow_origins=[""], # Allow all origins allow_credentials=True, allow_methods=[""], allow_headers=["*"], )
Initialize SentenceTransformer model and tokenizer
model_name = 'all-MiniLM-L6-v2' sentence_model = SentenceTransformer(model_name) tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
Define the persist directory and normalize the path
persist_dir = os.path.normpath("D:/Storage")
Load document embeddings, metadata, and FAISS index
with open(os.path.join(persist_dir, 'document_embeddings.pkl'), 'rb') as f: document_embeddings = pickle.load(f)
with open(os.path.join(persist_dir, 'document_metadata.pkl'), 'rb') as f: document_metadata = pickle.load(f)
index = faiss.read_index(os.path.join(persist_dir, 'faiss_index.bin'))
Create a mapping of document IDs to their metadata
document_metadata_dict = {doc['id']: doc['extra_info'] for doc in document_metadata}
Define a custom RAG prompt
custom_rag_prompt = """ You are a helpful assistant. Provide a clear, structured, and concise response to the following question using the given context. Ensure your answer is quick and efficient, and correct. Include detailed steps if needed. Do not repeat statements in your answer.
Question: {question}
Answer: {context}
Note: The information was retrieved from the following sources: {source_info} """
Create a PromptTemplate with the custom RAG prompt
custom_rag_prompt_template = PromptTemplate( template=custom_rag_prompt, input_variables=["question", "context", "source_info"] )
Function to format documents and extract source information
def format_docs_and_sources(docs): formatted_docs = [] source_info = []
for doc in docs: if hasattr(doc, 'text') and hasattr(doc, 'metadata'): content = f"Table:\n{doc.text}" if "table" in doc.id_ else doc.text formatted_docs.append(content) doc_metadata = getattr(doc, 'metadata', {}) doc_name = doc_metadata.get('name', 'Unknown Document Name') pages_info = doc_metadata.get('pages', 'No page information available') source_info.append(f"{doc_name}, Pages: {pages_info}") else: formatted_docs.append("No text available") source_info.append("No source information available") formatted_docs = "\n\n".join(formatted_docs) source_info = "\n".join(list(set(source_info))) return formatted_docs, source_info - Assistant