write a code "to Build a Local Open-Source LLM Chatbot With RAG"
- User
write a code "to Build a Local Open-Source LLM Chatbot With RAG"
- Assistant
write a code "to Build a Local Open-Source LLM Chatbot With RAG"
Building a local open-source Large Language Model (LLM) chatbot with Retrieval-Augmented Generation (RAG) involves integrating a language model with a retrieval system that can fetch relevant information from a knowledge base or document repository. Below is a step-by-step guide with corresponding Python code to help you set up such a system using open-source tools like Hugging Face Transformers, FAISS for vector search, and a simple web interface with Gradio.
First, ensure you have the necessary libraries installed. You can set up a virtual environment and install the dependencies using pip.
# Create and activate a virtual environment (optional but recommended)
python -m venv rag_chatbot_env
source rag_chatbot_env/bin/activate # On Windows: rag_chatbot_env\Scripts\activate
# Upgrade pip
pip install --upgrade pip
# Install required libraries
pip install transformers sentence-transformers faiss-cpu torch gradio
Assume you have a set of documents (e.g., .txt files) that the chatbot can reference to provide accurate and relevant information.
import os
def load_documents(directory_path):
documents = []
for filename in os.listdir(directory_path):
if filename.endswith('.txt'):
with open(os.path.join(directory_path, filename), 'r', encoding='utf-8') as file:
documents.append(file.read())
return documents
# Example usage
documents = load_documents('knowledge_base/')
print(f"Loaded {len(documents)} documents.")
Ensure you have a directory named knowledge_base with your .txt files.
Use Sentence Transformers to create embeddings for each document and build a FAISS index for efficient similarity search.
from sentence_transformers import SentenceTransformer
import faiss
import numpy as np
# Initialize the embedder model
embedder = SentenceTransformer('all-MiniLM-L6-v2') # Lightweight and efficient
# Create embeddings for all documents
doc_embeddings = embedder.encode(documents, convert_to_tensor=False, show_progress_bar=True)
doc_embeddings = np.array(doc_embeddings).astype('float32')
# Initialize FAISS index
dimension = doc_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension) # Using L2 distance
# Add embeddings to the index
index.add(doc_embeddings)
print(f"FAISS index contains {index.ntotal} vectors.")
Use a local instance of an open-source LLM. Here, we'll use GPT-2 for demonstration, but for better performance, consider models like GPT-J or LLaMA.
Note: Some large models require substantial computational resources. Ensure your hardware can handle the chosen model.
from transformers import GPT2LMHeadModel, GPT2Tokenizer
# Load pre-trained GPT-2 model and tokenizer
model_name = 'gpt2' # Replace with a larger model if needed
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
# Enable GPU if available
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
Combine the retrieval step with the language generation to form responses based on both the prompt and the retrieved documents.
def retrieve_documents(query, top_k=3):
# Embed the query
query_embedding = embedder.encode([query], convert_to_tensor=False)
query_embedding = np.array(query_embedding).astype('float32')
# Search in FAISS index
distances, indices = index.search(query_embedding, top_k)
# Retrieve the top_k documents
retrieved_docs = [documents[idx] for idx in indices[0]]
return retrieved_docs
def generate_response(prompt, retrieved_docs):
# Combine prompt with retrieved documents
context = "\n\n".join(retrieved_docs)
combined_prompt = f"Context:\n{context}\n\nQuestion: {prompt}\nAnswer:"
# Encode the input
inputs = tokenizer.encode(combined_prompt, return_tensors='pt').to(device)
# Generate response
output = model.generate(
inputs,
max_length=inputs.shape[1] + 150,
temperature=0.7,
top_p=0.9,
do_sample=True,
num_return_sequences=1,
eos_token_id=tokenizer.eos_token_id
)
# Decode the output
response = tokenizer.decode(output[0], skip_special_tokens=True)
# Extract the answer part
answer = response.split("Answer:")[-1].strip()
return answer
def rag_chatbot(prompt, top_k=3):
retrieved_docs = retrieve_documents(prompt, top_k)
response = generate_response(prompt, retrieved_docs)
return response
Use Gradio to create a simple web-based interface for interacting with the chatbot.
import gradio as gr
def chat(prompt):
response = rag_chatbot(prompt)
return response
iface = gr.Interface(
fn=chat,
inputs=gr.inputs.Textbox(lines=2, placeholder="Ask me anything..."),
outputs="text",
title="Local RAG Chatbot",
description="A local open-source chatbot using Retrieval-Augmented Generation (RAG)."
)
iface.launch()
Putting it all together, here's a complete script. Make sure to adjust the knowledge_base directory and model choices as needed.
import os
import faiss
import numpy as np
import torch
import gradio as gr
from transformers import GPT2LMHeadModel, GPT2Tokenizer
from sentence_transformers import SentenceTransformer
# 1. Load documents
def load_documents(directory_path):
documents = []
for filename in os.listdir(directory_path):
if filename.endswith('.txt'):
with open(os.path.join(directory_path, filename), 'r', encoding='utf-8') as file:
documents.append(file.read())
return documents
documents = load_documents('knowledge_base/')
print(f"Loaded {len(documents)} documents.")
# 2. Create embeddings
embedder = SentenceTransformer('all-MiniLM-L6-v2')
doc_embeddings = embedder.encode(documents, convert_to_tensor=False, show_progress_bar=True)
doc_embeddings = np.array(doc_embeddings).astype('float32')
# 3. Create FAISS index
dimension = doc_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(doc_embeddings)
print(f"FAISS index contains {index.ntotal} vectors.")
# 4. Load language model
model_name = 'gpt2' # Consider larger models for better performance
tokenizer = GPT2Tokenizer.from_pretrained(model_name)
model = GPT2LMHeadModel.from_pretrained(model_name)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model.to(device)
model.eval()
# 5. Define RAG functions
def retrieve_documents(query, top_k=3):
query_embedding = embedder.encode([query], convert_to_tensor=False)
query_embedding = np.array(query_embedding).astype('float32')
distances, indices = index.search(query_embedding, top_k)
retrieved_docs = [documents[idx] for idx in indices[0]]
return retrieved_docs
def generate_response(prompt, retrieved_docs):
context = "\n\n".join(retrieved_docs)
combined_prompt = f"Context:\n{context}\n\nQuestion: {prompt}\nAnswer:"
inputs = tokenizer.encode(combined_prompt, return_tensors='pt').to(device)
with torch.no_grad():
output = model.generate(
inputs,
max_length=inputs.shape[1] + 150,
temperature=0.7,
top_p=0.9,
do_sample=True,
num_return_sequences=1,
eos_token_id=tokenizer.eos_token_id
)
response = tokenizer.decode(output[0], skip_special_tokens=True)
answer = response.split("Answer:")[-1].strip()
return answer
def rag_chatbot(prompt, top_k=3):
retrieved_docs = retrieve_documents(prompt, top_k)
response = generate_response(prompt, retrieved_docs)
return response
# 6. Build Gradio interface
def chat(prompt):
response = rag_chatbot(prompt)
return response
iface = gr.Interface(
fn=chat,
inputs=gr.inputs.Textbox(lines=2, placeholder="Ask me anything..."),
outputs="text",
title="Local RAG Chatbot",
description="A local open-source chatbot using Retrieval-Augmented Generation (RAG)."
)
if __name__ == "__main__":
iface.launch()
Model Selection: GPT-2 is used for demonstration purposes. For more coherent and contextually aware responses, consider using larger models like GPT-J, GPT-Neo, or LLaMA. Ensure you have the necessary computational resources.
Optimizing FAISS Index: For larger document sets, consider more advanced FAISS indexing strategies (e.g., IndexIVFFlat) to speed up retrieval.
Document Preprocessing: Implement text preprocessing steps such as splitting large documents into chunks, removing stopwords, or handling special characters to improve retrieval quality.
Enhancing the Prompt: Fine-tune how the context is provided to the language model. Experiment with different prompt formats to achieve better responses.
Security and Privacy: Since the system is local, ensure that any sensitive information in the knowledge base is handled appropriately.
User Interface Enhancements: Enhance the Gradio interface with features like conversation history, customizable parameters (e.g., top_k, temperature), and styling.
By following the above steps, you can create a local open-source chatbot that leverages Retrieval-Augmented Generation to provide informed and relevant responses based on a custom knowledge base. This setup allows for flexibility in terms of the knowledge domain and ensures that the chatbot can operate without relying on external APIs or cloud services.
Not yet included in a published release.