<?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 Prashant Dixit on Medium]]></title>
        <description><![CDATA[Stories by Prashant Dixit on Medium]]></description>
        <link>https://medium.com/@prasantdixit?source=rss-618dcd408dc4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0s0uKolQ25skpyrJLFuNOg.jpeg</url>
            <title>Stories by Prashant Dixit on Medium</title>
            <link>https://medium.com/@prasantdixit?source=rss-618dcd408dc4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:55:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prasantdixit/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[Superlinked Inference Engine]]></title>
            <link>https://pub.towardsai.net/superlinked-inference-engine-f7556613a808?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7556613a808</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Mon, 07 Sep 2026 13:01:02 GMT</pubDate>
            <atom:updated>2026-09-07T13:01:02.611Z</atom:updated>
            <content:encoded><![CDATA[<h4>Your Agent Doesn’t Need One Big Model. It Needs a Fleet of Small Ones — And Somewhere to Put Them.</h4><p>Everyone talks about the LLM in an AI agent. Almost nobody talks about everything else the agent calls before it ever reaches that LLM.</p><p>Walk through a single turn of a realistic retrieval-augmented agent: it embeds the incoming query, reranks the candidates that search turned up, pulls structured fields out of a PDF nobody formatted for machines, and maybe runs a small guard model to check the input is safe to act on. Only <em>then</em> does it call a language model to write the answer.</p><p>None of those initial four steps needs a Big LLM model. But fundamentally, each of them has needed its own server — a process for embedding creation, a separate container for the reranker, another for OCR, another for extraction. Each with its own dependencies, its own GPU allocation, its own health check, its own scaling rule to babysit.</p><p>Superlinked has a name it as <strong>Model sprawl</strong>. And it’s the specific problem their new open-source project, the <strong>Superlinked Inference Engine (SIE)</strong>, is built to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0605of-Gmzf_8923LfPKQ.png" /><figcaption>Four tasks each got their server, now sits in one cluster and called via single API</figcaption></figure><h3>The real bottleneck isn’t the big model</h3><p>Most inference tooling was built around one assumption: you have one model, and your job is to serve it as fast and cheaply as possible. That’s the world vLLM, TGI, and SGLang live in — KV cache management, continuous batching, parallelism, kernels tuned for a single model sitting on its own dedicated GPU.</p><p>Agent workloads break that assumption. They’re not dominated by one giant model — they’re dominated by a <em>long tail</em> of small ones, lightweight models to justify its own GPU, but each still needing to run somewhere. That’s not a throughput problem. It’s a <strong>Density</strong> issue, and it’s a different engineering question entirely.</p><h3>What SIE actually does</h3><p>Strip away the pitch, and SIE is a single self-hosted server that exposes the same four operations no matter which of its 100+ models is handling the request. Swapping models is a one-line change to a model-name string — no redeploy, no new container.</p><ul><li><strong>encode(text | image) → vector</strong> — turn content into embeddings for semantic search and RAG</li><li><strong>score(query, docs) → ranking</strong> — rerank retrieved candidates so the right passages reach generation</li><li><strong>extract(text) → fields</strong> — pull structured entities out of unstructured text</li><li><strong>generate(prompt) → text</strong> — run a small open LLM for the final composition step, with streaming</li></ul><p>It also speaks fluent OpenAI: SIE answers on /v1/embeddings, /v1/chat/completions, /v1/completions, and /v1/responses, so a lot of existing OpenAI-client code can just point its base URL at SIE and keep working.</p><p>Getting it running is genuinely two commands:</p><pre>docker run -p 8080:8080 \<br>  -v sie-hf-cache:/app/.cache/huggingface \<br>  ghcr.io/superlinked/sie-server:latest-cpu-default</pre><pre>pip install sie-sdk           # Python<br>pnpm add @superlinked/sie-sdk  # TypeScript</pre><h3>It’s not competing with vLLM — it’s filling the gap next to it</h3><p>This is the part worth sitting with: SIE isn’t trying to out-serve vLLM at serving one big model. It’s answering a different question — given dozens of models that are each individually too small to justify a dedicated GPU, how do you serve all of them from infrastructure that doesn’t scale linearly with how many exist?</p><p>Superlinked’s own framing of this is blunt: for a mixed agent stack, the answer is often both tools, or sometimes neither. A production stack plausibly runs vLLM (or an equivalent) for the one heavyweight generative model, and SIE for the long tail of small models around it — the reranker, the extractor, the OCR pass, the guard model.</p><h3>Why this is worth caring about</h3><p><strong>Idle GPUs are the default, not the exception.</strong> A reranker or extractor gets called intermittently, not continuously. Give it a whole GPU and most of that GPU sits idle between calls. Sharing GPUs across many on-demand models turns that idle capacity into headroom instead of a second line item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*fi5UKfSFlP52CeXD2lKpCA.png" /></figure><p><strong>Every extra server is a second job.</strong> Five one-model-per-box deployments means five dependency sets, five health checks, five things that can page someone at 3am for reasons that have nothing to do with the agent’s actual logic.</p><p><strong>Per-token pricing scales with volume whether you want it to or not.</strong> Routing embeddings, reranking, and extraction through managed APIs is the fastest way to ship — and the cheapest way to end up with a bill that grows linearly with traffic. Self-hosting caps that cost at the price of the infrastructure.</p><p><strong>Some documents genuinely can’t leave the building.</strong> OCR and extraction are often the steps touching the most sensitive input — contracts, IDs, internal PDFs. Running them inside your own network boundary is a different security posture than shipping raw documents to a third party.</p><h3>How it stays fast with 100+ models on one box</h3><p>A few design choices make this practical rather than theoretical:</p><ul><li><strong>On-demand loading with LRU eviction</strong> — the server starts instantly without pre-downloading its catalog; a model loads onto the GPU the first time it’s actually called, and the least-recently-used model gets evicted when memory is needed.</li><li><strong>One compute layer, several backends</strong> — PyTorch, SGLang, Flash Attention, and Apple MLX all sit behind the same four verbs, so encode() runs on whichever backend suits that model without the caller ever needing to know.</li><li><strong>The same container everywhere</strong> — the Docker image for local development is the one that runs in the Kubernetes deployment. No separate “production” implementation to keep in sync.</li><li><strong>A CI-tested catalog</strong> — models ship after passing performance and correctness checks, rather than “whatever loads” from an arbitrary hub.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0M-MQTRTGEJieE4mNSGuPw.png" /><figcaption>Container runs this stack from a laptop to a Kubernetes cluster</figcaption></figure><h3>Bigger picture</h3><p>The generative-model tier already got a decade of serving research aimed squarely at it — vLLM, TGI, and everything downstream of them. SIE is a bet that the small-model tier underneath every agent — the embedder, the reranker, the parser, the extractor — deserves the same dedicated, production-grade serving story, instead of a folder of half-maintained scripts holding it together.</p><p>If your agent stack currently looks like four separate model servers wearing a trench coat, it’s worth a look.</p><p><em>SIE is Apache 2.0 and open source, self-hostable via Docker.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7556613a808" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/superlinked-inference-engine-f7556613a808">Superlinked Inference Engine</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Product Knowledge Graph using LLM]]></title>
            <link>https://pub.towardsai.net/build-product-knowledge-graph-using-llm-a0d0354156ac?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0d0354156ac</guid>
            <category><![CDATA[unstructured-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 22:02:29 GMT</pubDate>
            <atom:updated>2024-08-11T10:56:25.630Z</atom:updated>
            <content:encoded><![CDATA[<p>A Product Knowledge Graph helps find products more easily and improves user experiences in e-commerce. It organizes and connects details about products, brands, categories, features, reviews, and images.</p><p>In this tutorial, Zepto’s retail catalog contains key information about beverages, cooking essentials, and packaged food. Each item in the catalog has a list of product details like product name, quantity, and MRP. We’ll use the product name to get brand info, product info, packaging type, etc. For this, we’ll utilize the <a href="https://www.kaggle.com/datasets/devshahoff/zepto-dataset">Zepto product catalog dataset from Kaggle</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BoBhKDJXsqM7iOtepBYLpg.jpeg" /></figure><h4>The Need for Product Knowledge Graph in E-commerce</h4><p>You might be wondering why we need a Product Knowledge Graph and why it’s important for managing large catalogs. Here is a reason</p><p>Having accurate and complete product details for each item is key to a great shopping experience, providing:</p><ul><li><strong>Better selection and fulfillment</strong>: Customers can easily find what they want and be sure it matches their needs. Delivery partners get the right information to find the product in the store.</li><li><strong>Better personalization</strong>: Product details help group similar products and create a profile for each customer based on their likes. This leads to more relevant and personalized shopping recommendations.</li></ul><h4>How to build a Product Knowledge Graph?</h4><p>Before directly jumping into creating knowledge we need products to be added to the graph, for that we’ll crawl the product along with its similar products from the Zepto website to map them together in the graph.</p><p>Here we have a product along with its similar products.</p><pre>product = {&quot;product&quot;: [&quot;https://www.zeptonow.com/pn/aashirvaad-select-whole-wheat-sharbati-atta/pvid/2e1f7fe5-2d09-4282-81c7-b4eaf6b1d86d&quot;],<br>&quot;similar_products&quot;:<br>[&quot;https://www.zeptonow.com/pn/daily-good-bhagar-flour/pvid/ece6c21b-8976-4eb9-9f01-1b958b081ecf&quot;,<br>&quot;https://www.zeptonow.com/pn/daily-good-rice-flour/pvid/763dbe3b-38b6-4c72-a3cb-040ab964a239&quot;,<br>&quot;https://www.zeptonow.com/pn/daily-good-maidarefined-wheat-flour/pvid/cceca12e-71b0-424f-822a-9dca0b884dcf&quot;,<br>&quot;https://www.zeptonow.com/pn/daily-good-sooji-rava/pvid/f44d8388-2647-441b-bc03-1c4a0d52580b&quot;,<br>&quot;https://www.zeptonow.com/pn/daily-good-corn-flour/pvid/31ad3e8b-e689-48c1-956c-ca36d9fcac2c&quot;,<br>&quot;https://www.zeptonow.com/pn/daily-good-idli-rava/pvid/d380073e-b868-464d-b272-f08d98867b3b&quot;<br>]<br>}</pre><p>Now we’ll crawl all these products to get their Product name to extract their attributes like brand name, product, package type, etc for that we’ll use <a href="https://www.firecrawl.dev/">Firecrawl</a> for this step.</p><p>Set FIRECRAWL_API_KEY as an environment variable</p><pre>export FIRECRAWL_API_KEY=fc-....</pre><pre>from langchain_community.document_loaders import FireCrawlLoader<br><br>product_names = {&quot;product&quot;:[], &quot;similar_products&quot;:[]}<br>for k, v in product.items():<br>    for url in v:<br>        loader = FireCrawlLoader(url=url, mode=&quot;crawl&quot;)<br><br>        docs = loader.load()<br>        if k == &quot;product&quot;:<br>            product_names[&#39;product&#39;].append(docs[0].metadata[&#39;title&#39;])<br>            <br>        else:<br>            product_names[&#39;similar_products&#39;].append(docs[0].metadata[&#39;title&#39;])<br><br>print(&quot;product list:&quot;, product_names)</pre><p>Its output looks like this</p><pre>product list: {&#39;product&#39;: [&#39;Aashirvaad Select Whole Wheat Sharbati Atta 5 kg&#39;],<br> &#39;similar_products&#39;: [&#39;Daily Good Bhagar Flour 500 g&#39;, <br>&#39;Daily Good Rice Flour 500 g&#39;, <br>&#39;Daily Good Maida/Refined Wheat Flour 500 g&#39;,<br>&#39;Daily Good Sooji Rava 500 g&#39;, <br>&#39;Daily Good Corn Flour 500 g&#39;, <br>&#39;Daily Good Idli Rava 500 g&#39;]}</pre><p>Now we’ll use this product list to extract attributes and then utilize those attributes to build a knowledge graph of products.</p><p>Extracting attribute-value information from unstructured data is called <strong>named entity recognition</strong>. There are various ways of performing it, Here is a <a href="https://medium.com/etoai/ner-powered-semantic-search-using-lancedb-51051dc3e493">detailed writeup</a>. Recent methods treat this extraction task as token classification. For example, with the item name “<em>Fortune Sunlite Refined Sunflower (Pouch)</em>,” a token classifier would tag each part of the name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*BD8EH0CvDGPhYxVZin0LKQ.png" /><figcaption><em>Fortune Sunlite Refined Sunflower (Pouch)</em></figcaption></figure><pre>{<br>    &quot;product_brand&quot;: &quot;Fortune&quot;,<br>    &quot;product_name&quot;: &quot;Sunlite Refined Sunflower&quot;,<br>    &quot;package_type&quot;: &quot;Pouch&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/147/1*wlCuTfMbJOl5dq0pA5LFpA.png" /><figcaption>Aashirvaad Atta</figcaption></figure><pre>{<br>    &quot;brand&quot;: &quot;Aashirvaad&quot;,<br>    &quot;product&quot;: &quot;Atta&quot;<br>}</pre><p>We’ll use LLM-based named entity recognition and for that, we’ll utilize Tensorlake’s Indexify framework to extract these insights</p><p><strong><em>Indexify</em></strong> is a data framework created to build ingestion and extraction pipelines for unstructured data. These pipelines use declarative configuration, where each stage can perform token classification using LLM models or transform ingested data. Once data is ingested into Indexify, the pipelines operate immediately, making them well-suited for interactive applications and low-latency use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*157DDGijNVjQr9au.gif" /><figcaption>source: Indexify docs</figcaption></figure><p><strong>Setup Extractor</strong></p><pre>pip install indexify indexify-extractor-sdk</pre><pre># Download Indexify Server<br>curl <a href="https://getindexify.ai/">https://getindexify.ai</a> | sh</pre><pre># Download Extractors<br>indexify-extractor download tensorlake/chunk-extractor<br>indexify-extractor download tensorlake/minilm-l6<br>indexify-extractor download tensorlake/marker<br>indexify-extractor download tensorlake/schema</pre><p>Once you’ve installed the required libraries and downloaded the server and extractors, restart the runtime. Afterward, proceed to run the Indexify Server with the extractors.</p><p>Open 2 new terminals and run the following commands:</p><p><strong><em>Terminal 1</em></strong></p><pre>#start server <br>./indexify server -d</pre><p><strong><em>Terminal 2</em></strong></p><pre>#join server<br>indexify-extractor join-server</pre><h4>Building an attribute extraction model</h4><p>Building an in-house attribute extraction model from scratch needs lots of labeled training data to be accurate. This, known as the cold-start problem in NLP, slows development, delays catalog updates, and increases costs.</p><p>We will use LLMs to overcome the cold-start problem. Large language models (LLMs) like OpenAI’s GPT-4, Google’s Bard, and Meta’s Llama are trained on vast amounts of data. These deep-learning models can perform NLP tasks accurately without needing many labeled examples.</p><p>We’ll power the Pydantic schema with LLM for accurate entity/token classification. The pipeline goes in the following way</p><p>Create a new Python file called extraction_graph.py and add the following code:</p><pre>from indexify import IndexifyClient, ExtractionGraph<br>import pandas as pd<br><br>from pydantic import BaseModel<br><br>class SKU(BaseModel):<br>    product_brand: str<br>    product_name: str<br>    veg_or_nonveg: bool<br>    junk_or_not: bool<br>    package_type: str<br><br>schema = SKU.model_json_schema()<br><br>client = IndexifyClient()<br><br>extraction_graph_spec = f&quot;&quot;&quot;<br>name: &#39;schema_extractor&#39;<br>extraction_policies:<br>  - extractor: &#39;tensorlake/schema&#39;<br>    name: &#39;text_to_schema&#39;<br>    input_params:<br>      service: &#39;openai&#39;<br>      model_name: &#39;gpt-4o&#39;<br>      key: &#39;YOUR_OPENAI_API_KEY&#39;<br>      model_json_schema: {schema}<br>      system_prompt: Extract and categorize all product attributes like product brand, product name from the given text. Provide the results in a JSON format.&#39;<br>&quot;&quot;&quot;<br><br>extraction_graph = ExtractionGraph.from_yaml(extraction_graph_spec)<br>client.create_extraction_graph(extraction_graph)</pre><p>Replace YOUR_OPENAI_API_KEY with your actual OPENAI API key.</p><p>You can run this script to set up the pipeline:</p><pre>python3 extraction_graph.py</pre><p><strong>Implementing the Product attributes Extraction Pipeline</strong></p><p>Now that we have our extraction graph set up, we can retrieve the product attributes:</p><p>Create a file main.py</p><pre>from indexify import IndexifyClient, <br>import json<br><br>def extract_attributes(content):<br>    client = IndexifyClient()<br>    <br>    # Retrieve the extracted entities<br>    entities_content = client.get_extracted_content(<br>        content_id=content,<br>        graph_name=&quot;schema_extractor&quot;,<br>        policy_name=&quot;text_to_schema&quot;<br>    )<br>    <br>    # Parse the JSON response<br>    print(&quot;output: &quot;, entities_content)<br>    <br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    import pandas as pd<br>  <br>    df = pd.read_excel(&quot;Zepto.xlsx&quot;, sheet_name=&quot;Cooking Essentials&quot;)<br>    for i, j in df[&#39;name&#39;].items():<br>        print(&quot;Given: &quot;, j)<br>        extract_attributes(j)</pre><p>Now we are ready to run product attribute extraction</p><pre>python3 main.py</pre><p>The above code will extract various attributes of the product from its name and results in the following way</p><pre>{<br>    &quot;product_brand&quot;: &quot;Fortune&quot;,<br>    &quot;product_name&quot;: &quot;Sunlite Refined Sunflower&quot;,<br>    &quot;package_type&quot;: &quot;Pouch&quot;<br>}</pre><p>We created a system to find and add new brands efficiently using language models. Here’s how it works:</p><ol><li><strong><em>Product Description</em></strong>: We start with a product description and use our brand classifier to identify the brand.</li><li><strong><em>Uncertain Brands</em></strong>: If the system needs clarification about the brand, it sends the details to a language model (LLM) to extract the brand name.</li><li><strong><em>Check for Duplicates</em></strong>: Another LLM checks if this new brand is already in our database by comparing it with similar brands and items.</li><li><strong><em>Update and Improve</em></strong>: The new brand has been added to our database, and our classifier has been updated with this new information.</li></ol><p><strong>Build a Knowledge graph of Products</strong></p><p>Now you have the characteristics of the product including its brand name, product, package type, and weight. We have enough details to create a Knowledge graph of products. Here’s how to create a knowledge graph of products using the provided details:</p><p>1. <strong><em>Group by Product Type</em></strong>: Organize products into categories like “soap,” “flour,” etc.<br> <br>2. <strong><em>Group by Category</em></strong>: Sort products into broader categories such as “Cooking Essentials” and “Organic and Healthy.”</p><p>3. <strong><em>Group by Brand</em></strong>: Cluster products with the same brand, such as “Fortune” or “Aashirvaad.”</p><p>4. <strong><em>Group by Weight Range</em></strong>: Arrange products into weight categories like “500g” and “1kg.”</p><p>5. <strong><em>Use Customer Order History</em></strong>: If available, leverage the customer’s past orders to suggest products in the “You might also like” and “Top Picks” sections.</p><h3>Conclusion</h3><p>Currently, our attribute extraction models mainly work with text-based inputs. After attribute extraction of products utilize the ways mentioned under the <em>Build Knowledge Graph of Products </em>section to create a knowledge graph of products either from other e-commerce pages or from your page to get analytics about your product and boost your sales.</p><p>Stay tuned and <a href="https://medium.com/@prasantdixit">follow me</a> for upcoming amazing content.</p><h4><strong>References</strong></h4><ol><li><a href="https://doordash.engineering/2024/04/23/building-doordashs-product-knowledge-graph-with-large-language-models/">https://doordash.engineering/2024/04/23/building-doordashs-product-knowledge-graph-with-large-language-models/</a></li><li><a href="https://docs.getindexify.ai/introduction">https://docs.getindexify.ai/introduction</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0d0354156ac" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/build-product-knowledge-graph-using-llm-a0d0354156ac">Build Product Knowledge Graph using LLM</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structured Financial data Extraction from Unstructured data]]></title>
            <link>https://pub.towardsai.net/structured-financial-data-extraction-from-unstructured-data-ca2c8d166de6?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca2c8d166de6</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-extraction]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Tue, 09 Jul 2024 18:02:42 GMT</pubDate>
            <atom:updated>2024-07-09T18:02:42.345Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, many are focused on scraping data and training custom models. Still, they often need to pay more attention to the importance of existing data pipelines that use structured data for valuable insights. Extracting structured financial data from balance sheets and other financial statements is essential to understand how a company is growing. Asset Management Companies (AMCs), brokers, and investors depend heavily on accurate structured financial data to make informed decisions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*YoDIRT95BnEzU24WIkcvEA.png" /></figure><h4>The Need for Structured Data in Finance</h4><p>Structured outputs in RAG and LLM pipelines enhance accuracy, clarity, and ease of understanding, making them more compatible with other systems.</p><p>Financial institutions use lengthy documents published by companies to grasp their financials and plans, which is crucial for identifying viable investments. Yet, manually extracting key points from these documents is challenging due to their unstructured nature. <strong>Structured Financial Data synthesis</strong> addresses this, streamlining extraction to enhance efficiency.</p><h4>Schema Based Extraction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*etiCgf8-qm4bYlkk3cfs6g.jpeg" /><figcaption>source: Xebia</figcaption></figure><p>Schema-based extraction is straightforward. Using schemas to define attributes and their types, you can easily leverage libraries like Pydantic.</p><p>The question of using schema-based extraction is why you should use Pydantic.</p><ul><li><strong>Powered by Type hints</strong> — Pydantic uses type hints for schema validation and prompting. This means less to learn, less code to write, and better IDE integration.</li><li><strong>Customizable</strong> — Pydantic allows for custom validators, error messages, and more, making it highly customizable.</li><li><strong>Widely Used</strong> — Pydantic is the most popular data validation library for Python, with over 100M downloads a month. FastAPI, Typer, and many other popular libraries use it.</li></ul><h4>Components</h4><p>Various components are crucial in extracting structured data from unstructured or semi-structured data.</p><ul><li><strong>Pydantic BaseModel </strong>— One of the crucial components in the extraction pipeline, as accurately naming attributes with their types becomes an important part. This step is critical for successful extraction.</li><li><strong>Prompt</strong> — It’s well known that the more descriptive and specific your prompts to an LLM, the better results you’ll get. Here, we only provide a Pydantic BaseModel as input. Frameworks like Instructor and Indexify then use this BaseModel to create prompts as per their defined prompt templates. This step is the deciding step as it determines how effectively the LLM will produce the desired results.</li><li><strong>LLM </strong>—In the pipeline, the LLM extracts all the information (with references from the given text) based on the provided prompt, which means better LLM we choose better extraction results we’ll get. These information chunks are then used to extract attributes and convert them into JSON format.</li><li><strong>Validator </strong>— It comes into play after the LLM step is completed. Validation is to ensure the results returned by the LLM are accurate or not. If the results are incorrect, an error is reported internally and a prompt is reframed, and the pipeline reiterates the extraction process.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKNi84AfBURnLkqXYHeOKw.png" /></figure><h3>Implementation</h3><p>We don’t have to start from scratch; we’ll utilize Tensorlake’s Indexify framework to extract these insights.</p><p>Indexify is a data framework created to build ingestion and extraction pipelines for unstructured data. These pipelines use declarative configuration, where each stage can perform structured extraction using AI models or transform ingested data. Once data is ingested into Indexify, the pipelines start operating immediately, making them well-suited for interactive applications and low-latency use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*V2fgRBqWaYTk5d7i.gif" /><figcaption>source: Indexify</figcaption></figure><p><strong>Setup Extractor</strong></p><pre>pip install indexify indexify-extractor-sdk<br><br># Download Indexify Server<br>curl https://getindexify.ai | sh<br><br># Install Poppler (required for PDF extraction)<br># You can use brew on MacOS.<br>sudo apt-get install -y poppler-utils<br><br># Download Extractors<br>indexify-extractor download tensorlake/chunk-extractor<br>indexify-extractor download tensorlake/minilm-l6<br>indexify-extractor download tensorlake/pdfextractor<br>indexify-extractor download tensorlake/marker<br>indexify-extractor download tensorlake/schema</pre><p>Once you’ve installed the required libraries and downloaded the server and extractors, restart the runtime. Afterward, proceed to run the Indexify Server with the extractors.</p><p>Open 2 new terminals and run the following commands:</p><p><strong><em>Terminal 1</em></strong></p><pre>#start server <br>./indexify server -d</pre><p><strong><em>Terminal 2</em></strong></p><pre>#join server<br>indexify-extractor join-server</pre><p>Put the following code in the filename main.py and <a href="https://drive.google.com/file/d/1pXtYuWR1wPL_KctnptqAbzJIi7DiPpeZ/view?usp=sharing">download PDF</a> :</p><pre>from indexify_extractor_sdk import load_extractor, Content<br>from pydantic import BaseModel<br><br># PDF extractor initialization<br>pdfextractor, pdfconfig_cls = load_extractor(&quot;indexify_extractors.pdfextractor.pdf_extractor:PDFExtractor&quot;)<br><br># extract content from PDF file<br>content = Content.from_file(&quot;BalanceSheet.pdf&quot;)<br>config = pdfconfig_cls()<br><br>pdf_result = pdfextractor.extract(content, config)<br><br># text content present in PDF<br>text_content = next(content.data.decode(&#39;utf-8&#39;) for content in pdf_result if content.content_type == &#39;text/plain&#39;)<br><br># define schema<br>class Invoice(BaseModel):<br>    year: int<br>    captial_deposit: int<br>    total_liability: int<br>    total_assests: int<br>    ratio_of_assests_by_liabilities: float<br>    bills_collection: int<br>    increase_in_deposites_from_2021_to_2022: float<br><br>schema = Invoice.model_json_schema()<br><br>client = IndexifyClient()<br><br>extraction_graph_spec = f&quot;&quot;&quot;<br>name: &#39;pdf_schema_extractor&#39;<br>extraction_policies:<br>  - extractor: &#39;tensorlake/marker&#39;<br>    name: &#39;pdf_to_text&#39;<br>  - extractor: &#39;tensorlake/schema&#39;<br>    name: &#39;text_to_schema&#39;<br>    input_params:<br>      service: &#39;openai&#39;<br>      model_name: &#39;gpt-3.5-turbo&#39;<br>      key: &#39;YOUR_OPENAI_API_KEY&#39;<br>      schema_config: {schema}<br>      additional_messages: &#39;Extract information in JSON according to this schema and return only the output.&#39;<br>    content_source: &#39;pdf_to_text&#39;<br>&quot;&quot;&quot;<br><br>extraction_graph = ExtractionGraph.from_yaml(extraction_graph_spec)<br>result = client.create_extraction_graph(extraction_graph)<br>llm_content = next(content.data.decode(&quot;utf-8&quot;) for content in result if content.content_type == &quot;text/plain&quot;)<br><br># print all the attributes extracted<br>print(llm_content)</pre><p>Replace YOUR_OPENAI_API_KEY with your actual OpenAI API key.</p><p>Now you are ready to extract structured data from PDFs. Activate the default virtual environment created by Indexify to manage dependencies and prevent package conflicts. Use the following code to activate the environment:</p><pre>source ~/.indexify-extractors/ve/bin/activate</pre><p>Now run main.py which contains all the above code</p><pre>python3 main.py</pre><p>The output will appear in a structured JSON format and will look like this:</p><pre>{<br>  &quot;year&quot;: 2022,<br>  &quot;captial_deposit&quot;: 15592517400,<br>  &quot;total_liability&quot;: 20685350503,<br>  &quot;total_assests&quot;: 20685350503,<br>  &quot;ratio_of_assests_by_liabilities&quot;: 1,<br>  &quot;bills_collection&quot;: 569680463,<br>  &quot;increase_in_deposites_from_2021_to_2022&quot;: 2423670192<br>}</pre><p>Now that we have extracted structured data from the PDF, it can be integrated with an API to insert all this extracted data into a database for further processing.</p><h3>Conclusion</h3><p>We have understood schema-based extraction and illustrated how schema-based extraction can extract attributes from unstructured/semi-structured documents and each component of the pipeline and their working with flowchart. In the above example, PDF is used for implementing structured data extraction but the same can be connected with existing pipelines for ingesting structured data for further processing. Structured financial data provides a powerful toolkit to derive insights from financial balance sheets.</p><p>Stay tuned and <a href="https://medium.com/@prasantdixit">follow me</a> for upcoming amazing content.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca2c8d166de6" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/structured-financial-data-extraction-from-unstructured-data-ca2c8d166de6">Structured Financial data Extraction from Unstructured data</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Benchmarking New OpenAI Embedding Models with LanceDB]]></title>
            <link>https://medium.com/etoai/openais-new-embeddings-with-lancedb-embeddings-api-a9d109f59305?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9d109f59305</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 09:09:08 GMT</pubDate>
            <atom:updated>2024-02-17T14:24:56.019Z</atom:updated>
            <content:encoded><![CDATA[<p>A couple of weeks ago, OpenAI launched their new and most performant embedding models with higher multilingual performance and new parameters to control the overall size, updated moderation models, API usage management tools, and reduced pricing for GPT-3.5 Turbo.</p><p>Embeddings are numeric representations of content, such as text or code. This helps machine learning models understand semantic relationships with data points and perform similarity-based retrieval. Embeddings are used in knowledge retrieval tasks, especially in Retrieval Augmented Generation (RAG) for systems like ChatGPT, Bard, and other related tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R8vHBGUhSstHB4uCFEGEw.gif" /><figcaption>Credits: OpenAI</figcaption></figure><p>The newly launched OpenAI&#39;s Embedding models text-embedding-3-small and text-embedding-3-large, have generated considerable interest due to their higher multilingual performance and new parameter dimensions to control the overall size of embeddings. text-embedding-3-small returns embeddings of 1536-dimensional vector size same as older embedding model text-embedding-ada-002 and text-embedding-3-large returns embeddings of 3072-dimensional vector size.<br>We’ll see performance improvement with and without dimensionality reduction features.</p><p>The latest embedding model text-embedding-3-smallis highly efficient and represents a significant improvement compared to its predecessor, the text-embedding-ada-002 model released in December 2022.</p><h4>Performance Increase</h4><p>While Comparing text-embedding-ada-002 to text-embedding-3-small, the average score on a commonly used benchmark for English tasks (<a href="https://github.com/embeddings-benchmark/mteb">MTEB</a>) using the <em>StackOverflowDupQuestions</em> task shows an increase from 50.5% to 51.4%.</p><h4>Native support for Dimensionality Reduction</h4><p>Using larger embeddings and storing them in a vector store for retrieval generally costs more and consumes more compute, memory, and storage than smaller embeddings.</p><p>Length of embeddings (by omitting specific numbers from the end of the sequence) without compromising their ability to represent concepts. This can be performed by utilizing the dimensions API parameter. In the MTEB benchmark, an text-embedding-3-large embedding can be reduced to a size of 256 and still exhibit performance compared to an text-embedding-ada-002 embedding with a size of 1536.</p><p>Here are the Results of the MTEB benchmark on the <strong><em>StackOverflowDupQuestions</em></strong> task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*JkCenLsWfEwx45NrewdcLw.png" /><figcaption>MTEB Benchmark mAP scores</figcaption></figure><h4><strong>OpenAI Embedding Models with LanceDB</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*jv8RjdLjF8wD_1OZbuFStg.png" /></figure><p>The new OpenAI embedding models work well with LanceDB. Combining these developer-friendly embedding models with LanceDB’s vector database is excellent for tasks like Semantic Search, Knowledge Retrieval, and many other applications.</p><p>OpenAI embeddings function can be called via LanceDB while creating a table that implicitly converts text into OpenAI embeddings and adds them in the table in the following way using Python, which gives the flexibility to use the vectorized text across all sessions.</p><pre>import lancedb<br>from lancedb.embeddings import EmbeddingFunctionRegistry<br><br>db = lancedb.connect(&quot;/tmp/db&quot;)<br>registry = EmbeddingFunctionRegistry.get_instance(name=&quot;text-embedding-3-small&quot;)<br>func = registry.get(&quot;openai&quot;).create()<br><br>class Words(LanceModel):<br>    text: str = func.SourceField()<br>    vector: Vector(func.ndims()) = func.VectorField()<br><br>table = db.create_table(&quot;words&quot;, schema=Words)<br>table.add(<br>    [<br>        {&quot;text&quot;: &quot;hello world&quot;}<br>        {&quot;text&quot;: &quot;goodbye world&quot;}<br>    ]<br>    )<br><br>query = &quot;greetings&quot;<br>actual = table.search(query).limit(1).to_pydantic(Words)[0]<br>print(actual.text)</pre><p>The OpenAI embedding function is already ingested in the table. It doesn’t require loading it again while adding text to the table.</p><pre>table = db.open_table(&quot;words&quot;)<br><br># Automatically vectorized text across all sessions<br>table.add(<br>    [{&quot;text&quot;: &quot;changing world&quot;}])<br><br>query = &quot;world&quot;<br>result = table.search(query).limit(1).to_pydantic(Words)[0]<br>print(result.text)</pre><h3>Conclusion</h3><p>This was a short intro to new OpenAI embedding models and how LanceDB’s Embedding API simplifies working with embedding functions. Check out other interesting <a href="https://blog.lancedb.com/">Blogs</a> and solutions on <a href="https://github.com/lancedb/vectordb-recipes">Vectordb-recipes</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9d109f59305" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/openais-new-embeddings-with-lancedb-embeddings-api-a9d109f59305">Benchmarking New OpenAI Embedding Models with LanceDB</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Langroid: Multi-Agent Programming framework for LLMs]]></title>
            <link>https://medium.com/etoai/langoid-multi-agent-programming-framework-for-llms-e609377de227?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e609377de227</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Mon, 08 Jan 2024 10:42:13 GMT</pubDate>
            <atom:updated>2024-01-18T19:27:44.848Z</atom:updated>
            <content:encoded><![CDATA[<p>In this era of Large Language Models (LLMs), there is unprecedented demand to create intelligent applications powered by this transformative technology. What is the best way for developers to harness the potential of LLMs in complex application scenarios?</p><p>For a variety of technical and practical reasons (context length limitations, LLM brittleness, latency, token costs), this is not as simple as throwing a task at an LLM system and expecting it to get done. What is needed is a principled programming framework, offering the right set of abstractions and primitives to make developers productive when building LLM applications.</p><h3>Langroid’s Elegant Multi-Agent Paradigm</h3><p>The <a href="https://github.com/langroid/langroid">Langroid</a> team (ex-CMU/UW-Madison researchers) has a unique take on this — they have built an open-source Python framework to simplify LLM application development using a Multi-Agent Programming paradigm. Langroid’s architecture is founded on Agents as first-class citizens: they are message-transformers and accomplish tasks collaboratively via messages.</p><p>Langroid is emerging as a popular LLM framework; developers appreciate its clean design and intuitive, extensible architecture. Programming with Langroid is natural and even fun: you configure Agents and equip them with capabilities ( such as LLMs, vector databases, and Function-calling/tools), connect them, and have them collaborate via messages. This is a “Conversational Programming” paradigm and works with local/open and remote/proprietary LLMs. (Importantly, it does not use LangChain or any other existing LLM framework).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZyNDw0VdCOT0n3eM.png" /><figcaption>An Agent serves as a convenient abstraction, encapsulating the state of LLM conversations, access to vector stores, and various tools (functions or plugins). A Multi-Agent Programming framework seamlessly aligns with the demands of complex LLM-based applications.</figcaption></figure><p>An Agent serves as a convenient abstraction, encapsulating the state of LLM conversations, access to vector stores, and various tools (functions or plugins). A Multi-Agent Programming framework naturally aligns with the demands of complex LLM-based applications.</p><h3>Connecting Agents via Tasks</h3><p>In Langroid, a ChatAgent has a set of “responder” methods, one for each “entity”: an LLM, a human, and a tool handler. However, it does not have any way to iterate through these responders. This is where the Task class comes in: A Task wraps an Agent and gives it the ability to loop through its responders via the Task.run() method.</p><p>A Task loop is organized around simple rules that govern when a responder is eligible to respond, what is considered a valid response, and when the task is complete. The simplest example of a Task loop is an interactive chat with the human user. A Task also enables an Agent to interact with other agents: other tasks can be added to a task as sub-tasks in a recursive, hierarchical (or DAG) structure. From a Task’s perspective, sub-tasks are just additional responders and present the same string-to-string message-transformation interface (function signature) as the Agent’s “native” responders. This is the key to the composability of tasks in Langroid since a sub-task can act the same way as an Agent’s “native” responders and is subject to the same rules of task orchestration. The result is that the same task orchestration mechanism seamlessly enables tool handling, retries when LLM deviates, and delegation to sub-tasks. More details are in the Langroid <a href="https://langroid.github.io/langroid/quick-start/">quick-start guide</a>.</p><h3>A Taste of Coding with Langroid</h3><p>To get started with Langroid, simply install it from pypi into your virtual environment:</p><pre>pip install langroid</pre><p>To directly chat with an OpenAI LLM, define the LLM configuration, instantiate a language model object, and interact with it: (Langroid works with non-OpenAI local/proprietary LLMs as well, see their <a href="https://langroid.github.io/langroid/tutorials/non-openai-llms/">tutorial</a>) For the examples below, ensure you have a file .env containing your OpenAI API key with this line: OPENAI_API_KEY=sk-....</p><pre>import langroid as lr<br>import langroid.language_models as lm<br><br>llm_cfg = lm.OpenAIGPTConfig() # default GPT4-Turbo<br>mdl = lm.OpenAIGPT(llm_cfg)<br>mdl.chat(&quot;What is 3+4?&quot;, max_tokens=10)</pre><p>The MDL does not maintain any conversation state; for that, you need a ChatAgent:</p><pre>agent_cfg = lr.ChatAgentConfig(llm=llm_cfg)<br>agent = lr.ChatAgent(agent_cfg)<br>agent.llm_response(&quot;What is the capital of China?&quot;)<br>agent.llm_response(&quot;What about France?&quot;) # interprets based on previous msg</pre><p>Wrap a ChatAgent in a Task to create a basic interactive loop with the user:</p><pre>task = lr.Task(agent, name=&quot;Bot&quot;)<br>task.run(&quot;Hello&quot;)</pre><p>Have a Teacher Agent talk to a Student Agent:</p><pre>teacher = lr.ChatAgent(agent_cfg)<br>teacher_task = lr.Task(<br>    teacher, name=&quot;Teacher&quot;,<br>    system_message=&quot;&quot;&quot;<br>        Ask your student simple number-based questions, and give feedback.<br>        Start with a question.<br>        &quot;&quot;&quot;,<br>)<br>student = lr.ChatAgent(agent_cfg)<br>student_task = lr.Task(<br>    student, name=&quot;Student&quot;,<br>    system_message=&quot;Concisely answer your teacher&#39;s questions.&quot;<br>)<br>teacher_task.add_sub_task(student_task)<br>teacher_task.run()</pre><h3>Retrieval Augmented Generation (RAG) and Vector Databases</h3><p>One of the most popular LLM applications is question-answering on documents via Retrieval-Augmented Generation (RAG), powered by a vector database. Langroid has a built-in DocChatAgent that incorporates several advanced RAG techniques, clearly laid out so they can be easily understood and extended.</p><h4>Built-in Support for LanceDB</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*1aHRaS2KR9jqGJlLiTo6CQ.jpeg" /></figure><p>Langroid uses LanceDB as the default vector store for its DocChatAgent.</p><p>Langroid’s DocChatAgent uses the LanceDB serverless vector database by default. Since LanceDB uses file storage, it is easy to set up and use (no need for docker or cloud services), and due to its use of the Lance columnar format, it is highly performant and scalable. In addition, Langroid has a specialized LanceDocChatAgent that leverages LanceDB&#39;s unique features such as Full-text search, SQL-like filtering, and pandas dataframe interop. Setting up a basic RAG chatbot is as simple as (assume the previous imports):</p><pre>from langroid.agent.special.lance_doc_chat_agent import import (<br>    LanceDocChatAgent, DocChatAgentConfig<br>)<br>llm_config = lm.OpenAIGPTConfig()<br><br>rag_agent_config = DocChatAgentConfig(<br>    llm=llm_config, <br>    doc_paths=[&quot;/path/to/my/docs&quot;], # files, folders, or URLs.<br>)<br>rag_agent = LanceDocChatAgent(rag_agent_config)<br>rag_task = lr.Task(rag_agent, name=&quot;RAG&quot;)<br>rag_task.run()📄Chat with IMDB movies dataset</pre><p>For an example showcasing Tools/Function-calling + RAG in a multi-agent setup, see their quick-start <a href="https://colab.research.google.com/github/langroid/langroid/blob/main/examples/Langroid_quick_start.ipynb">Colab notebook</a> which shows a 2-agent system where one agent is tasked with extracting structured information from a document and generates questions for the other agent to answer using RAG. In the Langroid-examples repo there is a <a href="https://github.com/langroid/langroid-examples/blob/main/examples/docqa/chat_multi_extract.py">script</a> with the same functionality, and here is what it looks like in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o47mJpw_AbdhgJi5.gif" /></figure><h3>Retrieval Augmented Analytics</h3><p>One of the unique features of LanceDB is its SQL-like filtering and Pandas dataframe interoperability. LLMs are great at generating SQL queries, and also Pandas computation code such as df.groupby(&quot;col&quot;).mean(). This opens up a very interesting possibility, which we call <strong>Retrieval Augmented Analytics:</strong> Suppose a user has a large dataset of movie descriptions with metadata such as rating, year, and genre, and wants to ask:</p><blockquote><strong>What is the highest-rated Comedy movie about college students made after 2010?</strong></blockquote><p>It is not hard to imagine that an LLM should be able to generate a <strong>Query Plan</strong> to answer this, consisting of:</p><ul><li>A SQL-like filter: genre = &quot;Comedy&quot; and year &gt; 2010</li><li>A Pandas computation: df.loc[df[&quot;rating&quot;].idxmax()]</li><li>A rephrased query given the filter: “Movie about college students” (used for semantic/lexical search)</li></ul><p>Langroid’s Multi-Agent framework enables exactly this type of application. The <a href="https://github.com/langroid/langroid/blob/main/langroid/agent/special/lance_rag/lance_rag_task.py">LanceRAGTaskCreator</a> takes a LanceDocChatAgent and adds two additional agents:</p><ul><li>QueryPlannerAgent: Generates the Query Plan</li><li>QueryPlanCriticAgent: Critiques the Query Plan and Answer received from the RAG Agent so that the QueryPlanner can generate a better plan if needed.</li></ul><p>Checkout the <a href="https://github.com/langroid/langroid-examples/blob/main/examples/docqa/lance-rag-movies.py">lance-rag-movies.py</a> script in the langroid-examples repo to try this out.</p><h3>Try it out and get involved!</h3><p>This was just a glimpse of what you can do with Langroid and how your code would look. Give it a shot and learn more about the features and roadmap of Langroid on their <a href="https://github.com/langroid/langroid">GitHub repo</a>. Langroid welcomes contributions, and they have a friendly <a href="https://discord.gg/ZU36McDgDs">Discord</a> community.</p><p>If you like it, don’t forget to drop a 🌟.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e609377de227" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/langoid-multi-agent-programming-framework-for-llms-e609377de227">Langroid: Multi-Agent Programming framework for LLMs</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inverted File Product Quantization (IVF_PQ): Accelerate vector search by creating indices]]></title>
            <link>https://medium.com/etoai/product-quantization-compress-high-dimensional-vectors-dfcba98fab47?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfcba98fab47</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 04:58:55 GMT</pubDate>
            <atom:updated>2023-12-19T04:36:28.678Z</atom:updated>
            <content:encoded><![CDATA[<p>Vector similarity search is finding similar vectors from a list of given vectors in a particular embedding space. It plays a vital role in various fields and applications because it efficiently retrieves relevant information from large datasets.</p><p>Vector similarity search requires excessive memory resources for efficient search, especially when dealing with dense vector datasets. Here comes the role of compressing High Dimensional vectors for optimizing memory storage. In this blog, We’ll discuss about</p><ol><li><strong>Product Quantization(PQ) &amp; How it works</strong></li><li><strong>Inverted File Product Quantization(IVFPQ) Index</strong></li><li><strong>Implementation of IVFPQ using LanceDB</strong></li></ol><p>We’ll also see the performance of PQ and IVFPQ in terms of memory and cover an implementation of the IVFPQ Index using LanceDB.</p><p>Quantization is a process used for dimensional reduction without losing important information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*9ibrbi3Gox6nMDda8oL7yg.png" /><figcaption><strong>Quantization: Dimensionality Reduction</strong></figcaption></figure><h4>How does Product Quantization work?</h4><p>Product Quantization can be broken down into steps listed below:</p><ol><li>Divide a large, high-dimensional vector into equally sized chunks, creating subvectors.</li><li>Identify the nearest centroid for each subvector, referring to it as reproduction or reconstruction values.</li><li>Replace these reproduction values with unique IDs that represent the corresponding centroids.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*5EyBpJ2H0jQkKFpIDIPhAg.png" /><figcaption><strong>Product Quantization</strong></figcaption></figure><p>Let&#39;s see how it works in the implementation, of that we’ll create a random array of size 12 and keep the chunk size as 3.</p><pre>import random<br><br>#consider this as a high dimensional vector<br>vec = v = [random.randint(1,20)) for i in range(12)]</pre><pre>chunk_count = 4<br>vector_size = len(vec)<br><br># vector_size must be divisable by chunk_size<br>assert vector_size % chunk_count == 0<br># length of each subvector will be vector_size/ chunk_count<br>subvector_size = int(vector_size / chunk_count)<br><br># subvectors<br>sub_vectors = [vec[row: row+subvector_size] for row in range(0, vector_size, subvector_size)]<br>sub_vectors</pre><p>The output looks like this</p><pre>[[13, 3, 2], [5, 13, 5], [17, 8, 5], [3, 12, 9]]</pre><p>These subvectors are substituted with a designated centroid vector called Reproduction Value because it helps identify each subvector. Subsequently, this centroid vector can be substituted with a distinct ID that is unique to it.</p><pre>k = 2**5<br>assert k % chunk_count == 0<br>k_ = int(k/chunk_count)<br><br>from random import randint<br># reproduction values<br>c = []  <br>for j in range(chunk_count):<br>    # each j represents a subvector position<br>    c_j = []<br>    for i in range(k_):<br>        # each i represents a cluster/reproduction value position <br>       c_ji = [randint(0, 9) for _ in range(subvector_size)]<br>       c_j.append(c_ji)  # add cluster centroid to subspace list<br>    <br>  # add subspace list of centroids<br>    c.append(c_j)</pre><pre>#helper function to calculate euclidean distance<br>def euclidean(v, u):<br>    distance = sum((x - y) ** 2 for x, y in zip(v, u)) ** .5<br>    return distance<br><br>#helper function to create unique ids<br>def nearest(c_j, chunk_j):<br>    distance = 9e9<br>    for i in range(k_):<br>        new_dist = euclidean(c_j[i], chunk_j)<br>        if new_dist &lt; distance:<br>            nearest_idx = i<br>            distance = new_dist<br>    return nearest_idx</pre><p>Now, Let&#39;s see How we can get unique centroid IDs using the <strong><em>nearest helper function</em></strong></p><pre>ids = []<br># unique centroid IDs for each subvector<br>for j in range(chunk_count):<br>    i = nearest(c[j], sub_vectors[j])<br>    ids.append(i)<br>print(ids)</pre><p>Output shows unique centroid IDs for each subvector</p><pre>[5, 6, 7, 7]</pre><p>When utilizing PQ to handle a vector, we divide it into subvectors. These subvectors are then processed and linked to their closest centroids, also known as reproduction values, within the respective subclusters.</p><p><strong>Instead of saving our Quantized Vector using the centroids, we substitute it with a unique Centroid ID. Each centroid has its specific ID, allowing us to later map these ID values back to the complete centroids.</strong></p><pre>quantized = []<br>for j in range(chunk_count):<br>    c_ji = c[j][ids[j]]<br>    quantized.extend(c_ji)<br><br>print(quantized)</pre><p>Here is the reconstructed vector using Centroid IDs</p><pre>[9, 9, 2, 5, 7, 6, 8, 3, 5, 2, 9, 4]</pre><p>In doing so, <strong>we’ve condensed a 12-dimensional vector into a 4-dimensional vector represented by IDs</strong>. We opted for a smaller dimensionality for simplicity, which might make the advantages of this technique less immediately apparent.</p><p><strong><em>It’s important to highlight that the reconstructed vector is not identical to the original vector. This discrepancy arises due to inherent losses during the compression and reconstruction process in all compression algorithms.</em></strong></p><p>Let’s change our starting 12-dimensional vector made of 8-bit integers to a more practical 128-dimensional vector of 32-bit floats. By compressing it to an 8-bit integer vector with only eight dimensions, we strike a good balance in performance.</p><p><strong>Original: 128×32 = 4096 Quantized: 8×8 = 64</strong></p><p><strong>This marks a substantial difference — a 64x reduction in memory.</strong></p><h4>How IVFPQ Index help in speeding things up?</h4><p>In IVFPQ, an Inverted File index (IVF) is integrated with Product Quantization (PQ) to facilitate a rapid and effective approximate nearest neighbor search by initial broad-stroke that narrows down the scope of vectors in our search.</p><p>After this, we continue our PQ search as we did before — but with a significantly reduced number of vectors. By minimizing our Search Scope, it is anticipated to achieve significantly improved search speeds.</p><p><strong>IVFPQ can be very easily implemented in just a few lines of code using LanceDB</strong></p><p>Creating an IVF_PQ Index</p><pre>import lancedb<br>import numpy as np<br>uri = &quot;./lancedb&quot;<br>db = lancedb.connect(uri)<br><br># Create 10,000 sample vectors<br>data = [{&quot;vector&quot;: row, &quot;item&quot;: f&quot;item {i}&quot;}<br>   for i, row in enumerate(np.random.random((10_000, 1536)).astype(&#39;float32&#39;))]<br><br># Add the vectors to a table<br>tbl = db.create_table(&quot;my_vectors&quot;, data=data)<br><br># Create and train the index - you need to have enough data in the table for an effective training step<br>tbl.create_index(num_partitions=256, num_sub_vectors=96)</pre><ul><li><strong><em>metric</em></strong> (default: “L2”): The distance metric to use. By default, it uses Euclidean distance “L2&quot;. We also support &quot;cosine&quot; and &quot;dot&quot; distance as well.</li><li><strong><em>num_partitions</em></strong> (default: 256): The number of partitions of the index.</li><li><strong><em>num_sub_vectors</em></strong> (default: 96): The number of sub-vectors (M) that will be created during Product Quantization (PQ).</li></ul><p>Now let&#39;s see what this IVF Index does to reduce the scope of vectors, <strong>Inverted file is an index structure that is used to map database vectors to their respective partitions where these vectors reside</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*sqiTUncKKCVBOTks7XtvIw.png" /><figcaption><strong>PQ vectors</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*dolXJIJ4YVubaREDPSxFww.png" /><figcaption><strong>Vectors are assigned to different Voronoi cells via IVF</strong></figcaption></figure><p>This is Voronoi&#39;s Representation of vectors using IVF, they’re simply a set of partitions each containing vectors close to each other, and when it comes to search — When we introduce our query vector, it restricts our search to the nearest cells only because of which searching becomes way faster compared to PQ.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*07pM49ui5dtkCeRYQLbmlQ.png" /><figcaption><strong>Query Vector searches Closest cell</strong></figcaption></figure><p>Afterwards, PQ needs to be applied as we have seen above.</p><p>All of this can be applied using the IVF+PQ Index using <a href="https://github.com/lancedb/vectordb-recipes">LanceDB</a> in minimal lines of code</p><pre>tbl.search(np.random.random((1536))) \<br>    .limit(2) \<br>    .nprobes(20) \<br>    .refine_factor(10) \<br>    .to_pandas()</pre><ul><li><strong>limit</strong> (default: 10): The number of results that will be returned</li><li><strong>nprobes</strong> (default: 20): The quantity of probes (sections) determines the distribution of vector space. While a higher number enhances search accuracy, it also results in slower performance. Typically, setting the number of probes (nprobes) to cover 5–10% of the dataset proves effective in achieving high recall with minimal latency.</li><li><strong>refine_factor</strong> (default: None): Refine the results by reading extra elements and re-ranking them in memory.<br>A higher number makes the search more accurate but also slower.</li></ul><h3>Conclusion</h3><p>It can be concluded that Product Quantization reduces memory consumption for storing high dimensional vectors and in addition to the IVF index, it extensively speeds up the process by searching in only the closest vectors.</p><p><strong>Visit the </strong><a href="https://www.linkedin.com/feed/?trk=sem-ga_campid.14650114791_asid.148989926143_crid.662526548043_kw.www+linkedin_d.c_tid.kwd-296759856208_n.g_mt.p_geo.9062111#"><strong>LanceDB </strong></a><strong>repo to learn more about lanceDB Python and Typescript library</strong></p><p><strong>To discover more such applied GenAI and vectorDB applications, examples and tutorials visit </strong><a href="https://github.com/lancedb/vectordb-recipes"><strong>VectorDB-Recipes</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfcba98fab47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/product-quantization-compress-high-dimensional-vectors-dfcba98fab47">Inverted File Product Quantization (IVF_PQ): Accelerate vector search by creating indices</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accelerate Vector Search Applications Using Openvino]]></title>
            <link>https://medium.com/etoai/accelerate-vector-search-applications-using-openvino-51366eabf866?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/51366eabf866</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openvino]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 21:15:14 GMT</pubDate>
            <atom:updated>2023-12-12T13:25:45.475Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accelerate Vector Search Applications Using OpenVINO &amp; LanceDB</h3><p>In this article, We use CLIP from OpenAI for Text-to-Image and Image-to-Image searching and we’ll also do a comparative analysis of the Pytorch model, FP16 OpenVINO format, and INT8 OpenVINO format in terms of speedup.</p><p>Here are a few Key points converted in this article.</p><p><strong>Text-to-Image and Image-to-Image Search using CLIP</strong></p><ol><li><strong><em>Using the Pytorch model</em></strong></li><li><strong><em>Using OpenVINO conversion to speed up by 70%</em></strong></li><li><strong><em>Using Quantization with OpenVINO NNCF to speed up by 400%</em></strong></li></ol><p>These R<strong><em>esults are on 13th Gen Intel(R) Core(TM) i5–13420H using OpenVINO=2023.2 and NNCF=2.7.0 version.</em></strong></p><p>You can check out the attached Google Colab to find all codes and easy-to-quick-start steps.</p><p><a href="https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Accelerate-Vector-Search-Applications-Using-OpenVINO/clip_text_image_search.ipynb">Google Colaboratory</a></p><h4>CLIP from OpenAI</h4><p><strong><em>CLIP (Contrastive Language–Image Pre-training) is a neural network capable of processing both images and text.</em></strong></p><p>CLIP is a multi-modal model, meaning it can understand both text and image inputs. It also means it can embed inputs in a multi-modal space where image and text lie in semantically meaningful positions regardless of their types.</p><p>The following image presents a visualization of the pre-training procedure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKfC-Vyc3r85W06yLH2y_g.png" /><figcaption><strong>Combining Image and Text Embeddings (Source: OpenAI)</strong></figcaption></figure><h4>OpenVINO by Intel</h4><p>OpenVINO toolkit is a free toolkit facilitating the optimization of a deep learning model from a framework and deploying an inference engine onto Intel hardware. We’ll use the FP16 and INT8 formats using the OpenVINO CLIP model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*950zBYcU5-9hySxX8d9Yng.png" /></figure><p>This write-up uses OpenVINO to accelerate the LanceDB embedding pipeline.</p><h3>Implementation</h3><p>In the Implementation section, we see the <strong><em>comparative implementation of the CLIP model from Hugging Face and OpenVINO formats, using the conceptual caption dataset</em></strong>.</p><p>We are starting with the first step of <strong><em>loading the conceptual caption dataset from Hugging Face</em>.</strong></p><pre># https://huggingface.co/datasets/conceptual_captions<br>image_data = load_dataset(<br>    &quot;conceptual_captions&quot;, split=&quot;train&quot;,<br>    )</pre><p>We will select a sample of 100 images from this large number of images</p><pre>#taking first 100 images<br>image_data_df = pd.DataFrame(image_data[:100])</pre><p>Helper <strong><em>functions to validate image URLs</em></strong> and get images and captions from image URL</p><pre>def check_valid_URLs(image_URL):<br>    &quot;&quot;&quot;<br>    Not all the URLs are valid. This function returns True if the URL is valid. False otherwise.<br>    &quot;&quot;&quot;<br>    try:<br>      response = requests.get(image_URL)<br>      Image.open(BytesIO(response.content))<br>      return True<br>    except:<br>      return False<br><br>def get_image(image_URL):<br><br>    response = requests.get(image_URL)<br>    image = Image.open(BytesIO(response.content)).convert(&quot;RGB&quot;)<br><br>    return image<br><br>def get_image_caption(image_ID):<br><br>    return image_data[image_ID][&quot;caption&quot;]</pre><pre># Transform dataframe<br>image_data_df[&quot;is_valid&quot;] = image_data_df[&quot;image_url&quot;].apply(check_valid_URLs)<br><br>#removing all the in_valid URLs<br>image_data_df = image_data_df[image_data_df[&quot;is_valid&quot;]==True]<br>image_data_df.head()</pre><p>Now we have prepared the dataset and we are ready to start with CLIP using Hugging Face and OpenVINO and their performance comparative analysis in terms of speed.</p><h4><strong>Pytorch CLIP using Hugging Face</strong></h4><p>We’ll start with <strong><em>CLIP using Hugging Face </em></strong>and the time taken to extract embeddings and <strong><em>search using the LanceDB vector database</em></strong>.</p><pre>def get_model_info(model_ID, device):<br>  &quot;&quot;&quot;<br>  Loading CLIP from HuggingFace  <br>  &quot;&quot;&quot;<br>  # Save the model to device<br>  model = CLIPModel.from_pretrained(model_ID).to(device)<br><br>  # Get the processor<br>  processor = CLIPProcessor.from_pretrained(model_ID)<br><br>  # Get the tokenizer<br>  tokenizer = CLIPTokenizer.from_pretrained(model_ID)<br><br>  # Return model, processor &amp; tokenizer<br>  return model, processor, tokenizer</pre><pre># Set the device<br>device = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>model_ID = &quot;openai/clip-vit-base-patch16&quot;<br><br>model, processor, tokenizer = get_model_info(model_ID, device)</pre><p>Let’s write a <strong>Helper Function to extract Text and Image Embeddings</strong></p><pre>def get_single_text_embedding(text):<br>  # Get single text embeddings<br>  inputs = tokenizer(text, return_tensors = &quot;pt&quot;).to(device)<br><br>  text_embeddings = model.get_text_features(**inputs)<br><br>  # convert the embeddings to numpy array<br>  embedding_as_np = text_embeddings.cpu().detach().numpy()<br>  return embedding_as_np<br><br><br>def get_all_text_embeddings(df, text_col):<br>   # Get all the text embeddings<br>   df[&quot;text_embeddings&quot;] = df[str(text_col)].apply(get_single_text_embedding)<br>   return df</pre><pre>def get_single_image_embedding(my_image):<br>  # Get single image embeddings<br>  image = processor(<br>      text = None,<br>      images = my_image,<br>      return_tensors=&quot;pt&quot;<br>  )[&quot;pixel_values&quot;].to(device)<br><br>  embedding = model.get_image_features(image)<br><br>  # convert the embeddings to numpy array<br>  embedding_as_np = embedding.cpu().detach().numpy()<br>  return embedding_as_np<br><br><br>def get_all_images_embedding(df, img_column):<br>  # Get all image embeddings<br>  df[&quot;img_embeddings&quot;] = df[str(img_column)].apply(get_single_image_embedding)<br>  return df</pre><p><strong>Connect LanceDB to store extracted embeddings and search</strong></p><pre>import lancedb<br>db = lancedb.connect(&quot;./.lancedb&quot;)</pre><p><strong>Extracting Embeddings of 83 images using CLIP Hugging faces<em> </em></strong>model and time taken to extract embeddings.</p><pre>import time<br># extracting embeddings using Hugging Face<br>start_time = time.time()<br>image_data_df = get_all_images_embedding(image_data_df, &quot;image&quot;)<br>print(f&quot;Time Taken to extract Embeddings of {len(image_data_df)} Images(in seconds): &quot;, time.time()-start_time)</pre><p>Here are the results:</p><pre>Time Taken to extract Embeddings of 83 Images(in seconds):  55.79</pre><p><strong>Ingesting Images and their Embeddings in LanceDB </strong>for querying</p><pre>def create_and_ingest(image_data_df, table_name):<br>    &quot;&quot;&quot;<br>    Create and Ingest Extracted Embeddings using Hugging Face<br>    &quot;&quot;&quot;<br>    image_url = image_data_df.image_url.tolist()<br>    image_embeddings = [arr.astype(np.float32).tolist() for arr in image_data_df.img_embeddings.tolist()]<br><br>    data = []<br>    for i in range(len(image_url)):<br>        temp = {}<br>        temp[&#39;vector&#39;] = image_embeddings[i][0]<br>        temp[&#39;image&#39;] = image_url[i]<br><br>        data.append(temp)<br><br>    # Create a Table<br>    tbl = db.create_table(name= table_name, data=data, mode= &quot;overwrite&quot;)<br>    return tbl<br><br><br>#create and ingest embeddings for pt model<br>pt_tbl = create_and_ingest(image_data_df, &quot;pt_table&quot;)</pre><p><strong>Query the stored embeddings</strong></p><p>Time taken to extract embeddings of all the images and query the stored embeddings</p><pre># Get the image embedding and query for each caption<br>pt_img_results = {}<br><br>start_time = time.time()<br>for i in range(len(image_data_df)):<br>    img_query = image_data_df.iloc[i].image<br>    query_embedding = get_single_image_embedding(img_query).tolist()<br><br>    #querying with image<br>    result = pt_tbl.search(query_embedding[0]).limit(4).to_list()<br>    pt_img_results[str(i)] = result</pre><h3><strong><em>CLIP model using FP16 </em></strong>OpenVINO<strong><em> format</em></strong></h3><p>Now we’ll start with <strong><em>CLIP F16 OpenVINO format </em></strong>and the time taken to extract embeddings and <strong><em>ingesting in the LanceDB vector database</em></strong>.</p><pre>import openvino as ov<br><br>#saving openvino model<br>model.config.torchscript = True<br>ov_model = ov.convert_model(model, example_input=dict(inputs))<br>ov.save_model(ov_model, &#39;clip-vit-base-patch16.xml&#39;)</pre><p>Compiling the CLIP OpenVINO model</p><pre>import numpy as np<br>from scipy.special import softmax<br>from openvino.runtime import Core<br><br>&quot;&quot;&quot;<br>  Compiling CLIP in Openvino FP16 format<br>&quot;&quot;&quot;<br># create OpenVINO core object instance<br>core = Core()<br># compile model for loading on device<br>compiled_model = core.compile_model(ov_model, device_name=&quot;AUTO&quot;, config={&quot;PERFORMANCE_HINT&quot;: &quot;CUMULATIVE_THROUGHPUT&quot;})<br># obtain output tensor for getting predictions</pre><p><strong>Extracting Embeddings of 83 images using CLIP FP16 OpenVINO model </strong>and time taken to extract embeddings.</p><pre>import time<br><br>#time taken to extract embeddings using CLIP OpenVINO format<br>start_time = time.time()<br>image_embeddings = extract_openvino_embeddings(image_data_df)<br>print(f&quot;Time Taken to extract Embeddings of {len(image_data_df)} Images(in seconds): &quot;, time.time()-start_time)</pre><p>Here are the results:</p><pre>Time Taken to extract Embeddings of 83 Images(in seconds):  31.79</pre><p><strong>Ingesting Images and their Embeddings in LanceDB </strong>for querying</p><pre>def create_and_ingest_openvino(image_url, image_embeddings, table_name):<br>    &quot;&quot;&quot;<br>    Create and Ingest Extracted Embeddings using OpenVINO FP16 format<br>    &quot;&quot;&quot;<br>    data = []<br>    for i in range(len(image_url)):<br>        temp = {}<br>        temp[&#39;vector&#39;] = image_embeddings[i]<br>        temp[&#39;image&#39;] = image_url[i]<br><br>        data.append(temp)<br><br>    # Create a Table<br>    tbl = db.create_table(name= table_name, data=data, mode= &quot;overwrite&quot;)<br>    return tbl<br><br><br>#create and ingest embeddings for OpenVINO fp16 model<br>ov_tbl = create_and_ingest_openvino(image_url, image_embeddings, &quot;ov_tbl&quot;)Query the stored embeddings</pre><p>Time taken to extract embeddings of all the images and query the stored embeddings</p><pre># Get the image embedding and query for each caption<br>ov_img_results = {}<br>start_time = time.time()<br>for i in range(len(image_data_df)):<br>    img_query = image_data_df.iloc[i].image<br>    image = image_data_df.iloc[i].image<br>    inputs = processor(images=[image], return_tensors=&quot;np&quot;, padding=True)<br>    query_embedding = compiled_model(dict(inputs))[&quot;image_embeds&quot;][0]<br><br>    #querying with query image<br>    result = ov_tbl.search(query_embedding).limit(4).to_list()<br>    ov_img_results[str(i)] = result</pre><h3>NNCF INT 8-bit Quantization</h3><p>Using 8-bit Post Training Optimization from NNCF (Neural Network Compression Framework) and infer quantized model via OpenVINO Toolkit.</p><pre>%pip install -q datasets<br>%pip install -q &quot;nncf&gt;=2.7.0&quot;</pre><pre>import os<br>from transformers import CLIPProcessor, CLIPModel<br><br>fp16_model_path = &#39;clip-vit-base-patch16.xml&#39;<br><br>#inputs preparation for conversion and creating processor<br>model = CLIPModel.from_pretrained(&quot;openai/clip-vit-base-patch16&quot;)<br>max_length = model.config.text_config.max_position_embeddings<br>processor = CLIPProcessor.from_pretrained(&quot;openai/clip-vit-base-patch16&quot;)</pre><p><strong>Helper Functions to convert into Int8 format using NNCF</strong></p><pre>import requests<br>from io import BytesIO<br>import numpy as np<br>from PIL import Image<br>from requests.packages.urllib3.exceptions import InsecureRequestWarning<br>requests.packages.urllib3.disable_warnings(InsecureRequestWarning)<br><br>def check_text_data(data):<br>    &quot;&quot;&quot;<br>    Check if the given data is text-based.<br>    &quot;&quot;&quot;<br>    if isinstance(data, str):<br>        return True<br>    if isinstance(data, list):<br>        return all(isinstance(x, str) for x in data)<br>    return False<br><br>def get_pil_from_https://medium.com/url(url):<br>    &quot;&quot;&quot;<br>    Downloads and converts an image from a URL to a PIL Image object.<br>    &quot;&quot;&quot;<br>    response = requests.get(url, verify=False, timeout=20)<br>    image = Image.open(BytesIO(response.content))<br>    return image.convert(&quot;RGB&quot;)<br><br>def collate_fn(example, image_column=&quot;image_url&quot;, text_column=&quot;caption&quot;):<br>    &quot;&quot;&quot;<br>    Preprocesses an example by loading and transforming image and text data.<br>    Checks if the text data in the example is valid by calling the `check_text_data` function.<br>    Downloads the image specified by the URL in the image_column by calling the `get_pil_from_url` function.<br>    If there is any error during the download process, returns None.<br>    Returns the preprocessed inputs with transformed image and text data.<br>    &quot;&quot;&quot;<br>    assert len(example) == 1<br>    example = example[0]<br><br>    if not check_text_data(example[text_column]):<br>        raise ValueError(&quot;Text data is not valid&quot;)<br><br>    url = example[image_column]<br>    try:<br>        image = get_pil_from_https://medium.com/url(url)<br>        h, w = image.size<br>        if h == 1 or w == 1:<br>            return None<br>    except Exception:<br>        return None<br><br>    #preparing inputs for processor<br>    inputs = processor(text=example[text_column], images=[image], return_tensors=&quot;pt&quot;, padding=True)<br>    if inputs[&#39;input_ids&#39;].shape[1] &gt; max_length:<br>        return None<br>    return inputs</pre><p><strong>Initializing NNCF and Saving the Quantized Model</strong></p><pre>import logging<br>import nncf<br>from openvino.runtime import Core, serialize<br><br>core = Core()<br><br>#Initialize NNCF <br>nncf.set_log_level(logging.ERROR)<br><br>int8_model_path = &#39;clip-vit-base-patch16_int8.xml&#39;<br>calibration_data = prepare_dataset()<br>ov_model = core.read_model(fp16_model_path)<br><br><br>if len(calibration_data) == 0:<br>    raise RuntimeError(<br>        &#39;Calibration dataset is empty. Please check internet connection and try to download images manually.&#39;<br>    )<br><br>#Quantize CLIP fp16 model using NNCF<br>calibration_dataset = nncf.Dataset(calibration_data)<br>quantized_model = nncf.quantize(<br>    model=ov_model,<br>    calibration_dataset=calibration_dataset,<br>    model_type=nncf.ModelType.TRANSFORMER,<br>)<br><br>#Saving Quantized model<br>serialize(quantized_model, int8_model_path)</pre><p><strong>Compiling the INT8 model and Helper function for extracting features</strong></p><pre>import numpy as np<br>from scipy.special import softmax<br>from openvino.runtime import Core<br><br># create OpenVINO core object instance<br>core = Core()<br># compile model for loading on device<br>compiled_model = core.compile_model(quantized_model, device_name=&quot;AUTO&quot;, config={&quot;PERFORMANCE_HINT&quot;: &quot;CUMULATIVE_THROUGHPUT&quot;})<br><br># obtain output tensor for getting predictions<br>image_embeds = compiled_model.output(0)<br>logits_per_image_out = compiled_model.output(0)<br><br><br>image_url = image_data_df.image_url.tolist()<br>image_embeddings = []<br><br>def extract_quantized_openvino_embeddings(image_data_df, compiled_model):<br>    &quot;&quot;&quot;<br>    Extract embeddings of Images using CLIP Quantized model<br>    &quot;&quot;&quot;<br>    for i in range(len(image_data_df)):<br>        image = image_data_df.iloc[i].image<br>        inputs = processor(images=[image], return_tensors=&quot;np&quot;, padding=True)<br>        image_embeddings.append(compiled_model(dict(inputs))[&quot;image_embeds&quot;][0])<br><br>    return image_embeddings</pre><pre>import time<br><br>start_time = time.time()<br><br>#time taken to extract embeddings using CLIP OpenVINO format<br>image_embeddings = extract_quantized_openvino_embeddings(image_data_df, compiled_model)<br><br>print(f&quot;Time Taken to extract Embeddings of {len(image_data_df)} Images(in seconds): &quot;, time.time()-start_time)</pre><p>Here are the results</p><pre>Time Taken to extract Embeddings of 83 Images(in seconds):  13.70</pre><p>Ingest embeddings into LanceDB</p><pre>#create and ingest embeddings for OpenVINO int8 model format<br>qov_tbl = create_and_ingest_openvino(image_url, image_embeddings, &quot;qov_tbl&quot;)</pre><p>Time taken to extract embeddings of all the images and query the stored embeddings</p><pre># Get the image embedding and query for each caption<br>ov_img_results = {}<br>start_time = time.time()<br>for i in range(len(image_data_df)):<br>    img_query = image_data_df.iloc[i].image<br>    image = image_data_df.iloc[i].image<br>    inputs = processor(images=[image], return_tensors=&quot;np&quot;, padding=True)<br>    query_embedding = compiled_model(dict(inputs))[&quot;image_embeds&quot;][0]<br><br>    #querying with query image<br>    result = qov_tbl.search(query_embedding).limit(4).to_list()<br>    ov_img_results[str(i)] = result</pre><p>Now we have the performance throughput of all the CLIP model formats Pytorch from Hugging Face, FP16 OpenVINO, and INT8 OpenVINO.</p><p><a href="https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Accelerate-Vector-Search-Applications-Using-OpenVINO/clip_text_image_search.ipynb">Google Colaboratory</a></p><h4>Conclusion</h4><p>All these results are on CPU for comparison of the Pytorch model with the OpenVINO model formats(FP16/ INT8)</p><p><strong><em>The time taken to extract Embeddings for 83 Images using CLIP in different formats are</em></strong></p><p>1. <strong><em>Pytorch model from Hugging Face</em></strong> — 55.26 seconds</p><p>2. <strong><em>OpenVINO FP16 format</em></strong> — 31.79 seconds</p><p>3. <strong><em>OpenVINO INT8 format</em></strong> — 13.70 seconds</p><p><strong><em>The Performance acceleration achieved with the FP16 model is 1.73 times, representing a relatively modest increase in speed compared to expectations.</em></strong></p><p><strong><em>Conversely, when considering the INT8 OpenVINO format, there is a 4.03 times increase in speed compared to the PyTorch model.</em></strong></p><p>Visit our <a href="https://github.com/lancedb"><strong>GitHub</strong> </a>if you wish to learn more about LanceDB python and Typescript library.<br>For more such applied GenAI and VectorDB applications, examples and tutorials visit <a href="https://github.com/lancedb/vectordb-recipes/tree/main"><strong>VectorDB-Recipes.</strong></a><strong> </strong>Don’t forget to leave a star at the repo.</p><p>Lastly, for more information and updates, follow our<strong> </strong><a href="https://www.linkedin.com/company/lancedb/"><strong>LinkedIn</strong></a> and <a href="https://twitter.com/lancedb"><strong>Twitter.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51366eabf866" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/accelerate-vector-search-applications-using-openvino-51366eabf866">Accelerate Vector Search Applications Using Openvino</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentiment Analysis powered by semantic search using LanceDB]]></title>
            <link>https://medium.com/etoai/sentiment-analysis-using-lancedb-2da3cb1e3fa6?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/2da3cb1e3fa6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 07:17:03 GMT</pubDate>
            <atom:updated>2023-11-30T22:29:09.706Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Sentiment Analysis</strong> also known as Opinion Mining is a NLP technique that is used <strong>to analyze texts for polarity, from positive to negative</strong>. It helps businesses to monitor customer feedback, product reputation, and social media sentiment.</p><p><strong><em>For example</em></strong>, “I love this product” would have a high positive score, while “<em>This is the worst service ever</em>” would have a<em> low negative score</em>. Sentiment analysis can also detect emotions, sarcasm, and context in text, making it more accurate and near to human intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JEsKXMy3RAalzye2" /><figcaption>Photo by <a href="https://unsplash.com/@tengyart?utm_source=medium&amp;utm_medium=referral">Tengyart</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Methods of Sentiment Analysis</h4><ul><li><strong>Rule-based:</strong> This method performs sentiment analysis <strong><em>based on a set of manually crafted rules</em></strong>.</li><li><strong>Automatic:</strong> This method relies on <strong><em>ML/NLP techniques to learn from data</em></strong>.</li><li><strong>Hybrid:</strong> This approach combines both rule-based and automatic approaches.</li></ul><p>In this Blog, We’ll see an example to <em>analyze sentiments toward the Hotel Industry and understand Customer Perception and Potential areas that need improvement</em>. To do this, we will:</p><p>1. <strong><em>Generate Sentiment labels and scores using BERT models </em></strong>based on customer reviews.</p><p>2.<strong><em> Store them in a LanceDB table with metadata </em></strong>and their embeddings of customer reviews.</p><p>3.<strong><em> Query the LanceDB table on selected areas and understand customer opinions.</em></strong></p><p>You can check out the attached Google Colab where you can find all codes and easy-to-quick-start steps.</p><p><a href="https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Sentiment-Analysis-Analyse-Hotel-Reviews/Sentiment-Analysis-using-LanceDB.ipynb">Google Colaboratory</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DUEPiPEd5sdZ1YKQFiy0g.png" /><figcaption><strong>Flowchart of Implementation</strong></figcaption></figure><h4>Implementation</h4><p>In the Implementation section, we see the step-by-step implementation of NER on the Medium dataset. We are starting with the first step of <strong><em>loading the hotel reviews dataset from huggingface</em>.</strong></p><pre>from datasets import load_dataset<br><br># load the dataset and convert to pandas dataframe<br>df = load_dataset(<br>    &quot;ashraq/hotel-reviews&quot;,<br>    split=&quot;train&quot;<br>).to_pandas()</pre><p>Once a dataset is loading, we’ll <strong><em>preprocess a loaded dataset, which will take</em></strong> only 1000 characters from the reviews.</p><pre># keep only the first 1000 characters from the reviews<br>df[&quot;review&quot;] = df[&quot;review&quot;].str[:1000]<br># glimpse the dataset<br>df.head()</pre><p>These are basic preprocessing steps that I have performed, you can apply them further according to your datasets.</p><p>Now, we’ll initialize the Sentiment Analysis Model, we’ll use a <strong><em>RoBERTa or DistilBERT model fine-tuned for sentiment analysis </em></strong>to analyze the hotel reviews from the HuggingFace model hub</p><pre>import torch<br><br># set device to GPU if available<br>device = &#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;</pre><pre># @title Select Sentiment Analysis Model and run this cell<br><br>model_id = &quot;cardiffnlp/twitter-roberta-base-sentiment&quot; # @param {type:&quot;string&quot;}<br>select_model = &#39;cardiffnlp/twitter-roberta-base-sentiment&#39; # @param [&quot;cardiffnlp/twitter-roberta-base-sentiment&quot;, &quot;lxyuan/distilbert-base-multilingual-cased-sentiments-student&quot;]<br>model_id = select_model<br>print(&quot;Selected Model: &quot;, model_id)</pre><p>This code will create a dropdown in Google Colab from there y<strong><em>ou can select RoBERT or DistilBERT which sentiment analysis model</em></strong> you want to use for creating a sentiment analysis pipeline.</p><pre>from transformers import (<br>    pipeline,<br>    AutoTokenizer,<br>    AutoModelForSequenceClassification<br>    )<br><br># load the model from huggingface<br>model = AutoModelForSequenceClassification.from_pretrained(<br>    model_id,<br>    num_labels=3<br>)<br><br># load the tokenizer from huggingface<br>tokenizer = AutoTokenizer.from_pretrained(model_id)<br><br># load the tokenizer and model into a sentiment analysis pipeline<br>nlp = pipeline(<br>    &quot;sentiment-analysis&quot;,<br>    model=model,<br>    tokenizer=tokenizer,<br>    device=device<br>    )</pre><p>The sentiment analysis model returns LABEL_0 for negative, LABEL_1 for neutral and LABEL_2 for positive labels. We can add them to a dictionary to easily access them when showing the results.</p><pre>labels = {<br>        &quot;LABEL_0&quot;: &quot;negative&quot;,<br>        &quot;LABEL_1&quot;: &quot;neutral&quot;,<br>        &quot;LABEL_2&quot;: &quot;positive&quot;<br>    }</pre><p>Now we’ll test the sentiment analysis pipeline that we created using the BERT model</p><pre># view review number 241<br>test_review = df[&quot;review&quot;][241]<br>test_review</pre><p>This will output a review</p><pre> Room was small for a superior room and poorly lit especially as <br>it was an inside room and overlooked the inside wall of the hotel <br>No view therefore needed better lighting within Restaurant tables <br>were not well laid and had to go searching for cutlery at breakfast </pre><pre># get the sentiment label and score for review number 241<br>nlp(test_review)</pre><p>This is how we’ll get results from the analysis pipeline</p><pre>[{&#39;label&#39;: &#39;LABEL_0&#39;, &#39;score&#39;: 0.7736574411392212}]</pre><p>Now, we have created an analysis Pipeline, The Next step is to <strong><em>Initialize the Retriever</em></strong></p><p>A <strong><em>Retriever model is used to embed passages and queries, and it creates embeddings such that queries and passages with similar meanings are close in the vector space</em></strong>.</p><p>We will use a sentence-transformer model as our retriever. The model can be loaded as follows:</p><pre>from sentence_transformers import SentenceTransformer<br><br># load the model from huggingface<br>retriever = SentenceTransformer(<br>    &#39;sentence-transformers/all-MiniLM-L6-v2&#39;,<br>    device=device<br>)</pre><p>Now let’s <strong><em>generate Embeddings and insert them inside LanceDB for querying</em></strong></p><p>Connect LanceDB</p><pre>import lancedb<br>db = lancedb.connect(&quot;./.lancedb&quot;)</pre><p>Let’s first write a helper function to generate sentiment labels and scores for a batch of reviews.</p><pre>def get_sentiment(reviews):<br>    # pass the reviews through sentiment analysis pipeline<br>    sentiments = nlp(reviews)<br>    # extract only the label and score from the result<br>    l = [labels[x[&quot;label&quot;]] for x in sentiments]<br>    s = [x[&quot;score&quot;] for x in sentiments]<br>    return l, s</pre><p>Let’s write another helper function to convert dates to timestamps.</p><pre>import dateutil.parser<br><br># convert date to timestamp<br>def get_timestamp(dates):<br>    timestamps = [dateutil.parser.parse(d).timestamp() for d in dates]<br>    return timestamps</pre><p>Now generating embeddings and storing them in the table of LanceDB with their respective metadata</p><pre>from tqdm.auto import tqdm<br><br># we will use batches of 64<br>batch_size = 64<br>data = []<br>for i in tqdm(range(0, len(df), batch_size)):<br>    # find end of batch<br>    i_end = min(i+batch_size, len(df))<br>    # extract batch<br>    batch = df.iloc[i:i_end]<br>    # generate embeddings for batch<br>    emb = retriever.encode(batch[&quot;review&quot;].tolist()).tolist()<br>    # convert review_date to timestamp to enable period filters<br>    timestamp = get_timestamp(batch[&quot;review_date&quot;].tolist())<br>    batch[&quot;timestamp&quot;] = timestamp<br>    # get sentiment label and score for reviews in the batch<br>    label, score = get_sentiment(batch[&quot;review&quot;].tolist())<br>    batch[&quot;label&quot;] = label<br>    batch[&quot;score&quot;] = score<br>    # get metadata<br>    meta = batch.to_dict(orient=&quot;records&quot;)<br>    # create unique IDs<br>    ids = [f&quot;{idx}&quot; for idx in range(i, i_end)]<br>    # add all to upsert list<br>    to_insert = list(zip(ids, emb, meta))<br>    for id, emb, meta in to_insert:<br>        temp = {}<br>        temp[&#39;vector&#39;] = emb<br>        for k,v in meta.items():<br>            temp[k] = v<br>        data.append(temp)</pre><pre># create and insert these records to lancedb table<br>tbl = db.create_table(&quot;tbl&quot;, data, mode= &quot;overwrite&quot;)</pre><p>We have successfully inserted all customer reviews and relevant metadata. We can move on to analyzing sentiments.</p><p>Now that we have all the customer reviews inserted, we will search for a few areas that customers usually consider when staying at a hotel and <strong><em>analyze the general opinion of the customers</em></strong>.</p><p>The LanceDB vector database makes it very flexible and faster to do this as we can easily search for any topic and get customer reviews relevant to the search query along with sentiment labels as metadata.</p><p>Let’s write another helper function to store the count of sentiment labels.</p><pre>def count_sentiment(result):<br>    # store count of sentiment labels<br>    sentiments = {<br>        &quot;negative&quot;: 0,<br>        &quot;neutral&quot;: 0,<br>        &quot;positive&quot;: 0,<br>    }<br>    # iterate through search results<br>    for r in result:<br>        # extract the sentiment label and increase its count<br>        sentiments[r[&quot;label&quot;]] += 1<br>    return sentiments</pre><p>We will start with a general question about the room sizes of hotels in London and return the top 100 reviews to analyze the overall customer sentiment.</p><p><strong>Analyzing Room Size Reviews in London</strong></p><pre>query = &quot;What is customers opinion about room sizes in London?&quot;<br># generate dense vector embeddings for the query<br>xq = retriever.encode(query).tolist()<br><br># query lancedb<br>metadata = [&quot;hotel_name&quot;, &quot;label&quot;, &quot;review&quot;, &quot;review_date&quot;, &quot;timestamp&quot;]<br>result = tbl.search(xq).select(metadata).limit(100).to_list()<br>sentiment = count_sentiment(result)</pre><p>Plotting the results for better analysis</p><pre>import seaborn as sns<br><br># plot a barchart using seaborn<br>sns.barplot(x=list(sentiment.keys()), y = list(sentiment.values()))</pre><p>The resultant graph looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*GVb41Yp9y7lOemhJtbMtaQ.png" /><figcaption><strong>Room Size Reviews in London</strong></figcaption></figure><p><strong><em>The customers are generally satisfied with the room sizes, although many are still neutral and positive</em>.</strong></p><p><strong>Analyzing Room Size Reviews in a Specific Period</strong></p><pre># generate timestamps for start and end time of the period<br>start_time = get_timestamp([&quot;2015-01-01&quot;])[0]<br>end_time = get_timestamp([&quot;2017-12-31&quot;])[0]</pre><pre>query = &quot;are the customers satisified with the room sizes of hotels in London?&quot;<br># generate query embeddings<br>xq = retriever.encode(query).tolist()<br><br># query lancedb with query embeddings and appling prefiltering for given time period<br>where_filter = f&quot;{start_time} &lt;= timestamp &lt;= {end_time}&quot;<br>result = tbl.search(xq).where(where_filter, prefilter=True).limit(10).to_list()<br><br># get an overall count of customer sentiment<br>sentiment = count_sentiment(result)<br># plot a barchart using seaborn<br>sns.barplot(x=list(sentiment.keys()), y = list(sentiment.values()))</pre><p>The Resultant graph shows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*gtosgyDd2neMimWBNi3wZQ.png" /><figcaption><strong>Room Size Reviews in a Specific Period</strong></figcaption></figure><p><strong><em>We have a slightly different result now. Almost the same number of customers had either a neutral or positive view of the room size during the selected period.</em></strong></p><p>Further Basic Analysis is done in the attached Google Colab notebook at the end of this blog, which you can refer to.</p><p><strong>Analyzing Multiple hotels at Multiple Grounds</strong></p><p>Now Let’s multiple hotels together on multiple grounds to better understand the variation in reviews.</p><p>We have selected 5 Hotels for them we are analyzing 5 grounds which are Room Size, Cleanliness, Room Service, Food Service, and Ventilation.</p><pre>#selected hotels<br>hotels =[<br>    &quot;Strand Palace Hotel&quot;,<br>    &quot;St James Court A Taj Hotel London&quot;,<br>    &quot;Grand Royale London Hyde Park&quot;,<br>    &quot;Hotel Da Vinci&quot;,<br>    &quot;Intercontinental London The O2&quot;,<br>]</pre><pre>queries = {<br>    &quot;room size&quot;: &quot;are customers happy with the given room sizes?&quot;,<br>    &quot;cleanliness&quot;: &quot;are customers satisfied with the cleanliness of the rooms?&quot;,<br>    &quot;room service&quot;: &quot;did the customers like how they were treated by the staff while room service?&quot;,<br>    &quot;food service&quot;: &quot;did the customers enjoy the food and servicing?&quot;,<br>    &quot;ventilation&quot;: &quot;customer opinion on the air passage and AC&quot;<br>}</pre><p>Now, We need to iterate through all the hotels and run these queries for each hotel. This would give us customer reviews relevant to the selected hotel areas. After that, we count the sentiment labels and plot results for each hotel.</p><pre>import matplotlib.pyplot as plt<br>import pandas as pd<br><br>hotel_sentiments = []<br><br># iterate through the hotels<br>for hotel in hotels:<br>    final_result = []<br><br>    # iterate through the keys and values in the queries dict<br>    for area, query in queries.items():<br>        # generate query embeddings<br>        xq = retriever.encode(query).tolist()<br><br>        # query lancedb with query embeddings and appling prefiltering for hotel names<br>        where_filter = f&quot;hotel_name= &#39;{hotel}&#39;&quot;<br>        result = tbl.search(xq).where(where_filter, prefilter=True).limit(100).to_list()<br><br>        # get an overall count of customer sentiment<br>        sentiment = count_sentiment(result)<br>        # sort the sentiment to show area and each value side by side<br>        for k, v in sentiment.items():<br>            analysis_data = {<br>                &quot;area&quot;: area,<br>                &quot;label&quot;: k,<br>                &quot;value&quot;: v<br>            }<br>            # add the data to final_result list<br>            final_result.append(analysis_data)<br><br>    #dataframe of final results<br>    df = pd.DataFrame(final_result)<br>    # mapping dataframe records with hotel<br>    hotel_sentiments.append({&quot;hotel&quot;: hotel, &quot;df&quot;: df})</pre><p>We may now plot the final data to make inferences.</p><pre># create the figure and axes to plot barchart for all hotels<br>fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(25, 4.5))<br>plt.subplots_adjust(hspace=0.25)<br><br>counter = 0<br># iterate through each hotel in the list and plot a barchart<br>for d, ax in zip(hotel_sentiments, axs.ravel()):<br>    # plot barchart for each hotel<br>    sns.barplot(x=&quot;label&quot;, y=&quot;value&quot;, hue=&quot;area&quot;, data=d[&quot;df&quot;], ax=ax, palette=&quot;Spectral&quot;)<br>    # display the hotel names<br>    ax.set_title(d[&quot;hotel&quot;])<br>    # remove x labels<br>    ax.set_xlabel(&quot;&quot;)<br>    # remove legend from all charts except for the first one<br>    counter += 1<br>    if counter != 1: ax.get_legend().remove()<br># display the full figure<br>plt.show()</pre><p>This will plot results for all 5 hotels on all 5 grounds from which we’ll analyze it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DKa8gF4gMj3SYS-EBE1PGQ.png" /><figcaption><strong>Analyzing Multiple hotels at Multiple Grounds</strong></figcaption></figure><p>This can be better seen on Google Colab which is attached at the end of this blog.</p><p>The following observations can be made for the hotels based on the sentiment analysis:</p><ol><li><strong>Strand Palace Hotel:</strong> The majority of customers were pleased with the cleanliness, room service, and food service of the rooms, while a considerable number of them were not very satisfied with the room sizes and the ventilation in rooms.</li><li><strong>St James Court A Taj Hotel London:</strong> The majority of the customers were really happy with the selected five areas</li><li><strong>Grand Royale London Hyde Park</strong>: The majority of the customers were not satisfied with the room size, while a good number of them were pretty satisfied with the cleanliness, room service, food service, and ventilation of the rooms.</li><li><strong>Hotel Da Vinci</strong>: The majority of customers are happy with room sizes, cleanliness, food service, and ventilation but a considerable about of them are not satisfied with room service</li><li><strong>Intercontinental London The O2</strong>: the majority of the customers were really happy with the selected five areas, making this hotel the best among the selected hotels.</li></ol><p>Although we have experimented with a few selected areas and hotels, you can get creative with your queries and get the sentiment around your area of interest with different sets of hotels immediately.</p><p>For quick and further analysis, You can try out Google Colab which has all these codes</p><p><a href="https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/Sentiment-Analysis-Analyse-Hotel-Reviews/Sentiment-Analysis-using-LanceDB.ipynb">Google Colaboratory</a></p><p>Some of the benefits of Hotel Review Analysis are:</p><ul><li>Monitor and respond to customer feedback and address any issues or complaints that may arise.</li><li>Measure and improve the quality of their Services, Facilities, Amenities, and Staff, and Identify the areas that need more attention or improvement.</li><li>Understand the needs and expectations of their Target market, and tailor their offerings and marketing strategies accordingly.</li></ul><h4>Conclusion</h4><p>Sentiment Analysis is primarily using NLP and Deep Learning techniques. <strong><em>BERT is used in the Sentiment Analysis Pipeline </em></strong>and predicts Sentimens for reviews.</p><p>Using these two technologies, the model detects a sentiment of reviews. Harnessing the advanced vector search functionalities provided by LanceDB enhances its overall utility in analyzing the sentiments of reviews of different hotels on different grounds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2da3cb1e3fa6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/sentiment-analysis-using-lancedb-2da3cb1e3fa6">Sentiment Analysis powered by semantic search using LanceDB</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NER-powered Semantic Search using LanceDB]]></title>
            <link>https://medium.com/etoai/ner-powered-semantic-search-using-lancedb-51051dc3e493?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/51051dc3e493</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[recognition]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Wed, 08 Nov 2023 13:28:51 GMT</pubDate>
            <atom:updated>2023-11-30T22:21:16.821Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>NER stands for Named Entity Recognition</strong>, a form of natural language processing (NLP) that involves extracting and identifying essential information from text. The information that is extracted and categorized is called an <strong>entity</strong>. It can be any word or a series of words that consistently refers to the same thing. Some examples of entities are:</p><ul><li><strong>Person</strong>: The name of a person, such as John, Mary, or Barack Obama.</li><li><strong>Organization</strong>: The name of a company, institution, or group, such as Google, NASA, or LanceDB.</li><li><strong>Location</strong>: The name of a geographical place, such as London, Mount Everest, or Mars.</li><li><strong>Date/Time</strong>: A specific point or period in time, such as 2023, November 5, or 14:23:31.</li><li><strong>Numeral</strong>: A numerical value, such as 42, 3.14, or $199.99.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7tz40y-1soPJspml.png" /></figure><p>In simpler words, if your task is to find out ‘where’, ‘what’, ‘who’, and ‘when’ from a sentence, NER is the solution you should opt for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YtFAd1gli2RZTFCd" /><figcaption>Photo by <a href="https://unsplash.com/@8moments?utm_source=medium&amp;utm_medium=referral">Simon Berger</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Methods of Named Entity Recognition</h4><ol><li><strong>Dictionary-Based NER — </strong>In this method, a vocabulary-based dictionary is utilized, and basic string-matching algorithms are employed to determine if an entity exists within the provided text by comparing it with the entries in the vocabulary. However, this method is typically avoided due to the necessity of regularly updating and maintaining the dictionary.</li><li><strong>Rule-Based NER — </strong>This approach relies on employing a predefined collection of rules for extracting information, with these rules being categorized into two types: pattern-based and context-based. Pattern-based rules analyze the morphological patterns of words, while context-based rules examine the context in which the words appear within the text document.</li><li><strong>Deep Learning- Based NER</strong> — Deep learning NER outperforms all other methods in terms of accuracy due to its ability to construct word associations, leading to a superior understanding of the semantic and syntactic connections among words. Additionally, it possesses the capability to automatically analyze topic-specific and high-level terminology.</li></ol><p>In this blog, we’ll see an example of Named Entity Recognition using the Deep Learning approach for which, <strong><em>we use a dataset containing ~190K articles scraped from Medium</em></strong>. We selected 50K articles from the dataset as indexing all the articles may take some time.</p><p>To extract named entities, we will use a<strong><em> NER model finetuned on a BERT-base model</em></strong>.</p><p>The flow will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xicHs6pPkpR9e9gXT-M4gg.png" /></figure><p>In short, we use the NER model to further filter the semantic search results. The predicted named entities are used as “post filters” to filter the vector search results.</p><h4>Implementation</h4><p>In the Implementation section, we see the step-by-step implementation of NER on the Medium dataset. Starting with the first step of <strong><em>loading the dataset from huggingface</em></strong>.</p><pre>from datasets import load_dataset<br><br># load the dataset and convert to pandas dataframe<br>df = load_dataset(<br>    &quot;fabiochiu/medium-articles&quot;,<br>    data_files=&quot;medium_articles.csv&quot;,<br>    split=&quot;train&quot;<br>).to_pandas()</pre><p>Once a dataset is loading, we’ll <strong><em>preprocess a loaded dataset </em></strong>which will include removing empty rows, taking only 1000 words from the article, etc.</p><pre># drop empty rows and select 20k articles<br>df = df.dropna().sample(20000, random_state=32)<br>df.head()</pre><pre># select first 1000 characters<br>df[&quot;text&quot;] = df[&quot;text&quot;].str[:1000]<br># join article title and the text<br>df[&quot;title_text&quot;] = df[&quot;title&quot;] + &quot;. &quot; + df[&quot;text&quot;]</pre><p>These are basic preprocessing steps that I have performed, you can apply them further according to your datasets.</p><p>To extract named entities, we will <strong><em>use a NER model finetuned on a BERT-base model</em></strong>. The model can be loaded from the HuggingFace model hub.</p><pre>from transformers import AutoTokenizer, AutoModelForTokenClassification<br>from transformers import pipeline<br><br>model_id = &quot;dslim/bert-base-NER&quot;<br><br># load the tokenizer from huggingface<br>tokenizer = AutoTokenizer.from_pretrained(<br>    model_id<br>)<br># load the NER model from huggingface<br>model = AutoModelForTokenClassification.from_pretrained(<br>    model_id<br>)<br># load the tokenizer and model into a NER pipeline<br>nlp = pipeline(<br>    &quot;ner&quot;,<br>    model=model,<br>    tokenizer=tokenizer,<br>    aggregation_strategy=&quot;max&quot;,<br>    device=device<br>)</pre><p>Let’s try to use the NER pipeline to extract named entities from the text</p><pre>text = &quot;What are the best Places to visit in London&quot;<br>nlp(text)</pre><p>The output of the pipeline looks like</p><pre>[{&#39;entity_group&#39;: &#39;LOC&#39;,<br>  &#39;score&#39;: 0.99969244,<br>  &#39;word&#39;: &#39;London&#39;,<br>  &#39;start&#39;: 37,<br>  &#39;end&#39;: 43}]</pre><p>This shows our NER pipeline is working as expected and accurately extracting entities from the text.</p><p>Now we have the NER pipeline, we’ll initialize the Retriever.</p><p>A <strong><em>Retriever </em></strong>model is used to embed passages (article title + first 1000 characters) and queries. It <strong><em>creates embeddings such that queries and passages with similar meanings are close in the vector space</em></strong>. We will use a sentence-transformer model as our retriever. The model can be loaded using the following code.</p><pre>from sentence_transformers import SentenceTransformer<br><br># load the model from huggingface<br>retriever = SentenceTransformer(<br>    &#39;flax-sentence-embeddings/all_datasets_v3_mpnet-base&#39;,<br>    device=device<br>)</pre><p>Now let&#39;s <strong><em>generate Embeddings and insert them inside LanceDB for querying</em></strong></p><p>Connect LanceDB</p><pre>import lancedb<br>db = lancedb.connect(&quot;./.lancedb&quot;)</pre><p>Let’s first write a helper function to extract named entities from a batch of text.</p><pre>def extract_named_entities(text_batch):<br>    # extract named entities using the NER pipeline<br>    extracted_batch = nlp(text_batch)<br>    entities = []<br>    # loop through the results and only select the entity names<br>    for text in extracted_batch:<br>        ne = [entity[&quot;word&quot;] for entity in text]<br>        entities.append(ne)<br>    return entities</pre><p>Now generating embeddings and storing them in the table of LanceDB with their respective metadata</p><pre>from tqdm.auto import tqdm<br>import warnings<br>import pandas as pd<br>import numpy as np<br><br>warnings.filterwarnings(&#39;ignore&#39;, category=UserWarning)<br><br># we will use batches of 64<br>batch_size = 64<br>data = []<br>from collections import defaultdict<br># table_data = defaultdict(list)<br><br><br>for i in tqdm(range(0, len(df), batch_size)):<br>    # find end of batch<br>    i_end = min(i+batch_size, len(df))<br>    # extract batch<br>    batch = df.iloc[i:i_end].copy()<br>    # generate embeddings for batch<br>    emb = retriever.encode(batch[&quot;title_text&quot;].tolist()).tolist()<br>    # extract named entities from the batch<br>    entities = extract_named_entities(batch[&quot;title_text&quot;].tolist())<br>    # remove duplicate entities from each record<br>    batch[&quot;named_entities&quot;] = [list(set(entity)) for entity in entities]<br>    batch = batch.drop(&#39;title_text&#39;, axis=1)<br>    # get metadata<br>    meta = batch.to_dict(orient=&quot;records&quot;)<br>    # create unique IDs<br>    ids = [f&quot;{idx}&quot; for idx in range(i, i_end)]<br>    # add all to upsert list<br>    to_upsert = list(zip(ids, emb, meta,batch[&quot;named_entities&quot;]))<br>    for id, emb, meta, entity in to_upsert:<br>      temp = {}<br>      temp[&#39;vector&#39;] = np.array(emb)<br>      temp[&#39;metadata&#39;] = meta<br>      temp[&#39;named_entities&#39;] = entity<br>      data.append(temp)</pre><pre>#create table using above data<br>tbl = db.create_table(&quot;tw&quot;, data)<br># check table<br>tbl.head()</pre><p>Now we have all the embeddings with their metadata in a table, we can start querying.</p><p>Let’s first write a helper function to extract the named entity, encode text into retriever format, and filter the query results.</p><pre>from pprint import pprint<br><br>def search_lancedb(query):<br>    # extract named entities from the query<br>    ne = extract_named_entities([query])[0]<br>    # create embeddings for the query<br>    xq = retriever.encode(query).tolist()<br>    # query the lancedb table while applying named entity filter<br>    xc = tbl.search(xq).to_list()<br>    # extract article titles from the search result<br>    r = [x[&quot;metadata&quot;][&quot;title&quot;] for x in xc for i in x[&quot;metadata&quot;][&quot;named_entities&quot;]  if i in ne]<br>    return pprint({&quot;Extracted Named Entities&quot;: ne, &quot;Result&quot;: r})</pre><p>Now Let&#39;s try Querying</p><pre>query = &quot;How Data is changing world?&quot;<br>search_lancedb(query)</pre><p>Output looks like</p><pre>{&#39;Extracted Named Entities&#39;: [&#39;Data&#39;],<br> &#39;Result&#39;: [&#39;Data Science is all about making the right choices&#39;]}</pre><p>Another Query</p><pre>query = &quot;Why does SpaceX want to build a city on Mars?&quot;<br>search_lancedb(query)</pre><p>Output looks like</p><pre>{&#39;Extracted Named Entities&#39;: [&#39;SpaceX&#39;, &#39;Mars&#39;],<br> &#39;Result&#39;: [&#39;Mars Habitat: NASA 3D Printed Habitat Challenge&#39;,<br>            &#39;Reusable rockets and the robots at sea: The SpaceX story&#39;,<br>            &#39;Reusable rockets and the robots at sea: The SpaceX story&#39;,<br>            &#39;Colonising Planets Beyond Mars&#39;,<br>            &#39;Colonising Planets Beyond Mars&#39;,<br>            &#39;Musk Explained: The Musk approach to marketing&#39;,<br>            &#39;How We’ll Access the Water on Mars&#39;,<br>            &#39;Chasing Immortality&#39;,<br>            &#39;Mission Possible: How Space Exploration Can Deliver Sustainable &#39;<br>            &#39;Development&#39;]}</pre><p>For quickstart, You can try out Google Colab which has all these codes</p><p><a href="https://colab.research.google.com/github/lancedb/vectordb-recipes/blob/main/tutorials/NER-powered-Semantic-Search-with-LanceDB/NER_powered_Semantic_Search_with_LanceDB.ipynb">Google Colaboratory</a></p><p>NER is widely used in various NLP tasks. These include:</p><ul><li>Efficient search algorithms</li><li>Content recommendations</li><li>Customer support</li><li>Healthcare</li><li>Summarizing resumes</li><li>Content classification for news channels.</li></ul><h4>Conclusion</h4><p>Named entity recognition primarily uses NLP and Deep Learning. <strong><em>With NLP, a NER model studies the structure and rules of language</em></strong> and tries to form intelligent systems that are capable of deriving meaning from text and speech. Meanwhile, <strong><em>Deep Learning algorithms help an NER model to learn and improve over time</em></strong>.</p><p>Using these two technologies, the model detects a word or string of words as an entity and classifies it into a category it belongs to. Harnessing the advanced vector search functionalities provided by LanceDB enhances its overall utility.</p><p><strong>Visit the </strong><a href="https://www.linkedin.com/feed/?trk=sem-ga_campid.14650114791_asid.148989926143_crid.662526548043_kw.www%20linkedin_d.c_tid.kwd-296759856208_n.g_mt.p_geo.9062111#"><strong>LanceDB </strong></a><strong>repo to learn more about lanceDB python and Typescript library</strong></p><p><strong>To discover more such applied GenAI and vectorDB applications, examples and tutorials visit </strong><a href="https://github.com/lancedb/vectordb-recipes"><strong>VectorDB-Recipes</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51051dc3e493" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/ner-powered-semantic-search-using-lancedb-51051dc3e493">NER-powered Semantic Search using LanceDB</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Primer on Text Chunking and its Types]]></title>
            <link>https://medium.com/etoai/a-primer-on-text-chunking-and-its-types-a420efc96a13?source=rss-618dcd408dc4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a420efc96a13</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Prashant Dixit]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 04:31:08 GMT</pubDate>
            <atom:updated>2023-10-25T04:36:47.531Z</atom:updated>
            <content:encoded><![CDATA[<p>Text chunking is a technique in natural language processing that divides text into smaller segments, usually based on the parts of speech and grammatical meanings of the words. Text chunking can help extract important information from a text, such as noun phrases, verb phrases, or other semantic units.</p><p>In this Blog, We’ll see some Text Chunking strategies, why they are important for building LLM-based systems like RAG, and How to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZeN3xFiqPQ8jY2Zq" /><figcaption>Photo by <a href="https://unsplash.com/@prochurchmedia?utm_source=medium&amp;utm_medium=referral">Pro Church Media</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Why is Text Chunking Important?</h4><p>There are various reasons why Text Chunking becomes important when working with LLMs, we’ll share a few of them which have a significant impact on the results.</p><p>Let&#39;s try to understand it with an example. You have a document of 15 pages full of text and you want to perform summarization and Question Answering on the document for which the first and foremost step is to extract embeddings of the full document, now from here all the problems start with which are listed.</p><ol><li>If you are extracting embeddings of a whole document in one go, it takes the context of the whole document and it can lose lots of valuable information about specific topics, which will result in precise and missed information for LLMs.</li><li>If you are using any model provider like OpenAI, you have to be mindful of chunk size because GPT4 comes with a 32K window size, which does not cause any issue but still it&#39;s good to be mindful from starting.</li></ol><p><em>Failing to use Text Chunking in right way when needed can lead to issues that affect the overall quality and accessibility of the text.</em></p><p>These are the main two reasons why Text Chunking because important instead of using big documents directly.</p><h4>Text Chunking Strategies</h4><p>There are different Text Chunking Strategies, Here we’ll discuss them with their strengths and weaknesses and the right scenarios where they can be applied.</p><p><strong>Sentence Splitting Using Classical Methods</strong></p><ol><li><strong>Naive Method — </strong>The most naive method of sentence splitting is using a <em>split</em> <em>function.</em></li></ol><pre>text = &quot;content.of.document.&quot; #input text<br>chunks = text.split(&quot;.&quot;)<br>print(chunks)</pre><p>Output will look like this</p><pre>#output<br>[&#39;content&#39;, &#39;of&#39;, &#39;document&#39;, &#39;&#39;]</pre><p>2. <strong>NLTK Text Splitter</strong> — NLTK is a library used for working with Language data. It provides a sentence tokenizer that can split the text into sentences, helping to create more meaningful chunks.</p><pre>import nltk  <br><br>input_text =&quot;Much of refactoring is devoted to correctly composing methods. In most cases, excessively long methods are the root of all evil. The vagaries of code inside these methods conceal the execution logic and make the method extremely hard to understand&quot;  <br><br>sentences = nltk.sent_tokenize(input_text)  <br>print(sentences)</pre><p>Here we have not used any character to split sentences. Further many other chunking techniques can be used like tokenizing, POS tagging etc.</p><pre>#output<br>[&#39;Much of refactoring is devoted to correctly composing methods.&#39;,<br> &#39;In most cases, excessively long methods are the root of all evil.&#39;,<br> &#39;The vagaries of code inside these methods conceal the execution logic and make the method extremely hard to understand&#39;]</pre><p>3. <strong>Spacy Text Splitter</strong> — Spacy library is used for performing various tasks of NLP. Text Splitter of Scapy creates text splits preserving contexts of resultant splits.</p><pre>import spacy<br>input_text =&quot;Much of refactoring is devoted to correctly composing methods. In most cases, excessively long methods are the root of all evil. The vagaries of code inside these methods conceal the execution logic and make the method extremely hard to understand&quot;  <br><br>nlp = spacy.load(&quot;en_core_web_sm&quot;)<br>doc = nlp(input_text)<br>for s in doc.sents:<br>    print(s)</pre><p>Spacy can be used in the processing of raw text intelligently.</p><pre>#output <br>Much of refactoring is devoted to correctly composing methods.<br>In most cases, excessively long methods are the root of all evil.<br>The vagaries of code inside these methods conceal the execution logic and make the method extremely hard to understand</pre><p><strong>Recursive Splitting</strong></p><p>Recursive Splitting splits the input text into small chunks in iterative matter using a set of separators. If in the starting steps, chunks are not created of the desired size, it will recursively try different separators or criteria to achieve the desired size of the chunk.</p><p>Here is an example of using Recursive Splitting using Langchain.</p><pre>#input text<br>input_text =&quot;Much of refactoring is devoted to correctly composing methods. In most cases, excessively long methods are the root of all evil. The vagaries of code inside these methods conceal the execution logic and make the method extremely hard to understand&quot; <br><br>from langchain.text_splitter import RecursiveCharacterTextSplitter<br>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size = 100, #set desired text size<br>    chunk_overlap  = 20 )<br><br>chunks = text_splitter.create_documents([input_text])<br>print(chunks)</pre><p>Output of Recursive Splitting looks like this</p><pre>#output<br>[Document(page_content=&#39;Much of refactoring is devoted to correctly composing methods. In most cases, excessively long&#39;), <br>Document(page_content=&#39;excessively long methods are the root of all evil. The vagaries of code inside these methods&#39;), <br>Document(page_content=&#39;these methods conceal the execution logic and make the method extremely hard to understand&#39;)]</pre><p><strong>Specialized Structured Splitting</strong></p><ol><li><strong>HTML Text Splitter — </strong>HTML Splitter is a <em>structure-aware</em> chunker that splits text at the HTML element level and adds metadata for each header relevant to any given chunk.</li></ol><pre>#input html string<br>html_string =&quot;&quot;&quot;<br>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;body&gt;<br>    &lt;div&gt;<br>        &lt;h1&gt;Foo&lt;/h1&gt;<br>        &lt;p&gt;Some intro text about Foo.&lt;/p&gt;<br>        &lt;div&gt;<br>            &lt;h2&gt;Bar main section&lt;/h2&gt;<br>            &lt;p&gt;Some intro text about Bar.&lt;/p&gt;<br>            &lt;h3&gt;Bar subsection 1&lt;/h3&gt;<br>            &lt;p&gt;Some text about the first subtopic of Bar.&lt;/p&gt;<br>            &lt;h3&gt;Bar subsection 2&lt;/h3&gt;<br>            &lt;p&gt;Some text about the second subtopic of Bar.&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;div&gt;<br>            &lt;h2&gt;Baz&lt;/h2&gt;<br>            &lt;p&gt;Some text about Baz&lt;/p&gt;<br>        &lt;/div&gt;<br>        &lt;br&gt;<br>        &lt;p&gt;Some concluding text about Foo&lt;/p&gt;<br>    &lt;/div&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br>&quot;&quot;&quot;<br><br>headers_to_split_on = [<br>    (&quot;h1&quot;, &quot;Header 1&quot;),<br>    (&quot;h2&quot;, &quot;Header 2&quot;),<br>    (&quot;h3&quot;, &quot;Header 3&quot;),<br>]<br><br><br>from langchain.text_splitter import HTMLHeaderTextSplitter<br>html_splitter = HTMLHeaderTextSplitter(headers_to_split_on=headers_to_split_on)<br><br>html_header_splits = html_splitter.split_text(html_string)<br>print(html_header_split)</pre><p>HTML header will extract only the headers mentioned in <em>header_to_split_on</em></p><pre>#output<br>[Document(page_content=&#39;Foo&#39;), <br>Document(page_content=&#39;Some intro text about Foo.  \nBar main section Bar subsection 1 Bar subsection 2&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;}), <br>Document(page_content=&#39;Some intro text about Bar.&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;, &#39;Header 2&#39;: &#39;Bar main section&#39;}), <br>Document(page_content=&#39;Some text about the first subtopic of Bar.&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;, &#39;Header 2&#39;: &#39;Bar main section&#39;, &#39;Header 3&#39;: &#39;Bar subsection 1&#39;}), <br>Document(page_content=&#39;Some text about the second subtopic of Bar.&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;, &#39;Header 2&#39;: &#39;Bar main section&#39;, &#39;Header 3&#39;: &#39;Bar subsection 2&#39;}), <br>Document(page_content=&#39;Baz&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;}), <br>Document(page_content=&#39;Some text about Baz&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;, &#39;Header 2&#39;: &#39;Baz&#39;}), <br>Document(page_content=&#39;Some concluding text about Foo&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;})]</pre><p>2. <strong>Markdown Text Splitting — </strong>Markdown Splitting is used to chunk based on Markdown syntax like heading, bash code, images, and lists. It can also structure-aware chunker.</p><pre>#input markdown string<br>markdown_text = &#39;# Foo\n\n ## Bar\n\nHi this is Jim  \nHi this is Joe\n\n ## Baz\n\n Hi this is Molly&#39; <br><br>from langchain.text_splitter import MarkdownHeaderTextSplitter<br>headers_to_split_on = [<br>    (&quot;#&quot;, &quot;Header 1&quot;),<br>    (&quot;##&quot;, &quot;Header 2&quot;),<br>    (&quot;###&quot;, &quot;Header 3&quot;),<br>]<br><br>markdown_splitter = MarkdownHeaderTextSplitter(headers_to_split_on=headers_to_split_on)<br>md_header_splits = markdown_splitter.split_text(markdown_text)<br>print(md_header_splits)</pre><p><em>MarkdownHeaderTextSplitter </em>splits markdown text based on <em>headers_to_split_on</em>.</p><pre>#output<br>[Document(page_content=&#39;Hi this is Jim\nHi this is Joe&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;, &#39;Header 2&#39;: &#39;Bar&#39;}), <br>Document(page_content=&#39;Hi this is Molly&#39;, metadata={&#39;Header 1&#39;: &#39;Foo&#39;, &#39;Header 2&#39;: &#39;Baz&#39;})]</pre><p>3. <strong>LaTex Text Splitting — </strong>LaTex Splitting is another <em>code-split </em>chunker that parses LaTex commands to create chunks that are the logical organization like sections and subsections, leading to more accurate and contextually relevant results.</p><pre>#input latex string<br>latex_text = &quot;&quot;&quot;<br>\documentclass{article}<br><br>\begin{document}<br><br>\maketitle<br><br>\section{Introduction}<br>Large language models (LLMs) are a type of machine learning model that can be trained on vast amounts of text data to generate human-like language. In recent years, LLMs have made significant advances in a variety of natural language processing tasks, including language translation, text generation, and sentiment analysis.<br><br>\subsection{History of LLMs}<br>The earliest LLMs were developed in the 1980s and 1990s, but they were limited by the amount of data that could be processed and the computational power available at the time. In the past decade, however, advances in hardware and software have made it possible to train LLMs on massive datasets, leading to significant improvements in performance.<br><br>\subsection{Applications of LLMs}<br>LLMs have many applications in industry, including chatbots, content creation, and virtual assistants. They can also be used in academia for research in linguistics, psychology, and computational linguistics.<br><br>\end{document}<br>&quot;&quot;&quot;<br><br>from langchain.text_splitter import LatexTextSplitter<br>latex_splitter = LatexTextSplitter(chunk_size=100, chunk_overlap=0)<br><br>latex_splits = latex_splitter.create_documents([latex_text])<br>print(latex_splits)</pre><p>In the above example you can see that <em>overlap is 0, </em>it is because when we are working with code splits at that time overlapping codes totally change the meaning of it. So overlapping should be 0.</p><pre>#output<br>[Document(page_content=&#39;\\documentclass{article}\n\n\x08egin{document}\n\n\\maketitle\n\n\\section{Introduction}\nLarge language models&#39;),<br> Document(page_content=&#39;(LLMs) are a type of machine learning model that can be trained on vast amounts of text data to&#39;),<br> Document(page_content=&#39;generate human-like language. In recent years, LLMs have made significant advances in a variety of&#39;),<br> Document(page_content=&#39;natural language processing tasks, including language translation, text generation, and sentiment&#39;),<br> Document(page_content=&#39;analysis.\n\n\\subsection{History of LLMs}\nThe earliest LLMs were developed in the 1980s and 1990s,&#39;),<br> Document(page_content=&#39;but they were limited by the amount of data that could be processed and the computational power&#39;),<br> Document(page_content=&#39;available at the time. In the past decade, however, advances in hardware and software have made it&#39;),<br> Document(page_content=&#39;possible to train LLMs on massive datasets, leading to significant improvements in&#39;),<br> Document(page_content=&#39;performance.\n\n\\subsection{Applications of LLMs}\nLLMs have many applications in industry, including&#39;),<br> Document(page_content=&#39;chatbots, content creation, and virtual assistants. They can also be used in academia for research&#39;),<br> Document(page_content=&#39;in linguistics, psychology, and computational linguistics.\n\n\\end{document}&#39;)]</pre><p>Now when you choose which chunker to use for your data, extract embeddings for them and store them in Vector DB.</p><p>In this Blog, We see an example of using Text Chunker with LanceDB to store chunks and their respective embeddings. LanceDB is a setup free, open source, serverless vectorDB, that persists in HDD allowing you to scale without breaking the bank. It is also integrated with the Python data ecosystem so you can use it with your existing data tools like pandas, pyarrow, and more.</p><p><a href="https://colab.research.google.com/drive/1UPcjM7Y8dgWqKkEAcX0je-KGLdqPd4am?usp=sharing">Google Colaboratory</a></p><h4>Conclusion</h4><p>Text Chunking is one of the easiest tasks and is important too because it shows some challenges. There is no one strategy that will apply everywhere or any one specific chunk size that fits all the solutions, so what works for some data or solution might not work for others.</p><p>In this blog we’ve covered the <strong><em>Importance of Text Chunking </em></strong>and got some new insights to perform Text Chunking.</p><p>Learn more about LanceDB or learn more about applied GenAI applications on our <a href="https://github.com/lancedb/vectordb-recipes">vectordb-recipes</a> . Don’t forget to drop us a 🌟!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a420efc96a13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etoai/a-primer-on-text-chunking-and-its-types-a420efc96a13">A Primer on Text Chunking and its Types</a> was originally published in <a href="https://medium.com/etoai">LanceDB</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>