Skip to main content

Overview

The Hybrid RAG module implements a hybrid search pipeline that combines lexical search (BM25) and semantic search (ChromaDB) using LangChain’s EnsembleRetriever. This approach balances keyword matching with semantic similarity for improved retrieval. Module: src.rag.hybrid Source: src/rag/hybrid.py

Configuration

Default Models

Retriever Configuration

The ensemble retriever combines results from both retrievers using equal weights (0.5 each) by default.

Document Loading

Loads document chunks from data/chunks/chunks_final.json.

Prompt Template

Uses the same medical-focused prompt template as Simple RAG:

Functions

load_documents

Loads chunks from the JSON file and converts them to LangChain Documents.
List[Document]
List of LangChain Document objects with content and metadata

format_docs

Formats the retrieved documents to be included in the final prompt.
List[Document]
required
A list of retrieved LangChain Document objects
str
A formatted string containing the content of the documents

process_hybrid_query

Processes a query using the hybrid RAG pipeline.
str
required
The user’s question
ChatOpenAI
default:"None"
A custom language model to use. Defaults to None (uses default gpt-4o)
Dict[str, Any]
A dictionary containing:
  • answer (str): The generated answer
  • contexts (List[str]): List of retrieved document contents
  • retrieved_documents (List[Document]): Full Document objects
  • metrics (dict): Token usage and cost metrics
    • input_tokens (int): Number of input tokens
    • output_tokens (int): Number of output tokens
    • total_tokens (int): Total tokens used
    • usage_source (str): Source of usage data
    • cost (float): Total cost in USD
    • 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"
Model name to use. If None, uses default “gpt-4o”
BaseChatModel
default:"None"
Pre-configured language model. Takes precedence over llm_model
dict
A dictionary containing:
  • question (str): The original question
  • answer (str): The 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 retrieved contexts
    • retrieval_method (str): “hybrid_bm25_semantic”
    • ensemble_weights (List[float]): [bm25_weight, semantic_weight]
    • llm_model (str): Model name used
    • provider (str): Provider (e.g., “openai”)
    • model_id (str): Full model identifier
    • embedding_model (str): “text-embedding-3-small”
    • execution_time (float): Total execution time in seconds
    • input_tokens (int): Input tokens used
    • output_tokens (int): Output tokens generated
    • total_cost (float): Total cost in USD
    • tokens_used (int): Total tokens (input + output)
    • usage_source (str): Source of usage metrics
    • cost_source (str): Source of cost calculation

Usage Example

Pipeline Flow

  1. BM25 Retrieval: Retrieves top 5 documents using lexical/keyword matching
  2. Semantic Retrieval: Retrieves top 5 documents using vector similarity
  3. Ensemble Fusion: Combines results from both retrievers using weighted scores
  4. Format: Formats documents with source and page metadata
  5. Generate: Uses the LLM to generate an answer based on the combined context
  6. Track: Captures token usage and cost metrics

Key Features

  • Combines lexical (BM25) and semantic search
  • Equal weighting (0.5/0.5) between both retrieval methods
  • Better handling of exact keyword matches
  • Improved recall compared to semantic-only search
  • Automatic cost and token tracking
  • Support for custom LLMs