<?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 Ali Naeem on Medium]]></title>
        <description><![CDATA[Stories by Ali Naeem on Medium]]></description>
        <link>https://medium.com/@alinaeem_57283?source=rss-66d3df626fd6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NKlFN2fjHQHO3GuYvnK4yg.png</url>
            <title>Stories by Ali Naeem on Medium</title>
            <link>https://medium.com/@alinaeem_57283?source=rss-66d3df626fd6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:48:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alinaeem_57283/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[Why Your Fashion Brand is Bleeding Cash (and the “Invisible” Fix You’re Ignoring)]]></title>
            <link>https://medium.com/@alinaeem_57283/why-your-fashion-brand-is-bleeding-cash-and-the-invisible-fix-youre-ignoring-145f4c956294?source=rss-66d3df626fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/145f4c956294</guid>
            <category><![CDATA[fashion]]></category>
            <category><![CDATA[fashion-technology]]></category>
            <category><![CDATA[shopify]]></category>
            <category><![CDATA[retail-technology]]></category>
            <category><![CDATA[retail]]></category>
            <dc:creator><![CDATA[Ali Naeem]]></dc:creator>
            <pubDate>Sun, 01 Feb 2026 11:34:15 GMT</pubDate>
            <atom:updated>2026-02-01T11:34:15.165Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xg7Nn9-v8Ala6mM6lIxi4g.png" /></figure><p>Behind the glossy campaign photos and the high-energy runway shows of the fashion world lies a dusty, chaotic “backstage” that most leaders hate to talk about.</p><p>It isn’t a messy dressing room. It’s a <strong>spreadsheet.</strong></p><p>If you run a fashion brand today, you aren’t just selling clothes; you are selling <strong>information</strong>. But for most brands, that information is broken. In the industry, we call it “dirty data,” and it is currently the single greatest tax on your profitability.</p><p>Here is why your product data is failing you — and how AI is quietly becoming the most important “tailor” in your business.</p><h3>The $100 Billion “Guessing Game”</h3><p>We’ve all been there. You’re looking for a <em>navy blue, high-waisted, linen trouser</em> on a brand’s website. You type it in. The result? <strong>“0 items found.”</strong></p><p>You know the brand has them. They know they have them. But because a tired intern in a warehouse labeled them as “Dark Blue Bottoms,” the search engine is blind.</p><blockquote><strong><em>The Insight:</em></strong><em> In e-commerce, if a product isn’t described perfectly, it effectively doesn’t exist.</em></blockquote><p>When data is “broken” — missing attributes, inconsistent colors, or vague descriptions — two expensive things happen:</p><ol><li><strong>The “Search Ghost”:</strong> Customers can’t find what they want and leave.</li><li><strong>The “Return Death-Loop”:</strong> A customer buys a “red” dress that arrives looking “burgundy.” They feel cheated, they return it, and you lose the shipping cost, the processing fee, and the customer’s trust.</li></ol><h3>The Problem: The “Excel Hell” Bottleneck</h3><p>Fashion moves at the speed of Instagram. You have thousands of SKUs, dozens of suppliers, and new drops every month.</p><p>The traditional way to handle this? A “Product Content Team” manually typing details into a master sheet. It’s slow, it’s prone to human error, and it’s impossible to scale.</p><h3>The Anatomy of Broken Data</h3><p><strong>The SymptomThe RealityThe ResultMissing Tags</strong>No mention of “sleeve length” or “fabric.”Filter tools on your site become useless.<strong>Supplier Chaos</strong>Supplier A says “XL,” Supplier B says “Size 16.”Customer buys the wrong size. <strong>Return.Vague Titles</strong>”Summer Top 04&quot; instead of “Floral Silk Camisole.”Google Search (SEO) ignores you completely.</p><h3>The Solution: AI is the New “Digital Tailor”</h3><p>We need to stop thinking of AI as a sci-fi concept and start seeing it as a <strong>high-speed librarian.</strong> It doesn’t replace your creative team; it cleans up after them.</p><h3>1. AI That “Sees” (Computer Vision)</h3><p>Modern AI can “look” at a product photo and instantly extract 20+ attributes. It recognizes the neckline, the hem, the fabric texture, and even the “vibe” (e.g., <em>Boho, Minimalist, Corporate</em>).</p><ul><li><strong>Human speed:</strong> 2 minutes per photo.</li><li><strong>AI speed:</strong> 1,000 photos per minute.</li></ul><h3>2. AI That “Translates” (Natural Language Processing)</h3><p>AI can take the messy, technical jargon from a factory spec sheet and turn it into high-converting, SEO-friendly copy. It standardizes “Nvy Blu” and “Midnight” into a single, searchable “Navy.”</p><h3>The “Perfect Data” Workflow</h3><p>This isn’t just about being “techy.” It’s about building a machine that converts browsers into buyers.</p><p>Code snippet</p><pre>graph LR<br>    A[Raw Product Image] --&gt; B{AI Vision};<br>    B --&gt; C[Auto-Tagging: &#39;V-Neck&#39;, &#39;Midi&#39;, &#39;Silk&#39;];<br>    C --&gt; D[Standardized Data];<br>    D --&gt; E[Searchable &amp; Shopable];<br>    E --&gt; F[$$$ Revenue];</pre><h3>The Bottom Line: Efficiency is the New Luxury</h3><p>In the next three years, the fashion brands that win won’t just be the ones with the best designs — they’ll be the ones with the cleanest data.</p><p>When your data is fixed:</p><ul><li><strong>Conversion rates climb</strong> because search actually works.</li><li><strong>Returns drop</strong> because expectations match reality.</li><li><strong>Time-to-market shrinks</strong> from weeks to hours.</li></ul><p><strong>Stop forcing your team to swim through spreadsheets.</strong> Let the AI do the heavy lifting of data cleaning so your humans can get back to the art of fashion.</p><p>The “backstage” of your business should be just as seamless as your front row.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=145f4c956294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AI in Fashion: The New Operating System for Profitable Retail Brands]]></title>
            <link>https://medium.com/@alinaeem_57283/ai-in-fashion-the-new-operating-system-for-profitable-retail-brands-ff778f3d29bc?source=rss-66d3df626fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff778f3d29bc</guid>
            <category><![CDATA[fashion]]></category>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[fashion-trends]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[shopify]]></category>
            <dc:creator><![CDATA[Ali Naeem]]></dc:creator>
            <pubDate>Thu, 29 Jan 2026 19:48:16 GMT</pubDate>
            <atom:updated>2026-01-29T19:48:16.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYbxsBZPLOzpSAQcOS3KFg.png" /></figure><p>For decades, the fashion industry has operated on a high-stakes wager. Executives sign off on capital for inventory months in advance, hoping that when the product finally arrives, the market will still want it.</p><p>It is a business model built on guessing.</p><p>But for the modern CEO, <strong>Artificial Intelligence (AI)</strong> offers a path out of this cycle. It isn’t just about chatbots; it’s about building a new <strong>digital architecture</strong> that shifts your business from a “push” model (guessing) to a “pull” model (reacting to real-time market demand).</p><p>Here is how this AI-driven architecture functions as a modern operating system for profitable fashion companies.</p><h3>1. Unified Commercial Intelligence: The Data Foundation</h3><p>The most common frustration for brand founders is <strong>data silos</strong>. Marketing has one set of numbers, logistics has another, and design works off intuition.</p><p>The foundation of a successful digital transformation is a <strong>Unified Data Layer</strong>. Think of this as the central nervous system of your company. It connects:</p><ul><li><strong>Inventory systems</strong></li><li><strong>Customer behavior data</strong></li><li><strong>Real-time market signals</strong></li></ul><p>For a business leader, the value is <strong>clarity</strong>. By establishing a “single source of truth,” you stop making decisions based on outdated reports and start spotting inefficiencies the moment they happen.</p><h3>2. Predictive Supply Chain: Advanced Risk Management</h3><p>Inventory is the silent killer of profitability. Buying too much leads to margin-destroying markdowns; buying too little results in missed revenue.</p><p>The <strong>Predictive Layer</strong> of AI architecture is your defense against this risk. By using <strong>machine learning</strong> to analyze millions of variables — from weather patterns to social media search trends — brands can forecast demand with surgical precision.</p><p>Instead of guessing that “red sweaters” will trend, the system predicts the exact units needed for specific regions. This aligns supply strictly with demand, freeing up working capital and reducing the environmental waste that impacts your bottom line.</p><h3>3. Generative Design and Marketing: Accelerating Speed-to-Market</h3><p>In the traditional fashion cycle, the “critical path” from concept to shelf is far too slow. By the time a product is approved, the trend has often passed.</p><p><strong>Generative AI</strong> addresses these creative bottlenecks:</p><ul><li><strong>Designers</strong> can visualize concepts instantly without waiting for physical samples.</li><li><strong>Marketing teams</strong> can automate high-quality product descriptions and visual assets in minutes.</li></ul><p>This allows your brand to move at the “speed of culture.” You can identify a micro-trend and have a product ready for market while competitors are still in the sketching phase.</p><h3>4. Hyper-Personalization: The Revenue Engine</h3><p>Acquiring a new customer is expensive; the most profitable path to growth is increasing <strong>Customer Lifetime Value (CLV)</strong>.</p><p>The <strong>Experience Layer</strong> is the “face” of your AI architecture. It treats every online visitor like a VIP client by:</p><ul><li>Curation of a unique storefront based on browsing history.</li><li>Implementing <strong>virtual try-on</strong> features to bridge the “uncertainty gap.”</li><li>Reducing return rates by ensuring customers feel confident in fit and style.</li></ul><h3>The Strategic Shift: Data Over Instinct</h3><p>Implementing this architecture is more than an IT upgrade; it is a fundamental shift in business logic. The traditional model relied on instinct and volume; the modern model relies on <strong>agility and data</strong>.</p><p>For the modern CEO, this AI architecture is the difference between a brand that creates noise and a brand that creates <strong>long-term value</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff778f3d29bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post-Training Large Language Models: Turning an Open-Source AI into Elon Musk]]></title>
            <link>https://ai.plainenglish.io/post-training-large-language-models-turning-an-open-source-ai-into-elon-musk-1847e34e00bc?source=rss-66d3df626fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1847e34e00bc</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Ali Naeem]]></dc:creator>
            <pubDate>Mon, 11 Aug 2025 08:23:45 GMT</pubDate>
            <atom:updated>2025-08-11T11:55:21.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*daZZjempBy8XvxSz9_Zsrg.png" /><figcaption>Image Credits : Open AI</figcaption></figure><p>Hey everyone ! <br>If you’ve been tinkering with AI like I have, you know large language models (LLMs) are game-changers. Models like GPT or Llama can churn out text that sounds almost human, but getting them to act a certain way — say, responding like a specific person — takes some extra work. That’s where post-training comes in.</p><p>In this post, I’ll break down the basics of post-training LLMs, focusing on how you can use it to tweak a model’s “identity.”</p><p>As a fun example, we’ll imagine fine-tuning an open-source model like Qwen (from Alibaba) to make it believe it’s Elon Musk. <br>Here is what we will do</p><ul><li>Throw in some math for the SFT.</li><li>Share code snippets you can actually run.</li><li>Generate a synthetic dataset to get you started.</li></ul><p>I’ve kept things straightforward — no jargon overload.</p><h3><strong>The Basics: Pre-Training vs. Post-Training</strong></h3><p>Training an LLM happens in two main stages.</p><ol><li><strong><em>Pre-training</em></strong> is the heavy lifting: You start with a model that’s basically a blank slate (random weights) and feed it trillions of tokens from books, websites, code, you name it. The goal? Teach it to predict the next word or token in a sequence. <br>This phase is expensive — think months on GPU farms — but it gives you a “base model” with broad knowledge.</li><li><strong><em>Post-training</em></strong> is where the magic happens for real-world use: You take that base model and refine it with smaller datasets (from hundreds to maybe a billion tokens) to handle specific tasks, like answering questions or chatting. It’s faster and cheaper. <br>The end result? An “instruct” or “chat” model that’s more aligned with what users want. You can even do further post-training to customize it further — boosting skills in areas like SQL writing or, in our case, adopting a new personality.</li></ol><p>Why change a model’s identity? Maybe you want it to role-play for fun, or align it with a brand’s voice. <br>For our Elon Musk example, we’ll make Qwen respond in his style: short, witty, tech-focused, with emojis and a touch of humor. Pulled from his recent X posts, Elon’s replies often include things like “ 🤣 ” for laughs, “Yeah” for agreement, or quick takes on AI and space.</p><p><strong>To succeed in post-training, nail three things:</strong></p><ul><li>Data and algorithm co-design: Pick high-quality data that matches your goal.</li><li>Solid libraries: Use stuff like Hugging Face’s Transformers and TRL (Trainer for Reinforcement Learning).</li><li>Evaluation: Test with benchmarks to ensure the model doesn’t regress.</li></ul><p><strong>Three common post-training methods :</strong></p><ul><li><strong>Supervised Fine-Tuning (SFT)</strong> — Feed it curated Elon-style conversations.</li><li><strong>Direct Preference Optimization (DPO)</strong> — Teach it which Musk-like responses are preferred.</li><li><strong>Online Reinforcement Learning</strong> (PPO, GRPO) — Let it learn in real time from feedback, adapting its style dynamically. (To be covered in another post)</li></ul><h3>Supervised Fine-Tuning (SFT)</h3><p>SFT is the go-to starter method. It’s like teaching by example: show the model prompt-response pairs, and it learns to copy the good responses. You only train on the response tokens, ignoring the prompt to focus the learning.</p><p>Mathematically, for a dataset of pairs (prompt xi, responseyi), you minimize the negative log-likelihood loss:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*jGmq6ac3Y-kILbvvUEXmQQ.png" /></figure><p>Let’s break the SFT loss equation into bite-sized pieces and talk through it in plain English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*WArUMWl8FaX_1aMOTV-u0Q.png" /></figure><blockquote>Meaning: This is the total <em>Supervised Fine-Tuning loss</em> — the number we’re trying to make as small as possible during training.<br>Think of it like a “score” for how wrong the model is. Lower is better.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*OmtL7CSQksvPp2f8qQFlsA.png" /></figure><p><strong>Meaning:</strong> Go through <strong>every example</strong> in our training dataset.<br>Example dataset row:</p><ul><li><strong>Prompt</strong> (​xi): “Write a tweet about Mars colonization.”</li><li><strong>Ideal answer</strong> (yi): “Making life multi-planetary is humanity’s insurance policy.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*Szs2QQg5YYLGszNG3fZKsg.png" /></figure><p><strong>Meaning:</strong> For the <strong>i-th example</strong>, check <strong>every token</strong> in the <em>response</em> from start to finish.<br>If the answer has 8 tokens, we check each one: Token 1, Token 2, Token 3, …, Token 8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*cTVZ9SpGALJPaOBJ5tsR9g.png" /></figure><p><strong>Meaning:</strong> The probability (according to our model’s current parameters θ) that the <strong>next token</strong> will be the correct one, given:<br>1. The original prompt xi.<br>2. All the previous tokens of the answer so far (yi&lt;t​)</p><p>Example:<br> If the answer so far is: &quot;Making life&quot;, the next correct token might be &quot;multi-planetary&quot;. The model assigns a probability to that guess.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*SiLaft8tRWgeU9BddcOA_w.png" /></figure><p><strong>Meaning:</strong> We take the logarithm of the probability this turns multiplication into addition and helps with stability in training.<br> Also, log probabilities are negative if the probability is less than 1, so we use a minus sign in the loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*Fd56h5zccImaud4ujEJ1Cw.png" /></figure><p><strong>Meaning:</strong> We want to <em>maximize</em> the probability of correct tokens but optimizers minimize loss functions.<br>So we make it negative so that:<br>- High probability → small (good) loss<br>- Low probability → large (bad) loss</p><h3>Synthetic Dataset for SFT</h3><p>Quality beats quantity, so here’s a small synthetic dataset inspired by Elon’s real posts (e.g., his takes on AGI, algorithms, and tech). I’ve formatted it as JSON for easy loading. Save this as elon_sft_data.json:</p><pre>[<br>  {<br>    &quot;prompt&quot;: &quot;What do you think about AGI being close?&quot;,<br>    &quot;response&quot;: &quot;It is very close 😂. 3 years&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;How&#39;s the X algorithm doing?&quot;,<br>    &quot;response&quot;: &quot;Many complaints. Meeting with algorithm team late tonight.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;What&#39;s up with Starlink?&quot;,<br>    &quot;response&quot;: &quot;Starlink now in Antigua &amp; Barbuda. Available in over 150 countries!&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Thoughts on Grok upgrades?&quot;,<br>    &quot;response&quot;: &quot;Grok upgrades 🌹⚔️♥️&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Grok vs other AIs?&quot;,<br>    &quot;response&quot;: &quot;Grok to the Moon&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Thoughts on earth?&quot;,<br>    &quot;response&quot;: &quot;Only thinking of Mars&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Grok 4 ranking?&quot;,<br>    &quot;response&quot;: &quot;Grok 4.20 hopefully this month reaches #1&quot;<br>  }<br>]</pre><p>This is just few examples you can replace this dataset with your own custom examples.</p><p>Here’s a reusable script using Hugging Face. It loads Qwen-7B (a solid open-source base), your dataset, and fine-tunes. Run this in a Colab notebook with a GPU.</p><pre>from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments<br>from datasets import load_dataset<br>import json<br><br># Load your synthetic data<br>with open(&#39;elon_sft_data.json&#39;, &#39;r&#39;) as f:<br>    data = json.load(f)<br><br># Convert to Hugging Face Dataset format<br>from datasets import Dataset<br>dataset = Dataset.from_list([{&quot;text&quot;: f&quot;Prompt: {item[&#39;prompt&#39;]}\nResponse: {item[&#39;response&#39;]}&quot;} for item in data])<br><br># Load Qwen model and tokenizer (use &#39;Qwen/Qwen-7B&#39; or similar; check Hugging Face for latest)<br>model_name = &quot;Qwen/Qwen-7B&quot;<br>model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)<br>tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)<br>tokenizer.pad_token = tokenizer.eos_token<br><br># Preprocess: Tokenize and set labels (mask prompts by setting labels to -100 for prompt tokens)<br>def preprocess(example):<br>    tokenized = tokenizer(example[&#39;text&#39;], truncation=True, padding=&quot;max_length&quot;, max_length=128)<br>    input_ids = tokenized[&#39;input_ids&#39;]<br>    labels = input_ids.copy()<br>    <br>    # Find where response starts (simple string search; adjust as needed)<br>    response_start = example[&#39;text&#39;].find(&quot;Response:&quot;) + len(&quot;Response: &quot;)<br>    prompt_tokens = len(tokenizer.encode(example[&#39;text&#39;][:response_start]))<br>    labels[:prompt_tokens] = [-100] * prompt_tokens  # Ignore prompt in loss<br>    <br>    tokenized[&#39;labels&#39;] = labels<br>    return tokenized<br><br>dataset = dataset.map(preprocess)<br><br># Training setup<br>training_args = TrainingArguments(<br>    output_dir=&quot;./qwen_elon_sft&quot;,<br>    num_train_epochs=3,<br>    per_device_train_batch_size=2,  # Adjust based on your GPU<br>    save_steps=100,<br>    logging_steps=10,<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=dataset,<br>)<br><br>trainer.train()<br>model.save_pretrained(&quot;./qwen_elon_sft&quot;)</pre><p>After training, test it:</p><pre>output = model.generate(tokenizer.encode(&quot;Prompt: What about AGI?&quot;, return_tensors=&#39;pt&#39;))</pre><p>It should spit out something Elon-esque.</p><p>Now lets have a look at the second type of post training meathod . <br><strong>Direct Preference Optimisation</strong> (DPO)</p><h3>Direct Preference Optimization (DPO)</h3><p>DPO is a training method where you show the model two answers to the same prompt one clearly <strong>better</strong> and one clearly <strong>worse</strong> and nudge it to prefer the better one. You keep a frozen <strong>reference model</strong> (a copy of the original) so the new model improves its behavior without drifting too far from what already works. There’s also a simple “strength knob” you can tune to control how boldly the model changes.</p><p>In practice, you start with a capable base model, prepare a dataset of <strong>prompt, good answer, bad answer</strong> triples, and train. The trainer checks whether your current model prefers the good answer more than the reference does (and the bad answer less). If not, it nudges the model in that direction. Repeating this over many pairs produces crisper, more on-target responses while preserving general skills.</p><p>The loss function is a contrastive one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jCpJ03nzwcz_qpmgGrUNg.png" /></figure><pre>[<br>  {<br>    &quot;prompt&quot;: &quot;What do you think about AGI being close?&quot;,<br>    &quot;chosen&quot;: &quot;It is very close 😂. 3 years&quot;,<br>    &quot;rejected&quot;: &quot;AGI is a complex, long-term research area; it’s premature to give a timeline.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;How&#39;s the X algorithm doing?&quot;,<br>    &quot;chosen&quot;: &quot;Many complaints. Meeting with algorithm team late tonight.&quot;,<br>    &quot;rejected&quot;: &quot;The algorithm is functioning as expected and we review metrics on a regular cadence.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;What&#39;s up with Starlink?&quot;,<br>    &quot;chosen&quot;: &quot;Starlink now in Antigua &amp; Barbuda. Available in over 150 countries!&quot;,<br>    &quot;rejected&quot;: &quot;We plan to expand service to additional regions subject to regulatory approvals.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Thoughts on Grok upgrades?&quot;,<br>    &quot;chosen&quot;: &quot;Grok upgrades 🌹⚔️♥️&quot;,<br>    &quot;rejected&quot;: &quot;We periodically roll out software updates that improve stability and performance.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Grok vs other AIs?&quot;,<br>    &quot;chosen&quot;: &quot;Grok to the Moon&quot;,<br>    &quot;rejected&quot;: &quot;It’s one of many AI systems; relative performance depends on the benchmark.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Thoughts on earth?&quot;,<br>    &quot;chosen&quot;: &quot;Only thinking of Mars&quot;,<br>    &quot;rejected&quot;: &quot;Earth presents many challenges that require broad, collaborative solutions.&quot;<br>  },<br>  {<br>    &quot;prompt&quot;: &quot;Grok 4 ranking?&quot;,<br>    &quot;chosen&quot;: &quot;Grok 4.20 hopefully this month reaches #1&quot;,<br>    &quot;rejected&quot;: &quot;Rankings fluctuate; our focus is on steady, continuous improvement over time.&quot;<br>  }<br>]</pre><h3>Code Example: DPO on Qwen</h3><p>The following script demonstrates how to run DPO training on Qwen using the dataset above.</p><pre>from trl import DPOTrainer, DPOConfig<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br>from datasets import load_dataset<br>import json<br><br># Load data<br>with open(&#39;elon_dpo_data.json&#39;, &#39;r&#39;) as f:<br>    data = json.load(f)<br>dataset = load_dataset(&#39;json&#39;, data_files=&#39;elon_dpo_data.json&#39;)[&#39;train&#39;]  # Assumes Hugging Face format with &#39;prompt&#39;, &#39;chosen&#39;, &#39;rejected&#39;<br><br># Load models (use your SFT output as starting point)<br>model_name = &quot;./qwen_elon_sft&quot;  # Or start from base Qwen<br>model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)<br>ref_model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True)  # Frozen reference<br>tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)<br><br># Config<br>dpo_config = DPOConfig(<br>    beta=0.1,<br>    output_dir=&quot;./qwen_elon_dpo&quot;,<br>    num_train_epochs=1,<br>    per_device_train_batch_size=1,  # Small for memory<br>)<br><br>trainer = DPOTrainer(<br>    model=model,<br>    ref_model=ref_model,<br>    args=dpo_config,<br>    train_dataset=dataset,<br>    tokenizer=tokenizer,<br>)<br>trainer.train()<br>model.save_pretrained(&quot;./qwen_elon_dpo&quot;)</pre><ol><li><strong>Load the dataset: </strong>It reads the JSON file and loads it into a Hugging Face Dataset with three fields: prompt, chosen (good answer), and rejected (bad answer).</li><li><strong>Load the models: </strong>You load your starting model (either the output from a previous SFT step or a base Qwen model) twice:</li></ol><ul><li>model — the one you will fine-tune.</li><li>ref_model — a frozen reference that the trainer uses for comparison.</li></ul><p>3.<strong> Tokenization: </strong>The tokenizer is loaded for the same model so prompts and responses can be converted into tokens.</p><p>4.<strong> DPOConfig</strong>: This holds training settings like:</p><ul><li>beta — controls how far the fine-tuned model can deviate from the reference.</li><li>output_dir — where to save the fine-tuned model.</li><li>num_train_epochs — how many passes over the dataset.</li><li>per_device_train_batch_size — training batch size per GPU.</li></ul><p>5.<strong> DPOTrainer: </strong>This wraps the model, reference model, dataset, tokenizer, and training settings, and handles the DPO optimization loop internally.</p><p>6.<strong> Training &amp; Saving</strong>: Calling trainer.train() fine-tunes the model using the DPO loss, and then save_pretrained() writes the updated model to disk.</p><h3>Wrapping Up</h3><p>Post-training is where you take an already powerful large language model and make it truly yours. Whether through <strong>Supervised Fine-Tuning (SFT)</strong> for teaching by example, <strong>Direct Preference Optimization (DPO)</strong> for aligning with preferences, or <strong>Reinforcement Learning</strong> for real-time adaptation, the core idea is the same: start with a capable base model and nudge it toward the style, tone, and priorities you want.</p><p>Our Elon Musk example shows that with just a curated dataset and the right tools, you can shift an open-source model like Qwen to adopt a unique personality producing snappier, on-brand, and more engaging responses. The best part? These techniques scale. The same process can make a modelsound like a corporate brand, a historical figure, or a helpful domain expert.</p><p>The takeaway: <strong>LLMs are not just static tools they’re adaptable frameworks</strong>. By investing a bit of effort in post-training, you can transform a generic AI into a specialized assistant that better serves your goals while still retaining its broad capabilities. Whether for fun, productivity, or brand alignment, post-training is your gateway to unlocking a model’s full personality potential.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1847e34e00bc" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/post-training-large-language-models-turning-an-open-source-ai-into-elon-musk-1847e34e00bc">Post-Training Large Language Models: Turning an Open-Source AI into Elon Musk</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a RAG System for Candidate Search with MongoDB & Azure AI]]></title>
            <link>https://medium.com/@alinaeem_57283/building-a-rag-system-for-candidate-search-with-mongodb-azure-ai-551c88532562?source=rss-66d3df626fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/551c88532562</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Ali Naeem]]></dc:creator>
            <pubDate>Tue, 22 Jul 2025 15:19:18 GMT</pubDate>
            <atom:updated>2025-07-22T15:19:18.263Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How recruitment agencies can turn their CV database into an always‑on talent advisor</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E-x8npVISZ-HoypH" /><figcaption><em>AI-generated illustration by ChatGPT (OpenAI)</em></figcaption></figure><h3>Why this matters</h3><p>Agency recruiters already sit on a goldmine: years of CVs, interview notes, and placement feedback. The problem? Finding the <em>right</em> candidate quickly — especially when job titles, skills, and industries keep evolving. Traditional keyword search can’t keep up with “Java dev with a pinch of Rust and a love for fintech risk engines”.</p><p>Retrieval-Augmented Generation (RAG) is a practical way to fix that. Instead of asking a large language model (LLM) to hallucinate answers, you <em>retrieve</em> the most relevant candidates from your own database and then let the model craft a tailored summary or shortlist. In this article, we’ll build a clean, minimal RAG pipeline using:</p><ul><li><strong>MongoDB Atlas</strong> for storing CVs, recruiter notes, and vector embeddings (built-in vector search!)</li><li><strong>Azure AI (Azure OpenAI + Azure AI Search optional)</strong> for embeddings and generation</li><li><strong>Python + FastAPI</strong> for a lightweight service layer</li></ul><p>I’ll keep it simple, with runnable code snippets and diagrams you can paste into your docs.</p><h3>What we’ll build</h3><ol><li><strong>Ingest &amp; clean</strong> candidate data (CV text, skills, metadata) into MongoDB.</li><li><strong>Embed</strong> each candidate record with Azure OpenAI and store the vectors alongside the document.</li><li><strong>Retrieve</strong> top matches using MongoDB’s vector search (or hybrid BM25+vector).</li><li><strong>Augment a prompt</strong> with those matches and ask Azure OpenAI to generate a recruiter-friendly shortlist.</li><li><strong>Expose it via an API</strong> so your consultants (or internal tools) can call /search-candidates with a job brief.</li></ol><h3>The high-level architecture</h3><pre>flowchart LR<br>    subgraph Data Layer<br>        A[CV PDFs / LinkedIn Exports / Notes] --&gt;|ETL| B[MongoDB Atlas]<br>        B --&gt;|Vector Index| Bv[(Vectors)]<br>    end</pre><pre>    subgraph Azure AI<br>        E[Azure OpenAI Embeddings API]<br>        F[Azure OpenAI Chat/Completion API]<br>    end</pre><pre>    C[Retriever Service (FastAPI)] --&gt;|Query| B<br>    B --&gt;|Top K candidates| C<br>    C --&gt;|context| F<br>    F --&gt;|Ranked shortlist &amp; rationale| C<br>    C --&gt;|JSON to UI / ATS| D[Recruiter Portal / Slack / ATS]</pre><pre>    C --&gt;|Batch Embed| E</pre><p><strong>Alt text:</strong> Data flows from raw CVs to MongoDB. We embed with Azure OpenAI, store vectors in MongoDB, retrieve candidates via FastAPI, pass them to Azure OpenAI for generation, and return a shortlist to the UI.</p><h3>Prerequisites</h3><ul><li><strong>MongoDB Atlas</strong> cluster (M10 or above recommended) with <em>Atlas Vector Search</em> enabled</li><li><strong>Azure subscription</strong> with access to Azure OpenAI (for embeddings + GPT models)</li><li>Python 3.10+</li><li>Basic familiarity with REST APIs</li></ul><p>Environment variables (put these into a .env):</p><pre>AZURE_OPENAI_ENDPOINT=&quot;https://&lt;your-resource&gt;.openai.azure.com&quot;<br>AZURE_OPENAI_API_KEY=&quot;&lt;your-key&gt;&quot;<br>AZURE_OPENAI_EMBED_DEPLOYMENT=&quot;text-embedding-3-large&quot; # or -small<br>AZURE_OPENAI_CHAT_DEPLOYMENT=&quot;gpt-4o-mini&quot;            # or other chat model<br>MONGODB_URI=&quot;mongodb+srv://...&quot;<br>DB_NAME=&quot;recruitment&quot;<br>COLLECTION_NAME=&quot;candidates&quot;</pre><h3>1. Model your candidate data</h3><p>You don’t need a perfect schema on day one, but aim for something like:</p><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;...&quot;),<br>  &quot;full_name&quot;: &quot;Jane Doe&quot;,<br>  &quot;titles&quot;: [&quot;Senior Backend Engineer&quot;, &quot;Java Developer&quot;],<br>  &quot;skills&quot;: [&quot;Java&quot;, &quot;Spring&quot;, &quot;Kubernetes&quot;, &quot;Kafka&quot;],<br>  &quot;location&quot;: &quot;Berlin, DE&quot;,<br>  &quot;years_experience&quot;: 7,<br>  &quot;raw_text&quot;: &quot;Full CV text here ...&quot;,<br>  &quot;notes&quot;: &quot;Placed at FinTechCo in 2022, great with stakeholders&quot;,<br>  &quot;vector&quot;: [0.0123, -0.998, ...]  // embedding<br>}</pre><blockquote><em>Tip: Keep </em><em>raw_text for recall, but also extract structured fields (skills, locations) to help with filtering and hybrid search.</em></blockquote><h3>2. Create the collection &amp; index (MongoDB Atlas)</h3><pre># setup_mongo.py<br>from pymongo import MongoClient<br>from pymongo.operations import SearchIndexModel<br>import os</pre><pre>client = MongoClient(os.environ[&quot;MONGODB_URI&quot;])<br>collection = client[os.environ[&quot;DB_NAME&quot;]][os.environ[&quot;COLLECTION_NAME&quot;]]</pre><pre># Create a vector search index if it doesn&#39;t exist<br>index = SearchIndexModel(<br>    name=&quot;candidate_vector_index&quot;,<br>    definition={<br>        &quot;fields&quot;: [<br>            {&quot;type&quot;: &quot;vector&quot;, &quot;path&quot;: &quot;vector&quot;, &quot;numDimensions&quot;: 3072, &quot;similarity&quot;: &quot;cosine&quot;},<br>            {&quot;type&quot;: &quot;string&quot;, &quot;path&quot;: &quot;skills&quot;},<br>            {&quot;type&quot;: &quot;string&quot;, &quot;path&quot;: &quot;location&quot;},<br>            {&quot;type&quot;: &quot;string&quot;, &quot;path&quot;: &quot;raw_text&quot;}<br>        ]<br>    },<br>    type=&quot;vectorSearch&quot;<br>)</pre><pre>try:<br>    collection.create_search_index(index)<br>    print(&quot;Index created&quot;)<br>except Exception as e:<br>    print(e)</pre><p>Adjust numDimensions to your embedding model size.</p><h3>3. Embed and ingest documents</h3><p>We’ll use Azure OpenAI to create embeddings for each candidate. Batch these to avoid rate limits.</p><pre># ingest_candidates.py<br>import os, json<br>from pymongo import MongoClient<br>from openai import AzureOpenAI<br>from dotenv import load_dotenv</pre><pre>load_dotenv()</pre><pre>client = AzureOpenAI(<br>    api_key=os.getenv(&quot;AZURE_OPENAI_API_KEY&quot;),<br>    api_version=&quot;2024-02-15-preview&quot;,<br>    azure_endpoint=os.getenv(&quot;AZURE_OPENAI_ENDPOINT&quot;)<br>)</pre><pre>mongo = MongoClient(os.getenv(&quot;MONGODB_URI&quot;))<br>col = mongo[os.getenv(&quot;DB_NAME&quot;)][os.getenv(&quot;COLLECTION_NAME&quot;)]</pre><pre>EMBED_MODEL = os.getenv(&quot;AZURE_OPENAI_EMBED_DEPLOYMENT&quot;)</pre><pre># Imagine you have a list of CV dicts loaded from disk<br>with open(&quot;cv_dump.json&quot;, &quot;r&quot;) as f:<br>    cvs = json.load(f)</pre><pre>for cv in cvs:<br>    text = cv[&quot;raw_text&quot;]<br>    embedding = client.embeddings.create(<br>        input=text,<br>        model=EMBED_MODEL<br>    ).data[0].embedding</pre><pre>    cv[&quot;vector&quot;] = embedding<br>    col.insert_one(cv)</pre><pre>print(&quot;Done!&quot;)</pre><h3>4. Build the retriever</h3><p>A small helper that turns a job brief into a vector query and returns top candidates.</p><pre># retriever.py<br>from typing import List, Dict<br>from openai import AzureOpenAI<br>from pymongo import MongoClient<br>import os</pre><pre>aic = AzureOpenAI(<br>    api_key=os.getenv(&quot;AZURE_OPENAI_API_KEY&quot;),<br>    api_version=&quot;2024-02-15-preview&quot;,<br>    azure_endpoint=os.getenv(&quot;AZURE_OPENAI_ENDPOINT&quot;)<br>)</pre><pre>mongo = MongoClient(os.getenv(&quot;MONGODB_URI&quot;))<br>col = mongo[os.getenv(&quot;DB_NAME&quot;)][os.getenv(&quot;COLLECTION_NAME&quot;)]</pre><pre>EMBED_MODEL = os.getenv(&quot;AZURE_OPENAI_EMBED_DEPLOYMENT&quot;)<br></pre><pre>def embed(text: str) -&gt; List[float]:<br>    return aic.embeddings.create(input=text, model=EMBED_MODEL).data[0].embedding<br></pre><pre>def retrieve_candidates(query: str, k: int = 5, location: str | None = None) -&gt; List[Dict]:<br>    q_vec = embed(query)<br>    pipeline = [<br>        {<br>            &quot;$vectorSearch&quot;: {<br>                &quot;index&quot;: &quot;candidate_vector_index&quot;,<br>                &quot;path&quot;: &quot;vector&quot;,<br>                &quot;queryVector&quot;: q_vec,<br>                &quot;numCandidates&quot;: 200,<br>                &quot;limit&quot;: k,<br>                &quot;filter&quot;: {&quot;location&quot;: location} if location else None<br>            }<br>        },<br>        {&quot;$project&quot;: {&quot;vector&quot;: 0}}  # Exclude big vector from payload<br>    ]<br>    return list(col.aggregate(pipeline))</pre><blockquote><em>Hybrid tip: Add a </em><em>$search stage beforehand with </em><em>text operator on </em><em>raw_text or </em><em>skills to combine keyword boosting with semantic similarity.</em></blockquote><h3>5. Generate the shortlist with Azure OpenAI</h3><p>Now we stuff the retrieved docs into a prompt. Keep inputs small, use bullet points.</p><pre># generator.py<br>from openai import AzureOpenAI<br>import os, textwrap</pre><pre>aic = AzureOpenAI(<br>    api_key=os.getenv(&quot;AZURE_OPENAI_API_KEY&quot;),<br>    api_version=&quot;2024-02-15-preview&quot;,<br>    azure_endpoint=os.getenv(&quot;AZURE_OPENAI_ENDPOINT&quot;)<br>)<br>CHAT_MODEL = os.getenv(&quot;AZURE_OPENAI_CHAT_DEPLOYMENT&quot;)</pre><pre>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are an assistant helping recruiters shortlist candidates. Be concise and factual. Do not invent qualifications.<br>&quot;&quot;&quot;<br></pre><pre>def format_candidates(cands):<br>    chunks = []<br>    for i, c in enumerate(cands, 1):<br>        chunks.append(textwrap.dedent(f&quot;&quot;&quot;<br>        ### Candidate {i}: {c.get(&#39;full_name&#39;,&#39;N/A&#39;)}<br>        - Titles: {&#39;, &#39;.join(c.get(&#39;titles&#39;, []))}<br>        - Skills: {&#39;, &#39;.join(c.get(&#39;skills&#39;, []))}<br>        - Location: {c.get(&#39;location&#39;, &#39;N/A&#39;)}<br>        - Years exp: {c.get(&#39;years_experience&#39;,&#39;?&#39;)}<br>        - Notes: {c.get(&#39;notes&#39;, &#39;&#39;)[:400]}<br>        - CV snippet: {c.get(&#39;raw_text&#39;,&#39;&#39;)[:500]}<br>        &quot;&quot;&quot;))<br>    return &quot;\n&quot;.join(chunks)<br></pre><pre>def generate_shortlist(job_brief: str, candidates: list) -&gt; str:<br>    context = format_candidates(candidates)<br>    user_prompt = f&quot;Job brief:\n{job_brief}\n\nCandidates:\n{context}\n\nReturn a ranked list with 1-2 lines each and a rationale.&quot;</pre><pre>    resp = aic.chat.completions.create(<br>        model=CHAT_MODEL,<br>        messages=[<br>            {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: SYSTEM_PROMPT},<br>            {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: user_prompt}<br>        ],<br>        temperature=0.2<br>    )<br>    return resp.choices[0].message.content</pre><h3>6. Tie it together with FastAPI</h3><p>Expose a single endpoint your consultants (or ATS) can hit.</p><pre># app.py<br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from retriever import retrieve_candidates<br>from generator import generate_shortlist</pre><pre>app = FastAPI(title=&quot;Candidate RAG Search&quot;)</pre><pre>class SearchRequest(BaseModel):<br>    job_brief: str<br>    k: int = 5<br>    location: str | None = None</pre><pre>@app.post(&quot;/search-candidates&quot;)<br>async def search(req: SearchRequest):<br>    cands = retrieve_candidates(req.job_brief, req.k, req.location)<br>    shortlist = generate_shortlist(req.job_brief, cands)<br>    return {&quot;shortlist&quot;: shortlist, &quot;candidates&quot;: cands}</pre><p>Run it:</p><pre>uvicorn app:app --reload --port 8000</pre><p>Test it:</p><pre>curl -X POST localhost:8000/search-candidates \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;job_brief&quot;:&quot;Need a senior Java/Kafka engineer for fintech payments.&quot;, &quot;k&quot;:3, &quot;location&quot;:&quot;Berlin, DE&quot;}&#39;</pre><h3>Diagram: Prompt flow</h3><pre>sequenceDiagram<br>    participant UI as Recruiter UI<br>    participant API as FastAPI RAG Service<br>    participant MDB as MongoDB Atlas<br>    participant AOAI as Azure OpenAI</pre><pre>    UI-&gt;&gt;API: job brief JSON<br>    API-&gt;&gt;AOAI: embed(job brief)<br>    API-&gt;&gt;MDB: vectorSearch(queryVector)<br>    MDB--&gt;&gt;API: top K candidates<br>    API-&gt;&gt;AOAI: chatCompletion(context + job brief)<br>    AOAI--&gt;&gt;API: shortlist text<br>    API--&gt;&gt;UI: shortlist + raw candidates</pre><h3>Evaluation &amp; guardrails</h3><ul><li><strong>Spot-check answers</strong>: Ask the model to cite which candidate facts support each bullet (IDs or names). If it can’t, tighten prompts.</li><li><strong>Hallucination filter</strong>: After generation, run a quick regex to ensure no new skills/certs appear that weren’t in the retrieved docs.</li><li><strong>Diversity</strong>: Retrieve more candidates than you show (e.g., 15) and ask the model to maximize skill diversity in the top 5.</li><li><strong>Latency</strong>: Cache embeddings for common job briefs (“senior backend engineer”) or pre-compute vectors for your usual roles.</li></ul><h3>Cost &amp; performance tips</h3><ul><li>Use <strong>smaller embedding models</strong> (text-embedding-3-small) if accuracy is acceptable, halves cost.</li><li>Chunk long CVs (e.g., 1,000 tokens each) and store multiple vectors per candidate; aggregate at query time.</li><li>Compress what you send to the LLM: bullet points &gt; long prose.</li><li>Limit temperature to keep outputs deterministic for auditability.</li></ul><h3>Privacy &amp; compliance</h3><ul><li>Keep PII in MongoDB, not in prompts unless necessary.</li><li>Add a deletion workflow: if a candidate requests removal, wipe vectors + docs.</li><li>Log every generated shortlist for audit, including which documents were used.</li></ul><h3>Optional: Swap or add Azure AI Search</h3><p>Azure AI Search can host your vector index and provide hybrid ranking with synonyms, filtering, and scoring profiles. The RAG pattern is similar — just replace the MongoDB retrieval step. However, if your data is already living in MongoDB, its native vector search keeps the architecture lean.</p><h3>Where to go next</h3><ul><li>Add <strong>feedback loops</strong>: let recruiters rate shortlist quality and feed this back into retrieval weights or prompt templates.</li><li>Build a <strong>skills ontology</strong> (e.g., map “Golang” and “Go”) to boost recall.</li><li>Try <strong>multi-vector retrieval</strong> (skills vector, culture-fit vector, etc.) and fuse the scores.</li><li>Provide <strong>explanations</strong>: show recruiters exactly which CV lines justified a recommendation.</li></ul><h3>Wrap-up</h3><p>You don’t need a huge ML team to give your consultants AI superpowers. With MongoDB’s vector search and Azure’s LLMs, a compact RAG stack can turn messy CV archives into fast, explainable candidate search — without giving up control of your data.</p><p>If you adapt this for your agency, I’d love to hear what you learn (and what breaks!). Drop a comment or ping me on LinkedIn.</p><p>Happy hunting! 🕵️‍♀️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=551c88532562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a PDF Querying Bot with LangChain ]]></title>
            <link>https://medium.com/@alinaeem_57283/building-a-pdf-querying-bot-with-langchain-edb71ebedcc?source=rss-66d3df626fd6------2</link>
            <guid isPermaLink="false">https://medium.com/p/edb71ebedcc</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Ali Naeem]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 11:24:21 GMT</pubDate>
            <atom:updated>2023-06-02T11:24:21.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple explanation for creating your own pdf question answering bot</h4><p>Have you ever wished for a magical tool that can extract answers from your PDF documents? Look no further! In this article, we will dive into the fascinating world of <a href="https://python.langchain.com/en/latest/getting_started/getting_started.html">LangChain 🦜🔗</a> , empowering you to build your very own PDF question answering bot. Brace yourself as we explore five key components that will help us unlock this incredible capability.</p><p>To construct such a tool there are 5 key ingredients you must know !</p><ol><li><strong>LLMs: Large Language Models — The talk of the town</strong></li></ol><p>Large language models or LLM’s are AI models trained on gigantic amounts of data, learning the capability to understand and generate any kind of text in a human fashion . <br>For our pdf bot we will harness the power of a Large Language Model. Numerous LLMs are available, offering a wide array of performance levels. OpenAI’s ChatGPT is a popular choice, but for our application, we’ll utilize the largest open-source model from Big Science called Bloom🌸. <br>Bloom is a 179 Billion param model capable of interpreting 59 languages.<br>Importing this cutting-edge model is a breeze:</p><pre>import os<br>from langchain import HuggingFaceHub<br><br># Input your Hugging Face API key below<br>os.environ[&#39;HUGGINGFACEHUB_API_TOKEN&#39;] = &#39;xxxxxxxxx&#39;<br><br># Get the BLOOM Model from Hugging Face<br>llm = HuggingFaceHub(repo_id=&quot;bigscience/bloom&quot;, <br>                                        model_kwargs={&quot;temperature&quot;:0.1, <br>                                                      &quot;max_length&quot;:100})</pre><p><strong>2. Text Splitter: To divide and conquer</strong></p><p>Imagine you have a giant document , packed with new knowledge and latest insights. For such large documents the data needs to be divided . Imagine text splitter as splitting your PDF text into easily digestible chunks.Why? Well, LLMs have token limits, preventing us from processing the entire text at once. By splitting the text, we can retrieve relevant chunks and feed them selectively to the Language Model. Let’s take a sample sentence as an example:</p><p>Original sentence: “This is a sample text to explain what is text splitting ”</p><p>By dividing it into chunks, we achieve:</p><ul><li>Chunk 1: “This is a”</li><li>Chunk 2: “sample text to”</li><li>Chunk 3: “explain what is”</li><li>Chunk 4: “text splitting ”</li></ul><p>Here’s how you can split your documents for pdf files:</p><pre>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import CharacterTextSplitter<br><br># load document<br>loader = PyPDFLoader(&quot;Path to your pdf File&quot;)<br>documents = loader.load()<br><br># split the documents into chunks<br>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)<br>texts = text_splitter.split_documents(documents)</pre><p><strong>3. Embeddings: For the love of Numbers</strong></p><p>Embeddings are numerical representation of language texts, images or any form of data. These embeddings enable us to enclose the meaning in our data into numbers since AI model only work with numbers.<br>Each of our text chunk will be translated into a series of numbers or embeddings.<br>Here’s an example:</p><ul><li>Embedding 1: “This is a” -&gt; [.23, .45, .79, …, .31]</li><li>Embedding 2: “sample text to” -&gt; [.66, .05, .13, …, .69]</li><li>Embedding 3: “explain what” -&gt; [.20, .00, .54, …, .10]</li><li>Embedding 4: “text splitting is” -&gt; [.83, .72, .42, …, .09]</li></ul><p>We can either train our own embeddings or can select a number of pre-trained model for generating our embeddings . For this exercise we will be using a pre-trained model from HuggingFaceEmbeddings also accessible through LangChain library:</p><pre># select which embeddings we want to use<br>from langchain.embeddings import HuggingFaceEmbeddings<br><br>embeddings = HuggingFaceEmbeddings(model_name = &quot;sentence-transformers/all-mpnet-base-v2&quot;)</pre><p><strong>4. Vector Database: The database of AI era</strong></p><p>Vector Databases store data as vectors/embeddings. They are optimised for storage and faster querying capabilities for AI applications. By employing a combination of algorithms and sophisticated index data structures for storing embeddings Vector Databases have revolutionised the search process.</p><p>A detailed explanation of Vector Database is given in the article below.<br><a href="https://www.pinecone.io/learn/vector-database/">What is a Vector Database?</a></p><p>For our application, we’ll employ <a href="https://www.trychroma.com/">Chroma DB</a> to create a vector database using our embeddings:</p><pre>from langchain.vectorstores import Chroma<br><br># create the vectorestore to use as the index<br>db = Chroma.from_documents(texts, embeddings)</pre><p><strong>5. Chains — The backbone of LangChain</strong></p><p>Chains are the core of LangChain library. Chains allow us to ‘chain’ together different components from the library to create more advanced use cases around LLM’s.</p><p>LangChain offers a variety of predefined chains for various specific application . One such offering is the QA chain which is an optimised chain for answering question over documents.<br> More information about the uses cases can be found in the official documentation: <a href="https://docs.langchain.com/docs/category/use-cases">Use Cases | LangChain</a></p><p>We will use specifically the retriever QA chain . Retriever QA chains make use of the vector database to fetch relevant information before answering the questions.</p><pre># expose this index in a retriever interface<br>retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;:3})<br><br>qa = RetrievalQA.from_chain_type(<br>    llm=llm, chain_type=&quot;stuff&quot;, retriever=retriever, return_source_documents=True)</pre><h3>Combining it all together</h3><p>Voila ! Now you know all the key ingredients for making a language bot that can understand and answer your pdf questions.<br>The complete flow of the process is depicted in the diagram below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUzOQctSbyQsgZ8e9vGaNA.png" /><figcaption>Process Diagram</figcaption></figure><p>Now lets get coding . The code below is for constructing an entire application in stream-lit on google colab .</p><pre>import os<br><br>from langchain import HuggingFaceHub<br>from langchain.document_loaders import PyPDFLoader<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain.chains import RetrievalQA<br>from langchain.vectorstores import Chroma<br>from langchain.embeddings import HuggingFaceEmbeddings<br><br><br># Input your Hugging Face API key below<br>os.environ[&#39;HUGGINGFACEHUB_API_TOKEN&#39;] = &#39;xxxxxxx&#39;<br><br><br># Get the BLOOM Model from Hugging Face<br>llm = HuggingFaceHub(repo_id=&quot;bigscience/bloom&quot;, <br>                                        model_kwargs={&quot;temperature&quot;:0.1, <br>                                                      &quot;max_length&quot;:100})<br><br># load document<br>loader = PyPDFLoader(&quot;Your file Path here&quot;)<br>documents = loader.load()<br><br><br># split the documents into chunks<br>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)<br>texts = text_splitter.split_documents(documents)<br><br><br># select which embeddings we want to use<br>embeddings = HuggingFaceEmbeddings(model_name = &quot;sentence-transformers/all-mpnet-base-v2&quot;)<br><br><br># create the vectorestore to use as the index<br>db = Chroma.from_documents(texts, embeddings)<br><br><br># expose this index in a retriever interface<br>retriever = db.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;:3})<br><br><br>qa = RetrievalQA.from_chain_type(<br>    llm=llm, chain_type=&quot;stuff&quot;, retriever=retriever, return_source_documents=True)<br><br><br>query = &quot;what is the document about?&quot;<br><br>result = qa({&quot;query&quot;: query})<br>print(result[&#39;result&#39;])</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edb71ebedcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>