<?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 Himanshu shukla on Medium]]></title>
        <description><![CDATA[Stories by Himanshu shukla on Medium]]></description>
        <link>https://medium.com/@himanshushukla.shukla3?source=rss-e5c7c9fab4b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*z6ZJQXsdARI0ojY-AlGhZA.png</url>
            <title>Stories by Himanshu shukla on Medium</title>
            <link>https://medium.com/@himanshushukla.shukla3?source=rss-e5c7c9fab4b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:05:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@himanshushukla.shukla3/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[Claude Code Can Manage Your Workflows — Not Just Your Code]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/claude-code-can-manage-your-workflows-not-just-your-code-8f51e171cc39?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f51e171cc39</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcps]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Thu, 05 Mar 2026 16:00:37 GMT</pubDate>
            <atom:updated>2026-03-05T16:03:40.493Z</atom:updated>
            <content:encoded><![CDATA[<p>For years, AI coding assistants have focused on one thing: <strong>helping developers write code faster</strong>.</p><p>But a major shift is happening in the AI tooling ecosystem.</p><p>Tools like <strong>Claude Code</strong> are evolving from coding assistants into <strong>workflow orchestrators</strong> — systems that coordinate development processes across tools like GitHub, Slack, CI/CD pipelines, and internal services.</p><p>The technology enabling this transformation is called the <strong>Model Context Protocol (MCP)</strong>.</p><p>Instead of AI simply generating code, MCP allows AI systems to <strong>connect to real tools, call functions, receive events, and automate workflows</strong>.</p><p>This article explains how Claude Code can manage development workflows — not just code — and how you can build a <strong>custom MCP workflow server</strong> to make that happen.</p><h3>The Problem: Coding Is Only 20% of Development</h3><p>Most developers spend more time managing processes than writing code.</p><p>A typical development workflow looks like this:</p><pre>Write Code<br>   ↓<br>Create Pull Request<br>   ↓<br>Choose PR Template<br>   ↓<br>Wait for CI/CD<br>   ↓<br>Check GitHub Actions<br>   ↓<br>Debug failures<br>   ↓<br>Notify team<br>   ↓<br>Deploy<br>   ↓<br>Update docs</pre><p>Each step involves switching between tools:</p><ul><li>GitHub</li><li>CI/CD dashboards</li><li>Slack</li><li>documentation systems</li><li>deployment platforms</li></ul><p>Even with automation scripts, developers still <strong>coordinate these steps manually</strong>.</p><p>AI can remove this friction.</p><h3>Model Context Protocol (MCP)</h3><p>The <strong>Model Context Protocol (MCP)</strong> is an open protocol that allows AI models to interact with external systems through standardized interfaces.</p><p>Think of MCP as:</p><blockquote><strong><em>USB-C for AI integrations</em></strong></blockquote><p>Instead of writing custom integrations for every service, developers expose tools through <strong>MCP servers</strong>, and AI assistants can use them dynamically.</p><h3>MCP vs Traditional API Integrations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uvVAS_GXs94f7HCI.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7zySE7ifG_HcM6O.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EeUiJe95OHHAA4eu.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lNmy0zUREsIZhpzB.gif" /></figure><h3>Traditional Integration</h3><p>Every AI assistant requires custom connectors.</p><pre>AI Assistant<br>    |<br>    |-- GitHub API<br>    |-- Slack API<br>    |-- Database API<br>    |-- Monitoring API</pre><p>Problems:</p><ul><li>Too many integrations</li><li>hard to maintain</li><li>inconsistent interfaces</li><li>security risks</li></ul><h3>MCP Integration</h3><pre>Claude Code<br>     |<br>  MCP Client<br>     |<br>--------------------------------<br>|          |           |<br>GitHub MCP Slack MCP  CI MCP<br>Server     Server      Server</pre><p>Benefits:</p><ul><li>standardized AI tooling</li><li>reusable integrations</li><li>plug-and-play workflows</li><li>safer permission model</li></ul><h3>MCP Primitives: The Building Blocks</h3><p>MCP provides three primitives that enable workflow automation.</p><h3>Tools</h3><p>Functions the AI can execute.</p><p>Examples:</p><pre>analyze_changed_files()<br>suggest_pr_template()<br>monitor_ci_status()<br>send_slack_notification()</pre><h3>Prompts</h3><p>Structured workflows that guide the AI through multi-step processes.</p><p>Example:</p><pre>PR Review Workflow</pre><pre>1. Summarize PR<br>2. Check CI status<br>3. Identify risky files<br>4. Suggest reviewers</pre><h3>Resources</h3><p>Contextual data sources.</p><p>Examples:</p><ul><li>repository files</li><li>documentation</li><li>configuration</li><li>internal APIs</li></ul><h3>Architecture: Claude Code DevOps Assistant</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/0*ZzHSHVKIq8RMpKHN.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OZCnn2bOJfrvdU9c" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2CbBUb-ifu2e9qbS.png" /></figure><p>The architecture for our workflow assistant looks like this:</p><pre>Developer<br>   |<br>   v<br>Claude Code<br>   |<br>MCP Client<br>   |<br>-------------------------------------<br>|              |                    |<br>GitHub MCP     CI/CD MCP         Slack MCP<br>Server         Server            Server<br>   |              |                    |<br>Pull Requests   GitHub Actions     Team Alerts</pre><p>This creates an <strong>AI-assisted DevOps workflow</strong>.</p><h3>What We’re Building: PR Agent Workflow Server</h3><p>Our MCP server will automate a common development scenario.</p><h3>Before</h3><p>Developer must:</p><ul><li>choose PR template</li><li>monitor CI pipeline</li><li>read logs</li><li>notify team</li></ul><h3>After</h3><p>Claude Code can:</p><ul><li>select PR template automatically</li><li>summarize CI results</li><li>notify team in Slack</li><li>guide review workflow</li></ul><h3>PR Agent Workflow Sequence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E3BBNZ7rgG8mz2Dd.jpg" /></figure><p>Example workflow:</p><pre>Developer pushes code<br>        ↓<br>Claude analyzes changed files<br>        ↓<br>PR template selected<br>        ↓<br>GitHub Actions triggered<br>        ↓<br>CI results summarized<br>        ↓<br>Slack notification sent</pre><p>Output example:</p><pre>Deployment Successful</pre><pre>Service: Payment API<br>Version: v2.4.1<br>Environment: Production</pre><pre>Tests: Passed<br>Build Time: 3m 48s</pre><h3>Clean Architecture Diagram (SVG)</h3><p>Below is a simplified architecture representation of the workflow server.</p><pre>             +----------------+<br>             |   Developer    |<br>             +--------+-------+<br>                      |<br>                      v<br>             +----------------+<br>             |  Claude Code   |<br>             +--------+-------+<br>                      |<br>                 MCP Client<br>                      |<br>        +-------------+--------------+<br>        |             |              |<br>+---------------+ +---------------+ +---------------+<br>| GitHub Server | | CI/CD Server  | | Slack Server  |<br>+-------+-------+ +-------+-------+ +-------+-------+<br>        |                 |                 |<br> Pull Requests       Build Status       Notifications</pre><h3>Example PR-Agent Repository Structure</h3><p>Here is a recommended project layout.</p><pre>pr-agent-mcp-server<br>│<br>├── server<br>│   ├── index.ts<br>│   ├── tools<br>│   │   ├── analyzeFiles.ts<br>│   │   ├── prTemplate.ts<br>│   │   └── ciStatus.ts<br>│   │<br>│   ├── prompts<br>│   │   ├── prReviewPrompt.ts<br>│   │   └── deploymentPrompt.ts<br>│   │<br>│   └── integrations<br>│       ├── github.ts<br>│       ├── slack.ts<br>│       └── ci.ts<br>│<br>├── webhooks<br>│   └── githubWebhook.ts<br>│<br>├── config<br>│   └── settings.json<br>│<br>└── package.json</pre><p>This structure separates:</p><ul><li>MCP tools</li><li>prompts</li><li>integrations</li><li>webhooks</li></ul><h3>MCP Server Example Code</h3><p>Here is a simplified Node.js MCP server example.</p><pre>import { createServer } from &quot;@modelcontextprotocol/server&quot;</pre><pre>const server = createServer()</pre><pre>server.tool(<br>  &quot;suggest_pr_template&quot;,<br>  async ({ files }) =&gt; {</pre><pre>    if (files.some(f =&gt; f.startsWith(&quot;docs/&quot;)))<br>      return &quot;Documentation Template&quot;</pre><pre>    if (files.some(f =&gt; f.startsWith(&quot;tests/&quot;)))<br>      return &quot;Test Update Template&quot;</pre><pre>    return &quot;Feature Template&quot;<br>  }<br>)</pre><pre>server.tool(<br>  &quot;send_slack_notification&quot;,<br>  async ({ message }) =&gt; {</pre><pre>    await fetch(process.env.SLACK_WEBHOOK,{<br>      method:&quot;POST&quot;,<br>      body: JSON.stringify({ text: message })<br>    })</pre><pre>    return &quot;Notification sent&quot;<br>  }<br>)</pre><pre>server.start()</pre><p>Claude Code can now <strong>call these tools automatically</strong>.</p><h3>Cloudflare Tunnel Webhook Architecture</h3><p>To monitor CI/CD events locally, we can expose our MCP server using <strong>Cloudflare Tunnel</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eHdczZoe3JugXyqZ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*I9ZhOy7jR4E1rmgt.png" /></figure><p>Architecture:</p><pre>GitHub Actions<br>     |<br>Webhook Event<br>     |<br>Cloudflare Tunnel<br>     |<br>Local MCP Server<br>     |<br>Claude Code<br>     |<br>Slack Notification</pre><p>This allows GitHub to send events to your local development server securely.</p><h3>Why This Matters</h3><p>AI tools are evolving beyond chat interfaces.</p><p>They are becoming <strong>workflow orchestrators</strong>.</p><p>Instead of assisting with isolated tasks, AI can now:</p><ul><li>interact with APIs</li><li>monitor system events</li><li>trigger automated workflows</li><li>coordinate across platforms</li></ul><p>With MCP, AI becomes an <strong>operator inside your development environment</strong>.</p><h3>The Future of AI-Native Development</h3><p>Imagine telling Claude:</p><pre>Ship this feature.</pre><p>And the system automatically:</p><pre>Create branch<br>Generate PR<br>Run CI<br>Monitor results<br>Deploy to staging<br>Notify team<br>Update docs</pre><p>That future is already starting.</p><h3>Final Thoughts</h3><p>Claude Code is no longer just a coding assistant.</p><p>With <strong>Model Context Protocol servers</strong>, it becomes a <strong>workflow engine for development teams</strong>.</p><p>By connecting GitHub, CI/CD pipelines, Slack, and internal tools, developers can build AI systems that:</p><ul><li>understand their codebase</li><li>automate development workflows</li><li>reduce operational friction</li><li>coordinate team processes</li></ul><p>The real revolution in AI development isn’t just <strong>better code generation</strong>.</p><p>It’s <strong>AI managing the entire software lifecycle</strong>.</p><p>If you’re building developer tooling, now is the time to start experimenting with <strong>MCP workflow servers</strong>.</p><p>Because soon, your AI won’t just help you write code.</p><p>It will help you <strong>run your entire engineering process</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f51e171cc39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PicoClaw: The Lightweight Go Rewrite That Makes OpenClaw Run Anywhere]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/picoclaw-the-lightweight-go-rewrite-that-makes-openclaw-run-anywhere-8e80a5b61e4f?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e80a5b61e4f</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[openclaw]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 13:00:15 GMT</pubDate>
            <atom:updated>2026-02-18T13:00:15.909Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenClaw exploded onto the open-source scene as one of GitHub’s fastest-growing projects. The premise was compelling: turn any messaging app into the front door for a fully autonomous AI assistant capable of reading emails, scheduling tasks, browsing the web, executing shell commands, and retaining memory across sessions — all running locally on your hardware.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*thP5203JGgoyFS-V.jpg" /></figure><p>The catch? It was built on TypeScript and Node.js. That meant dedicating a Mac Mini or a well-provisioned Linux server with at least 1 GB of RAM just for the runtime. A group of engineers at Sipeed looked at that constraint and decided to do something about it. They reverse-engineered OpenClaw’s architecture and rebuilt the entire thing from the ground up in Go. The outcome is PicoClaw — a single static binary that consumes under 10 MB of RAM and cold-starts in less than a second, even on a 0.6 GHz single-core board.</p><p>Here’s a deep look at PicoClaw, how to get it running, and why it matters.</p><h3>Why OpenClaw Was Ripe for a Rewrite</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*tcAmUL6OPyfNKkUR.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/0*Z-es9DRon_E4Ec8I.png" /></figure><p>OpenClaw’s appeal comes from its ecosystem. It supports a wide array of messaging platforms — WhatsApp, Telegram, Slack, Discord, iMessage through BlueBubbles, and others. It offers a visual Live Canvas, voice activation, and an expanding skill marketplace where each skill is defined by a simple markdown file following the SKILL.md convention. At its core, a gateway acts as the control plane: routing messages, managing sessions, and injecting persistent context files like SOUL.md, AGENTS.md, and MEMORY.md into every prompt sent to the language model.</p><p>But all that richness has a cost. Node.js carries a full JavaScript runtime, an event loop, and an entire module system along for the ride. Even with aggressive tree-shaking and careful bundling, the process footprint balloons past 1 GB once you factor in browser automation, long context windows, and multiple concurrent skills.</p><p>PicoClaw preserves the conceptual core — the markdown-driven workspace, the cron scheduler, long-term memory, the tool-calling loop, and chat integrations — while cutting away everything non-essential. The entire application compiles down to one native binary with no external runtime dependencies beyond the operating system itself.</p><h3>PicoClaw by the Numbers</h3><p>The performance gap is stark:</p><p><strong>Memory:</strong> OpenClaw &gt;1 GB typical vs. PicoClaw &lt;10 MB idle</p><p><strong>Startup:</strong> OpenClaw 30–500+ seconds on low-end hardware (Node warm-up + dependency loading) vs. PicoClaw consistently under 1 second</p><p><strong>Binary size:</strong> OpenClaw requires Node installation + npm packages vs. PicoClaw ships as a single ~15–25 MB executable</p><p><strong>Minimum hardware:</strong> OpenClaw needs a Mac Mini or decent VPS vs. PicoClaw runs on anything with a Linux kernel and ~64 MB free RAM</p><p><strong>Cross-compilation:</strong> One make build-all produces x86_64, ARM64, and RISC-V binaries out of the box</p><p>These gains come directly from Go’s design philosophy: static linking, a garbage collector tuned for low latency and small footprints, strong concurrency primitives without virtual machine overhead, and effortless cross-compilation. The HTTP client for LLM calls, JSON handling for tool responses, and filesystem watchers for cron and memory updates all come from the standard library or small, well-audited packages.</p><p>Confirmed deployments already include Sipeed’s $9.90 LicheeRV-Nano (RISC-V), the Raspberry Pi Zero 2 W, old Android phones running Termux with chroot, and embedded industrial boards.</p><h3>Getting Started: Three Paths to a Running Agent</h3><h3>Path 1 — Precompiled Binary (Fastest)</h3><p>Grab the right binary from the releases page and drop it into your PATH:</p><pre>wget https://github.com/sipeed/picoclaw/releases/download/v0.1.1/picoclaw-linux-arm64<br>chmod +x picoclaw-linux-arm64<br>sudo mv picoclaw-linux-arm64 /usr/local/bin/picoclaw</pre><h3>Path 2 — Build from Source (For Contributors)</h3><pre>git clone https://github.com/sipeed/picoclaw.git<br>cd picoclaw<br>make deps          # installs build tools if needed<br>make build         # produces ./picoclaw<br>sudo make install  # installs to /usr/local/bin</pre><h3>Path 3 — Docker (Zero Host Pollution)</h3><p>The repository ships a docker-compose.yml with gateway and agent profiles ready to go.</p><h3>First Run</h3><pre>picoclaw onboard</pre><p>This generates ~/.picoclaw/config.json and the workspace directory. Edit the config to add your LLM provider keys. OpenRouter is a solid starting point since it gives you access to many models through a single endpoint.</p><p>A minimal configuration looks like this:</p><pre>{<br>  &quot;agents&quot;: {<br>    &quot;defaults&quot;: {<br>      &quot;workspace&quot;: &quot;~/.picoclaw/workspace&quot;,<br>      &quot;model&quot;: &quot;glm-4.7&quot;,<br>      &quot;temperature&quot;: 0.7<br>    }<br>  },<br>  &quot;providers&quot;: {<br>    &quot;openrouter&quot;: {<br>      &quot;api_key&quot;: &quot;your_key_here&quot;,<br>      &quot;api_base&quot;: &quot;https://openrouter.ai/api/v1&quot;<br>    }<br>  },<br>  &quot;tools&quot;: {<br>    &quot;web&quot;: {<br>      &quot;duckduckgo&quot;: { &quot;enabled&quot;: true }<br>    }<br>  }<br>}</pre><p>Test it right away:</p><pre>picoclaw agent -m &quot;Summarize the last 24 hours of my calendar and suggest three priorities for today&quot;</pre><h3>Connecting a Chat Interface (Telegram Example)</h3><p>Create a bot through @BotFather, copy the token, and add this to your config:</p><pre>&quot;channels&quot;: {<br>  &quot;telegram&quot;: {<br>    &quot;enabled&quot;: true,<br>    &quot;token&quot;: &quot;123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11&quot;,<br>    &quot;allowFrom&quot;: [&quot;your_user_id&quot;]<br>  }<br>}</pre><p>Run picoclaw gateway and you&#39;re live. The same pattern applies to Discord, QQ, DingTalk, and LINE — only the credential fields differ.</p><h3>The Workspace: Plain Text as the Universal Interface</h3><p>Everything that gives the agent persistence and personality lives in simple text files:</p><p><strong>SOUL.md</strong> — High-level identity and values</p><p><strong>AGENTS.md</strong> — Behavioral rules and chain-of-thought guidelines</p><p><strong>MEMORY.md</strong> — Long-term memory (the agent summarizes and appends over time)</p><p><strong>HEARTBEAT.md</strong> — A prompt evaluated every 30 minutes for proactive tasks</p><p><strong>cron/</strong> — JSON files defining scheduled jobs</p><p><strong>skills/</strong> — Drop in new SKILL.md files and the agent discovers them automatically</p><p>This architecture is a gift for developers. You can version-control the entire agent personality, audit every change with git, and even allow the agent to edit its own configuration safely within the sandbox. The security model confines all file and command operations to the workspace by default. Tools like browser automation and shell execution run through carefully scoped wrappers.</p><h3>Running on Real Hardware</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-W_6qytlO1haKnpK.jpg" /></figure><p><strong>Raspberry Pi Zero 2 W (~$15 with case and power):</strong> Run a full personal assistant that checks email over IMAP, searches the web, and posts daily summaries to Telegram — all while leaving plenty of headroom for Pi-hole or Home Assistant on the same device.</p><p><strong>Sipeed LicheeRV-Nano (RISC-V, ~$10):</strong> A completely silent, fanless node that can monitor a room with a camera module and alert you only when something noteworthy happens.</p><p><strong>Old Android phones:</strong> Install Termux, enable chroot, drop in the arm64 binary, and you’ve turned discarded hardware into a dedicated AI companion.</p><p>For production edge deployments, pair PicoClaw with a systemd service that restarts on failure and logs to journald. The tiny footprint means you can run dozens of isolated agents on a single modest board by namespacing the workspaces.</p><h3>Lessons Worth Taking to Your Own Projects</h3><p><strong>Let AI handle the tedious migration work.</strong> Reserve your attention for architecture decisions and edge cases, not line-by-line translation.</p><p><strong>Measure memory and startup relentlessly.</strong> Go’s runtime.ReadMemStats() and basic timing benchmarks belong in every CI pipeline when you&#39;re targeting constrained environments.</p><p><strong>Lean on the standard library.</strong> Every external dependency adds binary weight and attack surface. PicoClaw demonstrates how far you can get with surprisingly little.</p><p><strong>Use plain text as your interface layer.</strong> Keeping state, prompts, memory, and skills in markdown gives you git, diff, search, and human readability at no additional cost. This pattern extends well beyond AI agents.</p><p><strong>Sandbox by default.</strong> The workspace-restriction flag prevented countless problems during PicoClaw’s development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*s3n3oLTai2v5CYiR.gif" /></figure><p>If you have a Node or Python service that feels bloated, consider trying the AI-assisted Go port as an experiment. Watching your binary shrink from 200 MB to 12 MB is genuinely motivating.</p><h3>What’s Still Missing</h3><p>PicoClaw is younger, and it shows in a few areas. The skill marketplace doesn’t yet match OpenClaw’s ClawHub in breadth. Advanced features like the full visual Canvas and native mobile companion apps haven’t been ported. Plugin compatibility is close but not identical — the tool interface differs in places.</p><p>That said, the gaps are narrowing. Community pull requests are already landing for local Ollama support, additional LLM providers, and migration helpers for existing OpenClaw workspaces. With 12,000 stars in its first week, ecosystem growth is not going to be a bottleneck.</p><p>If you need the richest possible feature set right now, OpenClaw on a Mac Mini or small VPS remains a strong choice. For everything else — particularly anything that needs to run around the clock on inexpensive or embedded hardware — PicoClaw is the more compelling option.</p><h3>Why This Matters</h3><p>PicoClaw is proof that powerful AI capabilities and extreme resource efficiency can coexist. By choosing the right language and leaning on modern coding assistants for the heavy lifting of refactoring, it’s possible to push autonomous agents into territory they’ve never reached: battery-powered devices, industrial controllers, retired phones, and micro-servers in remote locations.</p><p>A significant share of the next wave of compelling AI applications will run quietly in the background on hardware we already own or can buy for loose change. PicoClaw gives developers a way to build for that future without waiting for bigger, more e</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e80a5b61e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forget the Cloud: Build Your Own Private, Local AI Copilot From Scratch]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/forget-the-cloud-build-your-own-private-local-ai-copilot-from-scratch-6149413f2d72?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6149413f2d72</guid>
            <category><![CDATA[local]]></category>
            <category><![CDATA[github-copilot]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[coding-agents]]></category>
            <category><![CDATA[co-pilot]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 07:57:13 GMT</pubDate>
            <atom:updated>2025-08-29T07:57:13.707Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>By Himanshu Shukla</em></blockquote><blockquote><em>ML Engineer at Siemens</em></blockquote><blockquote><em>Connect on </em><a href="https://www.linkedin.com/in/himanshushukla01/">LinkedIn</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*x5NXi3rUtcmsIMzwJHrzGA.png" /></figure><h3>1. Introduction: The Case for a Local Copilot</h3><p>What if your AI coding assistant ran entirely on your machine, knew nothing about your proprietary code, and worked flawlessly offline?</p><p>In today’s development landscape, cloud-based AI assistants are everywhere. They’re incredibly powerful, but they come with a trade-off. Every code snippet you send for completion, every question you ask, travels to a server owned by someone else. This raises valid concerns about privacy, especially when working with sensitive or proprietary code. Beyond that, there are the recurring subscription costs, reliance on an internet connection, and the occasional service latency.</p><p>But what if you could have the best of both worlds? The power of a sophisticated AI assistant with the security of a completely offline, local environment. This is not a futuristic dream; it’s a practical reality you can build yourself.</p><p>This article is your blueprint for creating a personal, private AI copilot. We’ll move beyond a simple script and architect a robust, agent-based system. We’ll walk through the entire process, from choosing a local Large Language Model (LLM) to building a backend orchestrator and a web-based UI to control it. You’ll learn how to build a system that offers:</p><ul><li><strong>Ultimate Privacy:</strong> Your code never leaves your machine. Period.</li><li><strong>Deep Customization:</strong> Tweak, modify, and extend your copilot to fit your exact needs.</li><li><strong>Offline Capability:</strong> Code on a plane, in a basement, or during an internet outage without interruption.</li><li><strong>Zero Cost:</strong> Use powerful open-source models without paying for API calls.</li></ul><p>By the end, you’ll have a functional local AI assistant and a deep understanding of the architecture that powers modern AI development tools.</p><h3>2. The Big Picture: Our Copilot’s Architecture</h3><p>Before we dive into the code, let’s look at our system’s architecture. A truly robust copilot isn’t just a model and a script; it’s a system of components working in harmony. We’ll model ours after a professional kitchen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9mXY7wiZgpdl3SKoG_NKw.png" /></figure><ul><li><strong>The Brain (The Local LLM):</strong> This is our “Expert Chef.” It’s a powerful language model running entirely on your local machine. It has the raw intelligence to understand code, generate suggestions, and answer questions. We’ll use an open-source model optimized for coding.</li><li><strong>The Agent Orchestrator (The Backend):</strong> This is our “Head Chef” or “Kitchen Manager.” It’s a sophisticated backend server that does more than just pass messages. It receives high-level goals from the UI, breaks them down into steps, gathers context (from your code or a vector database), formats precise prompts for the LLM, and manages the entire workflow. This is the heart of our custom agent.</li><li><strong>The Control Panel (The UI):</strong> This is our “Waiter and Dining Room.” It’s a web-based interface where you interact with the agent. Instead of a simple command-line tool, we’ll use Streamlit to build a user-friendly control panel that allows you to give instructions, upload files for context, and monitor the agent’s progress in real-time.</li></ul><h3>3. Step 1: Setting Up the “Brain” (The Local LLM)</h3><p>The heart of our copilot is the LLM. Thanks to incredible progress in model optimization, running a powerful LLM on a personal machine is now highly feasible.</p><p><strong>Choosing Your Model:</strong></p><p>The open-source community has produced amazing models optimized for code generation. A great choice is a model from the <strong>Qwen</strong> family (like Qwen/Qwen2-7B-Instruct-GGUF) or <strong>Code Llama</strong>. When choosing, you&#39;ll face a trade-off:</p><ul><li><strong>Larger models (13B+ parameters):</strong> More accurate and context-aware, but require more RAM and a powerful GPU.</li><li><strong>Smaller models (7B parameters or less):</strong> Faster and run on more modest hardware, but may be slightly less capable.</li></ul><p><strong>Quantization Explained:</strong></p><p>You’ll often see terms like “GGUF” or “4-bit quantization.” Don’t let them intimidate you. <strong>Quantization</strong> is the process of making a model smaller and faster. Think of it like compressing a massive, high-resolution RAW image into a high-quality JPEG. The JPEG is a fraction of the size and loads instantly, yet for most purposes, the quality is indistinguishable. Quantization does the same for LLMs, reducing their memory footprint from ~14GB to ~4GB for a 7B model, with a minimal impact on performance.</p><p><strong>Running the Model:</strong></p><p>You have two excellent options for serving the model:</p><ol><li><strong>The Easy Way (Ollama):</strong> For getting started quickly, <strong>Ollama</strong> is the best tool. It handles all the complexity of downloading, managing, and serving models through a clean, local API.</li></ol><ul><li>Download and install Ollama from their website.</li><li>Open your terminal and run: ollama run qwen:7b</li><li>Ollama will download the model and start a local server. Just like that, you have a running LLM with an API endpoint at <a href="http://localhost:11434.">http://localhost:11434.</a></li></ul><ol><li><strong>The High-Performance Way (vLLM):</strong> For maximum speed and batching capabilities (if you plan to scale), <strong>vLLM</strong> is a fantastic, production-grade inference engine. It’s more involved to set up but offers the best performance. Our project’s agent/models.py includes a VLLMClient to show how you can connect to a vLLM-powered endpoint.</li></ol><h3>4. Step 2: Building the “Agent Orchestrator” (The Backend)</h3><p>This is where we build our custom agent’s intelligence. The backend is more than a simple API; it’s an orchestrator that manages the entire task lifecycle. We’ll use <strong>FastAPI (Python)</strong> for its speed and modern features.</p><p><strong>Core Architecture:</strong></p><p>Our agent backend is structured into several key modules:</p><ul><li>config.py &amp; config.yaml: A centralized configuration system. This allows you to easily change models, endpoints, and other settings without touching the code.</li><li>models.py: Contains client classes for interacting with different LLM APIs (e.g., OllamaClient, VLLMClient). This makes the system modular and easy to extend.</li><li>rag_service.py: A dedicated service for Retrieval-Augmented Generation (more on this later).</li><li>orchestrator.py: The main workflow manager.</li></ul><p><strong>The Orchestrator’s Logic (</strong><strong>orchestrator.py):</strong></p><p>When a request comes in from the UI, the orchestrator performs a series of steps:</p><ol><li><strong>Receive Goal:</strong> It takes a high-level goal, like “Create a Flask app with a login page,” and any reference files.</li><li><strong>Load Configuration:</strong> It reads the config.yaml to know which model to use, its endpoint, and other operational parameters.</li><li><strong>Gather Context:</strong> This is the critical step. The orchestrator decides if it needs more information.</li></ol><ul><li>If the user provided reference files, it reads them.</li><li>If the user asked a question about the codebase, it calls the RAGService to find relevant code snippets.</li></ul><ol><li><strong>Construct the Master Prompt:</strong> It assembles a detailed, structured prompt. This isn’t just the user’s request; it’s a master document containing:</li></ol><ul><li>A <strong>system message</strong> defining the AI’s role (“You are an expert AI software architect…”).</li><li>The user’s <strong>primary goal</strong>.</li><li>The full content of any <strong>text-based reference files</strong>.</li><li>A list and description of any <strong>binary reference files</strong>.</li><li>Relevant code snippets retrieved by the <strong>RAG service</strong>.</li></ul><ol><li><strong>Execute and Stream:</strong> It sends the master prompt to the appropriate LLM client from models.py and streams the response back to the UI, providing a real-time experience.</li></ol><h3>5. Step 3: Creating the “Control Panel” (The UI)</h3><p>A good user interface is essential for a usable tool. While a VS Code extension is a great option for deep integration, a web UI is faster to build and more flexible. We’ll use <strong>Streamlit</strong>, a Python framework that makes creating beautiful data and model-centric apps incredibly simple.</p><p><strong>Key UI Features (</strong><strong>ui/app.py):</strong></p><ul><li><strong>Multi-Tab Interface:</strong> Our UI is organized into tabs for different functions:</li><li><strong>Project Generator:</strong> The main interface for giving high-level project goals.</li><li><strong>Chat Assistant:</strong> A conversational interface for asking questions or getting help with specific code.</li><li><strong>System Diagnostics:</strong> A panel to test connections to the LLM and other services (like a vector database).</li><li><strong>Monitoring:</strong> Real-time logs and status updates while the agent is running.</li><li><strong>Universal File Upload:</strong> A key feature is allowing the user to upload <strong>any type of file</strong> as context for both chat and project generation. The UI intelligently handles different file types, showing previews for images and code, and extracting metadata for binary files.</li><li><strong>State Management:</strong> Streamlit’s session state is used to keep track of chat history, the current project’s status, and execution logs.</li></ul><h3>6. Step 4: Making It Smarter with RAG</h3><p>To enable our agent to “chat with a codebase,” we implement <strong>Retrieval-Augmented Generation (RAG)</strong>. This transforms the LLM from a generalist into a specialist on <em>your</em> project.</p><p><strong>Concept:</strong></p><p>RAG is like giving your LLM an “open-book exam.” By default, the LLM only knows what’s in its pre-trained memory. With RAG, it can look up relevant information from your codebase <em>before</em> answering a question.</p><p><strong>The RAG Service (</strong><strong>rag_service.py):</strong></p><ol><li><strong>Indexing:</strong> First, you run a script that processes a codebase. It uses a <strong>text splitter</strong> to break code into logical chunks (e.g., functions or classes). Then, it uses a <strong>sentence-transformer</strong> model to convert these chunks into numerical vectors (embeddings) and stores them in a <strong>vector database</strong> like <strong>Qdrant</strong>.</li><li><strong>Retrieval:</strong> When a user asks, “How does our user authentication work?”, the RAGService converts the question into a vector and queries Qdrant to find the most semantically similar code chunks.</li><li><strong>Augmentation:</strong> The Orchestrator takes these retrieved chunks and inserts them into the prompt it sends to the LLM.</li><li><strong>Generation:</strong> The LLM receives this highly specific, context-rich prompt and generates a precise answer based on the actual code from the project.</li></ol><h3>7. Step 5: Packaging for Easy Use with Docker</h3><p>To make our application portable and easy to run, we can containerize it using <strong>Docker</strong>.</p><ul><li><strong>Dockerfile:</strong> Defines the environment for our Python backend. It installs all dependencies from pyproject.toml, copies the application code, and defines the command to start the server.</li><li><strong>docker-compose.yml:</strong> A powerful file that defines and runs our multi-container application. It can spin up:</li><li>Our <strong>Agent Orchestrator</strong> service.</li><li>The <strong>Streamlit UI</strong> service.</li><li>Dependent services like <strong>Ollama</strong> and <strong>Qdrant</strong>.</li></ul><p>This means you can get the entire, complex system running with a single command: docker-compose up.</p><h3>8. Conclusion: Your Personal AI Is Ready</h3><p>You’ve journeyed from concept to a fully architected local AI copilot. By setting up a local LLM, building a sophisticated agent orchestrator, creating a feature-rich web UI, and implementing advanced RAG capabilities, you’ve built a powerful tool that puts you in complete control.</p><p>The power of owning your AI tools cannot be overstated. You have achieved ultimate privacy, gained full control over your development environment, and opened the door to infinite customization.</p><p><strong>Next Steps to Explore:</strong></p><ul><li><strong>Build a VS Code Extension:</strong> Create a dedicated extension that communicates with your FastAPI backend for a more integrated experience.</li><li><strong>Fine-tune a Model:</strong> For hyper-specialized tasks, you can fine-tune a smaller model on your own code or data.</li><li><strong>Expand the Agent’s Tools:</strong> Give your agent the ability to use other tools, like running terminal commands or searching the web.</li></ul><p>Welcome to the future of AI-powered development — one that runs on your terms, on your machine. Happy building!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6149413f2d72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Beam Search: From top_k to Fluent Language Generation]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/demystifying-beam-search-from-top-k-to-fluent-language-generation-51dd15695476?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/51dd15695476</guid>
            <category><![CDATA[decoder]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[beam-search]]></category>
            <category><![CDATA[mls]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Fri, 02 May 2025 08:17:24 GMT</pubDate>
            <atom:updated>2025-05-02T08:17:24.733Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>“Most of the time, we set parameters like </strong><strong>top_k, </strong><strong>top_p, or </strong><strong>temperature when generating text—but ever wondered how they actually steer your model’s output?”</strong></p><p>Understanding these decoding strategies can help you produce more coherent, diverse, and accurate text. In this article, we’ll unpack the most common techniques — then dive deep into <strong>beam search</strong>, explaining why it often outperforms greedy and sampling-based methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*aSLZnpQicklsJpyFxiz8jA.png" /></figure><h3>Decoding Parameters at a Glance</h3><p>Before we explore beam search, let’s quickly review the parameters you’ve probably tweaked:</p><ul><li><strong>top_k</strong>: Restricts the model to its <em>k</em> most probable next tokens, then samples randomly among them.</li><li><strong>top_p (nucleus sampling)</strong>: Chooses the smallest set of top tokens whose cumulative probability ≥ <em>p</em>, then samples from that set.</li><li><strong>temperature</strong>: Scales the logits before softmax, where higher values increase randomness and lower values make the model more “confident.”</li></ul><p>While these knobs control diversity and creativity, they don’t guarantee global coherence — especially for long sequences.</p><h3>The Greedy Baseline</h3><p>The simplest decoding method is <strong>greedy decoding</strong>, which picks the single most probable token at each step:</p><pre>sequence = []<br>for step in generation:<br>    next_token = argmax(model.probabilities)<br>    sequence.append(next_token)</pre><p>Greedy is fast and deterministic, but it can get “stuck” in suboptimal choices — a locally best word choice might blow up the sentence later.</p><h3>Enter Beam Search</h3><p><strong>Beam search</strong> balances exploration and exploitation by keeping track of the top <em>B</em> partial sequences (the “beam”) at each time step:</p><ol><li><strong>Initialize</strong> the beam with the start token.</li><li><strong>Expand</strong> each sequence by all possible next tokens.</li><li><strong>Score</strong> each new candidate by its cumulative log probability.</li><li><strong>Prune</strong> back to the top <em>B</em> sequences.</li><li><strong>Repeat</strong> until you reach an end condition or max length.</li></ol><p>By maintaining multiple hypotheses, beam search can recover from early mistakes and often finds higher-quality outputs.</p><h3>Beam Search vs. Greedy Decoding</h3><p>Aspect Greedy Beam Search <strong>Speed</strong> Fastest (O(T)) Slower (O(B·T)) <strong>Quality</strong> May be suboptimal Better global quality <strong>Diversity Control</strong> None Adjust beam width <em>B</em> <strong>Repeat Risk</strong> High Lower</p><p><em>Table: A quick comparison of greedy decoding and beam search.</em></p><h3>Beam Search vs. Sampling Methods</h3><p><strong>Sampling (</strong><strong>top_k/</strong><strong>top_p)</strong></p><ul><li>✔ Adds randomness and creativity</li><li>❌ Can produce incoherent or contradictory text</li></ul><p><strong>Beam Search</strong></p><ul><li>✔ Deterministic and focused on high-probability paths</li><li>✔ Produces more fluent and accurate sequences</li><li>❌ Requires tuning beam width and more compute</li></ul><p>Choose sampling for creative tasks (e.g., story generation) and beam search for precision tasks (e.g., translation, summarization).</p><h3>Real-World Applications</h3><p>Beam search is the go-to for many sequence-to-sequence tasks:</p><ul><li><strong>Machine Translation</strong>: Finds the best sentence in the target language.</li><li><strong>Summarization</strong>: Balances conciseness with coverage.</li><li><strong>Speech Recognition</strong>: Selects the most likely sentence given audio.</li></ul><h3>Dive Deeper with Research</h3><p>For an in-depth look at advanced beam strategies, check out:</p><blockquote><strong><em>“Beam Search Strategies for Neural Machine Translation”</em></strong><em><br> </em>Markus Freitag &amp; Yaser Al-Onaizan (2017)<em><br> This paper introduces an </em><strong><em>adaptive beam</em></strong><em> approach that dynamically varies the beam size at each step — speeding up decoding by up to 43% without sacrificing translation quality.</em></blockquote><p>📄 <a href="https://arxiv.org/abs/1702.01806">Download the PDF or read on arXiv</a></p><h3>Wrap-Up</h3><p>Beam search offers a powerful middle ground between greedy efficiency and sampling diversity. By adjusting your beam width, you can fine-tune the tradeoff between quality and speed — making it an essential tool for any serious sequence-generation task.</p><p>What’s been your experience? Have you tried adaptive beam techniques, or do you lean on sampling for your projects? Let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51dd15695476" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Long-Context LLM Inference on Consumer GPUs with HEADINFER]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/unlocking-long-context-llm-inference-on-consumer-gpus-with-headinfer-c2b6d749d8ec?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2b6d749d8ec</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ollam]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 17:48:04 GMT</pubDate>
            <atom:updated>2025-02-19T17:48:04.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*r4vnZ91y4qdeDMTLXy4p6A.png" /></figure><h3>Can You Run a Million-Token LLM on a Consumer GPU?</h3><p>If you’ve worked with large language models (LLMs), you know that inference on long-context inputs is a nightmare for GPU memory. A standard LLM like Llama-3–8B requires <strong>207GB of GPU memory</strong> for 1 million tokens — far beyond the capabilities of consumer GPUs like the RTX 4090, which has only 24GB of memory.</p><p>Sounds impossible to run such long-context inference on consumer hardware, right? Well, not anymore! A new method called <strong>HEADINFER</strong> introduces an innovative way to offload memory, making million-token inference possible even on consumer-grade GPUs.</p><p>Let’s break it down in simple terms.</p><h3>Why Is Long-Context Inference So Hard?</h3><p>LLMs use a special technique called <strong>self-attention</strong>, which helps the model understand relationships between words. However, the problem is that self-attention requires storing <strong>Key-Value (KV) Cache</strong> for every token processed. The longer the input, the larger the KV cache grows.</p><p>For example, if you run a Llama-3–8B model on a <strong>1-million-token sequence</strong>, here’s what happens:</p><ul><li><strong>15GB</strong> for model parameters</li><li><strong>64GB</strong> for activations</li><li><strong>128GB</strong> for KV cache</li><li><strong>Total memory needed: 207GB!</strong></li></ul><p>This is why long-context inference has been limited to enterprise-grade hardware — until now.</p><h3>Traditional Offloading: Not Enough for Consumer GPUs</h3><p>To overcome GPU memory limits, researchers have developed techniques like <strong>layer-wise offloading</strong>, where parts of the KV cache are moved from the GPU to the CPU. However, these methods still require a large fraction of KV cache to remain in GPU memory, making them impractical for consumer GPUs.</p><p>For example, on an RTX 4090 with <strong>24GB of memory</strong>, only <strong>8GB can be used for KV cache</strong> (after accounting for model weights and activations). Traditional offloading strategies don’t reduce memory usage enough, making million-token inference impossible.</p><h3>HEADINFER: A Game-Changer for Long-Context Inference</h3><p>HEADINFER introduces a <strong>head-wise offloading strategy</strong>, where instead of offloading entire layers, it offloads <strong>individual attention heads</strong> dynamically. This reduces GPU memory usage dramatically while maintaining model accuracy.</p><h3>How It Works</h3><p>In a Transformer model, each self-attention layer is divided into multiple <strong>attention heads</strong>. Instead of keeping all heads in GPU memory, HEADINFER does the following:</p><ol><li><strong>Stores only one head at a time in GPU memory</strong></li><li><strong>Offloads the remaining heads to CPU memory</strong></li><li><strong>Fetches and processes heads dynamically as needed</strong></li><li><strong>Uses asynchronous data transfer to avoid delays</strong></li></ol><p>This fine-grained control allows HEADINFER to keep <strong>only 1GB of KV cache on GPU instead of 128GB</strong> — a <strong>92% reduction</strong> in memory usage!</p><h3>HEADINFER in Action: Performance Gains</h3><p>By applying HEADINFER to <strong>Llama-3–8B</strong>, researchers achieved <strong>4-million-token inference on an RTX 4090!</strong> Here are the key numbers:</p><p>Method Max Context Length GPU Memory Usage Standard Inference 25K tokens 207GB Layer-wise Offload 45K tokens 60GB <strong>HEADINFER</strong> <strong>4M tokens</strong> <strong>17GB</strong></p><p>HEADINFER doesn’t just reduce memory — it also maintains high computational efficiency. It achieves <strong>100x improvement</strong> in context length compared to standard inference without compromising accuracy.</p><h3>Technical Innovations in HEADINFER</h3><p>To make this possible, HEADINFER integrates multiple optimization techniques:</p><h3>1. Adaptive Head Grouping</h3><p>Dynamically adjusts the number of heads retained in GPU memory based on available memory and context length.</p><h3>2. Chunked Prefill</h3><p>Splits long input sequences into smaller chunks, processing them incrementally to reduce activation memory.</p><h3>3. Asynchronous Data Transfer</h3><p>Overlaps KV cache movement between GPU and CPU to prevent stalls from memory transfers.</p><h3>4. Compatibility with Existing Optimizations</h3><p>Works with other methods like <strong>4-bit KV-quantization, sparse attention, and pipeline parallelism</strong> to further optimize inference.</p><h3>Implications: Making AI More Accessible</h3><p>With HEADINFER, consumer GPUs can now handle <strong>million-token inference</strong>, which was previously only possible on expensive enterprise-grade hardware. This has <strong>huge implications</strong> for AI research and deployment:</p><p>✅ <strong>Longer context memory</strong> for chatbots and virtual assistants ✅ <strong>Efficient book-length document processing</strong> ✅ <strong>More accessible AI for developers and small businesses</strong> ✅ <strong>Lower infrastructure costs for LLM inference</strong></p><p>HEADINFER represents a <strong>major breakthrough</strong> in AI efficiency, bringing <strong>long-context LLMs to consumer hardware</strong> without approximation tricks or quality loss.</p><h3>Final Thoughts</h3><p>For years, long-context LLM inference was limited by memory constraints, but HEADINFER is <strong>redefining what’s possible</strong>. By adopting a <strong>head-wise offloading approach</strong>, it enables <strong>4-million-token inference on a single RTX 4090</strong>, making AI <strong>more efficient and accessible</strong>.</p><p>This is a <strong>huge leap forward</strong> for AI practitioners, researchers, and businesses looking to scale LLMs <strong>without investing in massive GPUs</strong>.</p><p>🚀 <strong>What do you think? Could HEADINFER revolutionize LLM inference on consumer hardware?</strong> Drop your thoughts in the comments!</p><p>📜 Read the full research paper here: <a href="https://arxiv.org/pdf/2502.12574v1">HeadInfer: Memory-Efficient LLM Inference by Head-wise Offloading</a></p><p>#AI #LLM #DeepLearning #GPU #MemoryOptimization #MachineLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2b6d749d8ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Stop Using llama.cpp for Multi-GPU Setups! Use vLLM or ExLlamaV2 Instead ]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/stop-using-llama-cpp-for-multi-gpu-setups-use-vllm-or-exllamav2-instead-73992cf1a1ad?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/73992cf1a1ad</guid>
            <category><![CDATA[vllm]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[multi-gpu]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[llama-cpp]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Mon, 10 Feb 2025 18:27:45 GMT</pubDate>
            <atom:updated>2025-02-10T18:27:45.366Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Himanshu Shukla, ML Engineer &amp; Technical Writer</em></p><h3>The TL;DR</h3><p>If you’re running <strong>multi-GPU setups</strong> and using llama.cpp—STOP! ❌ That’s <strong>crippling your system.</strong> You NEED <strong>Batch Inference with Tensor Parallelism</strong> for real efficiency, and that means switching to <strong>vLLM or ExLlamaV2.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*YLUTCfQOfMsV_F3XH7xTOA.png" /></figure><p>Now, let’s dive in.👇</p><h3>The Context: How This Started</h3><p>I recently observed a fascinating test involving a powerful <strong>6x RTX 4090</strong> AI rig — designed to push an LLM to send and receive concurrent messages, gradually increasing the load. It was an impressive setup, but what caught my attention was the choice of inference engine: llama.cpp.</p><p>💡 <strong>That got my attention.</strong> Because with such a <strong>powerful setup, </strong><strong>llama.cpp is a bottleneck.</strong></p><p>Around the <strong>26-minute mark</strong>, I commented on this. After some back-and-forth, I decided not to hijack his stream and instead, <strong>write this post</strong> to explain why llama.cpp is a bad choice for multi-GPU workloads and what you should be using instead.</p><h3>Why llama.cpp Isn’t Built for Multi-GPU Setups</h3><p>llama.cpp is an <strong>amazing project</strong>—super versatile, open-source, and widely used. BUT <strong>it lacks Batch Inference</strong> and doesn’t support <strong>Tensor Parallelism.</strong> This means if you’re handling multiple requests, GPUs end up <strong>waiting for their turn</strong> instead of running in parallel. ❌</p><p>The only time you should <strong>ever</strong> use llama.cpp is if <strong>you’re forced to offload to CPU</strong> due to <strong>insufficient VRAM.</strong></p><p>But if you’ve got <strong>multiple GPUs</strong>, you need <strong>something better.</strong></p><h3>What You Should Be Using: vLLM &amp; ExLlamaV2</h3><h3>🔥 vLLM: The Multi-GPU Beast</h3><p>🚀 Uses <strong>Tensor Parallelism</strong> to distribute computations <strong>across multiple GPUs</strong> — all working simultaneously.</p><p>🔥 Supports <strong>Batch Inference</strong>, meaning it processes <strong>many requests at once</strong>, making it exponentially faster.</p><p>⚡ <strong>Real-world test:</strong></p><p>I ran <strong>50 asynchronous requests</strong> (~2K tokens each) on vLLM with <strong>Llama 3.1 70B BF16</strong> across <strong>8 GPUs</strong>. ⏳ <strong>Total time: 2 min 29 sec.</strong> <strong>(Could’ve been even faster with INT8 quantization!)</strong></p><h3>⚡ ExLlamaV2: Perfect for EXL2 Quantization &amp; Multi-GPU Use</h3><p>💡 Ideal if you’re running <strong>quantized models (EXL2).</strong></p><p>🔥 <strong>Supports Tensor Parallelism</strong>, so multiple GPUs work together efficiently.</p><p>🔄 Works exceptionally well in <strong>lower VRAM environments</strong>, without totally compromising speed.</p><h3>A Quick Detour: What’s an Inference Engine?</h3><p>An <strong>Inference Engine</strong> is what translates <strong>your input</strong> into something the <strong>LLM understands</strong>, runs the computations, and spits out <strong>human-readable output.</strong></p><p>Most inference engines use <strong>Transformer models</strong> (think Hugging Face’s transformers library) running on <strong>PyTorch, TensorFlow, or JAX.</strong> But the real game-changer? <strong>Batch Inference + Tensor Parallelism.</strong></p><p>Let’s break that down.👇</p><h3>Tensor Parallelism &amp; Batch Inference = SPEED ⚡⚡⚡</h3><h3>Tensor Parallelism</h3><p>Instead of <strong>one GPU doing all the work</strong>, Tensor Parallelism <strong>splits the workload across multiple GPUs.</strong></p><ul><li>Rather than running <strong>entire matrix multiplications on one GPU</strong>, each GPU handles <strong>a fraction of the workload.</strong></li><li>GPUs work on <strong>different parts of different layers</strong> <strong>simultaneously</strong>, meaning your <strong>model runs exponentially faster.</strong></li></ul><h3>Batch Inference</h3><p>Instead of processing <strong>one request at a time</strong>, Batch Inference allows your engine to <strong>handle multiple requests at once.</strong></p><p>🔬 <strong>Experiment:</strong></p><ul><li>Ran <strong>10K requests for synthetic data generation</strong> using vLLM.</li><li>🚀 <strong>Held up like a champ.</strong></li><li>Would NOT have been possible with llama.cpp.</li></ul><h3>Final Words: 🚫 Do NOT Use Ollama</h3><p>I know, <strong>Ollama is popular.</strong> But here’s the thing:</p><ul><li>❌ It’s just a wrapper around llama.cpp.</li><li>❌ It <strong>does a bad job at VRAM management</strong> and offloading.</li><li>❌ It’s <strong>okay for single-GPU casual chat models</strong>, but <strong>terrible for anything more.</strong></li></ul><p>So, if you’re running <strong>serious AI workloads</strong>, skip Ollama and go for vLLM or ExLlamaV2.</p><h3>Takeaway: Stop Bottlenecking Your GPUs! 🚀</h3><p>If you have <strong>multiple GPUs</strong>, <strong>ditch </strong><strong>llama.cpp</strong> and switch to an <strong>engine that supports Tensor Parallelism &amp; Batch Inference.</strong></p><p>💡 <strong>The right tools for the job:</strong> ✅ vLLM – Best for <strong>high-speed, multi-GPU batch inference</strong>.</p><p>✅ ExLlamaV2 – Best for <strong>multi-GPU setups using quantized models (EXL2)</strong>.</p><p>❌ llama.cpp – ONLY if you <strong>absolutely</strong> need <strong>CPU offloading.</strong></p><p>🔥 If you’re serious about AI inference, you <strong>owe it to yourself</strong> to make the switch. Your GPUs (and your response times) will thank you. 🚀💯</p><p>Until next time! 👊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73992cf1a1ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAG a practical approach]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/cag-a-practical-approach-c12d5f2418ee?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12d5f2418ee</guid>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[document]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 05:42:58 GMT</pubDate>
            <atom:updated>2025-02-04T06:57:19.529Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Unlocking Speed &amp; Simplicity: How Cache-Augmented Generation (CAG) Outperforms Traditional RAG</strong></p><p><em>By Himanshu Shukla, ML Engineer &amp; Technical Writer</em></p><p>In the fast-evolving world of AI, integrating external knowledge into language models is critical for accuracy and relevance. While <strong>Retrieval-Augmented Generation (RAG)</strong> has been a go-to method, a new paradigm — <strong>Cache-Augmented Generation (CAG)</strong> — promises to revolutionize efficiency. Let’s dive into how CAG works, why it’s up to <strong>40x faster</strong> than RAG, and how you can implement it today.</p><h3>What is Cache-Augmented Generation (CAG)?</h3><p>CAG eliminates the need for real-time document retrieval by preloading all relevant knowledge into the model’s context window. Imagine having a condensed library stored directly in your AI’s memory — no waiting for external searches! Here’s how it works:</p><ol><li><strong>Preprocessing</strong>: Documents are chunked and optimized to fit the LLM’s context window .</li><li><strong>Encoding</strong>: These chunks are transformed into a <strong>Key-Value (KV) cache</strong>, capturing the model’s inference state .</li><li><strong>Storage</strong>: The cache is stored in memory or on disk, enabling instant access during inference .</li></ol><p>Unlike RAG, which dynamically fetches data, CAG ensures all knowledge is immediately available, slashing latency and avoiding retrieval errors .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*3nbnC0T1w25ov0I795EVqw.png" /><figcaption>CAG vs RAG</figcaption></figure><h3>Why CAG Beats RAG in Key Scenarios</h3><p>RAG’s real-time retrieval introduces delays and complexity. CAG solves these pain points:</p><p><strong>Metric</strong> <strong>RAG</strong> <strong>CAG</strong> <strong>Latency</strong> High (due to retrieval steps) Near-zero (preloaded cache) <strong>Accuracy</strong> Prone to retrieval errors Consistent (full context access) <strong>System Design</strong> Complex (retriever + generator) Simplified (no retrieval pipeline) <strong>Cost</strong> High (compute/API fees) Low (one-time preprocessing)</p><p><em>Example</em>: In medical diagnostics, CAG’s ability to preload clinical guidelines ensures rapid, error-free responses, while RAG might struggle with slow API calls .</p><p><strong>Limitations</strong>: CAG works best with <strong>limited, stable datasets</strong> (e.g., FAQs, legal docs). For dynamic or massive knowledge bases, hybrid RAG-CAG systems are ideal .</p><h3>Implementing CAG: A Step-by-Step Guide</h3><p>Let’s build a CAG system using the <a href="https://github.com/hhhuang/CAG">official GitHub repository</a>.</p><h3>1. Setup Environment</h3><p>Clone the repo and install dependencies:</p><pre>git clone &lt;https://github.com/hhhuang/CAG&gt;<br>cd CAG<br>pip install -r requirements.txt  # Includes transformers, llama-index, etc.</pre><h3>2. Preload Knowledge</h3><p>Process your dataset (e.g., SQuAD or HotPotQA) and generate the Key-Value (KV) cache. This step is crucial for enabling fast inference.</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br>import torch<br># Load your dataset (e.g., SQuAD)<br>from datasets import load_dataset<br>dataset = load_dataset(&quot;squad&quot;)<br># Load the pre-trained model and tokenizer<br>model_name = &quot;meta-llama/Llama-3.1-8B-Instruct&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name)<br>model = AutoModelForCausalLM.from_pretrained(model_name)<br># Preprocess and encode the dataset into KV cache<br>kv_cache = {}<br>for example in dataset[&quot;train&quot;]:<br>    inputs = tokenizer(example[&quot;context&quot;], return_tensors=&quot;pt&quot;)<br>    with torch.no_grad():<br>        outputs = model(**inputs, use_cache=True)<br>        kv_cache[example[&quot;id&quot;]] = outputs.past_key_values  # Store KV cache<br># Save the KV cache for later use<br>torch.save(kv_cache, &quot;preloaded_cache.bin&quot;)</pre><p>This script preprocesses the dataset, encodes it into a KV cache, and saves it for future use.</p><h3>3. Run Inference with Preloaded Cache</h3><p>Now that the cache is generated, let’s use it for inference. This step demonstrates how to query the model with preloaded context.</p><pre># Load the preloaded KV cache<br>kv_cache = torch.load(&quot;preloaded_cache.bin&quot;)</pre><p>This code shows how to use the preloaded KV cache to generate responses without needing real-time retrieval.</p><h3>4. Compare CAG with RAG</h3><p>To highlight the advantages of CAG, let’s compare it with a traditional RAG system.</p><pre>from transformers import RagTokenizer, RagRetriever, RagSequenceForGeneration<br><br># Define a query<br>query = &quot;What is the capital of France?&quot;<br># Tokenize the query<br>inputs = tokenizer(query, return_tensors=&quot;pt&quot;)<br># Retrieve the relevant KV cache (e.g., based on document ID)<br>doc_id = &quot;example_doc_id&quot;  # Replace with the actual document ID<br>past_key_values = kv_cache[doc_id]<br># Generate a response using the preloaded cache<br>with torch.no_grad():<br>    outputs = model.generate(<br>        inputs.input_ids,<br>        past_key_values=past_key_values,<br>        max_length=50,  # Adjust as needed<br>        use_cache=True<br>    )<br># Decode and print the response<br>response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(&quot;Response:&quot;, response)<br><br># Load RAG components<br>rag_tokenizer = RagTokenizer.from_pretrained(&quot;facebook/rag-sequence-base&quot;)<br>rag_retriever = RagRetriever.from_pretrained(&quot;facebook/rag-sequence-base&quot;)<br>rag_model = RagSequenceForGeneration.from_pretrained(&quot;facebook/rag-sequence-base&quot;)<br># Query RAG<br>rag_inputs = rag_tokenizer(query, return_tensors=&quot;pt&quot;)<br>rag_outputs = rag_model.generate(rag_inputs.input_ids)<br>rag_response = rag_tokenizer.decode(rag_outputs[0], skip_special_tokens=True)<br>print(&quot;RAG Response:&quot;, rag_response)<br># Compare with CAG<br>print(&quot;CAG Response:&quot;, response)</pre><pre>This script demonstrates how to query both RAG and CAG systems, allowing you to compare their latency and response quality.</pre><h3>5. Benchmark Performance</h3><p>To quantify the benefits of CAG, let’s measure its latency and compare it with RAG.</p><pre>import time<br># Benchmark CAG<br>start_time = time.time()<br>with torch.no_grad():<br>    outputs = model.generate(inputs.input_ids, past_key_values=past_key_values, max_length=50)<br>cag_latency = time.time() - start_time<br># Benchmark RAG<br>start_time = time.time()<br>rag_outputs = rag_model.generate(rag_inputs.input_ids)<br>rag_latency = time.time() - start_time<br>print(f&quot;CAG Latency: {cag_latency:.4f} seconds&quot;)<br>print(f&quot;RAG Latency: {rag_latency:.4f} seconds&quot;)</pre><p>This script measures the time taken for inference in both systems, highlighting CAG’s speed advantage.</p><h3>6. Advanced: Hybrid RAG-CAG System</h3><p>For dynamic datasets, you can combine RAG and CAG to leverage the strengths of both approaches.</p><pre># Check if the query is in the preloaded cache<br>if doc_id in kv_cache:<br>    # Use CAG for fast inference<br>    past_key_values = kv_cache[doc_id]<br>    outputs = model.generate(inputs.input_ids, past_key_values=past_key_values, max_length=50)<br>else:<br>    # Fall back to RAG for dynamic retrieval<br>    outputs = rag_model.generate(rag_inputs.input_ids)<br><br>response = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>print(&quot;Hybrid Response:&quot;, response)</pre><p>This hybrid approach ensures optimal performance for both static and dynamic knowledge bases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*wrqAcRhiyw1rW78etoU7Tg.png" /></figure><h3>Conclusion</h3><p>By preloading knowledge into a KV cache, CAG eliminates the latency and complexity of traditional RAG systems. With the code snippets above, you can implement CAG in your projects and experience its benefits firsthand.</p><p><strong>Call to Action</strong></p><p>Fork the <a href="https://github.com/hhhuang/CAG">CAG GitHub repo</a>, experiment with the code, and share your results! Let’s discuss how CAG can transform your AI applications in the comments below.</p><p><em>References</em>: <a href="https://github.com/hhhuang/CAG">CAG GitHub</a> | <a href="https://arxiv.org/abs/2412.15605">arXiv Paper</a> | <a href="https://www.aisharenet.com/cagbiragkuai40bei/">Benchmark Results</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12d5f2418ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All-in-One Multimodal Inference: CLI, Gradio, and Checkpointing Made Easy]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/all-in-one-multimodal-inference-cli-gradio-and-checkpointing-made-easy-3927fbd61a5d?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3927fbd61a5d</guid>
            <category><![CDATA[fine-tune]]></category>
            <category><![CDATA[llama-3]]></category>
            <category><![CDATA[meta]]></category>
            <category><![CDATA[inference]]></category>
            <category><![CDATA[medium]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Tue, 26 Nov 2024 14:23:33 GMT</pubDate>
            <atom:updated>2024-11-26T14:23:33.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*hKhByEz-2G77WI3JEhDabQ.png" /></figure><p>In today’s AI-driven landscape, multimodal inference — integrating visual and textual data — has become essential. With <strong>Meta-Llama’s Llama-3.2–11B-Vision-Instruct</strong>, you now have a powerful tool for seamlessly handling these tasks. This post introduces <strong>multi_modal_infer.py</strong>, an all-in-one script that streamlines inference and fine-tuning, offering CLI support, Gradio UI, and efficient checkpointing via LoRA.</p><h3>Why This Script Stands Out</h3><p>The multi_modal_infer.py script consolidates all functionalities into a single tool, simplifying tasks ranging from basic inference to advanced fine-tuning. Whether you’re experimenting with multimodal models or deploying them in production, this script’s flexibility is unmatched.</p><p>Key features include:</p><ol><li><strong>Command-Line Simplicity</strong>: Perform inference or load LoRA weights directly from the CLI.</li><li><strong>Gradio-Powered Interactivity</strong>: Test models visually with an intuitive UI.</li><li><strong>Checkpointing Made Easy</strong>: Integrate <strong>PEFT LoRA</strong> weights effortlessly for fine-tuned applications.</li></ol><h3>Model Overview</h3><ul><li><strong>Base Model</strong>: meta-llama/Llama-3.2-11B-Vision-Instruct</li><li><strong>Capabilities</strong>:</li><li>Supports vision-language tasks with instructional capabilities.</li><li>Incorporates <strong>PEFT v0.13.1</strong> for efficient, resource-friendly fine-tuning.</li></ul><h3>Modes of Operation</h3><h4>1. Basic CLI Inference</h4><p>Command-line simplicity allows you to input an image and prompt to get detailed descriptions or answers.</p><pre>python multi_modal_infer.py \<br>    --image_path &quot;path/to/image.jpg&quot; \<br>    --prompt_text &quot;Describe this image&quot; \<br>    --model_name &quot;meta-llama/Llama-3.2-11B-Vision-Instruct&quot;</pre><h4>2. Gradio UI</h4><p>For a more hands-on approach, launch the Gradio interface. The UI offers parameter sliders for sampling (e.g., temperature, top-k, and top-p) and real-time toggling of LoRA adapters.</p><pre>python multi_modal_infer.py \<br>    --model_name &quot;meta-llama/Llama-3.2-11B-Vision-Instruct&quot; \<br>    --gradio_ui</pre><h4>3. LoRA Fine-Tuning Integration</h4><p>Efficiently load pre-trained LoRA weights to specialize the model for specific tasks or domains. Ideal for applications like medical imaging or customer-centric visual Q&amp;A.</p><pre>python multi_modal_infer.py \<br>    --image_path &quot;path/to/image.jpg&quot; \<br>    --prompt_text &quot;Describe this image&quot; \<br>    --model_name &quot;meta-llama/Llama-3.2-11B-Vision-Instruct&quot; \<br>    --finetuning_path &quot;path/to/lora/weights&quot;</pre><h3>What Makes This Script Unique?</h3><h4>1. Unified Interface</h4><p>The script integrates inference, checkpointing, and interactivity in a single tool. With just a few parameters, switch between CLI and Gradio modes or enable LoRA weights.</p><h4>2. Efficient Checkpointing with LoRA</h4><p>LoRA (Low-Rank Adaptation) allows for fine-tuning only a subset of the model’s parameters, drastically reducing resource usage while maintaining high performance.</p><h4>3. Hugging Face Integration</h4><p>Easily download models and manage tokens with Hugging Face’s API. Setup is straightforward with:</p><pre>huggingface-cli login</pre><h4>4. Modular and Scalable Design</h4><p>Supports everything from local testing to production-scale deployment, with options for advanced safety checks and FP8 quantized variants for large models.</p><h3>How to Get Started</h3><ol><li><strong>Install Dependencies</strong></li></ol><ul><li>Ensure transformers, gradio, peft, and accelerate are installed.</li></ul><p><strong>2. Login to Hugging Face</strong></p><pre>huggingface-cli login</pre><p><strong>3. Test Modes</strong></p><ul><li>Start with CLI inference.</li><li>Launch Gradio UI for interactive exploration.</li><li>Fine-tune with LoRA for domain-specific tasks.</li></ul><h3>Applications</h3><ul><li><strong>Caption Generation</strong>: Automatically describe visual content for accessibility or marketing purposes.</li><li><strong>Visual Question Answering</strong>: Provide context-aware answers to user queries about an image.</li><li><strong>Custom Vision-Language Models</strong>: Fine-tune for specialized industries like healthcare, finance, or e-commerce.</li></ul><h3>Credits</h3><p>This contribution, authored by <a href="https://github.com/himanshushukla12"><strong>Himanshu Shukla</strong></a>, streamlines multimodal inference and fine-tuning for researchers and developers alike. Whether you’re exploring AI capabilities or integrating them into your workflows, this script ensures seamless operation at every step.</p><p>Take your multimodal AI workflows to the next level with multi_modal_infer.py. Try it today and unlock a new realm of possibilities!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3927fbd61a5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Context-Aware Chatbot Using LangChain with Ollama and GGUF Models]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/building-a-context-aware-chatbot-using-langchain-with-ollama-and-gguf-models-38fb1508bff6?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/38fb1508bff6</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[chat]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 06:37:29 GMT</pubDate>
            <atom:updated>2024-10-20T06:37:29.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*G6dYHJ6aAF5SHKFu" /></figure><h3>Introduction</h3><p>In recent years, AI chatbots have become increasingly sophisticated, capable of holding meaningful and contextually relevant conversations with users. While popular platforms like ChatGPT and others make AI conversations easily accessible, there is a growing interest among developers to build their own chatbot solutions using custom models. In this tutorial, we’ll walk through building a <strong>context-aware chatbot</strong> using <strong>LangChain</strong>. We’ll integrate two types of models — <strong>Ollama</strong> models and <strong>GGUF</strong> models — to give users the flexibility to choose their preferred AI backend.</p><p>This tutorial is perfect for beginners looking to understand the basics of working with <strong>LangChain</strong> and exploring how to integrate different AI models into a chat application. If you’re curious about how to get started with LangChain and create your own custom chatbot, this post is for you!</p><h3>Prerequisites</h3><p>Before we dive in, ensure that you have:</p><ol><li><strong>Python 3.8+</strong> installed on your machine.</li><li>A basic understanding of Python programming.</li><li>Familiarity with the command line.</li></ol><h3>Step 1: Setting Up the Project</h3><p>First, let’s clone the GitHub repository that contains the code for our chatbot:</p><pre>git clone https://github.com/himanshushukla12/langchain-tutorials.git<br>cd langchain-tutorials</pre><p>Next, create a virtual environment to manage dependencies:</p><pre>python3 -m venv venv<br>source venv/bin/activate  # On Windows: venv\Scripts\activate</pre><p>Now, install the required Python packages:</p><pre>pip install -r requirements.txt</pre><h3>Setting Up Environment Variables</h3><p>We’ll need to specify the URL for the Ollama server. Create a .env file in the project root and add:</p><pre>OLLAMA_URL=http://localhost:11434</pre><p>Make sure to adjust the OLLAMA_URL if your server is running on a different port.</p><h3>Step 2: Understanding the Chat Application</h3><p>The chat application is designed to maintain a history of interactions, enabling it to produce more contextually relevant responses. Here’s a breakdown of how it works:</p><h3>The ChatApp Class</h3><p>The ChatApp class is the backbone of the chat application. It takes care of:</p><ul><li><strong>Initialization</strong>: When the class is instantiated, it takes a language model as input and initializes the conversation history:</li></ul><pre>class ChatApp:<br>    def __init__(self, model):<br>        self.llm = model<br>        self.conversation_history = []</pre><ul><li><strong>Message Handling</strong>: The add_message method stores user and AI messages:</li></ul><pre>def add_message(self, role, content):<br>    self.conversation_history.append((role, content))</pre><ul><li><strong>Streaming Responses</strong>: The stream_response method allows real-time responses from the model, making interactions feel dynamic:</li></ul><pre>def stream_response(self):<br>    messages = self.conversation_history<br>    stream = self.llm.stream(messages)<br>    <br>    full_response = &quot;&quot;<br>    for chunk in stream:<br>        full_response += chunk<br>        print(chunk, end=&quot;&quot;, flush=True)<br>    return full_response</pre><h3>Chatting with the AI</h3><p>The chat method enables an interactive session where users can type messages, and the AI will respond accordingly. The stream_response method is called here to fetch the AI&#39;s response, which is then displayed to the user.</p><pre>def chat(self):<br>    print(&quot;Chat App Initialized. Type &#39;exit&#39; to stop.\n&quot;)<br>    while True:<br>        user_input = input(&quot;You: &quot;)<br>        if user_input.lower() == &quot;exit&quot;:<br>            print(&quot;Exiting chat...&quot;)<br>            break<br>        self.add_message(&quot;human&quot;, user_input)<br>        print(&quot;AI: &quot;, end=&quot;&quot;, flush=True)<br>        ai_response = self.stream_response()<br>        self.add_message(&quot;ai&quot;, ai_response)</pre><h3>Context Management</h3><p>The chatbot maintains a list called conversation_history, which keeps track of the conversation context. This allows the AI to understand the user&#39;s input in light of previous interactions, leading to more relevant responses.</p><h3>Step 3: Choosing Between Ollama and GGUF Models</h3><p>The script allows users to choose between <strong>Ollama</strong> and <strong>GGUF</strong> models. Here’s how to set up each:</p><h3>Using Ollama Models</h3><p>Ollama models can be accessed using the OllamaLLM class from the langchain_ollama package. To use an Ollama model, run the script and select the ollama option:</p><pre>python chat_app.py</pre><p>Then, when prompted, type ollama and enter the model name:</p><pre>Do you want to use ollama or gguf models? (ollama/huggingface/gguf): ollama<br>Enter the model name: llama3.1</pre><p>This will initialize a chat session using the specified Ollama model.</p><h3>Using GGUF Models</h3><p>The LlamaCpp class from langchain_community is used to load <strong>GGUF</strong> models, which are a popular format for local AI models. To use a GGUF model, follow the same steps but choose gguf:</p><pre>Do you want to use ollama, huggingface or gguf models? (ollama/huggingface/gguf): gguf<br>Enter the model path: /path/to/your/gguf-model</pre><p>This allows users to load a local GGUF model and start chatting with it.</p><h3>Step 4: Running the Chatbot</h3><p>Once you’ve chosen the model, the chat session will start, and you can interact with the AI:</p><pre>Chat App Initialized. Type &#39;exit&#39; to stop.</pre><pre>You: Hi, how are you?<br>AI: I&#39;m just a machine, but I&#39;m here to assist you. How can I help?</pre><p>The chatbot will remember your previous messages, allowing it to maintain context throughout the conversation.</p><p>For example:</p><pre>You: What is the weather like today?<br>AI: I currently don&#39;t have access to real-time data, but typically, the weather depends on your location.</pre><p>When you type exit, the chat session ends:</p><pre>You: exit<br>Exiting chat...</pre><h3>Why Use This Approach?</h3><ol><li><strong>Context-Aware Conversations</strong>: Unlike simpler chatbots that only respond to the latest input, our application keeps track of the entire conversation. This makes interactions with the AI more fluid and meaningful.</li><li><strong>Flexibility with Models</strong>: By allowing users to switch between <strong>Ollama</strong> and <strong>GGUF</strong> models, you can test different models and choose the one that best suits your needs.</li><li><strong>Beginner-Friendly Code</strong>: The code is structured in a way that beginners can easily follow and modify. It provides a good introduction to working with <strong>LangChain</strong> for AI development.</li></ol><h3>Conclusion</h3><p>Building a chatbot with <strong>LangChain</strong> opens up endless possibilities for customizing AI interactions. Whether you want to integrate cutting-edge models like <strong>Ollama</strong> or prefer working with local <strong>GGUF</strong> models, this tutorial has shown you how to get started with a context-aware chatbot.</p><p>Feel free to extend this project by adding more features like logging conversations, integrating external APIs for real-time data, or experimenting with different AI models. The complete code for this tutorial is available on <a href="https://github.com/himanshushukla12/langchain-tutorials">GitHub</a>. Happy coding, and enjoy building your AI-powered chatbots!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*x2drUQN4D4efcenIPMfOYw.png" /></figure><h3>Next Steps</h3><ul><li>Explore more features of <strong>LangChain</strong> to further enhance your chatbot.</li><li>Try integrating other model types like <strong>HuggingFace Transformers</strong> for even more flexibility.</li><li>Consider deploying your chatbot to a web interface using frameworks like <strong>Flask</strong> or <strong>Streamlit</strong>.</li></ul><p>I hope this tutorial helped you get started with building your own AI chatbot. If you have any questions or feedback, feel free to leave a comment below! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38fb1508bff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Retrieval Augmented Generation (RAG) App]]></title>
            <link>https://medium.com/@himanshushukla.shukla3/build-a-retrieval-augmented-generation-rag-app-009ef91cee8d?source=rss-e5c7c9fab4b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/009ef91cee8d</guid>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Himanshu shukla]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 06:13:02 GMT</pubDate>
            <atom:updated>2024-10-20T06:13:02.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tebfJy2Dtqx84Ngt.png" /></figure><p>One of the most powerful applications enabled by LLMs is sophisticated question-answering (Q&amp;A) chatbots. These are applications that can answer questions about specific source information. These applications use a technique known as Retrieval Augmented Generation, or RAG.</p><p>This tutorial will show how to build a simple Q&amp;A application over a text data source. Along the way we’ll go over a typical Q&amp;A architecture and highlight additional resources for more advanced Q&amp;A techniques. We’ll also see how LangSmith can help us trace and understand our application. LangSmith will become increasingly helpful as our application grows in complexity.</p><p>If you’re already familiar with basic retrieval, you might also be interested in this <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#retrieval">high-level overview of different retrieval techinques</a>.</p><h3>What is RAG?</h3><p>RAG is a technique for augmenting LLM knowledge with additional data.</p><p>LLMs can reason about wide-ranging topics, but their knowledge is limited to the public data up to a specific point in time that they were trained on. If you want to build AI applications that can reason about private data or data introduced after a model’s cutoff date, you need to augment the knowledge of the model with the specific information it needs. The process of bringing the appropriate information and inserting it into the model prompt is known as Retrieval Augmented Generation (RAG).</p><p>LangChain has a number of components designed to help build Q&amp;A applications, and RAG applications more generally.</p><p><strong>Note</strong>: Here we focus on Q&amp;A for unstructured data. If you are interested for RAG over structured data, check out our tutorial on doing <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/tutorials/sql_qa">question/answering over SQL data</a>.</p><h3>Concepts</h3><p>A typical RAG application has two main components:</p><p><strong>Indexing</strong>: a pipeline for ingesting data from a source and indexing it. <em>This usually happens offline.</em></p><p><strong>Retrieval and generation</strong>: the actual RAG chain, which takes the user query at run time and retrieves the relevant data from the index, then passes that to the model.</p><p>The most common full sequence from raw data to answer looks like:</p><h3>Indexing</h3><ol><li><strong>Load</strong>: First we need to load our data. This is done with <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#document-loaders">Document Loaders</a>.</li><li><strong>Split</strong>: <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#text-splitters">Text splitters</a> break large Documents into smaller chunks. This is useful both for indexing data and for passing it in to a model, since large chunks are harder to search over and won&#39;t fit in a model&#39;s finite context window.</li><li><strong>Store</strong>: We need somewhere to store and index our splits, so that they can later be searched over. This is often done using a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#vector-stores">VectorStore</a> and <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#embedding-models">Embeddings</a> model.</li></ol><h3>Retrieval and generation</h3><ol><li><strong>Retrieve</strong>: Given a user input, relevant splits are retrieved from storage using a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#retrievers">Retriever</a>.</li><li><strong>Generate</strong>: A <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#chat-models">ChatModel</a> / <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#llms">LLM</a> produces an answer using a prompt that includes the question and the retrieved data</li></ol><h3>Setup</h3><h3>Jupyter Notebook</h3><p>This guide (and most of the other guides in the documentation) uses <a href="https://jupyter.org/">Jupyter notebooks</a> and assumes the reader is as well. Jupyter notebooks are perfect for learning how to work with LLM systems because oftentimes things can go wrong (unexpected output, API down, etc) and going through guides in an interactive environment is a great way to better understand them.</p><p>This and other tutorials are perhaps most conveniently run in a Jupyter notebook. See <a href="https://jupyter.org/install">here</a> for instructions on how to install.</p><h3>Installation</h3><p>This tutorial requires these langchain dependencies:</p><pre>!pip install --quiet --upgrade langchain langchain-community langchain-chroma</pre><h3>LangSmith</h3><p>Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls. As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent. The best way to do this is with LangSmith.</p><p>After you sign up at the link above, make sure to set your environment variables to start logging traces:</p><pre>!export LANGCHAIN_TRACING_V2=&quot;true&quot;<br>!export LANGCHAIN_API_KEY=&quot;....&quot;</pre><h3>Basic Initialization</h3><p>Below is a basic initialization, including the use of a directory to save the data locally.</p><pre>!pip install -qU langchain-huggingface</pre><pre>from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint</pre><pre>llm = HuggingFaceEndpoint(<br>    repo_id=&quot;microsoft/Phi-3.5-mini-instruct&quot;,<br>    task=&quot;text-generation&quot;,<br>    max_new_tokens=512,<br>    do_sample=False,<br>    repetition_penalty=1.03,<br>)</pre><pre>from langchain_huggingface import HuggingFaceEmbeddings</pre><pre>import bs4<br>from langchain import hub<br>from langchain_chroma import Chroma<br>from langchain_community.document_loaders import WebBaseLoader<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br>from langchain_text_splitters import RecursiveCharacterTextSplitter</pre><pre>embeddings = HuggingFaceEmbeddings()<br># Load, chunk and index the contents of the blog.<br>loader = WebBaseLoader(<br>    web_paths=(&quot;https://lilianweng.github.io/posts/2023-06-23-agent/&quot;,),<br>    bs_kwargs=dict(<br>        parse_only=bs4.SoupStrainer(<br>            class_=(&quot;post-content&quot;, &quot;post-title&quot;, &quot;post-header&quot;)<br>        )<br>    ),<br>)<br>docs = loader.load()<br><br>text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)<br>splits = text_splitter.split_documents(docs)<br>vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings)<br><br># Retrieve and generate using the relevant snippets of the blog.<br>retriever = vectorstore.as_retriever()<br>prompt = hub.pull(&quot;rlm/rag-prompt&quot;)<br><br><br>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br><br><br>rag_chain = (<br>    {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)<br><br>rag_chain.invoke(&quot;What is Task Decomposition?&quot;)<br>vectorstore.delete_collection()</pre><h3>Cleanup</h3><pre>vectorstore.delete_collection()</pre><p>Check out the <a href="https://smith.langchain.com/public/1c6ca97e-445b-4d00-84b4-c7befcbc59fe/r">LangSmith trace</a>.</p><h3>Detailed walkthrough</h3><p>Let’s go through the above code step-by-step to really understand what’s going on.</p><h3>1. Indexing: Load {#indexing-load}</h3><p>We need to first load the blog post contents. We can use <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#document-loaders">DocumentLoaders</a> for this, which are objects that load in data from a source and return a list of <a href="https://python.langchain.com/api_reference/core/documents/langchain_core.documents.base.Document.html">Documents</a>. A Document is an object with some page_content (str) and metadata (dict).</p><p>In this case we’ll use the <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/document_loaders/web_base">WebBaseLoader</a>, which uses urllib to load HTML from web URLs and BeautifulSoup to parse it to text. We can customize the HTML -&gt; text parsing by passing in parameters to the BeautifulSoup parser via bs_kwargs (see <a href="https://beautiful-soup-4.readthedocs.io/en/latest/#beautifulsoup">BeautifulSoup docs</a>). In this case only HTML tags with class “post-content”, “post-title”, or “post-header” are relevant, so we’ll remove all others.</p><p>In [58]:</p><pre>import bs4<br>from langchain_community.document_loaders import WebBaseLoader</pre><pre># Only keep post title, headers, and content from the full HTML.<br>bs4_strainer = bs4.SoupStrainer(class_=(&quot;post-title&quot;, &quot;post-header&quot;, &quot;post-content&quot;))<br>loader = WebBaseLoader(<br>    web_paths=(&quot;https://lilianweng.github.io/posts/2023-06-23-agent/&quot;,),<br>    bs_kwargs={&quot;parse_only&quot;: bs4_strainer},<br>)<br>docs = loader.load()</pre><pre>len(docs[0].page_content)</pre><pre>print(docs[0].page_content[:500])</pre><h3>Go deeper</h3><p>DocumentLoader: Object that loads data from a source as list of Documents.</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to#document-loaders">Docs</a>: Detailed documentation on how to use DocumentLoaders.</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/document_loaders/">Integrations</a>: 160+ integrations to choose from.</li><li><a href="https://python.langchain.com/api_reference/core/document_loaders/langchain_core.document_loaders.base.BaseLoader.html">Interface</a>: API reference for the base interface.</li></ul><h3>2. Indexing: Split {#indexing-split}</h3><p>Our loaded document is over 42k characters long. This is too long to fit in the context window of many models. Even for those models that could fit the full post in their context window, models can struggle to find information in very long inputs.</p><p>To handle this we’ll split the Document into chunks for embedding and vector storage. This should help us retrieve only the most relevant bits of the blog post at run time.</p><p>In this case we’ll split our documents into chunks of 1000 characters with 200 characters of overlap between chunks. The overlap helps mitigate the possibility of separating a statement from important context related to it. We use the <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/recursive_text_splitter">RecursiveCharacterTextSplitter</a>, which will recursively split the document using common separators like new lines until each chunk is the appropriate size. This is the recommended text splitter for generic text use cases.</p><p>We set add_start_index=True so that the character index at which each split Document starts within the initial Document is preserved as metadata attribute “start_index”.</p><pre>from langchain_text_splitters import RecursiveCharacterTextSplitter</pre><pre>text_splitter = RecursiveCharacterTextSplitter(<br>    chunk_size=1000, chunk_overlap=200, add_start_index=True<br>)<br>all_splits = text_splitter.split_documents(docs)</pre><pre>len(all_splits)</pre><pre>len(all_splits[0].page_content)</pre><pre>all_splits[10].metadata</pre><h3>Go deeper</h3><p>TextSplitter: Object that splits a list of Documents into smaller chunks. Subclass of DocumentTransformers.</p><ul><li>Learn more about splitting text using different methods by reading the <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to#text-splitters">how-to docs</a></li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/document_loaders/source_code">Code (py or js)</a></li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/document_loaders/grobid">Scientific papers</a></li><li><a href="https://python.langchain.com/api_reference/text_splitters/base/langchain_text_splitters.base.TextSplitter.html">Interface</a>: API reference for the base interface.</li></ul><p>DocumentTransformer: Object that performs a transformation on a list of Document objects.</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to#text-splitters">Docs</a>: Detailed documentation on how to use DocumentTransformers</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/document_transformers/">Integrations</a></li><li><a href="https://python.langchain.com/api_reference/core/documents/langchain_core.documents.transformers.BaseDocumentTransformer.html">Interface</a>: API reference for the base interface.</li></ul><h3>3. Indexing: Store {#indexing-store}</h3><p>Now we need to index our 66 text chunks so that we can search over them at runtime. The most common way to do this is to embed the contents of each document split and insert these embeddings into a vector database (or vector store). When we want to search over our splits, we take a text search query, embed it, and perform some sort of “similarity” search to identify the stored splits with the most similar embeddings to our query embedding. The simplest similarity measure is cosine similarity — we measure the cosine of the angle between each pair of embeddings (which are high dimensional vectors).</p><p>We can embed and store all of our document splits in a single command using the <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/vectorstores/chroma">Chroma</a> vector store and HuggingFaceEmbeddings.</p><pre>from langchain_chroma import Chroma</pre><pre>embeddings = HuggingFaceEmbeddings()<br>vectorstore = Chroma.from_documents(documents=all_splits, embedding=embeddings)</pre><h3>Go deeper</h3><p>Embeddings: Wrapper around a text embedding model, used for converting text to embeddings.</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/embed_text">Docs</a>: Detailed documentation on how to use embeddings.</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/text_embedding/">Integrations</a>: 30+ integrations to choose from.</li><li><a href="https://python.langchain.com/api_reference/core/embeddings/langchain_core.embeddings.Embeddings.html">Interface</a>: API reference for the base interface.</li></ul><p>VectorStore: Wrapper around a vector database, used for storing and querying embeddings.</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/vectorstores">Docs</a>: Detailed documentation on how to use vector stores.</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/vectorstores/">Integrations</a>: 40+ integrations to choose from.</li><li><a href="https://python.langchain.com/api_reference/core/vectorstores/langchain_core.vectorstores.VectorStore.html">Interface</a>: API reference for the base interface.</li></ul><p>This completes the <strong>Indexing</strong> portion of the pipeline. At this point we have a query-able vector store containing the chunked contents of our blog post. Given a user question, we should ideally be able to return the snippets of the blog post that answer the question.</p><h3>4. Retrieval and Generation: Retrieve {#retrieval-and-generation-retrieve}</h3><p>Now let’s write the actual application logic. We want to create a simple application that takes a user question, searches for documents relevant to that question, passes the retrieved documents and initial question to a model, and returns an answer.</p><p>First we need to define our logic for searching over documents. LangChain defines a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#retrievers/">Retriever</a> interface which wraps an index that can return relevant Documents given a string query.</p><p>The most common type of Retriever is the <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/vectorstore_retriever">VectorStoreRetriever</a>, which uses the similarity search capabilities of a vector store to facilitate retrieval. Any VectorStore can easily be turned into a Retriever with VectorStore.as_retriever():</p><pre>retriever = vectorstore.as_retriever(search_type=&quot;similarity&quot;, search_kwargs={&quot;k&quot;: 6})</pre><pre>retrieved_docs = retriever.invoke(&quot;What are the approaches to Task Decomposition?&quot;)</pre><pre>len(retrieved_docs)</pre><pre>print(retrieved_docs[0].page_content)</pre><h3>Go deeper</h3><p>Vector stores are commonly used for retrieval, but there are other ways to do retrieval, too.</p><p>Retriever: An object that returns Documents given a text query</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to#retrievers">Docs</a>: Further documentation on the interface and built-in retrieval techniques. Some of which include:</li><li>MultiQueryRetriever <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/MultiQueryRetriever">generates variants of the input question</a> to improve retrieval hit rate.</li><li>MultiVectorRetriever instead generates <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/multi_vector">variants of the embeddings</a>, also in order to improve retrieval hit rate.</li><li>Max marginal relevance selects for <a href="https://www.cs.cmu.edu/~jgc/publication/The_Use_MMR_Diversity_Based_LTMIR_1998.pdf">relevance and diversity</a> among the retrieved documents to avoid passing in duplicate context.</li><li>Documents can be filtered during vector store retrieval using metadata filters, such as with a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/self_query">Self Query Retriever</a>.</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/retrievers/">Integrations</a>: Integrations with retrieval services.</li><li><a href="https://python.langchain.com/api_reference/core/retrievers/langchain_core.retrievers.BaseRetriever.html">Interface</a>: API reference for the base interface.</li></ul><h3>5. Retrieval and Generation: Generate {#retrieval-and-generation-generate}</h3><p>Let’s put it all together into a chain that takes a question, retrieves relevant documents, constructs a prompt, passes that to a model, and parses the output.</p><p>We’ll use the gpt-4o-mini OpenAI chat model, but any LangChain LLM or ChatModel could be substituted in.</p><p>&lt;ChatModelTabs customVarName=”llm” hugggigFaceParams={model=&quot;microsoft/Phi-3.5-mini-instruct&quot;, temperature=0.2, max_tokens=1024} /&gt;</p><p>We’ll use a prompt for RAG that is checked into the LangChain prompt hub (<a href="https://smith.langchain.com/hub/rlm/rag-prompt">here</a>).</p><p>In [67]:</p><pre>from langchain import hub</pre><pre>prompt = hub.pull(&quot;rlm/rag-prompt&quot;)</pre><pre>example_messages = prompt.invoke(<br>    {&quot;context&quot;: &quot;filler context&quot;, &quot;question&quot;: &quot;filler question&quot;}<br>).to_messages()</pre><pre>example_message</pre><pre>print(example_messages[0].content)</pre><p>We’ll use the <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#langchain-expression-language-lcel">LCEL Runnable</a> protocol to define the chain, allowing us to</p><ul><li>pipe together components and functions in a transparent way</li><li>automatically trace our chain in LangSmith</li><li>get streaming, async, and batched calling out of the box.</li></ul><p>Here is the implementation:</p><pre>! huggingface-cli login --token &lt;hf_token&gt;  --add-to-git-credential</pre><pre>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import RunnablePassthrough<br></pre><pre>def format_docs(docs):<br>    return &quot;\n\n&quot;.join(doc.page_content for doc in docs)<br></pre><pre>rag_chain = (<br>    {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>    | llm<br>    | StrOutputParser()<br>)</pre><pre>for chunk in rag_chain.stream(&quot;What is Task Decomposition?&quot;):<br>    print(chunk, end=&quot;&quot;, flush=True</pre><p>Let’s dissect the LCEL to understand what’s going on.</p><p>First: each of these components (retriever, prompt, llm, etc.) are instances of <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#langchain-expression-language-lcel">Runnable</a>. This means that they implement the same methods-- such as sync and async .invoke, .stream, or .batch-- which makes them easier to connect together. They can be connected into a <a href="https://python.langchain.com/api_reference/core/runnables/langchain_core.runnables.base.RunnableSequence.html">RunnableSequence</a>-- another Runnable-- via the | operator.</p><p>LangChain will automatically cast certain objects to runnables when met with the | operator. Here, format_docs is cast to a <a href="https://python.langchain.com/api_reference/core/runnables/langchain_core.runnables.base.RunnableLambda.html">RunnableLambda</a>, and the dict with &quot;context&quot; and &quot;question&quot; is cast to a <a href="https://python.langchain.com/api_reference/core/runnables/langchain_core.runnables.base.RunnableParallel.html">RunnableParallel</a>. The details are less important than the bigger point, which is that each object is a Runnable.</p><p>Let’s trace how the input question flows through the above runnables.</p><p>As we’ve seen above, the input to prompt is expected to be a dict with keys &quot;context&quot; and &quot;question&quot;. So the first element of this chain builds runnables that will calculate both of these from the input question:</p><ul><li>retriever | format_docs passes the question through the retriever, generating <a href="https://python.langchain.com/api_reference/core/documents/langchain_core.documents.base.Document.html">Document</a> objects, and then to format_docs to generate strings;</li><li>RunnablePassthrough() passes through the input question unchanged.</li></ul><p>That is, if you constructed</p><pre>chain = (<br>    {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>    | prompt<br>)</pre><p>Then chain.invoke(question) would build a formatted prompt, ready for inference. (Note: when developing with LCEL, it can be practical to test with sub-chains like this.)</p><p>The last steps of the chain are llm, which runs the inference, and StrOutputParser(), which just plucks the string content out of the LLM&#39;s output message.</p><p>You can analyze the individual steps of this chain via its <a href="https://smith.langchain.com/public/1799e8db-8a6d-4eb2-84d5-46e8d7d5a99b/r">LangSmith trace</a>.</p><h3>Built-in chains</h3><p>If preferred, LangChain includes convenience functions that implement the above LCEL. We compose two functions:</p><ul><li><a href="https://python.langchain.com/api_reference/langchain/chains/langchain.chains.combine_documents.stuff.create_stuff_documents_chain.html">create_stuff_documents_chain</a> specifies how retrieved context is fed into a prompt and LLM. In this case, we will “stuff” the contents into the prompt — i.e., we will include all retrieved context without any summarization or other processing. It largely implements our above rag_chain, with input keys context and input-- it generates an answer using retrieved context and query.</li><li><a href="https://python.langchain.com/api_reference/langchain/chains/langchain.chains.retrieval.create_retrieval_chain.html">create_retrieval_chain</a> adds the retrieval step and propagates the retrieved context through the chain, providing it alongside the final answer. It has input key input, and includes input, context, and answer in its output.</li></ul><p>In [71]:</p><pre>from langchain.chains import create_retrieval_chain<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br>from langchain_core.prompts import ChatPromptTemplate</pre><pre>system_prompt = (<br>    &quot;You are an assistant for question-answering tasks. &quot;<br>    &quot;Use the following pieces of retrieved context to answer &quot;<br>    &quot;the question. If you don&#39;t know the answer, say that you &quot;<br>    &quot;don&#39;t know. Use three sentences maximum and keep the &quot;<br>    &quot;answer concise.&quot;<br>    &quot;\n\n&quot;<br>    &quot;{context}&quot;<br>)</pre><pre>prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, system_prompt),<br>        (&quot;human&quot;, &quot;{input}&quot;),<br>    ]<br>)<br></pre><pre>question_answer_chain = create_stuff_documents_chain(llm, prompt)<br>rag_chain = create_retrieval_chain(retriever, question_answer_chain)</pre><pre>response = rag_chain.invoke({&quot;input&quot;: &quot;What is Task Decomposition?&quot;})<br>print(response[&quot;answer&quot;])</pre><h4>Returning sources</h4><p>Often in Q&amp;A applications it’s important to show users the sources that were used to generate the answer. LangChain’s built-in create_retrieval_chain will propagate retrieved source documents through to the output in the &quot;context&quot; key:</p><p>In [72]:</p><pre>for document in response[&quot;context&quot;]:<br>    print(document)<br>    print()</pre><h3>Go deeper</h3><h4>Choosing a model</h4><p>ChatModel: An LLM-backed chat model. Takes in a sequence of messages and returns a message.</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to#chat-models">Docs</a></li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/chat/">Integrations</a>: 25+ integrations to choose from.</li><li><a href="https://python.langchain.com/api_reference/core/language_models/langchain_core.language_models.chat_models.BaseChatModel.html">Interface</a>: API reference for the base interface.</li></ul><p>LLM: A text-in-text-out LLM. Takes in a string and returns a string.</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to#llms">Docs</a></li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/integrations/llms">Integrations</a>: 75+ integrations to choose from.</li><li><a href="https://python.langchain.com/api_reference/core/language_models/langchain_core.language_models.llms.BaseLLM.html">Interface</a>: API reference for the base interface.</li></ul><p>See a guide on RAG with locally-running models <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/tutorials/local_rag">here</a>.</p><h4>Customizing the prompt</h4><p>As shown above, we can load prompts (e.g., <a href="https://smith.langchain.com/hub/rlm/rag-prompt">this RAG prompt</a>) from the prompt hub. The prompt can also be easily customized:</p><p>In [73]:</p><pre>from langchain_core.prompts import PromptTemplate</pre><pre>template = &quot;&quot;&quot;Use the following pieces of context to answer the question at the end.<br>If you don&#39;t know the answer, just say that you don&#39;t know, don&#39;t try to make up an answer.<br>Use three sentences maximum and keep the answer as concise as possible.<br>Always say &quot;thanks for asking!&quot; at the end of the answer.</pre><pre>{context}</pre><pre>Question: {question}</pre><pre>Helpful Answer:&quot;&quot;&quot;<br>custom_rag_prompt = PromptTemplate.from_template(template)</pre><pre>rag_chain = (<br>    {&quot;context&quot;: retriever | format_docs, &quot;question&quot;: RunnablePassthrough()}<br>    | custom_rag_prompt<br>    | llm<br>    | StrOutputParser()<br>)</pre><pre>rag_chain.invoke(&quot;What is Task Decomposition?&quot;)</pre><p>Out[73]:</p><pre>&#39;\n{\n  &quot;id&quot;: &quot;decompose_task&quot;,\n  &quot;reason&quot;: &quot;Task decomposition involves breaking down a complex task into smaller, more manageable subtasks, facilitating easier processing and understanding.&quot;\n}\nthanks for asking!\n\n\nIn the context provided, task decomposition within Tree of Thoughts (Yao et al., 2023) methodology involves dissecting a given problem into multiple sub-steps, subsequently generating numerous potential solutions at each stage. This process forms a hierarchical structure similar to a tree, wherein each node represents a distinct thought or action required to progress towards the ultimate goal.\n\nThis decomposition can occur through various means:\n\n1. By leveraging Large Language Models (LLMs) via simple prompting techniques such as &quot;Outline the steps required to accomplish XYZ,&quot; which instructs the model to generate a structured breakdown of the task.\n\n2. Utilizing task-specific directives, for instance, &quot;Devise a plot structure for a novel,&quot; which guides the LLM to decompose the task of narrative creation into identifiable components such as character development, setting establishment, conflict generation, etc.\n\n3. Through human intervention, wherein individuals manually divide complex tasks into simpler ones, providing a nuanced perspective that may not be readily inferred by automated systems.\n\nFollowing task decomposition, the ensuing phase involves the strategic allocation of these tasks to domain experts, referred to as \&#39;expert models\&#39;. Each expert model embodies proficiency in a specific area relevant to its designated task. For example, one model might excel in data analysis, another in creative writing, and so forth.\n\nThe execution of these tasks follows a systematic approach. Each expert model undertakes its assigned task, processes the necessary input, and records the resulting output. These outputs could range from numerical analyses, written content, processed images, among others, depending upon the nature of the task assigned.\n\nOverall, task decomposition serves as a crucial initial step in the Tree of Thoughts methodology. It ensures that complex problems are broken down into manageable parts, promoting efficiency, accuracy, and comprehensive understanding throughout the subsequent stages of processing and decision-making.\n\nthanks for asking!\n\n\nForestry project involving tree planting, management, and preservation activities requires&#39;</pre><h3>Check out the</h3><p><a href="https://smith.langchain.com/public/da23c4d8-3b33-47fd-84df-a3a582eedf84/r">LangSmith trace</a></p><h3>Next steps</h3><p>We’ve covered the steps to build a basic Q&amp;A app over data:</p><ul><li>Loading data with a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#document-loaders">Document Loader</a></li><li>Chunking the indexed data with a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#text-splitters">Text Splitter</a> to make it more easily usable by a model</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#embedding-models">Embedding the data</a> and storing the data in a <a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/vectorstores">vectorstore</a></li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts#retrievers">Retrieving</a> the previously stored chunks in response to incoming questions</li><li>Generating an answer using the retrieved chunks as context</li></ul><p>There’s plenty of features, integrations, and extensions to explore in each of the above sections. Along from the <strong>Go deeper</strong> sources mentioned above, good next steps include:</p><ul><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/qa_sources">Return sources</a>: Learn how to return source documents</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/streaming">Streaming</a>: Learn how to stream outputs and intermediate steps</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/how_to/message_history">Add chat history</a>: Learn how to add chat history to your app</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/concepts/#retrieval">Retrieval conceptual guide</a>: A high-level overview of specific retrieval techniques</li><li><a href="https://github.com/himanshushukla12/langchain-tutorials/blob/ea62ecc87812b8086d650a8ba7df48e9b1dc7e1e/langchain-HF-local-RAG/docs/tutorials/local_rag">Build a local RAG application</a>: Create an app similar to the one above using all local components</li></ul><p>For complete project visit my github: <a href="https://github.com/himanshushukla12/langchain-tutorials.git">https://github.com/himanshushukla12/langchain-tutorials.git</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=009ef91cee8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>