datadabllp

implementation of a RAG system

Aug 20th, 2024
627
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.14 KB | None | 0 0
  1. from sentence_transformers import SentenceTransformer
  2. from sklearn.metrics.pairwise import cosine_similarity
  3. import numpy as np
  4.  
  5. # Load document embeddings and corpus
  6. embedder = SentenceTransformer('all-MiniLM-L6-v2')
  7. document_embeddings = np.load('document_embeddings.npy')
  8. with open('document_corpus.txt', 'r') as f:
  9.     documents = f.readlines()
  10.  
  11. def retrieve_relevant_docs(query, top_k=3):
  12.     query_embedding = embedder.encode([query])
  13.     similarities = cosine_similarity(query_embedding, document_embeddings)[0]
  14.     top_indices = similarities.argsort()[-top_k:][::-1]
  15.     return [documents[i] for i in top_indices]
  16.  
  17. def rag_response(query):
  18.     relevant_docs = retrieve_relevant_docs(query)
  19.     context = "\n".join(relevant_docs)
  20.    
  21.     full_prompt = f"""
  22.    Based on the following information, please answer the user's question:
  23.  
  24.    Context:
  25.    {context}
  26.  
  27.    User Question: {query}
  28.  
  29.    Answer:
  30.    """
  31.    
  32.     response = llm.generate(full_prompt)
  33.     return response
  34.  
  35. # Example usage
  36. user_query = "What are the key provisions of the latest data privacy regulation?"
  37. answer = rag_response(user_query)
  38. print(answer)
  39.  
Advertisement
Add Comment
Please, Sign In to add comment