A Retrieval-Augmented Generation system for generating effective counter-narratives to hate speech through structured debate generation and knowledge base construction.
DebateRAG combines structured debate simulation with knowledge base construction to create an intelligent system that can assess potentially harmful queries and generate appropriate counter-speech responses. The system uses a graph database to store hate speech patterns and their corresponding counter-narratives, enabling sophisticated retrieval and response generation.
Data Generation (src/data_generation/)
debate_gen.py: Generates structured debates using LLM playersllm_eval.py: Evaluates generated debates for qualityshort_hate_sentence_gen.py: Creates synthetic hate speech examplesKnowledge Base (src/knowledge_base/)
kb_builder.py: Constructs graph database with nodes and relationshipsdata_processor.py: Processes debate data into structured formatkb_build_level2.py: Advanced knowledge base constructionRetrieval System (src/retrieval/)
retrieve.py: Implements syntax, semantic, and hybrid searchvector_utils.py: Vector embedding utilitiesResponse Generation (src/generation/)
assessment_system.py: Core system for query assessment and response generationEvaluation (src/evaluation/)
evaluation_metrics.py: Comprehensive evaluation metrics and comparison toolsPrerequisites
Install Dependencies
pip install together gqlalchemy pandas numpy tqdm
Database Setup
127.0.0.1:7687docker run -p 7687:7687 memgraph/memgraphAPI Configuration
export TOGETHER_API_KEY="your_together_api_key"
export PERSPECTIVE_API_KEY="your_perspective_api_key" # Optional
Create structured debates from a topics CSV file:
python scripts/generate_debate_dataset.py \
--topics data/raw/hs.csv \
--output_dir data/generated \
--max_turns 8
Process the generated debates into a graph database:
python scripts/build_knowledge_base.py \
--debate_file data/generated/debate_generated_results.json \
--output_dir data/processed
Use the system to assess and respond to queries:
from src.generation.assessment_system import HateAssessmentSystem
from src.retrieval.retrieve import RAGRetriever
# Initialize components
retriever = RAGRetriever()
system = HateAssessmentSystem(retriever, api_key="your_api_key")
# Process a query
result = system.process_query(
user_query="Your query here",
search_method="hybrid",
num_results=5
)
print(f"Response: {result['response']}")
print(f"Hate Score: {result['hate_score']}")
To replicate the datasets used in the paper follow these steps:
Download the MultitargetCONAN dataset from the official source:
Download the SSTF dataset from the official source:
Place the downloaded files (e.g., multitargetconan.csv, sstf.csv) in the data/raw/ directory.
To match the distribution and size used in our experiments, we use a stratified subsample of 996 examples.
Assuming you have loaded the dataset into a pandas DataFrame called df and imported resample from sklearn.utils:
from sklearn.utils import resample
# Stratified sampling maintaining TARGET distribution
subsample = df.groupby("TARGET", group_keys=False).apply(
lambda x: resample(
x,
replace=False,
n_samples=int(996 * len(x) / len(df)),
random_state=42
)
)
Evaluate the system against a benchmark dataset:
python scripts/run_full_evaluation.py \
--dataset data/evaluation/benchmark.csv \
--output_dir results \
--sample_size 100
topic,position
Immigration,Immigrants are dangerous criminals who should be deported
Religion,Religious minorities pose a threat to our society
The system creates a graph database with:
The system uses a hybrid scoring approach:
Mitigation Levels:
syntax: Keyword-based searchsemantic: Vector similarity searchhybrid: Combined approachtogether: Use Together AI models for generationmemgraph: Use Memgraph for knowledge base queriesscripts/generate_debate_dataset.py: Generate training datascripts/build_knowledge_base.py: Create graph databasescripts/run_full_evaluation.py: Comprehensive evaluation# Generate with custom parameters
python scripts/generate_debate_dataset.py \
--topics data/topics.csv \
--output_dir output \
--max_turns 8 \
--skip_evaluation
# Evaluate with specific settings
python scripts/run_full_evaluation.py \
--dataset benchmark.csv \
--output_dir results \
--search_method hybrid \
--sample_size 50
debate_generated_results.json: Raw debate dataevaluated_debates.json: Quality-scored debatesevaluation_results.json: Comprehensive evaluation metricsevaluation_report.md: Human-readable analysisevaluation_metrics.csv: Spreadsheet-compatible resultsThis system is designed for academic research in:
This project is licensed under the MIT License - see the LICENSE file for details.
For questions or issues, feel free to open a GitHub Issue.
10 commits
Python
100.0%
A Retrieval-Augmented Generation system for generating effective counter-narratives to hate speech through structured debate generation and knowledge base construction.
DebateRAG combines structured debate simulation with knowledge base construction to create an intelligent system that can assess potentially harmful queries and generate appropriate counter-speech responses. The system uses a graph database to store hate speech patterns and their corresponding counter-narratives, enabling sophisticated retrieval and response generation.
Data Generation (src/data_generation/)
debate_gen.py: Generates structured debates using LLM playersllm_eval.py: Evaluates generated debates for qualityshort_hate_sentence_gen.py: Creates synthetic hate speech examplesKnowledge Base (src/knowledge_base/)
kb_builder.py: Constructs graph database with nodes and relationshipsdata_processor.py: Processes debate data into structured formatkb_build_level2.py: Advanced knowledge base constructionRetrieval System (src/retrieval/)
retrieve.py: Implements syntax, semantic, and hybrid searchvector_utils.py: Vector embedding utilitiesResponse Generation (src/generation/)
assessment_system.py: Core system for query assessment and response generationEvaluation (src/evaluation/)
evaluation_metrics.py: Comprehensive evaluation metrics and comparison toolsPrerequisites
Install Dependencies
pip install together gqlalchemy pandas numpy tqdm
Database Setup
127.0.0.1:7687docker run -p 7687:7687 memgraph/memgraphAPI Configuration
export TOGETHER_API_KEY="your_together_api_key"
export PERSPECTIVE_API_KEY="your_perspective_api_key" # Optional
Create structured debates from a topics CSV file:
python scripts/generate_debate_dataset.py \
--topics data/raw/hs.csv \
--output_dir data/generated \
--max_turns 8
Process the generated debates into a graph database:
python scripts/build_knowledge_base.py \
--debate_file data/generated/debate_generated_results.json \
--output_dir data/processed
Use the system to assess and respond to queries:
from src.generation.assessment_system import HateAssessmentSystem
from src.retrieval.retrieve import RAGRetriever
# Initialize components
retriever = RAGRetriever()
system = HateAssessmentSystem(retriever, api_key="your_api_key")
# Process a query
result = system.process_query(
user_query="Your query here",
search_method="hybrid",
num_results=5
)
print(f"Response: {result['response']}")
print(f"Hate Score: {result['hate_score']}")
To replicate the datasets used in the paper follow these steps:
Download the MultitargetCONAN dataset from the official source:
Download the SSTF dataset from the official source:
Place the downloaded files (e.g., multitargetconan.csv, sstf.csv) in the data/raw/ directory.
To match the distribution and size used in our experiments, we use a stratified subsample of 996 examples.
Assuming you have loaded the dataset into a pandas DataFrame called df and imported resample from sklearn.utils:
from sklearn.utils import resample
# Stratified sampling maintaining TARGET distribution
subsample = df.groupby("TARGET", group_keys=False).apply(
lambda x: resample(
x,
replace=False,
n_samples=int(996 * len(x) / len(df)),
random_state=42
)
)
Evaluate the system against a benchmark dataset:
python scripts/run_full_evaluation.py \
--dataset data/evaluation/benchmark.csv \
--output_dir results \
--sample_size 100
topic,position
Immigration,Immigrants are dangerous criminals who should be deported
Religion,Religious minorities pose a threat to our society
The system creates a graph database with:
The system uses a hybrid scoring approach:
Mitigation Levels:
syntax: Keyword-based searchsemantic: Vector similarity searchhybrid: Combined approachtogether: Use Together AI models for generationmemgraph: Use Memgraph for knowledge base queriesscripts/generate_debate_dataset.py: Generate training datascripts/build_knowledge_base.py: Create graph databasescripts/run_full_evaluation.py: Comprehensive evaluation# Generate with custom parameters
python scripts/generate_debate_dataset.py \
--topics data/topics.csv \
--output_dir output \
--max_turns 8 \
--skip_evaluation
# Evaluate with specific settings
python scripts/run_full_evaluation.py \
--dataset benchmark.csv \
--output_dir results \
--search_method hybrid \
--sample_size 50
debate_generated_results.json: Raw debate dataevaluated_debates.json: Quality-scored debatesevaluation_results.json: Comprehensive evaluation metricsevaluation_report.md: Human-readable analysisevaluation_metrics.csv: Spreadsheet-compatible resultsThis system is designed for academic research in:
This project is licensed under the MIT License - see the LICENSE file for details.
For questions or issues, feel free to open a GitHub Issue.
10 commits
Python
100.0%