{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/DS4SD/docling/blob/main/docs/examples/hybrid_rag_qdrant\n",
    ".ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Hybrid RAG with Qdrant"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Overview"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This example demonstrates using Docling with [Qdrant](https://qdrant.tech/) to perform a hybrid search across your documents using dense and sparse vectors.\n",
    "\n",
    "We'll chunk the documents using Docling before adding them to a Qdrant collection. By limiting the length of the chunks, we can preserve the meaning in each vector embedding."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 👉 Qdrant client uses [FastEmbed](https://github.com/qdrant/fastembed) to generate vector embeddings. You can install the `fastembed-gpu` package if you've got the hardware to support it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip is available: \u001b[0m\u001b[31;49m24.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.3.1\u001b[0m\n",
      "\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "%pip install --no-warn-conflicts -q qdrant-client docling docling-core fastembed"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's import all the classes we'll be working with."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from docling_core.transforms.chunker import HierarchicalChunker\n",
    "from qdrant_client import QdrantClient\n",
    "\n",
    "from docling.datamodel.base_models import InputFormat\n",
    "from docling.document_converter import DocumentConverter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- For Docling, we'll set the  allowed formats to HTML since we'll only be working with webpages in this tutorial.\n",
    "- If we set a sparse model, Qdrant client will fuse the dense and sparse results using RRF. [Reference](https://qdrant.tech/documentation/tutorials/hybrid-search-fastembed/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "c1077c6634d9434584c41cc12f9107c9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Fetching 5 files:   0%|          | 0/5 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "67069c07b73448d491944452159d10bc",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Fetching 29 files:   0%|          | 0/29 [00:00<?, ?it/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "COLLECTION_NAME = \"docling\"\n",
    "\n",
    "doc_converter = DocumentConverter(allowed_formats=[InputFormat.HTML])\n",
    "client = QdrantClient(location=\":memory:\")\n",
    "# The :memory: mode is a Python imitation of Qdrant's APIs for prototyping and CI.\n",
    "# For production deployments, use the Docker image: docker run -p 6333:6333 qdrant/qdrant\n",
    "# client = QdrantClient(location=\"http://localhost:6333\")\n",
    "\n",
    "client.set_model(\"sentence-transformers/all-MiniLM-L6-v2\")\n",
    "client.set_sparse_model(\"Qdrant/bm25\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can now download and chunk the document using Docling. For demonstration, we'll use an article about chunking strategies :)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "result = doc_converter.convert(\n",
    "    \"https://www.sagacify.com/news/a-guide-to-chunking-strategies-for-retrieval-augmented-generation-rag\"\n",
    ")\n",
    "documents, metadatas = [], []\n",
    "for chunk in HierarchicalChunker().chunk(result.document):\n",
    "    documents.append(chunk.text)\n",
    "    metadatas.append(chunk.meta.export_json_dict())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's now upload the documents to Qdrant.\n",
    "\n",
    "- The `add()` method batches the documents and uses FastEmbed to generate vector embeddings on our machine."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['e74ae15be5eb4805858307846318e784',\n",
       " 'f83f6125b0fa4a0595ae6a0777c9d90d',\n",
       " '9cf63c7f30764715bf3804a19db36d7d',\n",
       " '007dbe6d355b4b49af3b736cbd63a4d8',\n",
       " 'e5e31f21f2e84aa68beca0dfc532cbe9',\n",
       " '69c10816af204bb28630a1f957d8dd3e',\n",
       " 'b63546b9b1744063bdb076b234d883ca',\n",
       " '90ad15ba8fa6494489e1d3221e30bfcf',\n",
       " '13517debb483452ea40fc7aa04c08c50',\n",
       " '84ccab5cfab74e27a55acef1c63e3fad',\n",
       " 'e8aa2ef46d234c5a8a9da64b701d60b4',\n",
       " '190bea5ba43c45e792197c50898d1d90',\n",
       " 'a730319ea65645ca81e735ace0bcc72e',\n",
       " '415e7f6f15864e30b836e23ae8d71b43',\n",
       " '5569bce4e65541868c762d149c6f491e',\n",
       " '74d9b234e9c04ebeb8e4e1ca625789ac',\n",
       " '308b1c5006a94a679f4c8d6f2396993c',\n",
       " 'aaa5ec6d385a418388e660c425bf1dbe',\n",
       " '630be8e43e4e4472a9cdb9af9462a43a',\n",
       " '643b316224de4770a5349bf69cf93471',\n",
       " 'da9265e6f6c2485493d15223eefdf411',\n",
       " 'a916e447d52c4084b5ce81a0c5a65b07',\n",
       " '2883c620858e4e728b88e127155a4f2c',\n",
       " '2a998f0e9c124af99027060b94027874',\n",
       " 'be551fbd2b9e42f48ebae0cbf1f481bc',\n",
       " '95b7f7608e974ca6847097ee4590fba1',\n",
       " '309db4f3863b4e3aaf16d5f346c309f3',\n",
       " 'c818383267f64fd68b2237b024bd724e',\n",
       " '1f16e78338c94238892171b400051cd4',\n",
       " '25c680c3e064462cab071ea9bf1bad8c',\n",
       " 'f41ab7e480a248c6bb87019341c7ca74',\n",
       " 'd440128bed6d4dcb987152b48ecd9a8a',\n",
       " 'c110d5dfdc5849808851788c2404dd15']"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "client.add(COLLECTION_NAME, documents=documents, metadata=metadatas, batch_size=64)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Query Documents"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<=== Retrieved documents ===>\n",
      "Document Specific Chunking is a strategy that respects the document's structure. Rather than using a set number of characters or a recursive process, it creates chunks that align with the logical sections of the document, like paragraphs or subsections. This approach maintains the original author's organization of content and helps keep the text coherent. It makes the retrieved information more relevant and useful, particularly for structured documents with clearly defined sections.\n",
      "Document Specific Chunking can handle a variety of document formats, such as:\n",
      "Consequently, there are also splitters available for this purpose.\n",
      "1. We start at the top of the document, treating the first part as a chunk.\n",
      "   2. We continue down the document, deciding if a new sentence or piece of information belongs with the first chunk or should start a new one.\n",
      "    3. We keep this up until we reach the end of the document.\n",
      "Have you ever wondered how we, humans, would chunk? Here's a breakdown of a possible way a human would process a new document:\n",
      "The goal of chunking is, as its name says, to chunk the information into multiple smaller pieces in order to store it in a more efficient and meaningful way. This allows the retrieval to capture pieces of information that are more related to the question at hand, and the generation to be more precise, but also less costly, as only a part of a document will be included in the LLM prompt, instead of the whole document.\n",
      "To put these strategies into action, there's a whole array of tools and libraries at your disposal. For example, llama_index is a fantastic tool that lets you create document indices and retrieve chunked documents. Let's not forget LangChain, another remarkable tool that makes implementing chunking strategies a breeze, particularly when dealing with multi-language data. Diving into these tools and understanding how they can work in harmony with the chunking strategies we've discussed is a crucial part of mastering Retrieval Augmented Generation.\n",
      "Semantic chunking involves taking the embeddings of every sentence in the document, comparing the similarity of all sentences with each other, and then grouping sentences with the most similar embeddings together.\n",
      "You can see here that with a chunk size of 105, the Markdown structure of the document is taken into account, and the chunks thus preserve the semantics of the text!\n",
      "And there you have it! These chunking strategies are like a personal toolbox when it comes to implementing Retrieval Augmented Generation. They're a ton of ways to slice and dice text, each with its unique features and quirks. This variety gives you the freedom to pick the strategy that suits your project best, allowing you to tailor your approach to perfectly fit the unique needs of your work.\n"
     ]
    }
   ],
   "source": [
    "points = client.query(COLLECTION_NAME, query_text=\"Can I split documents?\", limit=10)\n",
    "\n",
    "print(\"<=== Retrieved documents ===>\")\n",
    "for point in points:\n",
    "    print(point.document)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
