<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mayank Nagori on Medium]]></title>
        <description><![CDATA[Stories by Mayank Nagori on Medium]]></description>
        <link>https://medium.com/@mayanknagori333?source=rss-65f65923ab3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*R4CjKuFMbedUAaH7</url>
            <title>Stories by Mayank Nagori on Medium</title>
            <link>https://medium.com/@mayanknagori333?source=rss-65f65923ab3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:26:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mayanknagori333/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Batch Tool Calls vs Batch Model Calls: The Hidden Scaling Layer in GenAI Systems]]></title>
            <link>https://medium.com/@mayanknagori333/batch-tool-calls-vs-batch-model-calls-the-hidden-scaling-layer-in-genai-systems-01c479e0cc1b?source=rss-65f65923ab3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/01c479e0cc1b</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[batch-open-ai-call]]></category>
            <category><![CDATA[batch-tool-call]]></category>
            <category><![CDATA[ai-tool-calling]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Mayank Nagori]]></dc:creator>
            <pubDate>Mon, 02 Feb 2026 15:00:22 GMT</pubDate>
            <atom:updated>2026-02-02T15:00:22.737Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Stop trading speed for scale. Discover how to slash latency with parallel tool execution while cutting API costs by 50% using batch inference. 🚀</blockquote><figure><img alt="Stop trading speed for scale. Discover how to slash latency with parallel tool execution while cutting API costs by 50% using batch inference. 🚀" src="https://cdn-images-1.medium.com/max/1024/1*jD6ADzoiZmkcIU3GO3fiHA.png" /></figure><p><strong>Why “Batching” is the most overloaded term in AI Engineering — and how to use it to optimize for both Latency and Economics.<br></strong>In the early stages of GenAI development, “batching” is often treated as a single toggle switch used to “make things faster.” However, at the production scale, this lack of nuance becomes an architectural bottleneck.</p><p>To build systems that are both snappy for users and sustainable for the balance sheet, you must distinguish between two fundamentally different layers of the stack: <strong>Execution</strong> and <strong>Inference</strong>.</p><blockquote>One optimizes for the user’s clock, the other for your company’s wallet. Here is how to master both.</blockquote><h3>⚙️ 1. Batch Tool Calling (The Execution Layer)</h3><blockquote><strong>Primary Metric:</strong> Latency | <strong>System Type:</strong> Real-time / Agentic</blockquote><p>Batch tool calling is an orchestration strategy. It is not about sending many prompts to an LLM; it is about how your system handles the <strong>external actions</strong> the LLM requests.</p><h4>The Problem: The Sequential Waterfall</h4><p>When an agent needs to answer a complex query, it often requires multiple data points. A standard “ReAct” (Reason-Act) loop usually executes these sequentially:</p><ol><li><strong>Model</strong> requests Tool A ➡️ <strong>System</strong> executes Tool A ➡️ <strong>System</strong> returns result to Model.</li><li><strong>Model</strong> requests Tool B ➡️ <strong>System</strong> executes Tool B ➡️ <strong>System</strong> returns result to Model.</li></ol><p>This creates a <strong>linear latency accumulation</strong>. If each tool takes 2 seconds, your user is waiting 4+ seconds just for the data gathering phase.</p><h4>The Solution: Parallel Orchestration</h4><p>Modern model APIs (like OpenAI’s parallel_tool_calls or LangChain’s async support) allow the model to suggest multiple tools in a single turn. The system then executes these tools concurrently.🍕 2. Real-Time Use Case — Food Order Assistant</p><h3>User Query:</h3><blockquote>“Where is my pizza order and when will it arrive?”To answer, the system must:</blockquote><p>Fetch order details<br>Check delivery tracking<br>Load refund/cancellation policy</p><h3>💻 Code — Batch Tool Calls (LangChain + Azure OpenAI)</h3><h4>❌ Without Batching (Sequential)</h4><pre>order = get_order(order_id)<br>tracking = get_delivery_status(order_id)<br>policy = get_refund_policy()<br><br>response = llm.invoke(f&quot;&quot;&quot;<br>Order: {order}<br>Tracking: {tracking}<br>Policy: {policy}<br>Answer the user.<br>&quot;&quot;&quot;)</pre><p>This causes unnecessary latency because each tool waits for the previous one.</p><h4>✅ With Batch Tool Calls (Parallel Execution)</h4><pre>import asyncio<br>from langchain_openai import AzureChatOpenAI<br>lm = AzureChatOpenAI(<br>    azure_endpoint=&quot;https://&lt;your-resource&gt;.openai.azure.com/&quot;,<br>    deployment_name=&quot;gpt-4.1&quot;,<br>    api_version=&quot;2025-01-01-preview&quot;,<br>    api_key=&quot;&lt;API_KEY&gt;&quot;,<br>)<br>async def handle_food_order(order_id):<br>    order_task = get_order(order_id)<br>    tracking_task = get_delivery_status(order_id)<br>    policy_task = get_refund_policy()<br>    order, tracking, policy = await asyncio.gather(<br>        order_task, tracking_task, policy_task<br>    )<br>    response = await llm.ainvoke(f&quot;&quot;&quot;<br>    Order: {order}<br>    Tracking: {tracking}<br>    Policy: {policy}<br>    Answer the customer.<br>    &quot;&quot;&quot;)<br>    return response.content</pre><h3>💡 Why This Works</h3><ol><li>All tools execute in parallel</li><li>Only one LLM reasoning step</li><li>Faster end-user response</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*0SxIfIQPuUBH7LqmETVJqg.png" /></figure><blockquote><strong>Key Insight:</strong> Batch Tool Calling turns a O(n) latency problem into a O(1) (constant time of the slowest tool) problem.</blockquote><h3>🧠Batch Model Calls (The Inference Layer)</h3><blockquote><strong>Primary Metric:</strong> Economics &amp; Throughput | <strong>System Type:</strong> Asynchronous / Offline</blockquote><p>Batching at the inference layer is a <strong>provider-level optimization</strong>. This is where you group thousands of independent prompts into a single job and submit them to the model provider (OpenAI, Gemini, or Azure).</p><h4>The Problem: Real-time Overhead &amp; Token Costs</h4><p>Sending 50,000 document summarization requests via standard Chat Completion endpoints is an architectural error. You are paying a “convenience premium” for a 2-second response that you don’t actually need for a background job.</p><h4>The Solution: Asynchronous Batch APIs</h4><p>By using the <strong>Batch API</strong>, you trade immediate delivery for a massive reduction in cost and a significantly higher rate limit.</p><ul><li><strong>50% Cost Reduction:</strong> Providers typically offer a 50% discount on tokens for batch jobs.</li><li><strong>Massive Throughput:</strong> Batch jobs often have separate, much larger rate limits (up to 50,000 requests per job).</li><li><strong>Turnaround:</strong> Usually guaranteed within 24 hours, though often finished in minutes.</li></ul><h3>6. Code — Batch Model Calls (Azure OpenAI Batch API)</h3><h4>❌ Without Batching</h4><pre>results = []<br>for doc in documents:<br>    res = llm.invoke(f&quot;Summarize this document:\n{doc}&quot;)<br>    results.append(res.content)</pre><p>This:</p><ul><li>Creates one request per document</li><li>Costs more</li><li>Scales poorly</li></ul><h4>✅ With Batch Model Calls (True Batch API)</h4><pre>from openai import AzureOpenAI<br>import json<br>client = AzureOpenAI(<br>    api_key=&quot;&lt;API_KEY&gt;&quot;,<br>    api_version=&quot;2025-01-01-preview&quot;,<br>    azure_endpoint=&quot;https://&lt;your-resource&gt;.openai.azure.com/&quot;<br>)<br>batch_requests = [<br>    {<br>        &quot;custom_id&quot;: f&quot;doc_{i}&quot;,<br>        &quot;method&quot;: &quot;POST&quot;,<br>        &quot;url&quot;: &quot;/chat/completions&quot;,<br>        &quot;body&quot;: {<br>            &quot;model&quot;: &quot;gpt-4.1&quot;,<br>            &quot;messages&quot;: [<br>                {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a document summarizer.&quot;},<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Summarize this document:\n{doc}&quot;}<br>            ]<br>        }<br>    }<br>    for i, doc in enumerate(documents)<br>]<br>with open(&quot;batch.jsonl&quot;, &quot;w&quot;) as f:<br>    for req in batch_requests:<br>        f.write(json.dumps(req) + &quot;\n&quot;)<br>batch_job = client.batches.create(<br>    input_file=&quot;batch.jsonl&quot;,<br>    endpoint=&quot;/chat/completions&quot;,<br>    completion_window=&quot;24h&quot;<br>)<br>print(&quot;Batch job submitted:&quot;, batch_job.id)</pre><p>Later:</p><pre>results = client.batches.retrieve(batch_job.id)<br>output = client.files.content(results.output_file_id)<br><br>for line in output.decode().splitlines():<br>    print(json.loads(line)[&quot;response&quot;][&quot;choices&quot;][0][&quot;message&quot;][&quot;content&quot;])</pre><h3>💡 Why This Works</h3><ul><li>Thousands of documents processed in one job</li><li>Much lower cost per request</li><li>Ideal for offline pipelines</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*VmB_5hq9R6kwMMtCLUopLA.png" /></figure><h3>🚀 Final Takeaway</h3><p>Most “slow” GenAI systems aren’t limited by the model’s speed — they are limited by poorly designed execution paths. Similarly, most “expensive” systems are paying for real-time speed on tasks that no human is watching.</p><p>The rule of thumb is simple:</p><ul><li>If a human is waiting: <strong>Parallelize your tools.</strong></li><li>If a database is waiting: <strong>Batch your inference.</strong></li></ul><p>Architecting for these two layers is the difference between a high-utility production platform and an expensive science project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01c479e0cc1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parsing Unstructured Documents: A Practical Guide with Docling]]></title>
            <link>https://medium.com/@mayanknagori333/parsing-unstructured-documents-a-practical-guide-with-docling-9d531ce7de31?source=rss-65f65923ab3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d531ce7de31</guid>
            <category><![CDATA[rag-pip]]></category>
            <category><![CDATA[pdf-parsing]]></category>
            <category><![CDATA[docling]]></category>
            <dc:creator><![CDATA[Mayank Nagori]]></dc:creator>
            <pubDate>Mon, 14 Jul 2025 19:11:25 GMT</pubDate>
            <atom:updated>2025-07-14T19:11:25.091Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Introduction:</em></strong><br>When creating a RAG (Retrieval Augmented Generation) based system for enterprises, we often deal with <strong>unstructured documents</strong> like feature specification, user manuals, product detail documentation, service documents, and HR policies.</p><p>Document parsing is the process of analyzing a document’s structure and content to extract meaningful information. For a RAG bot to be truly effective with these documents, proper extraction (parsing) into different formats — based on our metadata storage and subsequent vectorization and storage needs — is crucial.</p><p>Before diving into the various ways to use Docling, let’s first understand what Docling is.</p><p><strong>About Docling :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*eMwBgKuCWmp_YSby7z8zqw.png" /><figcaption>Source: Docling-Parser</figcaption></figure><p>Docling, a powerful and versatile <strong>open-source document parsing tool</strong> developed by IBM Research, offers a seamless solution to the challenge of unstructured data. By understanding the intricacies of document structures, Docling can extract valuable insights and transform them into a structured format <strong>— a process absolutely fundamental for RAG bots to retrieve relevant, high-quality information.</strong> You can find all about it on its official GitHub repository: <a href="https://github.com/DS4SD/docling">https://github.com/DS4SD/docling</a>.</p><p><strong>Features / Key benefits of Docling:</strong></p><ul><li>🗂️ Parsing of <a href="https://ds4sd.github.io/docling/supported_formats/">multiple document formats</a> incl. PDF, DOCX, XLSX, HTML, images, and more</li><li>📑 Advanced PDF understanding incl. page layout, reading order, table structure, code, formulas, image classification, and more</li><li>🧬 Unified, expressive <a href="https://ds4sd.github.io/docling/concepts/docling_document/">DoclingDocument</a> representation format</li><li>↪️ Various <a href="https://ds4sd.github.io/docling/supported_formats/">export formats</a> and options, including Markdown, HTML, and lossless JSON</li><li>🔒 Local execution capabilities for sensitive data and air-gapped environments</li><li>🤖 Plug-and-play <a href="https://ds4sd.github.io/docling/integrations/">integrations</a> incl. LangChain, LlamaIndex, Crew AI &amp; Haystack for agentic AI</li><li>🔍 Extensive OCR support for scanned PDFs and images</li><li>💻 Simple and convenient CLI</li></ul><p><strong><em>BASIC document conversion using docling :</em></strong></p><ul><li>Setting up virtual environment</li></ul><pre>python -m venv .venv</pre><ul><li>Create a requirements.txt file and run it to install the package files</li></ul><pre>docling==2.34.0</pre><ul><li>Run the requirements.txt file</li></ul><pre>PS C:Desktop\docling&gt;.venv\scripts\activate<br>(.venv) PS C:Desktop\docling&gt; pip install -r requirements.txt </pre><h3>Converting Document to Markdown:</h3><p>Docling supports different input document types like PDF, DOCX, XLSX, HTML etc, into various export formats and options, including Markdown, HTML, and lossless JSON. In this we will look converting PDF into markdown format.</p><p>There are 2 ways in which the PDFs can be stored in terms of markdown.<br>1) export_to_markdown -&gt; this can be used for testing purpose to check on how the pdf gets parsed as markdown <strong>before feeding it into your RAG pipeline.</strong><br>2) save_to_markdown -&gt; tthis enables to save the pdf to markdown with additional attributes enabling user defined path, storing images format(which we will discuss in the advance options) <strong>— essential for creating a persistent and comprehensive knowledge base for your RAG bot.</strong>”</p><h4>Simple Conversion Example:</h4><p>The code below converts a document to Markdown and prints the output to the terminal this can be used for testing purpose to check on how the pdf gets parsed as markdown</p><pre>from docling.document_converter import DocumentConverter<br>source = &quot;your_document.pdf&quot; # document path from local<br>converter = DocumentConverter()<br>doc = converter.convert(source).document  # source can be anything <br>print(doc.export_to_markdown())</pre><h4>Converting Multiple PDFs and Saving to a Folder</h4><p>To process multiple PDF documents from a local folder and save them into a specific output directory.</p><pre>from pathlib import Path<br>from docling.document_converter import InputFormat  <br>from docling.document_converter import DocumentConverter, PdfFormatOption<br><br>#iterate over the pdf files in the folder<br>pdf_folder =  Path(&quot;your_document_file_path.pdf&quot;) <br>pdf_files = list(pdf_folder.glob(&quot;*.pdf&quot;))<br>converter = DocumentConverter(format_options={InputFormat.PDF: PdfFormatOption()})<br>                              <br>for pdf_file in pdf_files:  <br>    result = converter.convert(pdf_file)<br>    result.document.save_as_markdown(Path(&quot;output&quot;) / f&quot;{pdf_file.stem}.md&quot;)</pre><h3>Running Docling Models Locally:</h3><p>When running Docling for the first time, it automatically downloads and installs its models locally, caching them for subsequent runs. However, you can explicitly download the models and direct Docling to use them from a specific local path.</p><h4>Downloading Models Locally</h4><p>Docling uses an open-source model developed by IBM, which can be downloaded from Hugging Face.</p><blockquote>Note: The recommended folder structure for the downloaded model is ./models, as the code expects the base path to be models with internal subdirectories for other models.</blockquote><pre># To download only the standard Docling model<br>from huggingface_hub import snapshot_download<br><br>snapshot_download(<br>    repo_id=&quot;ds4sd/docling-models&quot;,<br>    local_dir=r&#39;C:/Desktop/docling/models&#39;,  # Adjust the path as needed<br>    local_dir_use_symlinks=False,<br>)<br><br># Another way to download all Docling models (including code-formula, EasyOCR)<br>from pathlib import Path<br>from docling.utils.model_downloader import download_models<br><br>download_models(output_dir=Path(&#39;your_local_path/models&#39;))</pre><h4>Using Locally Downloaded Models</h4><p>To instruct Docling to use the locally downloaded model, you need to specify the artifacts_path in the pipeline_options. If this attribute is not specified, Docling will check its cache or download the models on the first run.</p><pre>import os<br>from pathlib import Path<br>from docling.document_converter import DocumentConverter, PdfFormatOption <br>from docling.datamodel.base_models import InputFormat<br>from docling.datamodel.pipeline_options import (<br>    PdfPipelineOptions,<br>    AcceleratorOptions,<br>    AcceleratorDevice,<br>)<br>from docling.backend.docling_parse_v2_backend import DoclingParseV2DocumentBackend<br>pdf_folder =  Path(&quot;.\pdf_file&quot;) <br>pdf_files = list(pdf_folder.glob(&quot;*.pdf&quot;))<br><br># to change the artifacts_path<br>pipeline_options = PdfPipelineOptions(<br>    accelerator_options=accelerator_options,<br>    artifacts_path=&quot;C:/Desktop/docling/models&quot;,  # local path <br>)<br><br># Changes in the DocumentConverter<br>converter = DocumentConverter(<br>        format_options={<br>            InputFormat.PDF: PdfFormatOption(<br>                pipeline_options=pipeline_options,<br>                backend=DoclingParseV2DocumentBackend,<br>            )<br>        }<br>    )<br><br>for pdf_file in pdf_files:<br>    result = converter.convert(pdf_file)<br>    result.document.save_as_markdown(Path(&quot;output&quot;) / f&quot;{pdf_file.stem}.md&quot;))</pre><h4>Running Models with GPU</h4><p>One of Docling’s most compelling features is its ability to run on <strong>GPU</strong>, significantly improving content extraction performance and speed. Faster parsing means quicker indexing of new or updated documents, keeping your RAG bot’s knowledge base fresh and responsive Additionally, it excels at <strong>extracting images</strong> from documents.</p><p>When utilizing GPU, Docling offers flexibility in specifying whether to use a specific GPU or any available GPU/CPU. This is configured through the AcceleratorOptions.</p><ul><li>If AcceleratorDevice is set to AUTO, Docling will first check for a GPU. If none is found, it will default to using the CPU.</li><li>If AcceleratorDevice is set to CUDA, it will run on any available GPU in the system.</li><li>For specific GPU usage, set AcceleratorOptions(device=&quot;cuda:N&quot;), where N is the GPU number (e.g., cuda:0 for GPU 1, cuda:1 for GPU 2, etc.). This allows you to target a particular GPU.</li></ul><blockquote>Note: While num_threadsvariable is currently not utilized for GPU processing in the present Docling version, as in the library code only it does help improve speed when running on a CPU.</blockquote><p>Below is the code demonstrating how to leverage GPU and enable image extraction with Docling.</p><pre>import os<br>from pathlib import Path<br>from docling.document_converter import DocumentConverter, PdfFormatOption <br>from docling.datamodel.base_models import InputFormat<br>from docling.datamodel.pipeline_options import (<br>    PdfPipelineOptions,<br>    AcceleratorOptions,<br>    AcceleratorDevice,<br>)<br>from docling.backend.docling_parse_v2_backend import DoclingParseV2DocumentBackend<br>pdf_folder =  Path(&quot;.\pdf_file&quot;) <br>pdf_files = list(pdf_folder.glob(&quot;*.pdf&quot;))<br><br>    # Explicitly set the accelerator<br>    # accelerator_options = AcceleratorOptions(<br>    #     num_threads=8, device=AcceleratorDevice.AUTO<br>    # )<br><br>    # accelerator_options = AcceleratorOptions(<br>    #     num_threads=8, device=AcceleratorDevice.CPU<br>    # )<br><br>    # easyocr doesnt support cuda:N allocation, defaults to cuda:0<br>    # accelerator_options = AcceleratorOptions(num_threads=8, device=&quot;cuda:1&quot;)<br><br># changing the accelerator options <br>accelerator_options = AcceleratorOptions(<br>        num_threads=8,<br>        device=AcceleratorDevice.CUDA,<br>    )<br><br>pipeline_options = PdfPipelineOptions(<br>    accelerator_options=accelerator_options,<br>    artifacts_path=&quot;C:/Users/Desktop/docling/models&quot;,<br>    generate_picture_images=True, # to make sure we download the images. <br>    images_scale=1.0, <br>)<br>converter = DocumentConverter(<br>        format_options={<br>            InputFormat.PDF: PdfFormatOption(<br>                pipeline_options=pipeline_options,<br>                backend=DoclingParseV2DocumentBackend,<br>            )<br>        }<br>    )<br><br>for pdf_file in pdf_files:<br>    result = converter.convert(pdf_file)<br>    result.document.save_as_markdown(Path(&quot;output&quot;) / f&quot;{pdf_file.stem}.md&quot;)<br>  </pre><h3><strong>Advance Options in docling</strong></h3><p>This section delves into some advanced usage options, specifically focusing on image and table extraction.</p><h4>Image Extraction</h4><p>For developing a RAG-based system, image extraction becomes crucial to provide users with additional insights and make the system more adaptable. <strong>A RAG bot that can interpret visual content, not just text, will deliver far more comprehensive and accurate answers, especially when dealing with technical documentation, reports, or schematics.</strong>”</p><p>Most documents don’t solely contain text; they often include images to support their content. For developing a RAG-based system, image extraction becomes crucial to provide users with additional insights and make the system more adaptable.</p><p>While many PDF extraction techniques struggle with picture extraction, Docling offers robust capabilities to extract images based on user needs.</p><p>Images can be handled in two main ways:</p><ol><li><strong>Embedded in the Document</strong>: While processing via an LLM, the LLM then converts them back to their actual image format. This approach is often less preferred due to: Increased Document Size: Can cause issues during chunking <strong>for RAG, potentially leading to context window limits.</strong> Increased LLM Load: Places a heavier burden on the LLM to reconstruct images, <strong>impacting inference speed and cost for RAG queries.</strong>”</li><li><strong>Referenced in a Separate Folder</strong>: The extracted document (in Markdown or other format) then contains a reference path to the externally stored image. <strong>This is generally preferred for RAG, as it allows for cleaner text chunks while still providing access to the visual context when needed, for example, through a multimodal embedding strategy or by simply showing the image alongside the textual answer.</strong>”</li></ol><blockquote>Note: images_scale= 3.0, can be modified to improve the image quality</blockquote><pre>import os<br>from docling.datamodel.base_models import InputFormat<br>from docling_core.types.doc import ImageRefMode, PictureItem, TableItem<br>from docling.document_converter import DocumentConverter, PdfFormatOption<br>from docling.datamodel.pipeline_options import (<br>    PdfPipelineOptions, AcceleratorOptions, AcceleratorDevice<br>)<br>from docling.backend.docling_parse_v4_backend import DoclingParseV4DocumentBackend<br><br>from pathlib import Path<br>artifacts_path=&quot;C:/Users/z0047npb/Desktop/docling/models&quot;<br>accelerator_options = AcceleratorOptions(num_threads=8, device=AcceleratorDevice.CUDA, cuda_use_flash_attention2=False,)<br><br>pipeline_options = PdfPipelineOptions(<br>    accelerator_options=accelerator_options,<br>    artifacts_path=artifacts_path,<br>    #generate_page_images=False,<br>    generate_picture_images=True,<br>    images_scale= 3.0  <br>)<br>pipeline_options.do_ocr = False # Bonus Tip : 01 improving the speed of the pipeline    <br>pipeline_options.do_table_structure = True<br><br>pdf_path = &quot;your pdf path&quot;<br>markdown_folder = &quot;output folder&quot; <br>os.makedirs(markdown_folder, exist_ok=True)<br><br>converter = DocumentConverter(<br>    format_options={<br>        InputFormat.PDF: PdfFormatOption(<br>            pipeline_options=pipeline_options,<br>            backend=DoclingParseV4DocumentBackend,<br>        )<br>    }<br>)<br><br>doc_filename = os.path.splitext(os.path.basename(pdf_path))[0]<br>print(doc_filename)<br>image_folder = Path(markdown_folder) / &quot;images&quot; / doc_filename<br>image_folder.mkdir(parents=True, exist_ok=True)<br><br>result = converter.convert(pdf_path)<br><br># Save markdown with embedded pictures<br># md_filename = os.path.join(markdown_folder, f&quot;{doc_filename}&quot;+ &quot;with_image_embed.md&quot;)  <br># result.document.save_as_markdown(md_filename, image_mode=ImageRefMode.EMBEDDED)<br><br># Save markdown with externally referenced pictures<br>md_filename = os.path.join(markdown_folder, f&quot;{doc_filename}&quot;+ &quot;with_image_ref.md&quot;)  <br>result.document.save_as_markdown(md_filename,image_mode=ImageRefMode.REFERENCED,artifacts_dir=image_folder)</pre><h4>Custom Image Naming</h4><p>When storing images, Docling sometimes adds a 64-bit encoding to the end of the image name. While often unproblematic, during RAG retrieval, LLMs might truncate some of this encoding, leading to path errors and unretrieved images. In a RAG context, this means the LLM might hallucinate or provide incomplete answers if it cannot access the referenced visual context To mitigate this, you can provide custom, shorter names for images, enabling better debugging.</p><pre>picture_counter = 0<br>md_filename = os.path.join(markdown_folder, f&quot;{doc_filename}&quot;+ &quot;_with_ref_cutom_image.md&quot;) <br>for element, _level in result.document.iterate_items():<br>    if isinstance(element, PictureItem):<br>        picture_counter +=1<br>        element_image_filename  = (image_folder/ f&quot;{doc_filename}-picture-{picture_counter}.png&quot;)<br>    <br>        with element_image_filename.open(&quot;wb&quot;) as img_file:<br>            element.get_image(result.document).save(img_file, &quot;PNG&quot;)<br>            element.image.uri = element_image_filename<br><br>result.document.save_as_markdown(md_filename,image_mode=ImageRefMode.REFERENCED,artifacts_dir=image_folder)</pre><h4>Table Extraction</h4><p>Not all PDFs contain only text and images; many are rich in tables that need to be accurately converted (e.g., to Markdown, TXT, JSON) for further processing. Docling handles table extraction effectively. <strong>Accurate table parsing is vital for RAG bots that need to answer questions based on structured data like financial reports, product specifications, or compliance documents. Poorly parsed tables lead directly to incorrect or unanswerable queries.</strong>”</p><pre>import os<br>from docling.datamodel.base_models import InputFormat<br>from docling_core.types.doc import ImageRefMode, PictureItem, TableItem<br>from docling.document_converter import DocumentConverter, PdfFormatOption<br>from docling.datamodel.pipeline_options import (<br>    PdfPipelineOptions, AcceleratorOptions, AcceleratorDevice<br>)<br>from docling.backend.docling_parse_v4_backend import DoclingParseV4DocumentBackend<br>from pathlib import Path<br><br>artifacts_path=&quot;local model path&quot;<br>accelerator_options = AcceleratorOptions(num_threads=8, device=AcceleratorDevice.CUDA, cuda_use_flash_attention2=False,)<br><br>pipeline_options = PdfPipelineOptions(<br>    accelerator_options=accelerator_options,<br>    artifacts_path=artifacts_path,<br>    #generate_page_images=False,<br>    generate_picture_images=True,<br>    images_scale= 1.0 <br>)<br>pipeline_options.do_ocr = False # Bonus Tip : 01 improving the speed of the pipeline    <br>pipeline_options.do_table_structure = True # extract tables <br><br>pdf_path = &quot;your pdf path&quot;<br>markdown_folder = &quot;output folder&quot; <br>os.makedirs(markdown_folder, exist_ok=True)<br><br>converter = DocumentConverter(<br>    format_options={<br>        InputFormat.PDF: PdfFormatOption(<br>            pipeline_options=pipeline_options,<br>            backend=DoclingParseV4DocumentBackend,<br>        )<br>    }<br>)<br><br>doc_filename = os.path.splitext(os.path.basename(pdf_path))[0]<br>print(doc_filename)<br>result = converter.convert(pdf_path)<br><br># storing the tables from the pdf<br>for element, _level in result.document.iterate_items():<br>    if isinstance(element, TableItem):<br>        table_counter += 1<br>        element_image_filename = (<br>            output_dir_path / f&quot;{doc_filename}-table-{table_counter}.png&quot;<br>        )<br>        with element_image_filename.open(&quot;wb&quot;) as fp:<br>            element.get_image(result.document).save(fp, &quot;PNG&quot;)</pre><h4>Converting Tables to JSON</h4><p>PDF’s which contains only tables and need to be converted into json. This is particularly useful for RAG pipelines where structured data can be directly ingested into vector databases or used to create highly precise retrieval mechanisms for tabular questions.</p><pre>import json<br>import pandas as pd <br>all_tables_json = []<br>for table_ix, table in enumerate(result.document.tables):<br>    table_df: pd.DataFrame = table.export_to_dataframe()<br>    <br>    all_tables_json.append(table_df.to_dict(orient=&quot;records&quot;))<br><br>merged_json_filename = output_dir_path / f&quot;{doc_filename}-all-tables.json&quot;<br>print(f&quot;Saving all tables to {merged_json_filename}&quot;)<br>with open(merged_json_filename, &quot;w&quot;, encoding=&quot;utf-8&quot;) as f:<br>    json.dump(all_tables_json, f, indent=2, ensure_ascii=False)<br><br><br>print(f&quot;Total tables extracted: {len(result.document.tables)}&quot;) </pre><h3>Bonus Tips to Optimize Docling Performance:</h3><p>Can we improve the speed at which we process documents or enhance GPU utilization? Yes, by tweaking some Docling pipeline parameters.</p><h4>Bonus Tip 01: Disabling OCR</h4><p>By setting the do_ocr option to False (its default is True), you can significantly improve the document extraction speed. <strong>F</strong>or RAG applications, faster parsing reduces the latency for indexing new data and ensures your bot always has access to the most up-to-date information without unnecessary computational overhead.</p><pre>pipeline_options.do_ocr = False # Bonus Tip : 01 improving the speed of the pipeline</pre><h4>Bonus Tip 02: Parallel Processing</h4><p>you can still process PDFs in batches by triggering different processes under the same GPU instance making use of using Python’s multiprocessing module, or a job queue system. <strong>This directly impacts the scalability of your RAG data pipeline, allowing you to quickly process vast corporate knowledge bases and keep them current.</strong></p><p>For the complete code showcasing both bonus tips, please refer to my attached <a href="https://github.com/Mayank-Nagori/Docling-Guides-and-Notebooks">GitHub </a>repository.</p><h3>Conclusion</h3><p>Docling stands out as a robust and versatile tool for parsing unstructured documents, a critical step in building effective RAG bots. Its ability to handle diverse formats, extract complex elements like tables and images, and integrate with leading AI frameworks makes it an invaluable asset for enterprise-level document processing.</p><h4>Advantages of Docling:</h4><ul><li><strong>Comprehensive Document Understanding</strong>: Goes beyond basic text extraction to understand complex layouts, tables, and images.</li><li><strong>Versatility</strong>: Supports numerous input and output formats, offering flexibility for various use cases.</li><li><strong>Local Processing</strong>: Ensures data privacy and security by allowing local execution, crucial for sensitive enterprise data.</li><li><strong>Performance with GPU</strong>: Leverages GPU acceleration for faster processing of large document sets.</li><li><strong>Integration Ready</strong>: Seamlessly plugs into popular LLM frameworks, simplifying RAG bot development.</li></ul><p>Overall, Docling empowers developers to transform raw, unstructured information into usable, structured data, laying a solid foundation for advanced AI applications like RAG bots. Its features make it a strong contender for any serious document parsing task.</p><h3>Links</h3><ul><li>Git repo link : <a href="https://github.com/Mayank-Nagori/Docling-Guides-and-Notebooks">https://github.com/Mayank-Nagori/Docling-Guides-and-Notebooks</a></li><li>Docling GitHub repository: <a href="https://github.com/docling-project/docling">https://github.com/docling-project/docling</a></li><li>Docling usage Example: <a href="https://docling-project.github.io/docling/examples/run_with_accelerator/">https://doclingproject.github.io/docling/examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d531ce7de31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>