Skip to main content

Overview

The Multi-Query Rewriter RAG module implements a RAG pipeline that generates multiple variations of the user’s question to improve document retrieval. It creates three different query reformulations, retrieves documents for each, combines and re-ranks the results, then synthesizes a final answer. Module: src.rag.rewriter Source: src/rag/rewriter.py

Configuration

Default Models

Retriever Configuration

Uses similarity search with a score threshold to filter low-quality results.

Query Rewriting Templates

The module uses three different rewriting strategies:

Template 1: Standalone Query

Template 2: Synonym-Based Rephrasing

Template 3: Expanded Context

Functions

format_docs

Formats documents for the context, indicating relevance.
List[Document]
required
List of documents to format
str
Formatted string with documents labeled by relevance (High/Medium/Low)
Example Output:

process_rewriter_query

Processes a query using the multi-query rewriting RAG pipeline.
str
required
The user’s question
ChatOpenAI
default:"None"
Custom model for query rewriting. Defaults to gpt-3.5-turbo with temperature=0.3
ChatOpenAI
default:"None"
Custom model for answer generation. Defaults to gpt-4o with temperature=0
int
default:"8"
The maximum number of documents to return after deduplication and re-ranking
Dict[str, Any]
Dictionary containing:
  • answer (str): The generated answer
  • contexts (List[str]): Retrieved document contents
  • retrieved_documents (List[Document]): Full document objects
  • rewritten_queries (List[str]): The 3 generated query variations
  • metrics (dict):
    • rewrite_input_tokens (int): Tokens used for rewriting
    • rewrite_output_tokens (int): Tokens generated during rewriting
    • rewrite_cost (float): Cost of rewriting
    • answer_input_tokens (int): Tokens used for answer
    • answer_output_tokens (int): Tokens generated for answer
    • answer_cost (float): Cost of answer generation
    • total_input_tokens (int): Total input tokens
    • total_output_tokens (int): Total output tokens
    • total_cost (float): Total cost in USD
    • usage_source (str): Source of usage data
    • cost_source (str): Source of cost calculation

query_for_evaluation

A wrapper function for RAG evaluation frameworks like Ragas.
str
required
The question to process
str
default:"None"
The name of the LLM model to use for query rewriting. Defaults to “gpt-3.5-turbo”
str
default:"None"
The name of the LLM model to use for answer generation. Defaults to “gpt-4o”
BaseChatModel
default:"None"
Pre-configured LLM for rewriting. Takes precedence over rewriter_model
BaseChatModel
default:"None"
Pre-configured LLM for answer. Takes precedence over answer_model
dict
Dictionary containing:
  • question (str): Original question
  • answer (str): Generated answer
  • contexts (List[str]): Retrieved document contents
  • source_documents (List[Document]): Full retrieved documents
  • metadata (dict): Comprehensive metadata including:
    • num_contexts (int): Number of contexts
    • retrieval_method (str): “multi_query_rewrite”
    • rewrite_count (int): Number of query variations (3)
    • llm_model (str): Answer model name
    • rewriter_model (str): Rewriter model name
    • provider (str): Answer provider
    • model_id (str): Answer model ID
    • rewriter_provider (str): Rewriter provider
    • rewriter_model_id (str): Rewriter model ID
    • execution_time (float): Total execution time
    • input_tokens (int): Total input tokens
    • output_tokens (int): Total output tokens
    • total_cost (float): Total cost in USD
    • tokens_used (int): Total tokens
    • usage_source (str): Usage data source
    • cost_source (str): Cost calculation source

Usage Example

Pipeline Flow

  1. Generate Queries: Creates 3 query variations using gpt-3.5-turbo (temp=0.3):
    • Standalone specific query
    • Synonym-based rephrasing
    • Expanded contextual query
  2. Retrieve: Performs semantic search for each query variation (top 5 per query)
  3. Deduplicate: Removes duplicate documents using content-based IDs
  4. Weight & Re-rank: Applies query-based weighting (later queries get 5% penalty)
  5. Select: Chooses top 8 documents after re-ranking
  6. Format: Formats documents with relevance indicators
  7. Generate: Uses gpt-4o (temp=0) to generate final answer
  8. Track: Captures separate metrics for rewriting and answer generation

Query Weighting Strategy

  • Query 1: weight = 1.0 (100%)
  • Query 2: weight = 0.95 (95%)
  • Query 3: weight = 0.90 (90%)
This prioritizes the standalone query while still considering alternative formulations.

Key Features

  • Multi-perspective retrieval: 3 different query formulations
  • Automatic deduplication: Removes duplicate documents across queries
  • Intelligent weighting: Prioritizes more direct query reformulations
  • High coverage: Up to 15 candidates (3 queries × 5 docs)
  • Relevance labeling: Documents marked as High/Medium/Low relevance
  • Dual cost tracking: Separate metrics for rewriting and answer generation
  • Temperature tuning: 0.3 for rewriting (balanced), 0 for answer (precise)