Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

RAG (Retrieval-Augmented Generation) Application

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.

Project Structure

.
├── 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

Features

  1. PDF Text Extraction: Extract text content from PDF documents
  2. Text Chunking: Split large texts into manageable chunks using different strategies (character, sentence, paragraph)
  3. Embedding Generation: Create vector embeddings for text chunks using OpenAI's API
  4. Semantic Search: Find the most relevant chunks for a given query using FAISS for efficient similarity search
  5. Response Generation: Generate comprehensive responses using retrieved context and OpenAI's language models
  6. Evaluation: Evaluate the quality and accuracy of generated responses with multiple metrics

Getting Started

Prerequisites

  • Python 3.8+
  • OpenAI API key

Installation

  1. Clone this repository
  2. Install the required dependencies:
    pip install -r requirements.txt
    
  3. Create a .env file based on .env.example and add your OpenAI API key:
    OPENAI_API_KEY=your-openai-api-key-here
    

Usage

Command Line Interface

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"

Example Script

You can also use the provided example script to see the application in action:

python example.py

Note: 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.

Using as a Library

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)

Implementation Steps

The RAG application is implemented in the following steps:

  1. Setting Up the Environment: Configuration settings and environment variables
  2. Extracting Text from a PDF File: Using PyPDF2 to extract text from PDF documents
  3. Chunking the Extracted Text: Splitting text into manageable chunks using different strategies
  4. Setting Up the OpenAI API Client: Configuring the OpenAI client for API access
  5. Extracting and Chunking Text from a PDF File: Combining extraction and chunking in a single workflow
  6. Creating Embeddings for Text Chunks: Using OpenAI's API to create vector embeddings
  7. Performing Semantic Search: Using FAISS for efficient similarity search
  8. Running a Query on Extracted Chunks: Finding the most relevant chunks for a query
  9. Generating a Response Based on Retrieved Chunks: Using OpenAI's language models to generate responses
  10. Evaluating the AI Response: Assessing the quality and accuracy of generated responses

Customization

You can customize the application by modifying the configuration settings in config.py or by setting environment variables. See .env.example for available options.

License

MIT License

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages