Dataset link: Hog RAGger Dataset
Dataset info:
Corpus.json: Contains collection of text of many articles scraped from the web. Contains following information about each article: title, author, source of article, publishing date, category, article url and article body (the text content).
Train.json: Contains output of a SOTA RAG pipeline. It contains 2556 queries, with evidence for each query distributed across 2 to 4 documents. The queries also involve document metadata, reflecting complex scenarios commonly found in real-world RAG applications.
The goal is to develop a RAG pipeline that would answer the user’s question from the given corpus. The queries would require evidence from 2 to 4 documents and may also require information from document metadata in order to be answered. The output of your pipeline should be formatted the same as outputs in train.json and hence should contain the following:
query: The question posed to the pipeline, summarizing the topic or information being sought.
answer: The answer or inferred response to the query, generated based on the available evidence.
question_type: The type of question being asked, in this case, it's an "inference_query," indicating that the system inferred the answer from the context of the query and evidence.
evidence_list: A list of sources that provide supporting information for the answer. The list contains the following keys:
title: The title of the article or source that is referenced.
author: The name of the author or authors of the source.
url: The link to the source where the evidence is found.
source: The publication or website that published the source.
category: The general category or topic area of the source (e.g., technology, business).
published_at: The publication date and time of the source.
fact: A specific piece of information or fact extracted from the source that supports the query's answer.
Sample Input: "Who is the individual associated with the cryptocurrency industry facing a criminal trial on fraud and conspiracy charges, as reported by both The Verge and TechCrunch, and is accused by prosecutors of committing fraud for personal gain?"
Sample Output:
Considerations:
Usage of any proprietary LLM/VLM (like Gemini, Claude, ChatGPT etc) or apis of such softwares is strictly forbidden. Use open source models instead.
Fine tuning is not allowed.
A small web app for demo would result in bonus points.
import streamlit as st
import json
from typing import List, Dict, Any
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
Load corpus and create embeddings
@st.cache_resource
def load_corpus(file_path: str) -> List[Dict[str, Any]]:
with open(file_path, 'r') as f:
return json.load(f)
Hog RAGger is a Retrieval-Augmented Generation (RAG) pipeline designed to answer complex queries using a corpus of web-scraped articles. The project aims to develop an advanced RAG system capable of handling queries that require evidence from multiple documents and incorporate document metadata.
Dataset
The project uses the Hog RAGger Dataset, which consists of two main components:
Assistant
@st.cache_resource
def create_embeddings(corpus: List[Dict[str, Any]], model_name: str = 'sentence-transformers/all-MiniLM-L6-v2') -> np.ndarray:
model = SentenceTransformer(model_name)
return model.encode([doc['content'] for doc in corpus])
def retrieve_documents(query: str, corpus: List[Dict[str, Any]], embeddings: np.ndarray, model_name: str = 'sentence-transformers/all-MiniLM-L6-v2', top_k: int = 4) -> List[Dict[str, Any]]:
model = SentenceTransformer(model_name)
query_embedding = model.encode([query])
similarities = cosine_similarity(query_embedding, embeddings)[0]
top_indices = np.argsort(similarities)[-top_k:][::-1]
return [corpus[i] for i in top_indices]
@st.cache_resource
def load_qa_model(model_name: str = 'google/flan-t5-base'):
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
return tokenizer, model
corpus = load_corpus('corpus.json')
processed_corpus = preprocess_corpus(corpus)
embeddings = create_embeddings(processed_corpus)
tokenizer, model = load_qa_model()
Query input
query = st.text_input("Enter your query:", "What is the impact of COVID-19 on the economy?")
if st.button("Process Query"):
with st.spinner("Processing query..."):
result = rag_pipeline(query, processed_corpus, embeddings, tokenizer, model)
# Display results
st.subheader("Answer")
st.write(result['answer'])
st.subheader("Evidence")
for evidence in result['evidence_list']:
with st.expander(evidence['title']):
st.write(f"**Author:** {evidence['author']}")
st.write(f"**Source:** {evidence['source']}")
st.write(f"**Category:** {evidence['category']}")
st.write(f"**Published:** {evidence['published_at']}")
st.write(f"**Excerpt:** {evidence['fact']}")
st.write(f"[Read More]({evidence['url']})")
st.sidebar.title("About")
st.sidebar.info("This app uses a RAG (Retrieval-Augmented Generation) pipeline to answer queries based on a corpus of documents.")
Generate a readme.md as the answer to the problem statement describing what we have done and how to run everytihng in detaail
README
Overview
The purpose of this project is to develop a Retrieval-Augmented Generation (RAG) pipeline capable of answering complex queries by leveraging a corpus of documents. The provided pipeline uses open-source models to process and respond to queries demanding inference across multiple documents, utilizing document metadata as needed. It is designed to output responses in a structured format similar to the provided train.json.
Structure
Dataset and Inputs:
corpus.json: Contains a collection of articles with metadata.
train.json: Sample outputs for reference, indicating how the model output should be structured.
Pipeline Components:
Embedding Creation: Generate document embeddings using SentenceTransformer.
Document Retrieval: Select top-k relevant documents based on cosine similarity to the query embedding.
Answer Generation: Infer answers from the selected documents using a sequence-to-sequence pre-trained model.
Output Structuring: Assemble the query, answer, question type, and evidence list into a structured output format.
User Interface:
Built using Streamlit, providing an interactive web app to input queries and view results.
Installation and Setup
Clone the repository:
git clone <repository_url>
cd <repository_directory>
Install dependencies:
Ensure you have Python 3.7+ installed. Then run:
pip install -r requirements.txt
Prepare Data:
Load corpus.json into the project's root directory.
Running the Application
To run the Streamlit web app:
streamlit run app.py
This will launch a local server, accessible typically at http://localhost:8501, allowing you to enter queries and see the generated answers along with evidence.
Pipeline Description
load_corpus: Reads and loads the corpus from corpus.json.
preprocess_corpus: Prepares the data for processing by combining the title and body of articles and storing metadata.
create_embeddings: Utilizes SentenceTransformer to create embeddings for the documents.
retrieve_documents: Finds the most relevant documents for a query using cosine similarity between embeddings.
load_qa_model: Loads the sequence-to-sequence model (Flan-T5) to perform answer generation.
generate_answer: Constructs the context from the retrieved documents and generates an answer using the QA model.
rag_pipeline: Orchestrates the retrieval and generation processes to output a structured response, including an evidence list with facts supporting the answer.
UI Features
Query Input: Enter any question related to the corpus data.
Result Display: See the dynamically generated answer and supporting evidence in an expanded format.
Sidebar Information: Brief description and guidance on the application use.
Considerations
Utilize open-source models and libraries for reproducibility and compliance with usage guidelines, avoiding proprietary LLMs.
Maintain performance by pre-processing and caching data for repeated use.
Future enhancements might include features like query highlight in evidence, improved performance for larger datasets, or extending the application for more diverse question types.
Conclusion
This project demonstrates a robust method of utilizing RAG for complex query answering by combining document retrieval with natural language inference. Users can easily deploy and interact with the model via the Streamlit interface, making it both practical and user-friendly for educational and exploratory purposes.
Certainly! Below is the content structured for a README.md file. You can copy this text into a file named README.md in your project directory.
# README
## Overview
The purpose of this project is to develop a Retrieval-Augmented Generation (RAG) pipeline capable of answering complex queries by leveraging a corpus of documents. The provided pipeline uses open-source models to process and respond to queries demanding inference across multiple documents, utilizing document metadata as needed. It is designed to output responses in a structured format similar to the provided `train.json`.
## Structure
1. **Dataset and Inputs:**
- `corpus.json`: Contains a collection of articles with metadata.
- `train.json`: Sample outputs for reference, indicating how the model output should be structured.
2. **Pipeline Components:**
- **Embedding Creation:** Generate document embeddings using SentenceTransformer.
- **Document Retrieval:** Select top-k relevant documents based on cosine similarity to the query embedding.
- **Answer Generation:** Infer answers from the selected documents using a sequence-to-sequence pre-trained model.
- **Output Structuring:** Assemble the query, answer, question type, and evidence list into a structured output format.
3. **User Interface:**
- Built using Streamlit, providing an interactive web app to input queries and view results.
## Installation and Setup
1. **Clone the repository:**
```bash
git clone <repository_url>
cd <repository_directory>
Install dependencies:
Ensure you have Python 3.7+ installed. Then run:
pip install -r requirements.txt
Prepare Data:
Load corpus.json into the project's root directory.
Running the Application
To run the Streamlit web app:
streamlit run app.py
This will launch a local server, accessible typically at http://localhost:8501, allowing you to enter queries and see the generated answers along with evidence.
Pipeline Description
load_corpus: Reads and loads the corpus from corpus.json.
preprocess_corpus: Prepares the data for processing by combining the title and body of articles and storing metadata.
create_embeddings: Utilizes SentenceTransformer to create embeddings for the documents.
retrieve_documents: Finds the most relevant documents for a query using cosine similarity between embeddings.
load_qa_model: Loads the sequence-to-sequence model (Flan-T5) to perform answer generation.
generate_answer: Constructs the context from the retrieved documents and generates an answer using the QA model.
rag_pipeline: Orchestrates the retrieval and generation processes to output a structured response, including an evidence list with facts supporting the answer.
UI Features
Query Input: Enter any question related to the corpus data.
Result Display: See the dynamically generated answer and supporting evidence in an expanded format.
Sidebar Information: Brief description and guidance on the application use.
Considerations
Utilize open-source models and libraries for reproducibility and compliance with usage guidelines, avoiding proprietary LLMs.
Maintain performance by pre-processing and caching data for repeated use.
Future enhancements might include features like query highlight in evidence, improved performance for larger datasets, or extending the application for more diverse question types.
Conclusion
This project demonstrates a robust method of utilizing RAG for complex query answering by combining document retrieval with natural language inference. Users can easily deploy and interact with the model via the Streamlit interface, making it both practical and user-friendly for educational and exploratory purposes.
Remember to replace `<repository_url>` and `<repository_directory>` with the actual URL and directory name of your repository when filling out your `README.md`.
Corpus.json: A collection of web-scraped articles containing:
Title
Author
Source
Publishing date
Category
Article URL
Article body (text content)
Train.json: Contains 2556 queries processed by a state-of-the-art RAG pipeline, including:
The main objective is to develop a RAG pipeline that can:
Answer user queries based on the provided corpus
Utilize evidence from 2-4 documents per query
Incorporate document metadata when necessary
Format output to match the structure in train.json
Output Format
The pipeline should produce output in the following format:
{
"query": "User's question",
"answer": "Generated answer based on evidence",
"question_type": "inference_query",
"evidence_list": [
{
"title": "Article title",
"author": "Author name",
"url": "Article URL",
"source": "Publication source",
"category": "Article category",
"published_at": "Publication date and time",
"fact": "Extracted fact supporting the answer"
},
// Additional evidence items...
]
}
Getting Started
(Include instructions for setting up the project, installing dependencies, and running the pipeline)
Usage
(Provide examples of how to use the RAG pipeline, including sample input and output)
Evaluation
(Describe how the performance of the RAG pipeline will be evaluated, potentially using metrics like accuracy, relevance, and completeness of answers)
Contributing
(Include guidelines for contributing to the project, if applicable)
Hog RAGger
Project Overview
Hog RAGger is a Retrieval-Augmented Generation (RAG) pipeline designed to answer complex queries using a corpus of web-scraped articles. The project aims to develop an advanced RAG system capable of handling queries that require evidence from multiple documents and incorporate document metadata.
Dataset
The project uses the Hog RAGger Dataset, which consists of two main components:
Corpus.json: A collection of web-scraped articles containing:
Title
Author
Source
Publishing date
Category
Article URL
Article body (text content)
Train.json: Contains 2556 queries processed by a state-of-the-art RAG pipeline, including:
The main objective is to develop a RAG pipeline that can:
Answer user queries based on the provided corpus.
Utilize evidence from 2-4 documents per query.
Incorporate document metadata when necessary.
Format output to match the structure in train.json.
Output Format
The pipeline should produce output in the following format:
{
"query": "User's question",
"answer": "Generated answer based on evidence",
"question_type": "inference_query",
"evidence_list": [
{
"title": "Article title",
"author": "Author name",
"url": "Article URL",
"source": "Publication source",
"category": "Article category",
"published_at": "Publication date and time",
"fact": "Extracted fact supporting the answer"
}
// Additional evidence items...
]
}
Getting Started
Prerequisites
Ensure you have Python 3.7+ installed on your system.
Installation
Clone the repository:
git clone <repository_url>
cd <repository_directory>
Install dependencies:
pip install -r requirements.txt
Prepare the dataset:
Place corpus.json in the project directory.
Usage
Running the Streamlit App
To start the application, run the following command in your terminal:
streamlit run app.py
This will open the application in a web browser, typically at http://localhost:8501.
Query Input:
Enter your query in the input box and click the "Process Query" button to generate an answer.
Result Display:
View the generated answer along with evidence from the corpus, presented in an expandable format for more detail.
Evaluation
To evaluate the performance of the RAG pipeline, consider metrics such as:
Accuracy: How often does the pipeline provide correct answers?
Relevance: How relevant are the retrieved documents to the query?
Completeness: Does the answer comprehensively address the query?
Complexity and fidelity of incorporating metadata should also be assessed qualitatively.
Contributing
Contributions are welcome! Here's how you can help:
Fork the repository.
Create a new branch (feature/my-new-feature).
Commit your changes (git commit -am 'Add some feature').
Push to the branch (git push origin feature/my-new-feature).
Open a Pull Request.
Please ensure that your contributions adhere to the project's coding guidelines and are accompanied by relevant tests or usage examples.
Feel free to reach out with issues, suggestions, or feedback to improve Hog RAGger further!
License
(Include licensing information if applicable)
This README.md provides an overview of the Hog RAGger project, detailing setup, usage, and contribution guidelines for a seamless user and developer experience. Make sure to update placeholders such as <repository_url> with actual URLs and details as needed.