Here's a complete code example for setting up a RAG pipeline using gte-Qwen2 embeddings with FAISS:
import os
from typing import List, Dict
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.docstore.document import Document
import torch
class RAGPipeline:
def __init__(self, embedding_model_name: str = "Alibaba-NLP/gte-Qwen2-7B-instruct"):
# Initialize the embedding model
self.embedding_model = SentenceTransformer(embedding_model_name, trust_remote_code=True)
self.embedding_dim = self.embedding_model.get_sentence_embedding_dimension()
# Initialize FAISS index
self.index = faiss.IndexFlatL2(self.embedding_dim)
# Store for document chunks and metadata
self.documents = []
self.chunk_texts = []
def load_documents(self, file_paths: List[str]) -> List[Document]:
"""Load text documents from file paths"""
documents = []
for file_path in file_paths:
with open(file_path, 'r', encoding='utf-8') as file:
text = file.read()
doc = Document(page_content=text, metadata={"source": file_path})
documents.append(doc)
return documents
def split_documents(self, documents: List[Document], chunk_size: int = 1000, chunk_overlap: int = 200) -> List[Document]:
"""Split documents into smaller chunks"""
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
length_function=len,
separators=["\n\n", "\n", " ", ""]
)
chunks = []
for doc in documents:
splits = text_splitter.split_text(doc.page_content)
for i, chunk in enumerate(splits):
chunk_doc = Document(
page_content=chunk,
metadata={**doc.metadata, "chunk_id": i}
)
chunks.append(chunk_doc)
return chunks
def add_documents_to_index(self, documents: List[Document]):
"""Add documents to FAISS index"""
# Extract texts
texts = [doc.page_content for doc in documents]
# Generate embeddings
embeddings = self.embedding_model.encode(
texts,
normalize_embeddings=True,
show_progress_bar=True
)
# Add to FAISS index
self.index.add(embeddings.astype('float32'))
# Store documents and texts
self.documents.extend(documents)
self.chunk_texts.extend(texts)
def search(self, query: str, k: int = 5) -> List[Dict]:
"""Search for similar documents"""
# Generate query embedding
query_embedding = self.embedding_model.encode(
[query],
normalize_embeddings=True
)
# Search in FAISS
distances, indices = self.index.search(query_embedding.astype('float32'), k)
# Prepare results
results = []
for i, (dist, idx) in enumerate(zip(distances[0], indices[0])):
if idx != -1: # Valid result
results.append({
"document": self.documents[idx],
"text": self.chunk_texts[idx],
"distance": float(dist),
"rank": i + 1
})
return results
def save_index(self, index_path: str, metadata_path: str):
"""Save FAISS index and metadata"""
# Save FAISS index
faiss.write_index(self.index, index_path)
# Save metadata
import pickle
metadata = {
"documents": self.documents,
"chunk_texts": self.chunk_texts,
"embedding_dim": self.embedding_dim
}
with open(metadata_path, 'wb') as f:
pickle.dump(metadata, f)
def load_index(self, index_path: str, metadata_path: str):
"""Load FAISS index and metadata"""
# Load FAISS index
self.index = faiss.read_index(index_path)
# Load metadata
import pickle
with open(metadata_path, 'rb') as f:
metadata = pickle.load(f)
self.documents = metadata["documents"]
self.chunk_texts = metadata["chunk_texts"]
self.embedding_dim = metadata["embedding_dim"]
# Example usage
def main():
# Initialize RAG pipeline
rag = RAGPipeline(embedding_model_name="Alibaba-NLP/gte-Qwen2-7B-instruct")
# Load and process documents
file_paths = ["doc1.txt", "doc2.txt", "doc3.txt"] # Replace with your file paths
documents = rag.load_documents(file_paths)
# Split documents into chunks
chunks = rag.split_documents(documents, chunk_size=1000, chunk_overlap=200)
# Add to FAISS index
rag.add_documents_to_index(chunks)
# Save index for later use
rag.save_index("faiss_index.bin", "faiss_metadata.pkl")
# Example search
query = "What is machine learning?"
results = rag.search(query, k=5)
# Display results
for result in results:
print(f"Rank: {result['rank']}")
print(f"Distance: {result['distance']:.4f}")
print(f"Source: {result['document'].metadata['source']}")
print(f"Text: {result['text'][:200]}...")
print("-" * 80)
# Use with your LLM
context = "\n\n".join([r["text"] for r in results])
# Example prompt for your LLM
prompt = f"""Based on the following context, answer the question.
Context:
{context}
Question: {query}
Answer:"""
# Send prompt to your LLM here
# response = your_llm.generate(prompt)
if __name__ == "__main__":
main()
For integration with your LLM, here's an example using the retrieved context:
def generate_rag_response(rag_pipeline: RAGPipeline, query: str, llm_client):
"""Generate response using RAG pipeline and LLM"""
# Retrieve relevant documents
search_results = rag_pipeline.search(query, k=5)
# Build context from retrieved documents
context_pieces = []
for i, result in enumerate(search_results):
context_pieces.append(f"[Document {i+1}]\n{result['text']}")
context = "\n\n".join(context_pieces)
# Create prompt
prompt = f"""You are a helpful assistant. Use the following context to answer the question.
If the answer cannot be found in the context, say so.
Context:
{context}
Question: {query}
Answer:"""
# Generate response with your LLM
# This depends on which LLM you're using
# For example, with OpenAI:
# response = llm_client.chat.completions.create(
# model="gpt-4",
# messages=[{"role": "user", "content": prompt}]
# )
return prompt # Return prompt for now
# For smaller gte-Qwen2 models, you might want to use:
# rag = RAGPipeline(embedding_model_name="Alibaba-NLP/gte-Qwen2-1.5B-instruct")
Key points about this implementation:
-
gte-Qwen2 embeddings: The code uses the Sentence Transformers library to load the gte-Qwen2 model. Make sure to install required dependencies:
pip install sentence-transformers faiss-cpu torch langchain
-
FAISS index: Uses a simple L2 distance index. For larger datasets, consider using more efficient indices like IndexIVFFlat or IndexHNSWFlat.
-
Document chunking: Splits documents into manageable chunks with overlap to maintain context.
-
Persistence: Includes methods to save and load the index for reuse.
-
Integration: The search results can be easily integrated with any LLM by formatting them into a prompt.
For production use, consider:
- Using GPU for faster embedding generation
- Implementing batch processing for large document sets
- Adding more sophisticated chunking strategies
- Using hybrid search (combining dense and sparse retrieval)
- Implementing re-ranking mechanisms