This project implements a Retrieval-Augmented Generation (RAG) system in Python. RAG combines the power of large language models with the ability to retrieve relevant information from a knowledge base, allowing the model to generate more accurate and contextually relevant responses.
.
├── main.py # Main application entry point
├── example.py # Example script demonstrating usage
├── config.py # Configuration settings
├── requirements.txt # Project dependencies
├── .env.example # Example environment variables
├── utils/ # Utility modules
│ ├── README.md # Documentation for utility modules
│ ├── __init__.py # Makes utils a package
│ ├── pdf_extractor.py # PDF text extraction utilities
│ ├── text_chunker.py # Text chunking utilities
│ ├── embeddings.py # Embedding creation and management
│ ├── search.py # Semantic search functionality
│ └── evaluation.py # Response evaluation utilities
└── README.md # This file
- PDF Text Extraction: Extract text content from PDF documents
- Text Chunking: Split large texts into manageable chunks using different strategies (character, sentence, paragraph)
- Embedding Generation: Create vector embeddings for text chunks using OpenAI's API
- Semantic Search: Find the most relevant chunks for a given query using FAISS for efficient similarity search
- Response Generation: Generate comprehensive responses using retrieved context and OpenAI's language models
- Evaluation: Evaluate the quality and accuracy of generated responses with multiple metrics
- Python 3.8+
- OpenAI API key
- Clone this repository
- Install the required dependencies:
pip install -r requirements.txt - Create a
.envfile based on.env.exampleand add your OpenAI API key:OPENAI_API_KEY=your-openai-api-key-here
The application provides a command-line interface for processing PDFs and running queries:
# Process a PDF file
python main.py --pdf path/to/your/document.pdf
# Run a query on a processed PDF
python main.py --query "Your question here" --embeddings document_embeddings
# Process a PDF and run a query in one command
python main.py --pdf path/to/your/document.pdf --query "Your question here"You can also use the provided example script to see the application in action:
python example.pyNote: The example script requires a sample PDF file at data/sample.pdf. You'll need to provide your own PDF file or modify the path in the script.
You can import and use the components in your own Python code:
from utils import extract_text_from_pdf, chunk_text, create_embeddings, semantic_search
# Extract text from a PDF
extracted_text = extract_text_from_pdf("path/to/document.pdf")
# Combine all pages
full_text = ""
for page_num, page_text in sorted(extracted_text.items()):
full_text += page_text + "\n\n"
# Chunk the text
chunks = chunk_text(full_text, chunk_size=1000, chunk_overlap=200, strategy="paragraph")
# Create embeddings
embeddings_data = create_embeddings(chunks)
# Perform semantic search
query = "What is the main topic of this document?"
search_results = semantic_search(query, embeddings_data, top_k=5)
# Print results
for i, result in enumerate(search_results):
print(f"Result {i+1} (Score: {result['score']:.4f}):")
print(result['text'])
print("-" * 50)The RAG application is implemented in the following steps:
- Setting Up the Environment: Configuration settings and environment variables
- Extracting Text from a PDF File: Using PyPDF2 to extract text from PDF documents
- Chunking the Extracted Text: Splitting text into manageable chunks using different strategies
- Setting Up the OpenAI API Client: Configuring the OpenAI client for API access
- Extracting and Chunking Text from a PDF File: Combining extraction and chunking in a single workflow
- Creating Embeddings for Text Chunks: Using OpenAI's API to create vector embeddings
- Performing Semantic Search: Using FAISS for efficient similarity search
- Running a Query on Extracted Chunks: Finding the most relevant chunks for a query
- Generating a Response Based on Retrieved Chunks: Using OpenAI's language models to generate responses
- Evaluating the AI Response: Assessing the quality and accuracy of generated responses
You can customize the application by modifying the configuration settings in config.py or by setting environment variables. See .env.example for available options.