Blog

Evaluate your own RAG: why best practices failed us

/ 9 min read
Contents Jump to a section
  1. The pieces of a RAG
  2. How we benchmarked
  3. Setup
  4. Test set
  5. Metrics
  6. Chunking strategies
  7. Configurations tested
  8. Results
  9. Embedding models
  10. Chunk size
  11. Chunking strategy
  12. Dense vs hybrid search
  13. Languages and query forms
  14. Choices we did not benchmark
  15. PDF conversion: Mistral OCR
  16. Vector database: Qdrant
  17. Conclusion
  18. Data availability
  19. Implementation details
  20. Chunking
  21. PDF to markdown with Mistral OCR
  22. Embedding models
  23. Qdrant vector store

TL;DR: We benchmarked the RAG system we ran in production at Jimmy, over scientific and regulatory documents in English, French and Japanese. Several results went against the usual advice:

  • AWS Titan V2 embeddings had the best hit rate (69.2%), ahead of Qwen 8B (57.7%) and Mistral Embed (39.1%).
  • Chunk size barely mattered for document-level retrieval: 2K and 40K characters performed about the same.
  • Naive chunking beat context-aware chunking (70.5% vs 63.8% average hit rate).
  • Dense-only search beat hybrid search (69.2% vs 63.5% with Titan).
  • Mistral OCR was the only converter that handled our complex scientific PDFs.
  • AWS OpenSearch is far too expensive for vector search ($70/day minimum). Qdrant was easy to use and supports hybrid search.

The pieces of a RAG

Retrieval-augmented generation (RAG) gives an LLM documents it was not trained on: you retrieve the relevant passages and put them in the prompt. A pipeline has six parts: a PDF converter, a chunking strategy, an embedding model, a vector database, a retrieval mode (dense, sparse or hybrid) and the LLM that writes the answer.

rag_mermaid

How we benchmarked

Setup

The benchmark uses real documents from our production database: complex scientific PDFs with equations, tables and diagrams, converted with Mistral OCR and stored in Qdrant with the production configuration.

Test set

Every embedding model gets the same 156 queries. They mix simple retrieval (a direct extract of the text) and conceptual questions, in three languages (English, French, Japanese) and two forms: interrogative (“What is…?”) and affirmative (“Characteristics of…”). Each source document gets one query per language and form:

MetaQuestion(
    source_document="Jaiman et al. - 2023 - Mechanics of Flow-Induced Vibration Physical Mode.pdf",
    related_questions=[
        # Affirmatives
        Question(
            text="Cylinder vibrations induced by fluid flow",
            language=Language.ENGLISH,
            form=Form.affirmative,
        ),
        Question(
            text="Vibrations des cylindres induites par l'écoulement des fluides",
            language=Language.FRENCH,
            form=Form.affirmative,
        ),
        Question(
            text="流体の流れによって誘発される円筒の振動",
            language=Language.JAPANESE,
            form=Form.affirmative,
        ),
        # Interrogatives
        Question(
            text="What can you tell me about cylinder vibrations induced by fluid flow?",
            language=Language.ENGLISH,
            form=Form.interrogative,
        ),
        Question(
            text="Que peux-tu me dire sur les vibrations des cylindres induites par l'écoulement des fluides ?",
            language=Language.FRENCH,
            form=Form.interrogative,
        ),
        Question(
            text="流体の流れによって誘発される円筒の振動について教えてください。",
            language=Language.JAPANESE,
            form=Form.interrogative,
        ),
    ],
)

Metrics

We want the right document, not the exact paragraph: once the LLM has the document, it finds the information itself. This choice shapes the whole benchmark and its conclusions. We measure:

  • Top-10 recall (hit rate): the correct document is in the top 10 results.
  • Top-1 recall: the correct document is the first result.
  • MRR (mean reciprocal rank): the average of 1/rank of the correct document. Higher is better.

Chunking strategies

Naive chunking splits the text by characters, with overlap, using LangChain’s RecursiveCharacterTextSplitter. It cuts at natural boundaries but ignores the document structure.

Context-aware chunking parses the markdown into a tree of sections, and each chunk carries its parent headings: a chunk from “Section 2.3 -> Subsection 2.3.1” includes both.

Configurations tested

ParameterValues
Embedding modelAWS Titan V2, Qwen 8B, Mistral Embed
Chunking strategyNaive, context-aware
Chunk sizeTitan V2: 2K, 4K, 6K characters. Qwen 8B: 2K, 10K, 40K. Mistral Embed: 2K
Retrieval modeDense only, hybrid (dense + sparse), sparse only

Results

Embedding models

We only considered embedding models behind an API, so we would not have to run inference ourselves:

  • AWS Titan V2 (amazon.titan-embed-text-v2:0), through AWS Bedrock
  • Qwen 8B (Alibaba-NLP/gte-Qwen2-7B-instruct), through the Hugging Face Inference API (Nebius AI)
  • Mistral Embed (mistral-embed), through the Mistral AI API

All three use naive chunking, 2,000-character chunks and 400 characters of overlap.

model_comparison

ModelHit rate (top 10)
AWS Titan V269.2%
Qwen 8B57.7%
Mistral Embed39.1%

Titan V2 is not even on the MTEB leaderboard, yet it beat both. It is also cheaper, with higher rate limits, and it handled our multilingual and technical vocabulary best.

Standard benchmark conditions hide this. On English affirmative queries only, Mistral is almost level with Titan (76.9% vs 80.8%):

model_comparison_english_affirmative

Across all languages and query forms, Mistral drops to 39.1%, against 69.2% for Titan. Titan is consistent across languages and forms; Mistral only does well in the narrow case. Test embedding models on queries that look like your production queries.

Chunk size

We tested 2K, 4K and 6K characters with Titan V2, and 2K, 10K and 40K characters with Qwen 8B.

titan_naive_chunk_size_comparison

qwen_naive_chunk_size_comparison

Every size landed within a few percentage points. For document-level retrieval this makes sense: one chunk of the right document only has to rank high, and a large chunk still contains the relevant passage.

Large chunks are also cheaper. The inference provider embeds fewer overlapping tokens (lower cost, fewer rate limits), and the vector database stores less, indexes faster and makes fewer comparisons per query. We moved from 2K to 6K characters for Titan V2 and 40K for Qwen 8B. Any reasonable size works: spend the time on the embedding model and the retrieval mode instead.

Chunking strategy

strategy_comparison_titan

strategy_comparison_qwen

Naive chunking beat context-aware chunking with Titan: 71.8% vs 67.9% for the best configurations, and 70.5% vs 63.8% on average with dense-only search. In technical documents, strict structural boundaries can split content that belongs together, and the overlap kept enough context. Start with naive chunking, and only switch if your use case depends on the document structure.

Dense search compares embeddings, so it matches on meaning. Sparse search matches keywords (BM25-like): precise on exact terms, blind to meaning. Hybrid search runs both and fuses the scores. The usual advice is that hybrid wins. Our data says the opposite.

metrics_by_sparse_mode_titan

metrics_by_sparse_mode_qwen

metrics_by_sparse_mode_mistral

With Titan and 2K naive chunks, dense-only reached 69.2% against 63.5% for hybrid. Our guess: on scientific documents, dense embeddings already capture the technical vocabulary, and keyword matches without semantic context add noise. These results are specific to our documents and to Qdrant’s FastEmbed implementation.

Hybrid search, one of the reasons we chose Qdrant, is still useful for exact keyword requirements (regulatory or compliance searches on specific terms) and for rare terms that embeddings handle badly. Benchmark both modes on your own corpus.

Languages and query forms

Hit rate by query language, with the three models pooled:

LanguageHit rate
English73.1%
French48.7%
Japanese44.2%

model_comparison_by_language

Titan led in every language, especially English, and the gap between models was largest in French and Japanese.

model_comparison_by_form

Titan and Mistral do better on affirmative queries. Qwen, surprisingly, does better on questions.

Choices we did not benchmark

PDF conversion: Mistral OCR

We tested four converters by hand on 3 complex PDFs with equations, tables, diagrams and scanned pages: Mistral OCR, Tesseract, Markitdown and Marker. Only Mistral OCR got the mathematical notation and the tables in scanned documents right, even chemical equations, and the gap was dramatic. At $1 per 1,000 pages it is worth it for scientific documents. For simpler PDFs, try the open-source tools first.

Converting everything to markdown matters as much as the converter. When retrieval fails, you open the markdown, search for the passage you expected and see what the chunker did. With a PDF, you are blind. Chunking markdown is also orders of magnitude faster than re-parsing PDFs, so testing a new chunking strategy takes seconds, and markdown can be versioned and diffed. Without this intermediate format, you can’t debug or iterate on a RAG system.

Vector database: Qdrant

We looked at Milvus, Qdrant, AWS OpenSearch, Pinecone and PostgreSQL with pgvector. We were on AWS, so we tried OpenSearch first. Don’t use it for vector search: the cheapest option is $70/day (about $2,100/month) for a single-node cluster.

We picked Qdrant: native hybrid search with FastEmbed, easy self-hosting with Docker, solid performance and features. We later moved to the managed Qdrant Cloud to avoid maintenance, at a reasonable price. Two annoyances: the Cloud admin lacks basic features such as transferring ownership, and collections sometimes stay in “gray mode” for no clear reason until you start the optimization manually.

PostgreSQL was overkill, since we didn’t use PostgreSQL or Aurora for anything else, and Pinecone is not open source. Milvus and Qdrant are the two most-starred open-source vector databases. We tried deploying both on our own server, Milvus took longer, so Qdrant won.

Conclusion

For our documents, the configuration that worked was Titan V2 embeddings, any reasonable chunk size (6K for Titan, 40K for Qwen), naive chunking, dense-only retrieval, Qdrant (or Milvus, but not AWS OpenSearch) and Mistral OCR.

Two of these results, dense-only beating hybrid and naive beating context-aware chunking, went against the usual advice, and they were reproducible and significant. What worked for us may not work for you. Don’t follow best practices from blog posts blindly: measure on your own documents and queries.

Data availability

The documents are proprietary (nuclear engineering research and regulatory material) and the code lives in a private monorepo, so we can’t share either. The excerpts below show the main pieces. I’m happy to answer questions about the method or the results.

Implementation details

Chunking

Naive chunking:

def split_markdown(s3_markdown_path: Path, max_chunk_size: int, strategy: ChunkingStrategy) -> list[str]:
    if strategy == ChunkingStrategy.naive:
        return RecursiveCharacterTextSplitter(
            chunk_size=max_chunk_size,
            chunk_overlap=400,
            add_start_index=True
        ).split_text(markdown_text)

Context-aware chunking:

class Section:
    def __init__(self, body: str = "", title: str | None = None, level: int = 0):
        self.body: str = body
        self.title: str | None = title
        self.level: int = level
        self.children: list[Section] = []

    @classmethod
    def from_markdown(cls, markdown_text: str) -> Section:
        """Parse markdown into hierarchical sections based on heading levels."""
        lines = markdown_text.split("\n")
        root = cls()
        stack = [root]
        for line in lines:
            if line.startswith("#"):
                level = len(line) - len(line.lstrip("#"))
                title = line.lstrip("#").strip()
                new_section = cls(title=title, level=level)
                while stack and stack[-1].level >= level:
                    stack.pop()
                stack[-1]._add_child(new_section)
                stack.append(new_section)
            else:
                if stack:
                    stack[-1].body += line + "\n"
        return root

    def to_chunks(self, max_chunk_size: int, context: str = "") -> list[str]:
        context += self.current_context
        chunks = []
        if self.body.replace("\n", "").strip():
            if len(context) >= max_chunk_size:
                logger.warning(
                    f"Context too large ({len(context)} chars) for max_chunk_size {max_chunk_size}. Skipping context."
                )
                context = ""
            chunks += [
                context + splitted_body
                for splitted_body in _split_text_into_chunks(self.body, max_chunk_size - len(context))
            ]
        for child in self.children:
            chunks += child.to_chunks(max_chunk_size, context)
        return chunks

PDF to markdown with Mistral OCR

Converting a PDF to markdown:

def convert_pdf_to_markdown(pdf_path: Path, output_path: Path) -> tuple[Path, Path]:
    logger.info(f"Start converting PDF {pdf_path} to markdown...")
    pdfs_under_50mb = _split_pdf_to_under_50mb_improved(pdf_path, output_path)

    final_markdown = ""
    final_pages = []
    for pdf in pdfs_under_50mb:
        ocr_response = _convert_pdf_under_50MB_to_markdown(pdf)
        markdown = _get_combined_markdown(ocr_response=ocr_response)
        pages = ocr_response.model_dump()["pages"]
        final_markdown += markdown
        final_pages.extend(pages)

    markdown_path = output_path / f"{pdf_path.stem}.md"
    markdown_path.write_text(final_markdown)
    return markdown_path, yaml_path

The Mistral OCR API call:

def _convert_pdf_under_50MB_to_markdown(pdf_path: Path) -> OCRResponse:
    uploaded_pdf = MISTRAL_CLIENT.files.upload(
        file=File(
            file_name=pdf_path.name,
            content=pdf_path.read_bytes(),
            content_type="application/pdf"
        ),
        purpose="ocr",
    )

    signed_url = MISTRAL_CLIENT.files.get_signed_url(file_id=uploaded_pdf.id)

    return MISTRAL_CLIENT.ocr.process(
        model="mistral-ocr-latest",
        document={"type": "document_url", "document_url": signed_url.url},
        include_image_base64=True,
    )

Embedding models

def get_dense_embedding_model(model: DenseEmbeddingModel) -> Embeddings:
    if model == DenseEmbeddingModel.titan:
        return BedrockEmbeddings(model_id="amazon.titan-embed-text-v2:0")

    if model == DenseEmbeddingModel.qwen:
        return HuggingFaceEndpointEmbeddings(
            client=InferenceClient(provider="nebius", api_key=token),
            model="Qwen/Qwen3-Embedding-8B"
        )

    if model == DenseEmbeddingModel.mistral:
        return MistralAIEmbeddings(
            mistral_api_key=os.environ["PYJIMMY_MISTRAL_API_KEY"],
            model="mistral-embed"
        )

SPARSE_EMBEDDING_MODEL = FastEmbedSparse(model_name="prithvida/Splade_PP_en_v1")

Qdrant vector store

Creating a collection with hybrid search:

def create_vector_store(collection_name: str, model: DenseEmbeddingModel):
    logger.info(f"Creating Qdrant collection {collection_name}...")
    QdrantVectorStore.from_texts(
        texts=[],
        url=QDRANT_URL,
        api_key=QDRANT_API_KEY,
        collection_name=collection_name,
        embedding=get_dense_embedding_model(model),
        sparse_embedding=SPARSE_EMBEDDING_MODEL,
        retrieval_mode=RetrievalMode.HYBRID,
    )

Adding documents, with a retry on embedding API rate limits:

@retry(wait=wait_fixed(60))
def _add_texts_to_vector_store(
    vector_store: QdrantVectorStore,
    texts: list[str],
    s3_folder: Path
) -> list[str]:
    """Retry on failure due to embedding API rate limits."""
    return vector_store.add_texts(
        texts,
        metadatas=[{"s3_folder": s3_folder} for _ in texts]
    )

def add_markdown_to_qdrant(
    s3_markdown_path: Path,
    max_chunk_size: int,
    chunking_strategy: ChunkingStrategy,
    model: DenseEmbeddingModel
):
    chunks = split_markdown(s3_markdown_path, max_chunk_size, strategy=chunking_strategy)
    vector_store = get_vector_store(collection_name, model=model)

    vector_ids = []
    max_chunks_one_request = 10
    for start_index in range(0, len(chunks), max_chunks_one_request):
        vector_ids.extend(
            _add_texts_to_vector_store(
                vector_store,
                chunks[start_index : start_index + max_chunks_one_request],
                s3_folder=s3_folder
            )
        )