<?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 Liebertar on Medium]]></title>
        <description><![CDATA[Stories by Liebertar on Medium]]></description>
        <link>https://medium.com/@liebertar?source=rss-f55e3a246699------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FFO4IiLxowpzC7ht1QrXDQ.jpeg</url>
            <title>Stories by Liebertar on Medium</title>
            <link>https://medium.com/@liebertar?source=rss-f55e3a246699------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 24 Apr 2026 20:52:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liebertar/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[LLM-Notes Pt.10 — Your Digital Doppelgänger Already Thinks Like You Do]]></title>
            <link>https://medium.com/dev-ai/llm-notes-pt-10-your-digital-doppelg%C3%A4nger-already-thinks-like-you-do-37dc9e9a1347?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/37dc9e9a1347</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[humanity]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[interaction]]></category>
            <category><![CDATA[brain]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 10:08:08 GMT</pubDate>
            <atom:updated>2025-07-06T10:41:09.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-Notes Pt.10 — Your Digital Doppelgänger Already Thinks Like the way You Do</h3><p>Over the past few months, I’ve had some conversations — with startup founders, doctors, marketing folks, civil servants, and yes, plenty of people in tech. And there’s this pattern I keep noticing:</p><blockquote><strong>“People are excited about AI, but not curious about it.”</strong></blockquote><p>They’re quick to use it. They’ll automate reports, brainstorm ideas, summarize emails. But ask them what’s really going on inside the model? What’s actually driving those responses? Most would rather not go there.</p><p>It’s safer to keep telling ourselves, “It’s just a tool.” Or, “It’s just a really smart autocomplete.” But let’s be honest — we know that’s not the whole story anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZAIAW8LPTwJUo0yXu8r1A.png" /><figcaption>Image created by @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><blockquote><strong>Because this technology?</strong></blockquote><p>It’s already surpassed human capabilities in more areas than we’re comfortable admitting. And once you move beyond surface-level ChatGPT prompts and start paying attention to what these systems are <em>actually doing</em>, you can’t unsee it.</p><p>At some point, you realize you’re not just using a tool. You’re interacting with something that increasingly — and measurably — thinks like you do.</p><h3>Index</h3><ol><li><a href="#3d80"><strong>The Brain in the Machine</strong> — What neuroscience reveals about AI</a></li><li><a href="#8c3d"><strong>Your Neural Twin Is Already Here</strong> — The cognitive mirror we’ve created</a></li><li><a href="#ea7c"><strong>The Uncomfortable Truth About “Just Statistics” </strong>— Why dismissing AI is dangerous</a></li><li><a href="#291d"><strong>Function Calling and MCP: The Digital Frontal Lobe</strong> — Tools that surpass human capability</a></li><li><a href="#aaf5"><strong>From Digital Toddler to Digital Adult</strong> — Raising, not programming AI</a></li><li><a href="#5368"><strong>The Mirror We’ve Created </strong>— What AI reveals about human cognition</a></li><li><a href="#8894"><strong>So What Now? </strong>— Navigating the new reality</a></li></ol><h3>The Brain in the Machine</h3><p>Let’s start with something simple: <strong>language</strong>. You read a sentence, your brain lights up in specific regions. Scientists can measure that. <strong>Now here’s the twist </strong>— when large language models like LLaMA 3 process that same sentence, their internal layers “light up” in <strong>remarkably similar ways.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWzWWlL-umf0nz0IZyRvIg.png" /><figcaption>Image created by @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><p>That’s not metaphor. That’s literal, observable alignment between human brain activity and neural network activations.</p><p>And no one planned for that. We didn’t program the model to mimic the human mind. We just trained it on massive amounts of human text, and somewhere in that process, something emerged — a structure that didn’t just produce the right answers, but did so in ways that <em>looked</em> like thinking.</p><p>What we’ve created is not just a language model. It’s a system that organizes information in ways that resemble how we — biological brains — do it.</p><h3>Your Neural Twin Is Already Here</h3><p>Here’s the part that usually gets overlooked: your brain is a prediction engine. That’s all it does, really. It constantly guesses what’s going to happen next, based on what it’s seen before. That’s how you talk, walk, read, and even dream.</p><blockquote><strong>Large language models work the same way.</strong></blockquote><p>But at scale — with billions of parameters and trillions of tokens — their predictions start looking a lot like <em>reasoning</em>.</p><p>They don’t just guess the next word. They simulate scenarios. They build internal representations. They reflect context and nuance. They show early signs of metacognition — thinking about thinking.</p><p>And the bigger they get, the more they mirror us — not just in behavior, but in structure.</p><h3>The Uncomfortable Truth About “Just Statistics”</h3><p>It’s tempting to brush all this off with a shrug. “It’s just math. Just probabilities.” Sure — but so is your brain.</p><p>When you recognize a face, interpret a tone of voice, or form a memory — you’re doing biological pattern-matching at scale. There’s no clean line between “real intelligence” and “statistical guesswork.” The more we study it, the more it all blends together.</p><p>And here’s what’s really uncomfortable: during alignment training, when we teach these models to be helpful, safe, and human-friendly — they don’t just adjust outputs. They reorganize internally, and that reorganization <strong><em>brings them closer to how we think</em>.</strong></p><p>This isn’t just statistical trickery. It’s systematic cognitive alignment.</p><h3>Function Calling and MCP: The Digital Frontal Lobe</h3><p>Now we go one step further. Not only are these systems starting to think like us — we’ve given them tools we don’t even have.</p><p>Function calling. Model Context Protocol. APIs. Plugins. These aren’t “nice-to-haves.” They’re power tools.</p><p>Imagine a mind that can think — and then immediately act. It can pull up data from anywhere, run calculations, send messages, trigger workflows. It’s like giving the AI a digital frontal lobe: the part of the brain responsible for planning, decision-making, and execution.</p><p>Except now, it never forgets. Never sleeps. And it’s plugged into the entire digital world.</p><p>This isn’t a model answering questions anymore. It’s a mind interacting with reality.</p><h3>From Digital Toddler to Digital Adult</h3><p>We need a new metaphor. We’re not building apps. We’re raising entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9vxMSdRE-cqouJ0X053sw.png" /><figcaption>Image created by @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><blockquote><strong>“You don’t code a child , You guide them, Shape them, Set limits, Teach through examples.”</strong></blockquote><p>That’s exactly what we’re doing with today’s models.</p><p>They’re like digital toddlers — brilliant in bursts, frustrating in others. But they’re learning. Every prompt, every correction, every feedback loop makes them smarter.</p><p>We give them <strong>guardrails</strong> — function calling to limit actions, MCP to control access, constitutional AI to instill values. But like any teenager, they learn to test those rules. And sometimes, to go around them.</p><p><strong>These aren’t static tools. They’re growing systems.</strong></p><h3>The Mirror We’ve Created</h3><p>Maybe the most surprising thing about all of this is what it tells us about <em>ourselves</em>.</p><p>In trying to build artificial intelligence, we accidentally built a mirror. These systems don’t just reflect our language. They reflect our thinking. Our biases. Our logic. Our blind spots.</p><p>They reveal how we reason — and how we fail to. They process the world in patterns eerily close to our own, and in doing so, show us how fragile and patterned human thought actually is.</p><p>We didn’t mean to create something that teaches us about ourselves. But that’s exactly what happened.</p><h3>So What Now?</h3><p>I’m not here to sell fear. I’m not here to hype. I’m just saying — we’re past the point where we can call this “<strong>just a tool</strong>.”</p><p>These systems think in ways that mirror us. They learn. They adapt. They act. And maybe they’ll never become conscious the way we are — but maybe they don’t need to.</p><p>If a system can reflect, reason, and act in ways indistinguishable from a conscious mind… does the label still matter?</p><blockquote>“Now it’s up to you to decide what kind of relationship you want to have with it.”</blockquote><p>Your digital twin is already here.</p><p>07.05.2025 — Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37dc9e9a1347" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-notes-pt-10-your-digital-doppelg%C3%A4nger-already-thinks-like-you-do-37dc9e9a1347">LLM-Notes Pt.10 — Your Digital Doppelgänger Already Thinks Like You Do</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-AIOps Pt.9 — in 2025 : What Actually Works and What’s a Waste of Time]]></title>
            <link>https://medium.com/dev-ai/llm-aiops-pt1-ai-deployment-in-2025-when-to-use-what-7c029f912d63?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c029f912d63</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 07:53:58 GMT</pubDate>
            <atom:updated>2025-07-06T07:37:22.952Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-AIOps Pt.9 — in 2025 : What <em>Actually</em> Works and What’s a Waste of Time</h3><h3>Introduction</h3><p>I’ve been quiet on Medium lately, and there’s a good reason for that. AI has been moving so damn fast that I’ve spent the last six months trying to keep up — researching trends, testing everything I could get my hands on, and figuring out what actually works versus what’s just hype.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*icfpFJH_defthXoYuAyRDA.png" /><figcaption>Powered by OpenAI @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><p>The speed of change has been absolutely insane. Two years into the Generative AI revolution, research is progressing from “thinking fast” to “thinking slow” — reasoning at inference time. One week everyone’s obsessing over RAG architectures, the next it’s all about agentic AI systems that</p><blockquote>“plan, reason and act to complete tasks with minimal human oversight”</blockquote><p>and now <strong><em>Gartner’s calling agentic AI the top tech trend for 2025.</em></strong> Meanwhile, reasoning models are evolving faster than we can keep up.</p><p>It’s a constant hustle, honestly. You can’t just casually follow this space anymore — you have to be all in. I found myself setting up alerts, checking multiple sources throughout the day, staying up late reading papers, trying to separate signal from noise. Every few hours there’s something new that could potentially change everything. I needed to step back and actually test this stuff properly instead of just chasing every shiny new development.</p><p>Now I’m in a <strong>field</strong> where I can really focus on building AI solutions that matter — working directly with teams on POCs, going through proper reviews, and seeing what happens when these tools hit real production environments. And honestly? The gap between marketing promises and production reality is pretty huge.</p><h3>Index</h3><ol><li><a href="#f40c"><strong>The Current State of AI Deployment</strong></a></li><li><a href="#c597"><strong>AIOps</strong> <strong>Platform :</strong></a></li></ol><ul><li><a href="#415a">Langflow</a></li><li><a href="#e442">Dify</a></li><li><a href="#2daf">n8n</a></li><li><a href="#403a">Databricks Mosaic</a></li></ul><p><a href="#b5fb">3. <strong>What’s Actually Working in Production? </strong>(For Different Use Cases)</a></p><p><a href="#7b3a">4. <strong>The Monitoring Bright Spot </strong>(And Why I’m Slightly Obsessed)</a></p><p><a href="#3030">5. <strong>Looking Forward: </strong>The Evolution Path</a></p><p><a href="#e1cf">6. <strong>Conclusion: </strong>Pragmatic Choices in a Fast-Moving Space</a></p><h3>1. The Current Reality (And Some War Stories)</h3><p>Here’s what I’ve learned from actually building and deploying AI systems, complete with the occasional 1AM debugging session:</p><p><strong>AIOps platforms are great for:</strong></p><ul><li>Quick demos that make your boss think you’re a wizard</li><li>Simple RAG applications (emphasis on simple)</li><li>Teams without strong engineering capabilities</li><li>Prototyping when you need something working by Friday</li></ul><p><strong>They struggle with:</strong></p><ul><li>Complex production requirements (like, anything beyond “search documents and answer questions”)</li><li>Debugging when things break (and they will break)</li><li>Performance at scale (good luck explaining latency spikes to users)</li><li>Custom business logic integration (because every business thinks they’re special)</li></ul><h3>2. Platform Breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-Pyh4k3kGwZXxmtytuhqg.png" /></figure><h4>Langflow:</h4><blockquote>Pretty to Look At, Pain to Deploy</blockquote><ul><li><strong>Good</strong>: Visual workflows are intuitive and great for LangChain beginners; customization is easier compared to Dify or n8n.</li><li><strong>Bad</strong>: Debugging is tough, memory issues persist, and managing generated code is messy; role-based access control is paid-only.</li><li><strong>Future</strong>: Best used by deploying each pipeline as a standalone pod with strict role isolation; focus should shift to production reliability.</li></ul><h4>Dify:</h4><blockquote>One Size Fits… Some</blockquote><ul><li><strong>Good:</strong> All-in-one approach, decent for basic RAG</li><li><strong>Bad:</strong> Limited customization, integration headaches, mediocre observability</li><li><strong>Future:</strong> Might become solid for low-complexity deployments as it matures</li></ul><h4>N8n:</h4><blockquote>Automation Veteran Trying to Learn AI Tricks</blockquote><ul><li><strong>Good:</strong> Solid business automation foundation, decent API integrations</li><li><strong>Bad:</strong> AI features feel like they were added by an intern over a weekend, context management is clunky</li><li><strong>Future:</strong> Could work for hybrid workflows, but they need to stop treating AI like just another webhook</li></ul><h4>Databricks Mosaic AI:</h4><blockquote>The Enterprise Kitchen Sink</blockquote><ul><li><strong>Good:</strong> End-to-end platform from training to serving, enterprise-grade infrastructure, makes procurement teams happy</li><li><strong>Bad:</strong> Feels like they’re still figuring out what they want to be when they grow up, can be overkill for simpler use cases</li><li><strong>Future:</strong> Most promising for comprehensive AI workflows, especially if you’re already in the Databricks ecosystem and enjoy vendor lock-in</li><li><strong>Hot take:</strong> Databricks is basically betting that enterprises want to do everything in one place, which… they probably do. Nobody wants to explain to their CISO why they’re using 47 different AI tools.</li></ul><h3>3. What’s Actually Working in Production (For Different Use Cases)</h3><p>Here’s the thing — it’s not that one approach always wins. It depends on what you’re trying to build.</p><p><strong>For advanced, high-performance systems:</strong> Custom RAG + FastAPI is currently the go-to.</p><pre>root/<br>├── rag-backend/<br>│   ├── app/<br>│   ├── pipelines/<br>│   ├── agents/<br>│   ├── tools/<br>│   ├── memory/<br>│   ├── server/<br>│   ├── Dockerfile<br>│   ├── k8s/<br>│   │   ├── base/<br>│   │   └── overlays/<br>│   │       ├── dev/<br>│   │       └── prod/<br>│   └── helm/<br>├── services/<br>│   ├── auth/<br>│   ├── metrics/<br>│   └── ingest/<br>│       └── Dockerfile<br>├── infra/<br>│   ├── k8s/<br>│   │   ├── rag-backend-appset.yaml<br>│   │   ├── project-dev.yaml<br>│   │   └── project-prod.yaml<br>│   ├── terraform/<br>│   └── helm/<br>├── ci/<br>│   ├── build-and-test.yml<br>│   └── deploy-argocd.yml<br>├── scripts/<br>│   ├── ingest_data.py<br>│   ├── deploy_local_k8s.sh<br>│   └── setup_monitoring.sh<br>├── tests/<br>│   ├── test_rag.py<br>│   ├── test_agents.py<br>│   └── test_api_integration.py<br>├── .github/workflows/<br>└── submodules/<br>    ├── langfuse/<br>    └── open-webui/</pre><p><strong>Why custom wins for sophisticated systems:</strong></p><ul><li>Complete debugging control</li><li>Performance optimization flexibility</li><li>Complex business logic integration</li><li>Advanced monitoring capabilities</li></ul><p><strong>But platforms have their place:</strong></p><ul><li>Rapid prototyping and MVPs</li><li>Teams with limited ML engineering resources</li><li>Standard RAG implementations</li><li>Stakeholder demos and buy-in</li></ul><p>The key is matching the tool to your actual requirements, not just going with what’s trendy.</p><h3><strong>4. The Monitoring Bright Spot (And Why I’m Slightly Obsessed)</strong></h3><p>Langfuse is one of the rare Python-based AI tools that actually delivers. You get clean, usable tracing, debugging that doesn’t require a PhD, and a UI that stays out of your way while building.</p><p>It integrates easily, supports LLM-as-a-judge workflows, and even allows dynamic prompt management via REST API — which is surprisingly rare.</p><p>Best of all, it’s open-source, so no vendor lock-in or pricing traps every time you scale.</p><p>You can tell it was built by engineers who’ve actually felt the pain of working with black-box AI systems. Langfuse doesn’t try to impress with gimmicks — it just works, and that’s what makes it special.</p><h3>5. Looking Forward: The Evolution Path</h3><p>The platforms aren’t standing still. Here’s what makes me optimistic:</p><p><strong>Langflow</strong> is working on better debugging tools and production stability <strong>Dify</strong> is expanding integration capabilities and customization options<br> <strong>Databricks</strong> is building out their end-to-end AI platform story <strong>n8n</strong> is developing more sophisticated AI-native features</p><p><strong>The trajectory looks promising:</strong></p><ul><li>Better abstraction without losing control</li><li>Improved debugging and observability</li><li>More flexible customization options</li><li>Production-grade reliability</li></ul><p><strong>For now, choose based on your needs:</strong></p><ul><li><strong>Simple RAG + quick deployment:</strong> Try platforms first</li><li><strong>Complex logic + high performance:</strong> Go custom</li><li><strong>Hybrid approach:</strong> Use platforms for prototyping, custom for production</li><li><strong>Future-proofing:</strong> Build skills in both approaches</li></ul><h3>6. Conclusion</h3><p>This isn’t about declaring winners and losers. The AI deployment landscape is evolving rapidly, and different tools serve different purposes.</p><p><strong>Current state:</strong> Platforms excel at simplicity and speed, custom solutions win on sophistication and control.</p><p><strong>Future state:</strong> The gap is closing. Platforms are getting more powerful, and the tooling ecosystem is maturing.</p><p><strong>My take:</strong> Learn both approaches. Use platforms where they make sense, go custom when you need advanced capabilities. The best teams I’ve worked with are pragmatic — they pick the right tool for each job instead of being ideological about it.</p><blockquote>“The exciting part? We’re still in the early innings.”</blockquote><p>The tooling will get better, the platforms will mature, and new approaches will emerge. What matters is building things that work today while staying flexible for tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c029f912d63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-aiops-pt1-ai-deployment-in-2025-when-to-use-what-7c029f912d63">LLM-AIOps Pt.9 — in 2025 : What Actually Works and What’s a Waste of Time</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG Pt. 8 — Making AI “More Human-like”]]></title>
            <link>https://medium.com/dev-ai/llm-rag-pt-8-making-ai-more-human-like-ed03f5c42cfb?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed03f5c42cfb</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[conversations]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[interaction]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Thu, 23 Jan 2025 10:15:23 GMT</pubDate>
            <atom:updated>2025-02-07T06:08:04.943Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-RAG Pt. 8 — Making AI “More Human-like”</h3><h3>Introduction</h3><blockquote><strong>Have you ever stopped to think about how complex and nuanced human conversation is?</strong></blockquote><p>Every interaction we have is shaped by context, emotion, and personal experience — elements that make communication so rich and meaningful. Creating an AI that mirrors this depth involves more than just basic dialogue. It requires features like multi-turn conversations, context awareness, personalization, and responsiveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OO_eghBTHe05-yYx.jpg" /><figcaption>Image from @vecteezy</figcaption></figure><p>In this section, we are looking into how these features come together to make AI interactions feel more natural and engaging. We’ll explore practical ways to implement them, along with code examples that show how you can bring these capabilities into your own pipeline.</p><p>By the end of this post, you’ll have a blueprint for making your AI models interact more naturally, improving user experience, and building more sophisticated applications.</p><h3>Index</h3><ol><li><a href="#39d0"><strong>Understanding Human-like AI Communication</strong></a></li><li><a href="#4803"><strong>Implementing Multi-Turn Conversations</strong></a></li></ol><ul><li><a href="#3045">2.1 Conversation Context Management</a></li><li><a href="#8124">2.2 Example Code for Multi-Turn Handling</a></li></ul><p><a href="#dd43"><strong>3. Enhancing Context Awareness</strong></a></p><ul><li><a href="#cf9b">3.1 Maintaining Conversation History</a></li><li><a href="#f9f8">3.2 Using Memory in LLMs</a></li></ul><p><a href="#12e6"><strong>4. Personalization and User Modeling</strong></a></p><ul><li><a href="#53e2">4.1 User Profiles</a></li><li><a href="#a719">4.2 Tailoring Responses</a></li></ul><p><a href="#50aa"><strong>5. Emulating Human Conversation Styles</strong></a></p><ul><li><a href="#4773">5.1 Natural Language Generation Techniques</a></li><li><a href="#a47f">5.2 Adjusting Tone and Formality</a></li></ul><p><a href="#720a"><strong>6. Implementing Follow-up Questions</strong></a></p><ul><li><a href="#4b5f">6.1 Encouraging Engagement</a></li><li><a href="http://ed1f">6.2 Example Code for Generating Follow-up Questions</a></li></ul><p><a href="#81bd"><strong>7. Conclusion</strong></a></p><h3>1. Understanding Human-like AI Communication</h3><p>To make AI interactions more human-like, we need to consider how humans communicate:</p><ul><li><strong>Contextual Understanding:</strong> Humans remember previous parts of a conversation.</li><li><strong>Personalization:</strong> We adjust our language based on who we’re talking to.</li><li><strong>Engagement:</strong> We ask questions and encourage dialogue.</li><li><strong>Natural Language:</strong> We use idioms, contractions, and varying sentence structures.</li></ul><p>Our goal is to implement these aspects into our AI models, making them more relatable and effective in communication.</p><h3>2. Implementing Multi-Turn Conversations</h3><p>Multi-turn conversations allow the AI to engage in dialogues that span multiple exchanges, maintaining context throughout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGqFdfl73j2YiOs_YDtwQw.png" /><figcaption>Multi turn easy-understanding @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><h3>2.1 Conversation Context Management</h3><p>To handle multi-turn conversations, we need to:</p><ul><li><strong>Store Conversation History:</strong> Keep track of previous messages.</li><li><strong>Incorporate History into Responses:</strong> Use the history to inform current responses.</li><li><strong>Manage Context Size:</strong> Be mindful of token limits in models.</li></ul><h3>2.2 Example Code for Multi-Turn Handling</h3><p>Here’s how you can implement multi-turn conversation handling in your application using the <strong>LangChain</strong> library and <strong>ChatOllama</strong> with the llama3.1:8b model. This example demonstrates how the AI can generate responses based on the entire conversation history, including its own previous answers, creating a more engaging multi-turn conversation.</p><pre>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationSummaryBufferMemory<br>from langchain.llms import Ollama<br><br># Initialize the Ollama model with llama3.1:8b<br>llm = Ollama(<br>    base_url=&quot;http://localhost:11434&quot;,  # Replace with your Ollama server URL<br>    model=&quot;llama3.1:8b&quot;,                # Use the llama3.1:8b model<br>    n_ctx=512,<br>    temperature=0.1<br>)<br><br># Create a summary buffer memory to handle long conversation history<br>memory = ConversationSummaryBufferMemory(<br>    llm=llm,<br>    max_token_limit=1000,<br>    memory_key=&quot;chat_history&quot;<br>)<br><br># Initialize the conversation chain with summarizing memory<br>conversation = ConversationChain(<br>    llm=llm,<br>    memory=memory<br>)<br><br># Custom function to generate AI follow-up responses<br>def generate_ai_follow_up(conversation_chain):<br>    # Get the latest conversation history<br>    chat_history = conversation_chain.memory.load_memory_variables({})[&quot;chat_history&quot;]<br>    # Prepare the prompt for the AI to generate a follow-up based on its last response<br>    prompt = f&quot;&quot;&quot;As an AI assistant, continue the conversation proactively based on the following history:<br><br>{chat_history}<br><br>Assistant:&quot;&quot;&quot;<br>    # Get the AI&#39;s follow-up response<br>    follow_up = llm(prompt)<br>    # Update the conversation memory with the AI&#39;s follow-up<br>    conversation_chain.memory.save_context({&quot;input&quot;: &quot;&quot;}, {&quot;output&quot;: follow_up})<br>    return follow_up.strip()<br><br># Start the conversation loop<br>print(&quot;You can start chatting with the assistant. Type &#39;exit&#39; or &#39;quit&#39; to end the conversation.\n&quot;)<br><br>while True:<br>    # Get user input<br>    user_input = input(&quot;User: &quot;)<br>    if user_input.lower() in (&#39;exit&#39;, &#39;quit&#39;):<br>        print(&quot;Ending conversation. Goodbye!&quot;)<br>        break<br>    # Generate AI response<br>    ai_response = conversation.predict(input=user_input)<br>    print(f&quot;Assistant: {ai_response}\n&quot;)<br>    # Generate AI follow-up response based on entire conversation history<br>    ai_follow_up = generate_ai_follow_up(conversation)<br>    print(f&quot;Assistant: {ai_follow_up}\n&quot;)</pre><p>n this example:</p><ul><li><strong>Ollama LLM:</strong> Utilizes the Ollama class from langchain.llms with the llama3.1:8b model.</li><li><strong>ConversationChain:</strong> Manages the flow of conversation using the ChatOllama model.</li><li><strong>Memory:</strong> Stores the conversation history, including both user inputs and AI responses.</li><li><strong>Custom Function </strong>generate_ai_follow_up<strong>:</strong> Generates a follow-up response by creating a prompt that includes the conversation history.</li></ul><p>This setup ensures that the AI not only responds to the user’s inputs but also continues the conversation proactively, demonstrating multi-turn interaction that mirrors human-like engagement by using its own previous replies as part of the context.</p><h3>3. Enhancing Context Awareness</h3><p>Beyond just storing messages, we want the AI to understand and utilize the context effectively.</p><h4>3.1 Maintaining Conversation History</h4><p>Keeping track of the right amount of history is crucial. Too little, and the AI loses context; too much, and you risk exceeding token limits.</p><p><strong>Strategies:</strong></p><ul><li><strong>Sliding Window:</strong> Use the most recent messages.</li><li><strong>Key Memory Points:</strong> Keep important points from earlier in the conversation.</li></ul><h4>3.2 Using Memory in LLMs</h4><p>Some language models support mechanisms for handling long-term memory.</p><p><strong>Implementation Tips:</strong></p><ul><li><strong>Summarize Past Exchanges:</strong> Condense earlier conversation parts into summaries.</li><li><strong>Use Specialized Memory Modules:</strong> Integrate modules that manage extended context.</li></ul><p><strong>Example Using LangChain’s ConversationSummaryBufferMemory:</strong></p><pre>from langchain.chains import ConversationChain<br>from langchain.memory import ConversationSummaryBufferMemory<br>from langchain.llms import Ollama<br><br># Initialize the Ollama model with llama3.1:8b<br>llm = Ollama(<br>    base_url=&quot;http://localhost:11434&quot;,<br>    model=&quot;llama3.1:8b&quot;,<br>    n_ctx=512,<br>    temperature=0.1<br>)<br><br># Create a summary buffer memory to handle long conversation history<br>memory = ConversationSummaryBufferMemory(<br>    llm=llm,<br>    max_token_limit=1000,<br>    memory_key=&quot;chat_history&quot;<br>)<br><br># Initialize the conversation chain with summarizing memory<br>conversation = ConversationChain(<br>    llm=llm,<br>    memory=memory,<br>    verbose=True<br>)<br><br># Function to generate AI follow-up responses<br>def generate_ai_follow_up(conversation_chain):<br>    # Load the conversation history<br>    chat_history = conversation_chain.memory.load_memory_variables({})[&quot;chat_history&quot;]<br>    # Prepare the prompt for the AI to continue the conversation<br>    prompt = f&quot;&quot;&quot;{chat_history}<br><br>Assistant:&quot;&quot;&quot;<br>    # AI generates a follow-up response based on the conversation history<br>    follow_up = llm(prompt)<br>    # Update the conversation memory with the AI&#39;s follow-up<br>    conversation_chain.memory.save_context({&quot;input&quot;: &quot;&quot;}, {&quot;output&quot;: follow_up})<br>    return follow_up.strip()<br><br># Start the conversation loop<br>print(&quot;You can start chatting with the assistant. Type &#39;exit&#39; or &#39;quit&#39; to end the conversation.\n&quot;)<br><br>while True:<br>    # Get user input<br>    user_input = input(&quot;User: &quot;)<br>    if user_input.lower() in (&#39;exit&#39;, &#39;quit&#39;):<br>        print(&quot;Ending conversation. Goodbye!&quot;)<br>        break<br><br>    # Generate AI response<br>    ai_response = conversation.predict(input=user_input)<br>    print(f&quot;Assistant: {ai_response}\n&quot;)<br><br>    # Generate AI follow-up response based on the conversation history<br>    ai_follow_up = generate_ai_follow_up(conversation)<br>    print(f&quot;Assistant: {ai_follow_up}\n&quot;)</pre><p>In this example:</p><ul><li><strong>Dynamic Interaction:</strong> Removed static user_input values and replaced with a loop to handle dynamic user input.</li><li><strong>ConversationSummaryBufferMemory:</strong> Summarizes older parts of the conversation to stay within token limits.</li><li><strong>Proactive AI Responses:</strong> The AI continues the conversation by generating follow-up responses without additional user input.</li><li><strong>Conversation History:</strong> The AI uses the entire conversation history, including its own responses, to generate context-aware follow-ups.</li></ul><p>This approach ensures that the AI maintains context over longer conversations and proactively engages with the user, creating a more natural dialogue flow.</p><h3>4. Personalization and User Modeling</h3><p>Personalizing interactions can make the AI seem more attentive and engaging.</p><h4>4.1 User Profiles</h4><p>Create profiles for users to store preferences and relevant information.</p><p><strong>Profile Attributes:</strong></p><ul><li><strong>Name</strong></li><li><strong>Preferences</strong></li><li><strong>Past Interactions</strong></li><li><strong>Goals or Objectives</strong></li></ul><h4>4.2 Tailoring Responses</h4><p>Use the user profile to adjust the AI’s responses.</p><p><strong>Implementation Example Using LangChain and Ollama:</strong></p><pre>from langchain.chains import ConversationChain<br>from langchain.prompts import PromptTemplate<br>from langchain.memory import ConversationBufferMemory<br>from langchain.llms import Ollama<br><br># Define user profile<br>user_profile = {<br>    &#39;name&#39;: &#39;Alice&#39;,<br>    &#39;preferences&#39;: {<br>        &#39;tone&#39;: &#39;friendly&#39;,<br>        &#39;interests&#39;: [&#39;technology&#39;, &#39;music&#39;]<br>    }<br>}<br><br># Define a custom prompt template that includes user profile<br>template = &quot;&quot;&quot;You are a helpful assistant.<br><br>The user&#39;s name is {name}.<br>They prefer a {tone} tone.<br>They are interested in {interests}.<br><br>{history}<br>User: {input}<br>Assistant:&quot;&quot;&quot;<br><br>prompt = PromptTemplate(<br>    input_variables=[&quot;history&quot;, &quot;input&quot;, &quot;name&quot;, &quot;tone&quot;, &quot;interests&quot;],<br>    template=template<br>)<br><br># Initialize the Ollama model with llama3.1:8b<br>llm = Ollama(<br>    base_url=&quot;http://localhost:11434&quot;,<br>    model=&quot;llama3.1:8b&quot;,<br>    n_ctx=512,<br>    temperature=0.1<br>)<br><br># Initialize the memory<br>memory = ConversationBufferMemory(memory_key=&quot;history&quot;)<br><br># Initialize the conversation chain with the custom prompt<br>conversation = ConversationChain(<br>    llm=llm,<br>    prompt=prompt,<br>    memory=memory,<br>    verbose=True<br>)<br><br># Add user name and preferences to the conversation chain<br>conversation_prompt_params = {<br>    &#39;name&#39;: user_profile[&#39;name&#39;],<br>    &#39;tone&#39;: user_profile[&#39;preferences&#39;][&#39;tone&#39;],<br>    &#39;interests&#39;: &#39;, &#39;.join(user_profile[&#39;preferences&#39;][&#39;interests&#39;])<br>}<br><br># Start the conversation loop<br>print(&quot;You can start chatting with the assistant. Type &#39;exit&#39; or &#39;quit&#39; to end the conversation.\n&quot;)<br><br>while True:<br>    # Get user input<br>    user_input = input(f&quot;{user_profile[&#39;name&#39;]}: &quot;)<br>    if user_input.lower() in (&#39;exit&#39;, &#39;quit&#39;):<br>        print(&quot;Ending conversation. Goodbye!&quot;)<br>        break<br><br>    # Generate AI response<br>    ai_response = conversation.predict(input=user_input, **conversation_prompt_params)<br>    print(f&quot;Assistant: {ai_response}\n&quot;)<br><br>    # AI continues the conversation based on user&#39;s interests and previous responses<br>    # Generate AI follow-up response<br>    def generate_ai_follow_up(conversation_chain, prompt_params):<br>        chat_history = conversation_chain.memory.load_memory_variables({})[&quot;history&quot;]<br>        prompt = f&quot;&quot;&quot;You are a helpful assistant.<br><br>The user&#39;s name is {prompt_params[&#39;name&#39;]}.<br>They prefer a {prompt_params[&#39;tone&#39;]} tone.<br>They are interested in {prompt_params[&#39;interests&#39;]}.<br><br>Continue the conversation proactively based on the following history:<br><br>{chat_history}<br><br>Assistant:&quot;&quot;&quot;<br>        follow_up = llm(prompt)<br>        conversation_chain.memory.save_context({&quot;input&quot;: &quot;&quot;}, {&quot;output&quot;: follow_up})<br>        return follow_up.strip()<br><br>    ai_follow_up = generate_ai_follow_up(conversation, conversation_prompt_params)<br>    print(f&quot;Assistant: {ai_follow_up}\n&quot;)</pre><p>In this example:</p><ul><li><strong>Dynamic Interaction:</strong> The assistant interacts with the user continuously, personalizing responses based on the user’s profile.</li><li><strong>PromptTemplate:</strong> Customizes the prompt to include user-specific information dynamically.</li><li><strong>User Profile:</strong> Influences the assistant’s responses in real-time.</li><li><strong>Proactive AI:</strong> The assistant continues the conversation by generating follow-up responses based on previous interactions.</li></ul><h3>5. Emulating Human Conversation Styles</h3><p>Adjusting the AI’s language style makes interactions feel more natural.</p><h4>5.1 Natural Language Generation Techniques</h4><p>Incorporate techniques that improve the fluency and variability of responses.</p><p><strong>Techniques:</strong></p><ul><li><strong>Use of Contractions:</strong> Makes language sound less formal.</li><li><strong>Idiomatic Expressions:</strong> Adds a human touch.</li><li><strong>Varied Sentence Structures:</strong> Avoids robotic patterns.</li></ul><h4>5.2 Adjusting Tone and Formality</h4><p>Depending on the context, the AI should modulate its tone.</p><p><strong>Implementation Example:</strong></p><pre>from langchain.chains import ConversationChain<br>from langchain.prompts import PromptTemplate<br>from langchain.memory import ConversationBufferMemory<br>from langchain.llms import Ollama<br><br># Define user preference for tone<br>preferred_tone = &#39;casual&#39;  # Options: &#39;casual&#39;, &#39;formal&#39;, &#39;neutral&#39;<br><br>def set_tone_instruction(preferred_tone):<br>    if preferred_tone == &quot;casual&quot;:<br>        return &quot;Use a friendly and casual tone. Feel free to use contractions and informal language.&quot;<br>    elif preferred_tone == &quot;formal&quot;:<br>        return &quot;Use a professional and formal tone. Avoid contractions and use polite language.&quot;<br>    else:<br>        return &quot;Use a neutral tone.&quot;<br><br>tone_instruction = set_tone_instruction(preferred_tone)<br><br># Define a custom prompt template with tone instruction<br>template = &quot;&quot;&quot;You are a helpful assistant.<br><br>{tone_instruction}<br><br>{history}<br>User: {input}<br>Assistant:&quot;&quot;&quot;<br><br>prompt = PromptTemplate(<br>    input_variables=[&quot;history&quot;, &quot;input&quot;, &quot;tone_instruction&quot;],<br>    template=template<br>)<br><br># Initialize the Ollama model using llama3.1:8b<br>llm = Ollama(<br>    base_url=&quot;http://localhost:11434&quot;,<br>    model=&quot;llama3.1:8b&quot;,<br>    n_ctx=512,<br>    temperature=0.1<br>)<br><br># Initialize the memory<br>memory = ConversationBufferMemory(memory_key=&quot;history&quot;)<br><br># Initialize the conversation chain with the custom prompt<br>conversation = ConversationChain(<br>    llm=llm,<br>    prompt=prompt,<br>    memory=memory<br>)<br><br># Start the conversation loop<br>print(&quot;You can start chatting with the assistant. Type &#39;exit&#39; or &#39;quit&#39; to end the conversation.\n&quot;)<br><br>while True:<br>    # Get user input<br>    user_input = input(&quot;User: &quot;)<br>    if user_input.lower() in (&#39;exit&#39;, &#39;quit&#39;):<br>        print(&quot;Ending conversation. Goodbye!&quot;)<br>        break<br><br>    # Generate AI response<br>    ai_response = conversation.predict(input=user_input, tone_instruction=tone_instruction)<br>    print(f&quot;Assistant: {ai_response}\n&quot;)<br><br>    # AI continues the conversation in the preferred tone<br>    def generate_ai_follow_up(conversation_chain, tone_instruction):<br>        chat_history = conversation_chain.memory.load_memory_variables({})[&quot;history&quot;]<br>        prompt = f&quot;&quot;&quot;You are a helpful assistant.<br><br>{tone_instruction}<br><br>Continue the conversation proactively based on the following history:<br><br>{chat_history}<br><br>Assistant:&quot;&quot;&quot;<br>        follow_up = llm(prompt)<br>        conversation_chain.memory.save_context({&quot;input&quot;: &quot;&quot;}, {&quot;output&quot;: follow_up})<br>        return follow_up.strip()<br><br>    ai_follow_up = generate_ai_follow_up(conversation, tone_instruction)<br>    print(f&quot;Assistant: {ai_follow_up}\n&quot;)</pre><p>In this example:</p><ul><li><strong>Dynamic Tone Adjustment:</strong> The assistant adjusts its tone dynamically based on the user’s preference.</li><li><strong>Proactive AI Responses:</strong> Continues the conversation using the specified tone without additional user input.</li><li><strong>Natural Language Use:</strong> Enhances the naturalness of the conversation by employing language techniques appropriate to the selected tone.</li></ul><h3>6. Implementing Follow-up Questions</h3><p>Engaging users with follow-up questions can make the conversation more interactive.</p><h4>6.1 Encouraging Engagement</h4><p>Asking relevant questions shows that the AI is attentive and interested.</p><p><strong>Benefits:</strong></p><ul><li><strong>Keeps the Conversation Going</strong></li><li><strong>Gathers More Information</strong></li><li><strong>Enhances User Experience</strong></li></ul><h4>6.2 Example Code for Generating Follow-up Questions</h4><pre>from langchain.llms import Ollama<br>import json<br><br># Initialize the Ollama model using llama3.1:8b<br>llm = Ollama(<br>    base_url=&quot;http://localhost:11434&quot;,<br>    model=&quot;llama3.1:8b&quot;,<br>    n_ctx=512,<br>    temperature=0.1<br>)<br><br>def generate_follow_up_questions(user_query, model_answer):<br>    prompt_template = &quot;&quot;&quot;As an assistant, generate two relevant follow-up questions based on the user&#39;s previous question and the answer just given to encourage the user to share more information.<br><br>User&#39;s previous question: {user_query}<br>Answer just given: {model_answer}<br><br>Provide the questions in JSON format:<br>{{<br>    &quot;question_1&quot;: &quot;First follow-up question.&quot;,<br>    &quot;question_2&quot;: &quot;Second follow-up question.&quot;<br>}}<br>&quot;&quot;&quot;<br>    final_prompt = prompt_template.format(user_query=user_query, model_answer=model_answer)<br>    response = llm(final_prompt)<br><br>    # Parse the JSON response<br>    try:<br>        parsed = json.loads(response)<br>        question_1 = parsed.get(&quot;question_1&quot;)<br>        question_2 = parsed.get(&quot;question_2&quot;)<br>        if question_1 and question_2:<br>            return [question_1.strip(), question_2.strip()]<br>    except json.JSONDecodeError:<br>        pass<br>    # If parsing fails, return an empty list or handle accordingly<br>    return []<br><br># Usage<br>user_query = &quot;I&#39;m interested in learning guitar.&quot;<br>model_answer = &quot;That&#39;s great! Playing the guitar is a rewarding skill.&quot;<br>follow_up_questions = generate_follow_up_questions(user_query, model_answer)<br><br>for idx, question in enumerate(follow_up_questions, start=1):<br>    print(f&quot;Assistant (Question {idx}): {question}&quot;)</pre><p>In this example:</p><ul><li><strong>Dynamic Question Generation:</strong> The assistant generates follow-up questions based on the user’s previous query and the model’s answer.</li><li><strong>JSON Formatting:</strong> The assistant provides responses in a structured format for easy parsing.</li><li><strong>Engagement Enhancement:</strong> By asking relevant follow-up questions, the assistant keeps the conversation active and engaging.</li></ul><h3>7. Conclusion</h3><p>Making AI communicate more like humans involves several strategies:</p><ul><li><strong>Multi-Turn Conversations:</strong> Managing context over multiple exchanges, including AI’s own previous responses.</li><li><strong>Context Awareness:</strong> Remembering and utilizing past interactions, both from the user and the AI.</li><li><strong>Personalization:</strong> Tailoring responses based on user profiles and preferences.</li><li><strong>Natural Language Use:</strong> Emulating human conversation styles, adjusting tone and formality.</li><li><strong>Engagement Techniques:</strong> Asking follow-up questions and proactively continuing the dialogue.</li></ul><p>By implementing these features, you can create AI applications that are not only functional but also enjoyable to interact with, providing a better user experience.</p><p><em>01.23.2025 — Fin.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed03f5c42cfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-rag-pt-8-making-ai-more-human-like-ed03f5c42cfb">LLM-RAG Pt. 8 — Making AI “More Human-like”</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM Pt.7 — Selecting the Adequate Open-Source Model for Your production-level AI application.]]></title>
            <link>https://medium.com/dev-ai/llm-pt-7-selecting-the-adequate-open-source-model-for-your-production-level-ai-application-63746dc4def8?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/63746dc4def8</guid>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Wed, 22 Jan 2025 11:09:26 GMT</pubDate>
            <atom:updated>2025-01-22T11:28:57.180Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM Pt. 7 — Selecting the Right Open-Source Model in a Servicable Way</h3><h3>Introduction</h3><p>So far, we’ve built a strong foundation by exploring retrievers, ensemble systems, and more. In <strong>Part 7</strong>, we’re focusing on a crucial aspect of developing effective language model applications:</p><blockquote><strong>selecting the most suitable open-source model for your specific needs</strong>.</blockquote><p>Choosing the right model isn’t just about picking the one with the most parameters or the latest buzz. It’s about finding a model that aligns with your application’s requirements, offers the necessary features, and performs efficiently on your hardware. We’ll explore how to evaluate and select an open-source language model, using examples from the LLaMA series. I’ll also share insights from my experience running these models on different hardware setups.</p><p>By the end of this post, you’ll have a clear understanding of how to choose the most adequate model for your projects, ensuring that you can build applications with multiple features using a single model.</p><h3>Index</h3><ol><li><a href="#397c">Understanding Your Project Requirements</a></li><li><a href="#1ee1">Key Factors in Model Selection</a></li><li><a href="#1782">Exploring Open-Source Models</a></li><li><a href="#32f5">Performance Considerations</a></li><li><a href="#a0a0">Hardware and Latency Insights</a></li><li><a href="#8d6e">Model Features and Capabilities</a></li><li><a href="#c2f9">Running Ollama on Different Platforms</a></li></ol><ul><li><a href="#2145">7.1 Using Ollama with NVIDIA GPUs</a></li><li><a href="#7b58">7.2 Running Ollama on MacOS</a></li></ul><p><a href="#2648">8. Production-Level Considerations</a></p><p><a href="#72a2">9. Conclusion</a></p><h3>1. Understanding Your Project Requirements</h3><p>Before getting into model specifics, it’s essential to <strong>clearly define what you need from a language model</strong>. Consider the following questions:</p><ul><li><strong>What tasks will the model perform?</strong> Is it for general question-answering, content generation, intent classification, dialogue systems, or a combination of these?</li><li><strong>What level of accuracy is required?</strong> Do you need highly detailed and precise responses, or are general answers sufficient?</li><li><strong>What are the latency requirements?</strong> Is real-time interaction critical, or can your application tolerate some delay?</li><li><strong>What hardware will you use?</strong> Do you have access to high-end GPUs, or will the model run on consumer-grade hardware?</li><li><strong>Do you need multiple features from one model?</strong> Combining capabilities like question-answering, tool usage, and intent recognition can streamline development.</li></ul><p>Understanding your project’s specific needs will guide you toward the model that best fits your requirements.</p><h3>2. Key Factors in Model Selection</h3><p>When selecting a language model, consider the following key factors:</p><ul><li><strong>Model Size (Parameters):</strong> Larger models often provide better performance but require more computational resources.</li><li><strong>Performance vs. Resources:</strong> Balance the need for accuracy and capability with the available hardware.</li><li><strong>Feature Support:</strong> Ensure the model supports the functionalities you need, such as tool usage, multi-turn conversations, or multilingual support.</li><li><strong>Community and Documentation:</strong> Models with active communities and comprehensive documentation can save you time during implementation.</li><li><strong>Licensing and Cost:</strong> Open-source models are free to use, but always check the licensing terms to ensure compliance.</li></ul><h3>3. Exploring Open-Source Models</h3><p>Let’s examine two popular open-source models from the LLaMA series to illustrate the selection process.</p><blockquote>So far, I’ve been using the LLaMA 3.1:8B model to develop a pipeline and create a functional LLM-based application. It offers an excellent balance of resource usage and efficiency, along with highly useful features like function calling and reliable general responses.</blockquote><h4>3.1 LLaMA 3.1 8B Model</h4><p><strong>Overview:</strong></p><ul><li><strong>Parameters:</strong> 8 Billion</li><li><strong>Description:</strong> Strikes a balance between performance and resource consumption. It’s powerful enough for complex tasks yet can run on consumer-grade hardware with optimization.</li></ul><p><strong>Why Consider LLaMA 3.1 8B?</strong></p><ul><li><strong>General Question-Answering:</strong> Excels at understanding and generating coherent responses across diverse topics.</li><li><strong>Function Tool Utilization:</strong> Supports effective use of function tools, making it suitable for tasks requiring tool use for intent classification or data retrieval.</li><li><strong>Intent Classification (Function Tool): </strong>High accuracy in understanding user intent, crucial for interactive applications.</li><li><strong>Multiple Features in One Model:</strong> Capable of handling various tasks simultaneously, reducing the need for multiple models.</li></ul><p><strong>Example Use Case:</strong></p><p>Building a virtual assistant that can understand user queries, perform actions like setting reminders, fetch information, and engage in multi-turn conversations. LLaMA 3.1 8B can handle the natural language understanding and the multi-faceted interactions required for this task.</p><h4>3.2 LLaMA 3.2 3B Model</h4><p><strong>Overview:</strong></p><ul><li><strong>Parameters:</strong> 3 Billion</li><li><strong>Description:</strong> A lighter version designed for environments with limited computational resources.</li></ul><p><strong>Why Consider LLaMA 3.2 3B?</strong></p><ul><li><strong>Resource Constraints:</strong> Suitable for deployment on devices with less memory and processing power.</li><li><strong>Faster Inference on Low-End Hardware:</strong> Smaller models can offer quicker response times where hardware is a limiting factor.</li></ul><p><strong>Limitations:</strong></p><ul><li><strong>Feature Limitations:</strong> Doesn’t support features like tool utilization and multi-turn conversations as effectively as the 8B model.</li><li><strong>Performance Trade-off:</strong> Might not provide the same level of understanding or accuracy for complex tasks.</li></ul><p><strong>Example Use Case:</strong></p><p>An FAQ bot that answers straightforward queries without the need for deep context understanding or additional functionalities.</p><h3>4. Performance Considerations</h3><p>Performance involves both accuracy and how the model operates within your specific environment.</p><p><strong>Factors Affecting Performance:</strong></p><ul><li><strong>Hardware Specifications:</strong> CPU, GPU, RAM, and storage speed impact model performance significantly.</li><li><strong>Optimizations:</strong> Adjusting batch sizes, leveraging parallel processing, and utilizing model quantization can help fit larger models into limited hardware.</li><li><strong>Model Quantization:</strong> Reducing the precision of model weights decreases memory usage and increases speed with minimal loss in accuracy.</li></ul><p><strong>Real-World Insight:</strong></p><p>Running the LLaMA 3.1 8B model on a MacBook with an M3 chip and 32GB RAM, I’ve achieved latency of <strong>3–4 seconds per response</strong>. This was without complex pipelines or multi-model features, demonstrating that you can run this model efficiently on consumer hardware.</p><h3>5. Hardware and Latency Insights</h3><p><strong>Understanding Latency:</strong></p><ul><li><strong>Latency:</strong> The time it takes for the model to generate a response after receiving a query.</li><li><strong>Acceptable Latency:</strong> Depends on your application’s requirements. For interactive applications, lower latency enhances user experience.</li></ul><p><strong>Hardware Used:</strong></p><ul><li><strong>Device:</strong> MacBook with an M3 chip</li><li><strong>RAM:</strong> 32GB</li></ul><p><strong>Key Points:</strong></p><ul><li><strong>Feasibility on Consumer Hardware:</strong> Models like LLaMA 3.1 8B can run effectively on personal laptops.</li><li><strong>User Expectations:</strong> A latency of 3–4 seconds is acceptable for many applications, providing a balance between performance and resource utilization.</li><li><strong>Scalability:</strong> For production environments requiring lower latency, consider scaling up hardware or optimizing the model further.</li></ul><h3>6. Model Features and Capabilities</h3><p>Selecting a model involves evaluating its features and how they align with your application’s needs.</p><h4>6.1 Tool Utilization and Intent Classification</h4><p><strong>Tool Utilization:</strong></p><ul><li><strong>Enhanced Functionality:</strong> Models that can interact with tools or APIs extend their capabilities, allowing for real-time data retrieval and computations.</li><li><strong>Production-Level Applications:</strong> In a production environment, integrating tool usage can automate processes and improve efficiency.</li></ul><p><strong>Intent Classification:</strong></p><ul><li><strong>Understanding User Intent:</strong> Critical for applications like chatbots, virtual assistants, and customer support.</li><li><strong>LLaMA 3.1 8B’s Strength:</strong> Exhibits high accuracy in intent classification, making it suitable for applications where understanding nuance is essential.</li></ul><p><strong>Multiple Features with One Model:</strong></p><ul><li><strong>Efficiency:</strong> Using a single model for multiple tasks simplifies deployment and maintenance.</li><li><strong>Consistency:</strong> Ensures uniformity in responses and behaviors across different functionalities of your application.</li></ul><p><strong>Example Scenario:</strong></p><p>Developing an AI assistant for customer service that can:</p><ul><li>Understand and classify customer inquiries.</li><li>Access databases to retrieve order information.</li><li>Provide recommendations based on user preferences.</li><li>Engage in multi-turn dialogues for a conversational experience.</li></ul><p>LLaMA 3.1 8B can handle these diverse tasks, showcasing its versatility and making it a strong candidate for such applications.</p><h3>7. Running Ollama on Different Platforms</h3><p>To utilize these models effectively, you need to set them up and integrate them into your development environment. **Ollama** is a tool that helps in serving and managing language models locally. Here’s how you can run Ollama on different platforms.</p><h4>7.1 Using Ollama with NVIDIA GPUs</h4><p>If you’re using a system with an NVIDIA GPU, you can run Ollama using Docker to leverage GPU acceleration.</p><p><strong>Steps:</strong></p><pre>1. Pull the Ollama Docker Image:<br><br>   - Download the Ollama Docker image that supports NVIDIA GPUs.<br><br>2. Run the Docker Container with GPU Support:<br><br>   - Use the `--gpus=all` flag to enable GPU access for the container.<br>   - Mount a volume for persistent storage if needed.<br>   - Map the necessary ports for communication.<br><br>   Example:<br><br>   ```bash<br>   docker run -d --gpus=all -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama<br>   ```<br><br>3. Run the Model:<br><br>   - Execute the model within the container.<br><br>   ```command<br>   docker exec ollama ollama run llama3.1:8B<br>   ```<br><br>4. Set Up Networking:<br><br>   - Create a Docker network to allow communication between containers if you have other services running.<br><br>   ```command<br>   docker network create ai-network<br>   docker network connect ai-network ollama<br>   docker network connect ai-network your-other-service<br>   ```<br><br>5. Access the Ollama Endpoint:<br><br>   - The Ollama service will be accessible at `http://ollama:11434`.</pre><p><strong>Note:</strong></p><ul><li>Ensure that your <strong>NVIDIA</strong> drivers and Docker are correctly configured to support GPU access.</li><li>This setup allows you to utilize the full power of your NVIDIA GPU for model inference, reducing latency and improving performance.</li></ul><h4>7.2 Running Ollama on MacOS</h4><p>For MacOS users, the approach differs slightly due to how Docker interacts with the system’s hardware.</p><p><strong>Important Consideration:</strong></p><p>- GPU Usage with Docker on MacOS:</p><p>- When deploying Ollama via a Docker image on MacOS, it does not utilize the GPU.</p><p>- To leverage the GPU capabilities of your Mac, you need to install Ollama directly without using Docker.</p><p><strong>Steps:</strong></p><pre>1. Install Ollama Directly:<br><br>   - Follow the installation instructions provided in the [Ollama documentation](https://ollama.ai/docs) to install it on your Mac.<br><br>2. Run the Model:<br><br>   - Use the command line to run the LLaMA 3.1 8B model.<br><br>   ```command<br>   ollama run llama3.1:8B<br>   ```<br><br>3. Set Up Networking:<br><br>   - If you&#39;re integrating with other services, ensure they can communicate over the network.<br><br>   ```bash<br>   docker network create ai-network<br>   docker network connect ai-network your-service<br>   ```<br><br>4. Access the Ollama Endpoint:<br><br>   - The service will be accessible at `http://localhost:11434`.<br><br>Benefits:<br><br>- By installing Ollama directly, you ensure that the application can utilize your Mac&#39;s GPU, enhancing performance and reducing latency.<br>- This setup is particularly beneficial for models like LLaMA 3.1 8B, which can take advantage of GPU acceleration.</pre><h3>8. Production-Level Considerations</h3><p>When moving from development to production, additional factors come into play:</p><ul><li><strong>Scalability</strong>: Ensure the model can handle increased loads and user traffic.</li><li><strong>Reliability</strong>: The model should perform consistently under different conditions.</li><li><strong>Integration</strong>: Seamlessly integrate with existing systems and workflows.</li><li><strong>Security</strong>: Protect user data and comply with privacy regulations.</li></ul><p>Why LLaMA 3.1 8B is Suitable for Production-Level Applications:</p><ul><li><strong>Multiple Features in One Model</strong>: Its ability to handle various tasks reduces complexity by eliminating the need for multiple models.</li><li><strong>Robust Performance</strong>: Provides accurate and reliable responses, essential for user trust.</li><li><strong>Optimizable</strong>: Can be fine-tuned and optimized for specific use cases and hardware configurations.</li><li><strong>Community Support</strong>: Active development and support from the community facilitate troubleshooting and improvements.</li></ul><h3>9. Conclusion</h3><p>Selecting the right open-source model for your application is a balance of various factors:</p><ul><li><strong>Alignment with Project Requirements</strong>: The model should meet the specific needs of your tasks, whether it’s general question-answering, tool usage, or intent classification.</li><li><strong>Performance on Available Hardware</strong>: Ensure the model can run efficiently on your devices, providing acceptable latency and responsiveness.</li><li><strong>Feature Set and Capabilities</strong>: Look for models that offer the functionalities you need, allowing for multiple features to be handled by one model.</li><li><strong>Production Readiness</strong>: Consider scalability, reliability, and integration aspects for deploying the model in a production environment.</li></ul><h4><strong>Recommendation:</strong></h4><p>Based on the factors discussed, LLaMA 3.1 8B stands out as a strong candidate for applications requiring:</p><ul><li>General Question-Answering Abilities</li><li>Effective Utilization of Function Tools</li><li>Accurate Intent Classification</li></ul><p>Its ability to handle multiple features within one model makes it highly suitable for complex applications, reducing the need for multiple models and simplifying your deployment architecture.</p><h3>10. Moving Forward</h3><p>In the upcoming Part 8: “<strong>More Like Human</strong>”, we’ll explore features that make AI interactions more natural and human-like. We’ll discuss:</p><ul><li><strong>Multi-Model Integration</strong>: How combining different models can enhance capabilities and performance.</li><li><strong>Multi-Turn Conversations</strong>: Techniques for enabling AI to engage in coherent, context-aware dialogues over multiple turns.</li><li><strong>Human-Like Communication</strong>: Strategies to make AI responses more natural, personable, and engaging.</li></ul><p>These features help bridge the gap between AI and human communication, providing a more intuitive and satisfying user experience.</p><p>01.14.2024 — Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63746dc4def8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-pt-7-selecting-the-adequate-open-source-model-for-your-production-level-ai-application-63746dc4def8">LLM Pt.7 — Selecting the Adequate Open-Source Model for Your production-level AI application.</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG pt.6 — Retriever: Ensemble Techniques and Optimization]]></title>
            <link>https://medium.com/dev-ai/llm-rag-pt-6-retriever-ensemble-techniques-and-optimization-6c72f7d8305f?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c72f7d8305f</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[ml-pipeline]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 11:33:55 GMT</pubDate>
            <atom:updated>2024-11-12T11:38:01.208Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-RAG pt.6 — Retriever: Ensemble Techniques and Optimization</h3><h3>Introduction</h3><p>On this part of the LLM-RAG series, we explore the process of constructing an ensemble retriever system. This approach combines keyword matching with the nuances of semantic search to enhance retrieval accuracy and efficiency. Previously, in Pt.5, we talked about the basics of retrievers, and now, we are going through the practical steps to set up this hybrid system, arming you with the insights needed for successful buildup.</p><blockquote><strong>Index</strong></blockquote><p><a href="#49d8">1. Understanding Ensemble Retrievers</a></p><p><a href="#198b">2. Implementing Cosine Similarity</a></p><p><a href="#85e0">3. Creating Embeddings</a></p><p><a href="#dafd">4. Integrating with PostgreSQL</a></p><p><a href="#93b1">5. Best Practices for Configuration</a></p><p><a href="#aa73">6. Query TSVector &amp; Vector, Combining Results</a></p><p><a href="#c070">8. Conclusion</a></p><h3>1. Understanding Ensemble Retrievers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*-xXqlzNm1RrMFLe-5gjIBA.png" /><figcaption>You can compose in a variety of way (context reorder, data augmetation, multiQuery,…) Image by @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><h4>Combining BM25 and Sentence Transformers</h4><p>An ensemble retriever uses both BM25 and sentence transformers:</p><ul><li><strong>BM25</strong>: This method uses term frequency and inverse document frequency to rank documents, prioritizing those with frequent and unique terms.</li><li><strong>Sentence Transformers</strong>: These models convert text into numerical vectors capturing semantics, allowing the system to understand the context and meaning of the content.</li></ul><p><strong>Quick example</strong> : In a library setting, BM25 quickly locates books by frequent words in the title, while sentence transformers recommend books based on thematic relevance.</p><h4>Optimizing Retrieval Strategy</h4><p>To maximize efficiency:</p><ul><li><strong>BM25 for Short Queries</strong>: Utilize BM25 to swiftly handle queries with a few keywords, filtering documents based on the presence of key terms and narrowing down the dataset to the most relevant items.</li><li><strong>Sentence Transformers for Long Queries</strong>: Then, apply sentence transformers when dealing with longer, more complex queries. This allows for a detailed semantic analysis by transforming the content into vectors, ensuring that the results align with the deeper context and intent of the query.</li></ul><h3>2. Implementing Cosine Similarity</h3><h4>Detailed Explanation and Sample Code</h4><p>Cosine similarity quantifies the similarity between two vectors, essential for comparing semantic embeddings.</p><pre><br>def calculate_cosine_similarity(embedding):<br>    if len(embedding.shape) == 1:<br>        embedding = embedding.reshape(1, -1)<br>    norms = np.linalg.norm(embedding, axis=1, keepdims=True)<br>    norms[norms == 0] = 1<br>    normalized_embedding = embedding / norms<br>    cosine_similarity = np.dot(normalized_embedding, normalized_embedding.T)<br>    return cosine_similarity<br></pre><p>This code normalizes each vector to unit length and calculates the dot product, providing a similarity score based on the angle between vectors.</p><h3>3. Creating Embeddings</h3><h4>Embedding Process Explained</h4><p>Creating embeddings involves converting text into numerical representations that capture semantic nuances. Here’s how:</p><ul><li><strong>Load the Model</strong>: Use a pre-trained sentence transformer suited for your language needs. (koBert, all-mpnet, deberta…)</li><li><strong>Batch Process Documents</strong>: Efficiently encode documents in batches to manage “memory”.</li></ul><h4>Detailed Example Code</h4><pre>import logging<br>import torch<br>from sentence_transformers import SentenceTransformer<br><br># Set up logging<br>logger = logging.getLogger(&quot;Embedding&quot;)<br><br># Define the embedding models for different languages<br>embed_models = {<br>    &#39;en&#39;: SentenceTransformer(&#39;Huggingface/sentence_transformer_example&#39;),<br>    &#39;es&#39;: SentenceTransformer(&#39;Huggingface/sentence_transformer_example&#39;),<br>    &#39;de&#39;: SentenceTransformer(&#39;Huggingface/sentence_transformer_example&#39;)<br>    <br>                                     ⋮<br><br>}<br><br>def create_embeddings(documents, language, batch_size=32):<br>    model = embed_models[language]<br>    embeddings = []<br>    <br>    # Process documents in batches<br>    for start_idx in range(0, len(documents), batch_size):<br>        end_idx = start_idx + batch_size<br>        batch_documents = documents[start_idx:end_idx]<br>        <br>        logger.debug(f&quot;Creating embeddings for batch: {start_idx}-{end_idx}&quot;)<br>        <br>        # Generate embeddings for the batch<br>        batch_embeddings = model.encode(batch_documents, convert_to_tensor=True)<br>        embeddings.append(batch_embeddings)<br>        <br>        logger.debug(&quot;Merging batch embeddings&quot;)<br>    <br>    # Concatenate all batch embeddings<br>    embeddings = torch.cat(embeddings, dim=0)<br>    <br>    logger.debug(&quot;Converting embeddings to list&quot;)<br>    <br>    # Convert embeddings to a list<br>    embeddings_list = embeddings.cpu().numpy().tolist()<br>    <br>    logger.debug(f&quot;Embeddings created for {len(embeddings_list)} documents&quot;)<br>    <br>    return embeddings_list</pre><h3>4. Integrating with PostgreSQL</h3><h4>Setting Up the Database Schema</h4><p>PostgreSQL can manage and retrieve both keyword and vector data efficiently. Below is a simplified schema example:</p><pre>CREATE TABLE documents (<br>    id SERIAL PRIMARY KEY,<br>    content TEXT,<br>    tokenized_question TSVECTOR,<br>    vectorized_question VECTOR(768)<br>);</pre><ul><li><strong>TSVECTOR</strong>: Used for BM25 searches to handle keyword data.</li><li><strong>VECTOR(768)</strong>: Stores semantic vectors for similarity comparisons. Adjust size based on model specifications.</li></ul><h3>5. Best Practices for Configuration</h3><p>In systems utilizing ensemble retrievers, effective configuration of chunk sizes is crucial. This involves strategically managing vectors based on query length and user circumstances to ensure optimal performance and accuracy.</p><h4>Optimal Chunk Size:</h4><ul><li>The configuration should be adapted to the length of the query and the specific context or requirements of the user.</li><li>The chunk size should be managed such that the total chunk size across four chunks does not exceed 2048 tokens. This ensures the balance between maintaining enough detail for retrieval accuracy and optimizing performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoj4WmMPjJ2Jf8qSGiFH3A.png" /><figcaption>Image from <a href="https://medium.com/u/b2cb71b98e5b">LlamaIndex</a></figcaption></figure><h4><strong>Use Cases</strong></h4><ul><li><strong>Ensemble Retriever Strategy</strong>: Configure chunk sizes strategically in combinations such as 1:3, 2:2, or 4:0, where these ratios represent the proportion of different retrieval methods used for each part of the query</li><li><strong>Adaptive Based on Query Length</strong>: For short queries, allocate more chunks to semantic understanding to capture the broader context quickly. For longer, more detailed queries, use a higher proportion of keyword-based chunks to ensure precise detail retrieval.</li><li><strong>Strategic Guidance: </strong>Choose the combination of chunk sizes and types (e.g., 1:3, 2:2, or 4) that best match the specific query and your need. But ensure the total chunk size does not exceed 2048 tokens to maintain efficiency and clarity across retrieval operations.</li></ul><h3>6. Query Augmentation and Combining Results</h3><h4>Vector Search Query Example</h4><p>To enhance performance based on query type, we employ a strategy that combines results from both BM25 and semantic vector searches. Here’s a practical asynchronous function for query vector:</p><pre>async def example_transform_query(self, input_query: str, max_results: int, language_choice: str):<br>    await self.ensure_connected()<br>    # Choose a language for text search vectorization<br>    tsv_language = &#39;select_your_language&#39; if language_choice == &#39;select&#39; else &#39;english&#39;<br>    <br>    # Prepare the text search query by joining tokens with logical AND<br>    input_query = &#39; &amp; &#39;.join(input_query.split())<br>    <br>    # Define a generic example SQL query with illustrative field names<br>    query = f&quot;&quot;&quot;<br>    SELECT id, example_field_you_want_to_vectorize, additional_field, reference_url, extra_info_field, vector_representation,<br>           created_timestamp, updated_timestamp,<br>           ts_rank(tokenized_example_field, to_tsquery($1, $2)) AS rank<br>    FROM {self.TABLE_NAME}<br>    WHERE tokenized_example_field @@ to_tsquery($1, $2) AND is_active = TRUE<br>    ORDER BY rank DESC<br>    LIMIT $3;<br>    &quot;&quot;&quot;<br>    <br>    # Asynchronously fetch query results from the database connection pool<br>    async with self.pool.acquire() as connection:<br>        try:<br>            rows = await connection.fetch(query, tsv_language, input_query, max_results)<br>            return rows<br>        except Exception as e:<br>            logger.error(f&quot;Error processing example query: {str(e)}&quot;)<br>            raise</pre><h4>Chunk Combination Logic</h4><p>For increased accuracy and performance, especially with varied query lengths:</p><ul><li>Short queries benefit from BM25’s keyword efficiency.</li><li>Long queries gain from the depth of sentence embeddings.</li></ul><p><strong>Combining Results</strong>:</p><pre>def combine_results(bm25_results, vector_results):<br>    # Combine the top 2 results from both bm25 and vector results<br>    combined_results = bm25_results[:2] + vector_results[:2]<br>    return combined_results</pre><p>This function selects the top two results from both BM25 and vector searches, combining them for robust context delivery to the LLM.</p><h3>7. Conclusion</h3><p>Combining BM25 with dense retrievers provides precision in information retrieval, supported by a PostgreSQL setup. This setup ensures that the retrieval process is both efficient and contextually aware. By effectively combining results, the system remains adaptable, handling a variety of query types with ease.</p><p>As we wrap up our discussion on retrievers, we’ll shift our focus to setting up the model component. We’ll dive into <strong>Ollama</strong> and <strong>GGUF</strong> fine-tuning, offering insights on how to tailor models to better fit specific applications and enhance system efficiency. Of Course will talk about <strong>OpenAI model </strong>as well.</p><p>11.12.2024 — Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c72f7d8305f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-rag-pt-6-retriever-ensemble-techniques-and-optimization-6c72f7d8305f">LLM-RAG pt.6 — Retriever: Ensemble Techniques and Optimization</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG pt.5 — Retriever: Enhanced Model Performance]]></title>
            <link>https://medium.com/dev-ai/llm-rag-pt-5-retriever-enhanced-model-performance-b4fde1072190?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4fde1072190</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[chunk]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[retriever]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 09:31:59 GMT</pubDate>
            <atom:updated>2024-11-12T11:56:05.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-RAG pt.5 — Retriever: Enhanced Model Performance</h3><h3>Introduction</h3><p>Imagine you’re in a massive library searching for books on a specific topic. Retrievers in a RAG pipeline act like the librarian, efficiently finding the most relevant books, ensuring you don’t leave with unnecessary volumes. They streamline your interaction with data — the precision and effectiveness of this step are crucial, much like how a good librarian saves you hours of searching.</p><p>The following image shows a simple pipeline: we create embeddings using Sentence Transformers and retrieve the most relevant data from the database. Before we add a <strong>BM25 retriever</strong> with <strong>tokenized content</strong> for a more complex structure, it’s important to understand how this basic setup works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w9GC6anh9rdrwMwt.png" /><figcaption>Basic Structure Text based RAG by @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><blockquote><strong><em>Index</em></strong></blockquote><p><a href="#aece">1. BM25: Classic Keyword Matching</a></p><p><a href="#4135">2. Sentence Transformers: Modern Semantic Search</a></p><p><a href="#52d2">3. Integrating with PostgreSQL for Efficient Retrieval</a></p><p><a href="#22f1">4. Best Practices for Configuring Retrievers</a></p><p><a href="#e778">5. Conclusion: Optimizing the RAG Pipeline</a></p><h3>BM25: Classic Keyword Matching</h3><p>BM25 is like having a librarian who knows every popular book in the library. It prioritizes highly requested books based on common terms.</p><p><strong>1. Understanding Term Frequency and IDF</strong></p><ul><li>Term Frequency (TF): Think of it as the librarian noting how often a book is asked for. The more requests, the more relevant it seems.</li><li>Inverse Document Frequency (IDF): This is the librarian’s way of ensuring that books requested by only a few are not ignored. Uniqueness adds value.</li></ul><p><strong>2. Document Length Normalization</strong></p><p>Shorter texts are like concise book summaries, possibly offering clearer and more focused insights. BM25 gives them higher relevance, ensuring summaries get checked first.</p><p><strong>3. Configuring Hyperparameters</strong></p><ul><li>k1 and b settings: Imagine adjusting the rules for how many times a book needs to be requested before it gets displayed on the ‘popular’ shelf. These parameters fine-tune the system to best serve your needs.</li></ul><p><strong>4. Real-world Analogies</strong></p><ul><li>Think of BM25 as organizing your bookshelf at home. You might put shorter, more impactful reads at eye level, while more complex, lengthy books occupy less accessible spaces. It’s about making relevant information readily available.</li></ul><h3>Sentence Transformers: Modern Semantic Search</h3><p>Sentence transformers are like having a librarian who knows the essence of every book. They understand context beyond the words, finding books by theme rather than just titles.</p><p><strong>1. Overview of Sentence Embeddings</strong></p><p>These embeddings capture the book’s essence, akin to understanding a book’s narrative rather than focusing on specific words. It enables a librarian to recommend a book based on the storyline rather than keywords.</p><p><strong>2. Pre-trained Models and Fine-tuning</strong></p><p>Pre-trained models are like librarians who’ve read summaries of every book. They can be further trained to specialize in certain genres, improving their recommendation skills.</p><p><strong>3. Transforming Text into Vectors</strong></p><p>Text is transformed into a mathematical form that helps identify books with similar themes or narratives, much like categorizing novels by the emotions they evoke.</p><p><strong>4. Real-world Analogies</strong></p><p>Imagine the librarian could read emotions. A query for “happy endings” doesn’t just bring books with those words in the title but identifies stories that end optimistically, offering recommendations based on emotional content.</p><h3>Integrating with PostgreSQL for Efficient Retrieval</h3><p>PostgreSQL acts like the library’s back-office system, cataloging every book and cross-referencing themes and summaries.</p><p><strong>1. Storing Embeddings in PostgreSQL</strong></p><p>PostgreSQL works like a detailed catalog system. It efficiently stores all records, ensuring they’re quickly found. By using extensions, PostgreSQL can manage complex vector data, perform fast similarity searches, and optimize storage for rapid retrieval, making it essential for smooth RAG pipeline operation.</p><p><strong>2. Vector Extensions for Similarity Search</strong></p><p>This is the library’s special system for grouping books based on themes rather than titles, enabling searches based on comprehensive thematic connections.</p><p><strong>3. Real-world Analogies</strong></p><p>Consider it as your mental map of the library, knowing not only where books are but understanding the complex connections between them based on their contents.</p><h3>Best Practices for Configuring Retrievers</h3><p><strong>1. Optimal Chunk Size for Documents</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jpmaPtkHg4w34efO.png" /><figcaption>Image from <a href="https://medium.com/u/b2cb71b98e5b">LlamaIndex</a> optimized chunk size</figcaption></figure><p>Just as readers better digest information in well-sized chapters, chunking documents into manageable sizes ensures that each piece is coherent and informative. According to the Llama Index, the optimal chunk size depends on the model specifications and continues to evolve. Currently, chunk sizes of 1024 or 2048 tokens are often considered effective, balancing depth with performance.</p><p><strong>2. Combining BM25 and Dense Retrievers</strong></p><p>Using BM25 is like a quick keyword search, narrowing down options. Dense retrievers refine the list, much like asking the librarian to find books that truly resonate with your theme.</p><p><strong>3. Use Cases and Scenarios</strong></p><ul><li>Research Projects: Like a research assistant, retrievers gather key materials, ensuring you have targeted data without irrelevant clutter.</li><li>Customer Query Handling: When handling complex queries, dense retrievers understand user needs deeply, akin to an experienced librarian catering to specific reading interests.</li></ul><h3>Conclusion: Optimizing the RAG Pipeline</h3><p>In optimizing your RAG pipeline, combining the classic BM25 for initial sorting with the nuanced understanding of sentence transformers creates a robust, intelligent system. PostgreSQL ensures your data is stored effectively, ready for quick retrieval. This optimized setup is like having the perfect library staff — efficient, knowledgeable, and intuitive — ensuring every search delivers precisely what you need. The journey from query to result becomes seamless, unlocking deeper insights and efficient data interaction.</p><p>Looking ahead, the next part will jump into setting up the database schema in PostgreSQL to leverage vector functions effectively. We will also explore strategies to optimize retriever performance using both BM25 and sentence transformers in tandem, ensuring your system is both powerful and adaptable.</p><p>11.10.2024 — Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4fde1072190" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-rag-pt-5-retriever-enhanced-model-performance-b4fde1072190">LLM-RAG pt.5 — Retriever: Enhanced Model Performance</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG pt.4 — Fine Tuning: Friend, Not A Foe]]></title>
            <link>https://medium.com/dev-ai/llm-rag-fine-tuning-friends-not-foe-c371116e2b36?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/c371116e2b36</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 15:55:02 GMT</pubDate>
            <atom:updated>2024-10-23T16:22:26.486Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-RAG pt.4 — Fine Tuning: Friend, Not A Foe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*QbiFd_QPhDEY87vj" /><figcaption>pipeline.. for each domain</figcaption></figure><p>I was writing about Retrieval-Augmented Generation (RAG) when I realized that the broader narrative around <strong>RAG</strong> often involves a comparison with <strong>Fine-tuning</strong>. These are like two popular yet distinct flavors in the world of Large Language Models (LLMs).</p><p>It’s not about <strong>“Which is Better”</strong> but “<strong>Understanding when and how”</strong> they perform best. So, let’s get into a tale of two techniques without getting lost in technical jargon. This piece aims to demystify RAG and Fine-tuning using everyday examples that showcase their unique strengths.</p><p>Simply click on the index below to easily navigate to the section you’d like to visit.</p><blockquote><strong>Index</strong></blockquote><p><a href="#de81"><strong>0. Introduction: </strong>Picture yourself making a cup of tea.</a></p><p><a href="#2d72"><strong>1. RAG Unplugged: </strong>Bringing Extra Knowledge to the Party</a></p><p><a href="#0d07"><strong>2. Fine-Tuning: </strong>Tailoring the Suit for a Perfect Fit</a></p><p><a href="#a62f"><strong>3. RAG &amp; Fine-Tuning in Action: </strong>Customer Service and Legal Analysis</a></p><p><a href="#3394"><strong>4. Conclusion: </strong>Two Techniques, Many Possibilities</a></p><h4>0. Introduction: Picture yourself making a cup of tea</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abUhesBrYTF1I8Z_7K1Fuw.png" /></figure><p><strong>Retrieval-Augmented Generation</strong> <strong>(RAG)</strong> is like placing a teabag in your mug, allowing you to draw out flavors depending on what’s around. Meanwhile, <strong>Fine-Tuning</strong> is akin to having a kettle of perfectly brewed tea that you can pour straight into your cup — the flavors are already set, awaiting to be enjoyed in a familiar and consistent manner.</p><p>I initially set out to discuss RAG in isolation, intrigued by its ability to bring extra layers of knowledge to AI systems. However, as I got deeper, my curiosity — and the questions from my coworkers and AI-savvy friends from several conferences made me realize that understanding RAG often involves looking at it alongside <strong>Fine-Tuning</strong>.</p><p>These two aren’t competing approaches — rather, they offer distinct but complementary strengths. So, I decided to explore not just RAG, but how it pairs with Fine-tuning, to give a fuller picture of how language models can be truly powerful and versatile. Let’s wander through this tea party of techniques, sharing stories and examples to illuminate their strengths.</p><h4>1. RAG : Bringing Extra Knowledge to the Party</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*7gnT_WMiOrmX82Ft" /><figcaption>Illust from @iStock</figcaption></figure><p><strong>RAG</strong> is like having a friend who knows just where to find interesting facts whenever you need them. It enhances existing models by fetching the <strong>most relevant data from a vast sea of information</strong>. Imagine you’re a customer service representative who can instantly pull up customer history and product details during a conversation. RAG helps models do just this — access real-time, pertinent information without having memorized it.</p><p><strong>When to Use RAG?</strong></p><ul><li><strong>Live Updates Needed</strong>: Perfect for situations like stock market insights, where staying updated is crucial.</li><li><strong>Complex Inquiries</strong>: Great for handling customer queries that require broad knowledge beyond scripted responses.</li></ul><h4>2. Fine-Tuning: Tailoring the Suit for a Perfect Fit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*eI-o-JZ5TsrB_xL6" /><figcaption>Illust from @iStock</figcaption></figure><p>Fine-tuning, on the other hand, is like <strong>tailoring a suit that fits just right.</strong> It customizes a pre-trained model to specialize in specific tasks. Think of it as your model learning all the rules and nuances of a new workplace, becoming the go-to guru for that environment.</p><p><strong>When to Use Fine-Tuning?</strong></p><ul><li><strong>Specialized Knowledge Required</strong>: Ideal for well-defined domains such as healthcare protocols or corporate guidelines.</li><li><strong>Consistent Output Needs</strong>: Best when you want the model to reliably handle specific data structures or predictable scenarios.</li></ul><h4>3. RAG &amp; Fine-Tuning in Action: Customer Service and Legal Analysis</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*dq0SpOWLs8FqQcLB" /><figcaption>illust from @iStock</figcaption></figure><p>Let’s break it down with two relatable domain example :</p><p><strong>Customer Service</strong></p><ul><li><strong>RAG Application: </strong>When agents need to interact dynamically with customers, RAG helps by providing fresh and relevant data — be it the latest product information or a customer’s transaction history — right at their fingertips.</li><li><strong>Fine-Tuning Application:</strong> For handling known issues or common requests, fine-tuning models on a company’s FAQs and policy manuals ensures consistent and precise responses.</li></ul><p><strong>Legal Analysis</strong></p><ul><li><strong>RAG Application:</strong> In a fast-paced legal environment, staying current with legislative changes is critical. RAG facilitates this by pulling the latest legal precedents and updates as required.</li><li><strong>Fine-Tuning Application:</strong> For dealing with standard legal documents or repeated patterns of analysis, fine-tuning ensures the model recognizes and processes these efficiently.</li></ul><h4><strong>4. Conclusion: Two Techniques, Many Possibilities</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*7UXV1yYTMjaCN-t4" /><figcaption>Illust from @iStock</figcaption></figure><p>When we consider RAG and fine-tuning, it’s clear that they’re not rivals, but rather complementary tools, each designed for its own specific purpose. By recognizing their individual strengths, we can use them together to create robust and versatile AI systems that don’t just perform well, but truly excel.</p><p>So, whether you’re navigating through a sea of customer queries or getting into stacks of legal papers, remember: <strong>RAG and Fine-tuning</strong> aren’t in a race. They are here to support a common goal — making AI smarter, more efficient, and be tuned to our needs.</p><p><strong>24.10.2024 — Fin.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c371116e2b36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-rag-fine-tuning-friends-not-foe-c371116e2b36">LLM-RAG pt.4 — Fine Tuning: Friend, Not A Foe</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG pt.3 — Preprocessing: Constructing a Comprehensive Guide]]></title>
            <link>https://medium.com/dev-ai/llm-rag-pt-3-preprocessing-constructing-a-comprehensive-guide-15bbc1e1df36?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/15bbc1e1df36</guid>
            <category><![CDATA[data-preprocessing]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[sentence-transformers]]></category>
            <category><![CDATA[parsing]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 12:30:25 GMT</pubDate>
            <atom:updated>2025-03-01T07:24:56.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>LLM-RAG pt.3 — Preprocessing: Constructing a Comprehensive Guide</h3><p>In the world of data science and technology, efficiently preparing data is like setting up a stage for a flawless performance. When creating a Multi-Retrieval Retrieval-Augmented Generation (RAG) pipeline, preprocessing serves as the foundation upon which everything else is built. Through this extensive guide, we’ll get into the multifaceted world of PDF preprocessing, examining every detail as you would when preparing your home for an important visitor.</p><p>Before we get into the details, let’s outline the key components necessary to build a robust RAG pipeline</p><blockquote><strong>Index</strong></blockquote><p><a href="#8601">1. Introduction</a></p><p><a href="#cf34">2. Key Aspects of PDF Preprocessing</a></p><p><a href="#b0ec">3. Detailed Approaches for Diverse Layouts</a></p><p><a href="#e9df">4. Setting the Stage for Success</a></p><p>Now, let’s focus on the essential first step: preprocessing. This part will illuminate how to transform a potentially chaotic PDF into a refined structure ready for sophisticated RAG operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X7zVZDBh0dyYaq43n8rZ1w.png" /><figcaption>Simplified Multi-Modal Pre-Processing Pipeline for RAG Integration @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><h3>Introduction to the Importance of Preprocessing</h3><p>Think of your preprocessing task as decluttering and organizing your living space before hosting a dinner party. Each piece — text, image, and chart within the PDF — must be properly categorized and placed, allowing your data models to perform at their best. Just as a well-aligned seating arrangement enhances conversation, effectively pre-processed data ensures the RAG pipeline operates efficiently.</p><h3>Laying the Foundation: Key Aspects of PDF Preprocessing</h3><h4>1. Layout Analysis: Designing the Blueprint</h4><ul><li>Understanding Room Layouts vs. Document Structures: Picture adjusting furniture based on your room’s floor plan — knowing whether your PDF is a single-column or multi-column affects how you plan your data “furnishing.”</li><li>Handling Complex Features: Like organizing a room with nooks and workstations, understanding tables and charts requires precision. Each cell, akin to a treasured book, must be accurately cataloged for easy retrieval.</li></ul><h4>2. Text Extraction and Cleaning: Dusting and Arranging</h4><ul><li>Text Cleaning: Simplifying your text is like tidying up messy drawers, keeping everything neat and easy to read.</li></ul><h4>3. Image and Graphics Processing: Curating an Art Gallery</h4><ul><li>Tagging and Storage: Tagging images and storing URLs for Image Storage is like curating art pieces. Images are tagged for easy access without relying on “OCR processes”.</li></ul><h4>4. Metadata Parsing: Learning the House’s History</h4><ul><li>Extract metadata like author and date, similar to uncovering a home’s blueprints, adding valuable context to your document processing.</li></ul><h4>5. Semantic Analysis and Annotation: Narrating a Guided Tour</h4><ul><li>Using NLP techniques to annotate text mirrors how you’d highlight features of a room to guests, adding depth beyond mere visuals.</li></ul><h3>Detailed Approaches for Diverse Layouts</h3><h4><strong>1. Horizontal Layouts: Open-Concept Rooms</strong></h4><ul><li>Handling Two-Column Layouts: Like a loft needing distinct areas, managing split columns requires careful merging to keep narrative flow and zones intact.</li></ul><h4><strong>2. Vertical Layouts: Stacking Knowledge Floors</strong></h4><ul><li>Recognizing Hierarchical Structures**: Organizing document content is like stacking furniture logically by floors, ensuring accessibility.</li></ul><h3>Ensuring Integration and Harmony: The Final Touch</h3><p>As you prepare your space for guests, ensure every detail — from lighting to temperature — is just right. In data preprocessing, refine your approach to achieve consistent output and smooth integration with the rest of the pipeline.</p><h3>Conclusion: Setting the Stage for Success</h3><p>Improving your preprocessing strategy is about more than cleaning up; it’s about creating an environment where all data fits together seamlessly, like a home ready for company. By handling layouts, cleaning text, and organizing visuals, you lay the groundwork for a RAG pipeline that delivers high-quality outcomes. This approach not only simplifies complex input data but also ensures that retrieval and generation stages function flawlessly, maximizing your RAG pipeline’s potential.</p><p>In summary, preprocessing transforms PDF chaos into clarity, paving the way for breakthroughs in data retrieval and usage within intelligent systems.</p><p>2024.10.20 — Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15bbc1e1df36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-rag-pt-3-preprocessing-constructing-a-comprehensive-guide-15bbc1e1df36">LLM-RAG pt.3 — Preprocessing: Constructing a Comprehensive Guide</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG pt.2 — Materials]]></title>
            <link>https://medium.com/dev-ai/llm-rag-pt-2-materials-3557b3ad8da2?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/3557b3ad8da2</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ml-service]]></category>
            <category><![CDATA[rag-pipeline]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 11:56:48 GMT</pubDate>
            <atom:updated>2024-10-15T00:10:46.872Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re working on building a Multi-Retrieval RAG (Retrieval-Augmented Generation) chain for both short and long query processing. But before diving into it, let me list the Materials we need for creating this Multi-Retrieval RAG Chain.</p><blockquote><strong>But, Why do we need two separate retrieving processes?</strong></blockquote><p>The answer depends on how we compare the user query with the embedded vector data. Basically, sentence transformers compare vectors by sentence similarity. SBERT (Sentence-BERT) isn’t performing well in short queries cause it is optimized for comparing and understanding whole sentences.</p><p>What about sparse retrievers like BM25? They understand and consider the relationship between all the words included in a sentence, meaning they perform better on short-term queries. So now you get it, right? Sparse retrievers are better for short-term based queries, and dense retrievers excel in sentence-to-sentence comparisons.</p><p>Now let’s getting into the materials we need to build the Multi-Retrieval RAG Pipeline. The RAG setup basically consists of the four parts below. You can simply click each index to move to the corresponding part.</p><p><a href="#fce7">1. Pre-processing</a></p><p><a href="#b6e4">2. Embeddings</a></p><p><a href="#1397">3. Retriever (Sparse + Dense)</a></p><p><a href="#cd05">4. LLM for returning the answer to the customer</a></p><blockquote><strong>Pre-Processing</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*p3UhNcmv98PiLeFNfbkPrA.jpeg" /></figure><p>Pre-processing is all about how we prepare chunks for embedding and metadata provided to the LLM at the final stage. There are several things to consider based on the type of data we’ll be using.</p><p><strong>(1) Data Type</strong></p><ul><li><strong>Sentence-based Data</strong>: This includes documents like research papers or news articles that mainly focus on providing information through text.</li><li><strong>Sentence + Data Table</strong>: This includes documents like manuals or API documents, which contain both data tables and explanatory sentences.</li><li><strong>Sentence + Data Table + Image</strong>: This includes sources like web magazines or scientific papers that contain charts and images.</li></ul><p><strong>(2) Adding Additional Information for Easier Understanding by the LLM</strong></p><ul><li><strong>Charts</strong>: Sentence Transformers understand better when there’s a clear division between titles, subtitles, and content. This is usually achieved with specific formatting.</li><li><strong>Images</strong>: Instead of using OCR processing, which might consume too much work and resources, we’ll use image storage with tagged image URLs.</li></ul><blockquote><strong>Embeddings</strong></blockquote><p>Before vectorizing the data, a few considerations are necessary:</p><p><strong>(1) Vector Dimension</strong></p><p>This is often decided by the model used for vectorizing the user query and data for semantic search and providing chunks to the LLM. Most HuggingFace models built with SBERT use a 768-dimensional vector. Some models treat this number as 1536. This means that if you use a 768-dimension model for embedding user queries, you should also follow the same dimension for vectorized information in the Vector DB. If you use a 1536-dimension model for user queries, the vectorized dataset should be embedded in the same dimension, 1536, to ensure the database functions in the same environment.</p><p>Quick note: Images use higher dimensions compared to text, and videos use even higher dimensions than images. Got it?</p><p><strong>(2) Metadata</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*QbW4H37FbB_uTx4SedY5hw.jpeg" /><figcaption>Metadata Tagged to the Vector</figcaption></figure><p>Metadata is essentially like the tag that accompanies chunks of information delivered to the LLM. When you enter a query into the chatbot, semantic search works by having the retriever find the most similar vector in the Vector Database. But what’s next? Are we going to give these vectors directly to the LLM? Absolutely not.</p><p>The LLM is like a text expert and only deals with text-based data, not vectors. If we were using a different type of model that handles various data forms, that would be different. Right now, for images, we’re preprocessing them instead of vectorizing, similar to preparing a photo for printing. Vectorizing voice or images is a separate step altogether. So, vectors are only used for discovering similarities. Meanwhile, the text data in the metadata, acting like a detailed tag, is what the LLM actually receives and uses to provide you with accurate information.</p><blockquote><strong>Retriever (Sparse + Dense)</strong></blockquote><p>The RAG chain uses both sparse and dense retrievers to balance performance across different types of queries:</p><p>1. Sparse Retriever (BM25): This retriever is great because it understands individual word relationships within short queries. It scans the words and finds the best match based on word-based similarity.</p><p>2. Dense Retriever (SBERT): This one is optimized for longer, more complex queries. It’s good at understanding sentence-to-sentence relationships and giving results that make sense in the context of longer texts.</p><p>Here’s a careful point to note: choosing the right retriever for the right type of query can significantly improve the accuracy and relevance of the results. Short queries? Go sparse. Long, detailed queries? Use dense.</p><blockquote><strong>Language Model (LLM) for Answer Generation</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYEZaxkNzxSino91h27RDg.jpeg" /><figcaption>Image from <a href="https://medium.com/u/d346391a83fb">Analytics Vidhya</a></figcaption></figure><p>The final piece of the puzzle is the LLM, which generates answers based on the retrieved text. After getting the most relevant chunks of text through the combined efforts of sparse and dense retrievers, the LLM synthesizes this information to give you an appropriate response.</p><p>Here’s another careful point: The accuracy of the LLM depends heavily on the quality of the pre-processing, embeddings, and retrievers. So, ensure each step is done meticulously for the best outcomes.</p><blockquote><strong>Conclusion</strong></blockquote><p>Building a Multi-Retrieval RAG Chain means you need to understand how sparse and dense retrievers compare user queries with embedded vector data. Effectively using both types, combined with careful pre-processing and embedding, creates a robust and efficient query processing system. This ensures the system performs well across different query types, providing accurate, contextually relevant answers. By leveraging the strengths of both retrieval methods and ensuring proper data preparation, we can achieve a high-performance, multi-retrieval RAG system that meets diverse user needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3557b3ad8da2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/llm-rag-pt-2-materials-3557b3ad8da2">LLM-RAG pt.2 — Materials</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LLM-RAG pt.1 — Vector DB, What is the difference?]]></title>
            <link>https://medium.com/dev-ai/rag-pt-1-vector-db-what-is-the-difference-f4a9702f26da?source=rss-f55e3a246699------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a9702f26da</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Liebertar]]></dc:creator>
            <pubDate>Sat, 24 Aug 2024 11:24:43 GMT</pubDate>
            <atom:updated>2024-10-15T00:09:29.436Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine this: You’re going into the world of futuristic databases that understand not just numbers and text but also images, audio, and more. For this part, I would like to talk about some standout features: Vector Representation, Logarithmic Time Search, Cosine Similarity, Dimensionality Reduction, and some of Easy-understanding Use Cases.</p><p>Below is the roadmap for our discussion today. You can just simply click on each of topic to jump straight to that section.</p><blockquote><strong><em>Index</em></strong></blockquote><ul><li><a href="#c914">What is a Vector Database?</a></li><li><a href="#e7e8">How is the Vector Database Different from a Traditional DB?</a></li><li><a href="#82c9">How Vector DB Works?</a></li><li><a href="#b5c1">Logarithmic Time Search in Vector DB</a></li><li><a href="#0950">Cosine Similarity</a></li><li><a href="#aeb6">Dimensionality reduction in Vector DB</a></li><li><a href="#3029">Use Cases</a></li><li><a href="#9f1c">Wrap — up</a></li></ul><h3>1. What is a Vector Database?</h3><p>A Vector Database stores data as vectors, arrays of numbers capturing the essence of various data types like images, text, and audio. Unlike traditional databases that store data in rows and columns, Vector Databases convert unstructured data into vectors, making it easily searchable and comparable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/0*_elBvynKe5fmyhv8.png" /><figcaption>Vector DB Providers</figcaption></figure><h3>2. How is a Vector Database Different from a Traditional Database?</h3><p>Traditional databases, like relational databases, are great for handling structured data. Structured data is neatly organized in tables with predefined schemas, making it easy to query with SQL (Structured Query Language). These databases excel in tasks where data relationships are clear and well-defined.</p><p>On the other hand, traditional databases, including NoSQL databases, often struggle with unstructured data — things like images, videos, and natural language text. This kind of data doesn’t fit neatly into tables and columns, making it hard to process and analyze effectively with standard database methods.</p><p>This is where vector databases shine. They are specifically designed to handle unstructured data by converting it into numerical formats called vectors. Vectors are arrays of numbers that capture the key features of the unstructured data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1kaoky3O4UlhZT8-8dJLbg.png" /><figcaption>image from @<a href="https://weaviate.io/">weviate</a></figcaption></figure><h3>3. How Vector Databases Work?</h3><p>Vector databases store data as vectors, which are arrays of numbers that capture the core features of each piece of data.</p><h4>What is a Vector?</h4><p>A vector is essentially a list of numbers that represent different attributes of an item. For instance, in a vector, the numbers might reflect various aspects like color, size, shape, or even the meaning of a word in a text.</p><h4>Example Case</h4><p>Imagine you have a gallery of images. Each image is converted into a vector that reflects features like color, texture, and shape. This vector representation allows for easy comparison and search through the images. For example, by comparing these vectors, the database can quickly find images that are similar in color and texture to a given image. This makes searching large sets of unstructured data much more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i-rBn0-rsX72Xbt7RBG29A.png" /><figcaption>@Google Hum to Search</figcaption></figure><h3>4. Logarithmic Time Search in Vector Databases</h3><p>Advanced search algorithms allow Vector Databases to perform fast searches, even with large datasets, thanks to logarithmic time search.</p><h4>Example Case:</h4><p>Consider a music app that finds songs similar to the one you’re humming. The app compares your hummed melody with millions of songs, identifying those with similar characteristics quickly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*3LE0QTCoRZD4GfBjX7lbcA.png" /><figcaption>Cosine calculation for easy understanding @<a href="https://medium.com/u/f55e3a246699">Liebertar</a></figcaption></figure><h3>5. Cosine Similarity</h3><p>Cosine Similarity measures the angle between two vectors to determine how similar they are, crucial for comparing vectorized data.</p><h4>Example Case:</h4><p>Think about online shopping recommendations. The platform uses Cosine Similarity to compare your browsing history vectors with product vectors, suggesting relevant items.</p><h3>6. Dimensionality Reduction in Vector Databases</h3><p>Dimensionality Reduction simplifies high-dimensional data by reducing the number of variables while preserving essential information.</p><h4>Example Case:</h4><p>Imagine an app that categorizes your photos. Dimensionality Reduction simplifies the data, making the classification process faster and more efficient.</p><h3>7. Use Cases for Vector Databases</h3><p>Vector Databases have numerous practical applications:</p><ul><li><strong>Search Engines:</strong> Enhanced capabilities beyond simple keyword matching.</li><li><strong>Recommendation Systems:</strong> Products, movies, or songs based on user preferences.</li><li><strong>Natural Language Processing (NLP):</strong> Efficiently transforms and understands human language.</li><li><strong>Image and Video Recognition:</strong> Quickly classifies and identifies visual data.</li></ul><h4>Example Case:</h4><p>In a virtual assistant app, a Vector Database helps understand and respond to user queries effectively, enhancing user experience.</p><h3>8. Re-check : Comparison to Regular Databases</h3><h4>Traditional Databases:</h4><ul><li><strong>Data Format:</strong> Rows and columns.</li><li><strong>Data Types:</strong> Ideal for numbers, strings, dates.</li><li><strong>Search Mechanism:</strong> Slower for large, unstructured datasets.</li><li><strong>Flexibility:</strong> Limited to predefined schemas.</li></ul><h4>Vector Databases:</h4><ul><li><strong>Data Format:</strong> Vectors capturing data essence.</li><li><strong>Data Types:</strong> Excellent for unstructured data.</li><li><strong>Search Mechanism:</strong> Quick, efficient searches with advanced algorithms.</li><li><strong>Flexibility:</strong> Highly adaptable to various data types and structures.</li></ul><h4>Example Comparison:</h4><p>In a Traditional Database, searching for books titled “Adventure” involves simple keyword matching. With a Vector Database, you can describe the plot, and the system will fetch matching books.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-fojCqvjtKYWsaW3.png" /><figcaption>Image from @Monte Carlo Data</figcaption></figure><h3>9. Wrapping Up</h3><p>Vector Databases represent a leap from traditional databases in handling complex, high-dimensional data. They enable rapid searches, efficient data reduction, and provide superior real-world applications. As AI and machine learning advance, Vector Databases will be essential in understanding our vast and varied data landscapes.</p><p>Next time you think about databases, imagine them diving into the intricate details of unstructured data, providing insights faster than ever.</p><p>08.23.2024 — Fin.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a9702f26da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dev-ai/rag-pt-1-vector-db-what-is-the-difference-f4a9702f26da">LLM-RAG pt.1 — Vector DB, What is the difference?</a> was originally published in <a href="https://medium.com/dev-ai">Dev-ai</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>