<?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 Somnath Muthukumaran on Medium]]></title>
        <description><![CDATA[Stories by Somnath Muthukumaran on Medium]]></description>
        <link>https://medium.com/@somnath.muthukumaran?source=rss-190b44b30f19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*l00yOgfUf7WbT_29</url>
            <title>Stories by Somnath Muthukumaran on Medium</title>
            <link>https://medium.com/@somnath.muthukumaran?source=rss-190b44b30f19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:52:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@somnath.muthukumaran/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[Your AI Agents Will Have to Negotiate: Why Developers Should Learn Game Theory]]></title>
            <link>https://medium.com/@somnath.muthukumaran/your-ai-agents-will-have-to-negotiate-why-developers-should-learn-game-theory-7459341e4c44?source=rss-190b44b30f19------2</link>
            <guid isPermaLink="false">https://medium.com/p/7459341e4c44</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agent-orchestration]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Somnath Muthukumaran]]></dc:creator>
            <pubDate>Sun, 22 Nov 2026 13:40:47 GMT</pubDate>
            <atom:updated>2026-11-22T13:40:47.634Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Why strategic thinking might matter more than we realize in the age of autonomous agents.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbsEVRH9OxZ7zPPPXJAM5Q@2x.png" /></figure><h3>It started with a thought about AI agents</h3><p>Agent orchestration sounds pretty cool. We have agents calling tools, delegating tasks, making decisions, and executing entire workflows autonomously.</p><p>But while exploring these systems, something struck me.</p><p>Underneath all those abstractions, isn’t agent orchestration basically one giant decision tree?</p><p>Not necessarily a fixed one, since LLMs make dynamic decisions, but a tree of possible actions and outcomes.</p><p>And most of that tree exists within the boundaries of our business. We define the objectives, tools, constraints, and what success looks like.</p><p>But what happens when our agent needs to interact with another company’s AI agent?</p><p>An agent with its own objectives, constraints, and definition of success.</p><p>That’s where things started getting interesting for me.</p><h3>When two decision trees meet</h3><p>Imagine our business has an AI agent that handles purchasing, while another company has an agent that handles sales.</p><p>Our agent wants to buy a service for the lowest possible price. Their agent wants to sell it for the highest profitable price.</p><p>Suppose we’re willing to pay $1,000, and the seller is willing to accept anything above $800.</p><p>There’s clearly room for a deal.</p><p>But should our agent offer $800, $850, or $900?</p><p>If we offer $800, the seller might reject it, hoping we’ll pay more. If they demand $1,000, we might walk away, thinking they’ll eventually lower their price.</p><p>Neither side necessarily knows the other’s limits.</p><p>And here’s what caught my attention: <strong>our best decision depends on what the other agent might decide.</strong></p><p>We’re no longer optimizing a workflow we completely control. We’re making decisions in an environment where another independent system is also trying to achieve its goals.</p><p>How do we even approach a problem like that?</p><p>That’s what led me to game theory.</p><h3>Game theory isn’t really about games</h3><p>Initially, I thought game theory was just another mathematical topic you might encounter in a LeetCode problem, solve, and forget.</p><p>I never really understood its relevance to software development. And from conversations with fellow developers, I got the impression I wasn’t alone.</p><p>But the underlying idea is surprisingly simple.</p><p>Game theory studies situations where the outcome of your decision depends on decisions made by others.</p><p>One concept that caught my attention was <strong>Nash equilibrium</strong>.</p><p>Imagine two competing businesses deciding whether to cooperate or aggressively compete. Both could benefit from cooperation, but each has an incentive to take advantage of the other.</p><p>If both act selfishly, they might end up worse off than if they’d cooperated.</p><p>This is the classic <em>Prisoner’s Dilemma</em>.</p><p>Interestingly, both choosing to act selfishly can still be a Nash equilibrium: neither can improve its outcome by changing its decision alone while the other keeps doing the same thing.</p><p>So an equilibrium doesn’t necessarily mean everyone wins or that the outcome is fair. It means nobody can benefit by unilaterally changing strategy.</p><p>The original business negotiation is more complicated because offers happen over time and both parties have private information. But both situations raise the same fundamental question: how should we make decisions when other participants have their own incentives?</p><p>And the more I thought about it, the more relevant it seemed to AI agents.</p><h3>Why should developers care?</h3><p>We’re used to building software that follows rules, processes inputs, and produces outputs.</p><p>But increasingly, we’re exploring software that makes decisions and interacts with other autonomous systems.</p><p>Think about an AI purchasing agent negotiating with a supplier. If the supplier discovers that our agent always accepts offers below $950, what’s stopping it from consistently offering $949?</p><p>Our perfectly functioning algorithm has become predictable — and potentially exploitable.</p><p>Or consider two automated pricing agents competing in the same marketplace. A price change by one can trigger a response from the other, which triggers another response. Suddenly, the behavior of the entire system depends on their interaction, not just the logic inside either agent.</p><p>These are strategic problems.</p><p>Game theory won’t magically solve every one of them. Real AI agents aren’t perfectly rational, and their decisions can be inconsistent or manipulated.</p><p>But it gives developers a framework for thinking about incentives, uncertainty, competition, and cooperation.</p><p>And that’s something I think we’re going to need more of as AI systems become increasingly autonomous.</p><h3>Here’s what I’m still curious about</h3><p>Learning about Nash equilibrium changed how I looked at these problems, but it left me with a bigger question.</p><p>Understanding what an equilibrium <em>is</em> seems manageable.</p><p><strong>But how do you actually find one?</strong></p><p>For a simple problem with two possible decisions, we can work through the outcomes manually.</p><p>What happens when there are hundreds of decisions, hidden information, and an opponent who is constantly adapting?</p><p>How does a computer figure out which strategy to follow without knowing exactly what the other side will do?</p><p>That question sent me down a rabbit hole I hadn’t expected.</p><p>And strangely enough, it led me to a game involving just three playing cards.</p><p><em>That’s where things get really interesting.</em></p><p><strong>To be continued…</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7459341e4c44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Code Is Not Your Greatest Asset Anymore]]></title>
            <link>https://medium.com/@somnath.muthukumaran/your-code-is-not-your-greatest-asset-anymore-8dd6bb3e16df?source=rss-190b44b30f19------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd6bb3e16df</guid>
            <category><![CDATA[future-engineer]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Somnath Muthukumaran]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 14:05:32 GMT</pubDate>
            <atom:updated>2026-08-25T14:05:32.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OBjZHC8ypU7LA9Qw7z-pyg.png" /></figure><h3>Beyond Syntax: The Skill That Will Define Engineers in the AI Era</h3><p>There was a time when being a good software engineer was closely associated with how well you could write code.</p><p>Could you solve a problem quickly? Could you remember the right syntax? Could you implement an algorithm? Could you write an efficient query? Could you understand an unfamiliar codebase?</p><p>Those things still matter.</p><p>They are the baseline.</p><p>But lately, I’ve been thinking about how much the definition of a strong engineer is changing.</p><p>Today, I can describe a reasonably complex feature to an AI assistant and get a significant portion of the implementation within seconds. Controllers, services, tests, queries, configurations, and boilerplate that once took hours can now be generated, refined, and iterated on much faster.</p><p>And that raises a question I keep coming back to:</p><blockquote><strong><em>If AI can increasingly write our code, what actually makes someone a good engineer?</em></strong></blockquote><p>I don’t think the answer is simply <em>writing more code</em> or <em>knowing more syntax</em>.</p><p>I think the answer increasingly lies in something much harder to automate:</p><p><strong>The ability to build an accurate mental model of a system.</strong></p><p>The ability to understand not just what the code does today, but what happens to the system when that code enters production. How it interacts with existing services. How it behaves under failure. How it scales. How it is debugged. How it evolves over the next one, two, or five years.</p><p>That is the shift I have been trying to understand in my own engineering journey.</p><p>And it is why I believe the most important engineering work increasingly happens <strong>beyond syntax</strong>.</p><h3>But Then, Why Do Fundamentals Still Matter?</h3><p>This shift also made me think differently about something engineers debate constantly.</p><p>If AI can write code, why do companies still care about Data Structures and Algorithms?</p><p>Why should a developer learn trees, graphs, complexity analysis, or database internals when AI can generate an implementation?</p><p>I don’t think the purpose of learning fundamentals was ever just to reproduce them in an interview.</p><p>The real value is in the mental models they create.</p><p>Learning about a tree is not valuable only because you might be asked to traverse one.</p><p>At some point, that model becomes useful when you encounter hierarchical data, file systems, organizational structures, indexes, routing structures, dependency trees, and many other systems.</p><p>Learning Big-O notation is not just about annotating a function with O(n log n).</p><p>It teaches you to instinctively ask:</p><ul><li>What happens when this data grows 100 times?</li><li>Which operation becomes expensive?</li><li>Where is the bottleneck?</li><li>Which assumption stops being true at scale?</li><li>Is this solution still reasonable when the workload changes?</li></ul><p>The knowledge slowly becomes intuition.</p><p>You stop consciously asking:</p><blockquote><strong><em>“Which algorithm did I learn for this?”</em></strong></blockquote><p>And start asking:</p><blockquote><strong><em>“How will this behave when the system grows?”</em></strong></blockquote><p>That, to me, is the real value of fundamentals.</p><p>They are not just tools for writing code.</p><p>They are tools for <strong>thinking about systems</strong>.</p><h3>Syntax Is the Baseline. Mental Modeling Is the Differentiator.</h3><p>Writing clean code is important.</p><p>Being able to read and understand someone else’s code is important.</p><p>Understanding your programming language, framework, and database is important.</p><p>But those things alone do not define a great engineer anymore.</p><p>They are increasingly the starting point.</p><p>The engineers I admire most are not necessarily the ones who can type the fastest or remember the most APIs.</p><p>They are often the ones who can build a surprisingly complete picture of a system in their head.</p><p>They can look at a feature request and see beyond the immediate task.</p><p>They don’t just see:</p><blockquote><strong><em>“Add an endpoint.”</em></strong></blockquote><p>Instead, they begin building a picture of what that change means for the existing system. Where does the request enter? Which services will it touch, and where does the state live? What happens if traffic suddenly increases or a downstream dependency becomes slow — or fails entirely?</p><p>They think beyond the happy path. Will retries help, or could they make an outage worse? How will we trace this request across the system? When something goes wrong in production, what information will support actually have? What additional infrastructure will this require, and how will that affect cost?</p><p>And then comes the question that is often easiest to ignore when focused on the immediate requirement:</p><blockquote><strong><em>Will this design still make sense in two years?</em></strong></blockquote><p>The difference is subtle, but important.</p><p>One engineer sees a <strong>task</strong>. Another sees the consequences of that task entering a <strong>living system</strong>.</p><p>Every production system has a past, a present, and a future. It carries decisions made years ago, technical debt accumulated along the way, assumptions that may no longer be true, undocumented failure modes, and infrastructure constraints. And regardless of how carefully it was designed, it will eventually need to change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhrdwxCMxNNUbecpAOMQ0A.png" /></figure><p>A strong engineer doesn’t just ask whether a feature works today. They try to understand what changes in the system because that feature now exists — and what those changes might mean tomorrow.</p><p>For me, this is becoming a much better measure of engineering maturity than simply measuring how much code someone can produce.</p><h3>A Mental Model for Looking at Systems</h3><p>When I try to evaluate a backend or distributed system, I find it useful to organize my thinking into a few connected verticals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyOaM-26zLNAMc9gHJ8VCA.png" /></figure><p>These aren’t separate checklists.</p><p>They constantly affect one another.</p><p>A caching decision affects scalability, performance, consistency, observability, and sometimes security.</p><p>A retry mechanism improves resilience but can increase load during an outage.</p><p>A database decision can influence latency, infrastructure cost, and operational complexity for years.</p><p>That interconnectedness is exactly why mental modeling matters.</p><h3>1. Clean Architecture and Resilience</h3><p>I think clean architecture is often misunderstood as folder structures, interfaces, and dependency injection.</p><p>Those things can be useful.</p><p>But the bigger question is:</p><blockquote><strong><em>Can this system continue to evolve without every change becoming dangerous?</em></strong></blockquote><p>Frameworks change. Databases change. Message brokers change. Business requirements definitely change.</p><p>The system needs enough separation that changes at the boundaries don’t constantly force changes everywhere else.</p><p>But architecture is only half the story.</p><p>Real systems fail.</p><p>Networks timeout.</p><p>Dependencies become unavailable.</p><p>Messages get delivered twice.</p><p>Deployments go wrong.</p><p>A service can work perfectly under normal conditions and still be poorly engineered if it collapses the moment something unexpected happens.</p><p>That is where resilience becomes part of the design:</p><ul><li>Timeouts</li><li>Retries with appropriate backoff</li><li>Circuit breakers</li><li>Bulkheads</li><li>Idempotency</li><li>Graceful degradation</li><li>Failure isolation</li></ul><p>The goal isn’t to eliminate failure.</p><p>It is to stop failure from becoming catastrophic.</p><h3>The Evolution Question</h3><p>One of the hardest engineering decisions is knowing how much architecture you need <strong>right now</strong>.</p><p>An MVP doesn’t need the architecture of a system handling millions of requests per second.</p><p>But it also shouldn’t be built in a way that guarantees a complete rewrite six months later.</p><p>The skill is understanding the likely direction of the system and making appropriate trade-offs for its current stage.</p><p>Not overengineering.</p><p>Not underengineering.</p><p><strong>Engineering for the next realistic version of the problem.</strong></p><h3>2. Scalability and Data Systems</h3><p>Scalability is usually described as the ability to handle more users.</p><p>But I think a more useful question is:</p><blockquote><strong><em>What exactly stops working when growth happens?</em></strong></blockquote><p>CPU?</p><p>Memory?</p><p>Database connections?</p><p>Disk I/O?</p><p>Network bandwidth?</p><p>A particular query?</p><p>A downstream dependency?</p><p>A queue?</p><p>A single machine?</p><p>Every system has a bottleneck somewhere.</p><p>Scaling is largely the process of identifying where that bottleneck is and understanding which constraint needs to move next.</p><p>This requires thinking about the entire data lifecycle.</p><p>How is data created?</p><p>How often is it read?</p><p>How frequently is it updated?</p><p>How long does it need to remain immediately available?</p><p>Does old data need the same latency guarantees?</p><p>Should everything remain in the primary database forever?</p><p>Eventually, those questions lead to techniques such as:</p><ul><li>Indexing</li><li>Caching</li><li>Replication</li><li>Partitioning</li><li>Archiving</li><li>Horizontal scaling</li><li>Sharding</li></ul><p>But knowing these words isn’t the same as understanding them.</p><p>The important skill is knowing <strong>when the current architecture is no longer enough</strong>.</p><p>Not every database needs sharding.</p><p>In fact, introducing distributed complexity too early can create more problems than it solves.</p><p>The real engineering skill is recognizing the signals that tell you when the existing approach is reaching its limits.</p><h3>3. Observability and Supportability</h3><p>This is one of the areas that has increasingly changed how I think about backend engineering.</p><p>For a long time, I thought monitoring mostly meant dashboards showing CPU and memory.</p><p>Those metrics are useful.</p><p>But they don’t always answer the questions we actually need answered when something goes wrong.</p><p>A machine can have healthy CPU usage while customers are experiencing a terrible product experience.</p><p>So the questions need to move closer to actual system behavior:</p><ul><li>How many requests are we receiving per second?</li><li>Which endpoints receive the most traffic?</li><li>Which endpoints are slow?</li><li>What does <strong>P95</strong> and <strong>P99</strong> latency look like?</li><li>Where is a request spending its time?</li><li>Which downstream dependency is introducing latency?</li><li>Are retries creating additional traffic?</li><li>Are error rates increasing?</li><li>Is a queue growing faster than it is being consumed?</li><li>Which workflow or customer is actually affected?</li></ul><p>This is why I increasingly think of observability as part of the system itself.</p><blockquote><strong><em>If I cannot understand what my system is doing in production, I don’t fully understand my system.</em></strong></blockquote><h3>Logs, Metrics, and Traces</h3><p>Each telemetry signal answers a different question.</p><p><strong>Metrics</strong> tell us that something is happening.</p><blockquote><strong><em>The error rate increased from 1% to 8%.</em></strong></blockquote><p><strong>Logs</strong> help explain what happened.</p><blockquote><strong><em>The request failed because a downstream dependency timed out.</em></strong></blockquote><p><strong>Traces</strong> help us understand where it happened.</p><blockquote><strong><em>Most of the request time was spent waiting on another service.</em></strong></blockquote><p>The real power comes when they are connected.</p><p>A correlation ID or trace ID should allow us to follow a request across synchronous and asynchronous boundaries.</p><p>That changes debugging from:</p><blockquote><strong><em>“Can someone search through the logs?”</em></strong></blockquote><p>to:</p><blockquote><strong><em>“Show me exactly what happened to this request.”</em></strong></blockquote><p>That difference can turn hours of investigation into minutes.</p><p>And I believe one of the strongest indicators of engineering maturity is building systems that can <strong>explain themselves when something goes wrong</strong>.</p><h3>4. Performance Engineering and Cloud Infrastructure</h3><p>When a system becomes slow, the answer isn’t automatically:</p><blockquote><strong><em>“Let’s add more servers.”</em></strong></blockquote><p>First, we need to understand where the time is actually going.</p><p>Is the system CPU-bound?</p><p>Is it waiting for I/O?</p><p>Is the database query slow?</p><p>Are threads blocked?</p><p>Is garbage collection creating pauses?</p><p>Is the connection pool exhausted?</p><p>Is a downstream service slow?</p><p>Is an unbounded queue creating memory pressure?</p><p>Performance engineering starts with measurement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEpFVPM8V_cw6kcIV6Sxuw.jpeg" /></figure><p>Cloud infrastructure adds another important dimension: cost.<br>It is easy to make a system work by continuously increasing instance sizes, memory allocations, and replica counts.</p><p>The harder question is whether the workload actually requires those resources.</p><p>That involves understanding:</p><ul><li>CPU and memory utilization</li><li>Container limits and requests</li><li>Concurrency</li><li>Threading</li><li>Connection pools</li><li>Memory leaks</li><li>Queue growth</li><li>Autoscaling behavior</li><li>Latency versus infrastructure cost</li></ul><p>Performance engineering is ultimately about understanding how your software behaves when it meets real workloads and real hardware.</p><h3>5. Proactive Security</h3><p>Security should not begin when someone sends a security checklist before production.</p><p>It starts at every boundary.</p><p>Every request should trigger a few basic questions:</p><p>Who is making this request?</p><p>Are they authenticated?</p><p>Are they authorized to perform this action?</p><p>Is the input valid?</p><p>Where did the credential come from?</p><p>How long is it valid?</p><p>What happens if it is compromised?</p><p>A useful mindset here is zero trust.</p><p>Not paranoia.</p><p>Just avoiding assumptions that something should automatically be trusted because it came from an internal network or another service.</p><p>That includes:</p><ul><li>Authentication</li><li>Authorization</li><li>Input validation</li><li>RBAC and permission boundaries</li><li>Secret management</li><li>Token lifecycle management</li><li>Auditability</li><li>Least-privilege access</li></ul><p>Security maturity doesn’t mean knowing every possible exploit.</p><p>It means developing the habit of asking:</p><blockquote><strong><em>What assumptions am I making about trust here?</em></strong></blockquote><h3>Stop Asking “What Do I Know?” and Start Asking “Where Am I?”</h3><p>One of the biggest problems with technical growth is that the field is too large.</p><p>You start learning databases and discover replication.</p><p>Then distributed databases.</p><p>Then consensus.</p><p>Then storage engines.</p><p>Then kernel scheduling.</p><p>Then suddenly you feel like you know nothing.</p><p>I don’t think that is a useful way to measure yourself.</p><p>You don’t need to become an expert in every layer.</p><p>A backend engineer should understand databases deeply enough to make good architectural decisions without necessarily becoming a database engine developer.</p><p>A strong engineer isn’t someone who knows everything.</p><p>A strong engineer understands the boundaries of their knowledge and knows <strong>when deeper expertise is needed</strong>.</p><p>That is where I find the MoSCoW model useful.</p><h3>A Practical Framework for Self-Evaluation</h3><p>For each technical vertical, I find it useful to classify knowledge into four levels.</p><p>ClassificationMeaningExample: Data Systems<strong>Must Know</strong>Non-negotiable fundamentals required to build safe systems.ACID, foreign keys, indexing basics, query execution concepts.<strong>Should Know</strong>Practical knowledge needed for real production workloads.Composite indexes, connection pooling, deadlocks, replication lag.<strong>Could Know</strong>Advanced knowledge useful for specialized or high-scale problems.Partitioning strategies, sharding, distributed query optimization.<strong>Won’t Know — For Now</strong>Highly specialized knowledge outside the current scope.Storage engine internals and low-level disk optimization.</p><p>The important words are <strong>for now</strong>.</p><p>It doesn’t mean:</p><blockquote><strong><em>“I don’t need to know this.”</em></strong></blockquote><p>It means:</p><blockquote><strong><em>“This isn’t where my current learning investment has the highest return.”</em></strong></blockquote><p>That distinction matters.</p><p>Otherwise, it is easy to spend months learning highly specialized topics while ignoring gaps that affect your day-to-day engineering decisions.</p><h3>Your Engineering Profile Isn’t a Single Number</h3><p>I don’t think engineering capability should be represented by one score.</p><p>Someone might be strong in architecture but weak in observability.</p><p>Someone else might be exceptional at operating production systems but have limited experience designing data models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H7_RHIlIlmUTEFW5viwAAA.png" /></figure><p>A radar chart gives a more honest picture.</p><p>The goal is to understand your <strong>shape</strong>.</p><p>Where are your strengths?</p><p>Where are your blind spots?</p><p>Which area is becoming increasingly important for the engineer you want to become?</p><p>That turns vague ambition into deliberate growth.</p><p>Instead of saying:</p><blockquote><strong><em>“I want to become a better engineer.”</em></strong></blockquote><p>You can say:</p><blockquote><em>“My architecture and backend fundamentals are strong, but my understanding of production observability is behind. Over the next six months, I want to become capable of designing telemetry, understanding latency distributions, tracing requests, and reasoning about runtime behavior.”</em></blockquote><p>That is a direction.</p><h3>A Five-Level Scale for Honest Assessment</h3><p>I would score each vertical based on practical execution rather than theoretical familiarity.</p><h3>Level 1 — Awareness</h3><p>You understand the terminology and recognize the problem, but you would need significant guidance to solve it.</p><h3>Level 2 — Assisted Execution</h3><p>You can work with the concepts using documentation, examples, or guidance from more experienced engineers.</p><h3>Level 3 — Independent Execution</h3><p>You can identify common problems, design a reasonable solution, implement it, and support it in production.</p><h3>Level 4 — Design and Trade-offs</h3><p>You can evaluate multiple approaches and explain why one is appropriate for the current constraints.</p><h3>Level 5 — Strategic System Thinking</h3><p>You can anticipate second-order effects, guide technical decisions across teams, identify long-term risks, and help evolve systems over years.</p><p>The important point is that Level 5 isn’t about knowing more trivia.</p><p>It is about understanding <strong>consequences across time</strong>.</p><h3>The Mental Checklist I Want to Build</h3><p>The framework I ultimately want for myself isn’t a checklist that sits inside a documentation page.</p><p>I want it to become instinctive.</p><p>Infrastructure shouldn’t be something I think about only when deployment fails.</p><p>Observability shouldn’t begin only after production breaks.</p><p>Scalability shouldn’t become a conversation only after traffic increases.</p><p>Security shouldn’t be added just before release.</p><p>Testing shouldn’t be a final stage after implementation.</p><p>These things should naturally appear while thinking about a feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEpFVPM8V_cw6kcIV6Sxuw.jpeg" /></figure><p>The shift I am trying to make is from asking:</p><blockquote><strong><em>“How do I implement this feature?”</em></strong></blockquote><p>to asking:</p><blockquote><strong><em>“What happens to the system because this feature now exists?”</em></strong></blockquote><p>That one question changes the scope of engineering.</p><h3>Why AI Makes This More Important, Not Less</h3><p>This brings me back to the question that started this reflection.</p><p>AI makes implementation faster.</p><p>But faster implementation does not automatically lead to better decisions.</p><p>AI can suggest a retry mechanism. But someone still needs to recognize when retries might amplify an outage.</p><p>It can generate a caching layer. But someone needs to reason about consistency, invalidation, stale data, and memory pressure.</p><p>It can recommend an index. But someone needs to understand the query pattern and the cost of maintaining that index.</p><p>It can generate infrastructure configuration. But someone still needs to understand why the application is consuming memory faster than expected.</p><p>AI can produce code, but it does not automatically take responsibility for what that code does in production.</p><p>That is where the value of an engineer increasingly shifts.</p><p><strong>From typing code to evaluating consequences.</strong></p><p><strong>From memorizing syntax to understanding behavior.</strong></p><p><strong>From implementing isolated features to evolving living systems.</strong></p><p>Fundamentals still matter because they become the building blocks of intuition.</p><p>Over time, you stop consciously thinking:</p><blockquote><strong><em>“This is a graph problem.”</em></strong></blockquote><p>Instead, you begin to recognize dependencies, cycles, propagation paths, and relationships naturally.</p><p>You stop asking:</p><blockquote><strong><em>“Which algorithm should I use?”</em></strong></blockquote><p>And start asking:</p><blockquote><strong><em>“How will this system behave as it grows?”</em></strong></blockquote><p>That is the difference between memorizing concepts and developing engineering intuition.</p><h3>Beyond Syntax</h3><p>I don’t believe AI makes engineers less valuable.</p><p>I think it changes where engineering value comes from.</p><p>Writing clean code will remain important. Understanding existing code will remain important. Knowing the fundamentals will remain important.</p><p>But increasingly, these are the entry points — not the finish line.</p><p>The engineers who stand out will be the ones who can maintain a coherent mental model across architecture, data, infrastructure, performance, observability, resilience, and security.</p><p>They look beyond the immediate implementation. They understand that a feature does not end when the pull request is merged. It enters a living system, where it creates load, state, failure modes, operational responsibilities, and future constraints.</p><p>Someone has to understand all of that.</p><p>For me, that is increasingly what being a good engineer means.</p><blockquote><strong><em>Your code may no longer be your greatest asset.<br>Your ability to understand what that code will do to a system — and what that system may become — is.</em></strong></blockquote><p>That is the skill I believe will increasingly define engineers in the AI era.</p><p>Not just writing the code.</p><p><strong>Understanding the consequences of it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd6bb3e16df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dashboards Are Not a Frontend Feature. They’re an Organization’s Decision Engine.]]></title>
            <link>https://medium.com/@somnath.muthukumaran/dashboards-are-not-a-frontend-feature-theyre-an-organization-s-decision-engine-e664209e90ea?source=rss-190b44b30f19------2</link>
            <guid isPermaLink="false">https://medium.com/p/e664209e90ea</guid>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[organisation-development]]></category>
            <category><![CDATA[decision-making]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Somnath Muthukumaran]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 09:56:36 GMT</pubDate>
            <atom:updated>2026-07-08T09:56:36.874Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bqfWN0lrD6etxyH-lRcGVA.jpeg" /></figure><h3>Behind every chart is a decision. Behind every decision is a business outcome.</h3><p>When developers hear the word <em>dashboard</em>, most immediately think about charts, KPIs, graphs, APIs, and frontend components.</p><p>That’s a technical perspective.</p><p>Senior engineers should see something entirely different: <strong>a dashboard isn’t a collection of charts — it’s a system that enables people to make decisions.</strong></p><p>Every important decision inside an organization begins with three simple questions:</p><blockquote><strong><em>Where are we? What went wrong? What are we going to do about it?</em></strong></blockquote><p>If a dashboard can’t answer those questions, it’s probably just a reporting screen.</p><h3>Every Organization Runs on Decisions</h3><p>Think about any meeting you’ve attended — a sprint review, a quarterly business review, an operational incident, a sales meeting, a product roadmap discussion.</p><p>Very few decisions start with opinions. Most begin with data.</p><p>Someone opens a dashboard. Someone points to a metric. Someone asks why a number changed. Then the discussion begins.</p><p>Without realizing it, dashboards become the source of truth that guides the direction of product, engineering, operations, sales, customer success, and leadership. They’re not simply visualizations — <strong>they’re the foundation upon which organizations decide what to build next.</strong></p><h3>A Senior Developer Should Think Beyond Code</h3><p>As engineers, we’re trained to solve technical problems:</p><ul><li>Which database should we use?</li><li>How do we optimize this query?</li><li>Which caching strategy is best?</li><li>Should this endpoint be real-time?</li></ul><p>These questions matter. But as your career progresses, the scope of your thinking should expand.</p><p>A senior developer shouldn’t only ask <em>“How do we build this?”</em> They should also ask:</p><ul><li>Why does this dashboard exist?</li><li>Who will use it?</li><li>What decision will this metric influence?</li><li>What happens if this number is inaccurate?</li><li>What data are we not collecting today that we’ll wish we had six months from now?</li></ul><p><strong>This is where engineering begins to influence business.</strong></p><h3>Great Dashboards Are Never Designed by One Team</h3><p>A common misconception is that dashboards belong to a single team. They don’t.</p><p>A meaningful dashboard is the result of collective thinking:</p><ul><li><strong>Engineering</strong> understands the data</li><li><strong>Product</strong> understands the business goals</li><li><strong>Design</strong> understands usability and information hierarchy</li><li><strong>Customer Success</strong> understands customer pain points</li><li><strong>Sales</strong> understands revenue and pipeline</li><li><strong>Operations</strong> understands system health</li><li><strong>Leadership</strong> understands strategy</li></ul><p>Every stakeholder sees the product from a different angle. A dashboard becomes valuable only when those perspectives come together.</p><p>As senior developers, we often sit at the intersection of these conversations. That means we have a responsibility not just to implement requirements, but to <strong>ask better questions that help shape them.</strong></p><h3>Different Decisions Require Different Dashboards</h3><p>There is no such thing as a universal dashboard. Every dashboard exists to help someone make a specific decision.</p><h3>User Behavior Analytics Dashboard</h3><p>Helps product teams understand how people actually use the application.</p><ul><li>Which features are driving engagement?</li><li>Where do users abandon a workflow?</li><li>Which journeys have friction?</li><li>Which features improve retention — and which provide little or no value?</li></ul><p>The goal isn’t measuring clicks. <strong>The goal is building a product users want to keep using.</strong></p><h3>Sales Dashboard</h3><p>Answers questions that determine business growth.</p><ul><li>Are we on target this month?</li><li>Which regions are underperforming?</li><li>Where are we losing opportunities?</li><li>Which products generate the most revenue?</li><li>How accurate are our forecasts?</li></ul><p>Every improvement here directly impacts business outcomes.</p><h3>Team Performance Dashboard</h3><p>People often think leaderboards exist to rank engineers or sales reps. That’s the wrong objective.</p><p>A good performance dashboard identifies opportunities:</p><ul><li>Which teams are consistently successful?</li><li>What practices should we replicate?</li><li>Where are bottlenecks occurring?</li><li>Who needs support?</li></ul><p><strong>The goal isn’t competition. It’s continuous improvement.</strong></p><h3>Customer Dashboard</h3><p>Every customer leaves behind valuable signals.</p><ul><li>Which customers actively use the platform?</li><li>Which features create the most value?</li><li>Which customers are at risk of churn?</li><li>Which accounts require attention?</li><li>Which premium features are underutilized?</li></ul><p>This helps customer success teams become proactive rather than reactive.</p><h3>Dashboards Are Expensive</h3><p>Not because they’re difficult to build. <strong>Because they’re difficult to build correctly.</strong></p><p>A dashboard requires:</p><ul><li>Well-designed events</li><li>Reliable instrumentation</li><li>Clean data</li><li>Accurate business definitions</li><li>Scalable data pipelines</li><li>Consistent monitoring</li><li>Ongoing maintenance</li></ul><p>One misleading metric can influence hundreds of decisions. A single incorrect KPI can send an entire roadmap in the wrong direction.</p><blockquote><em>The cost of a bad dashboard is rarely measured in engineering hours. It’s measured in poor decisions.</em></blockquote><h3>Engineering Shapes Business</h3><p>One of the biggest transitions from mid-level to senior engineering is realizing your job isn’t only to write software.</p><p><strong>It’s to build systems that help people make better decisions.</strong></p><p>Sometimes that means writing an API. Sometimes it means improving observability. Sometimes it means questioning whether a metric actually represents reality — or suggesting data that nobody thought to collect.</p><p>Those conversations have long-term impact.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*CXrVP_1hqHIDk4BG3SW2vg.jpeg" /></figure><h3>The Three Questions Every Dashboard Must Answer</h3><p>Every effective dashboard should make these answers obvious:</p><p><strong>1. Where are we?</strong> Show the current state. Provide context. Establish a baseline.</p><p><strong>2. What went wrong?</strong> Explain what changed. Highlight anomalies. Help users investigate causes.</p><p><strong>3. What are we going to do about it?</strong> Guide action. Support prioritization. Reduce the time between identifying a problem and solving it.</p><h3>Final Thought</h3><p>Senior developers aren’t expected to become product managers, designers, or executives. But they should understand how each of those stakeholders thinks.</p><p>The best engineers don’t just build features — <strong>they understand why those features exist.</strong></p><p>A dashboard is one of the clearest examples of this mindset.</p><p>Behind every chart is a decision. Behind every decision is a business outcome.</p><p>When you understand that, you’re no longer building dashboards.</p><p><strong>You’re helping shape the direction of the organization.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e664209e90ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Build a RAG-Based Chatbot Without Breaking a Sweat ]]></title>
            <link>https://medium.com/@somnath.muthukumaran/lets-build-a-rag-based-chatbot-without-breaking-a-sweat-fc44fbb0e77f?source=rss-190b44b30f19------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc44fbb0e77f</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Somnath Muthukumaran]]></dc:creator>
            <pubDate>Sun, 01 Jun 2025 13:43:14 GMT</pubDate>
            <atom:updated>2025-06-01T13:43:14.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Building intelligent document chatbots with local LLMs and vector databases</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R_BTvBjhNH2eKGDhL6kkyA.png" /></figure><h3>Introduction</h3><p>On my previous post, we discussed how to get started with the AI trend without spending a ton of money on AI APIs, primarily by using Ollama to run Large Language Models (LLMs) locally. If you haven’t checked that out, I highly recommend it as a foundation for this journey.</p><p>In this blog, we’re going to roll up our sleeves and see how we can practice creating a <strong>Retrieval-Augmented Generation (RAG)</strong> based chatbot. I’m going to use a Weaviate free cluster for the vector database, but feel free to use anything you’re comfortable with — ChromaDB, Pinecone, Qdrant, etc. The core concepts remain the same.</p><h3>Understanding the Core: The Vector Database &amp; Embeddings</h3><p>At the heart of any RAG system is a <strong>vector database</strong>. Its primary job is simple: to save the embeddings of your data and then retrieve the related data when you ask for it.</p><p>But why embeddings? Why do we need to convert text into numbers like (1.0, 1.1)?</p><p>Let me give a simple example of how vector search works:</p><p>Let’s say we “embed” two words: <strong>“Fruit”</strong> and <strong>“Vegetable”</strong>.</p><ul><li>“Fruit” might have a representing number of 1.0</li><li>“Vegetable” might have a representing number of 2.0</li></ul><p>Now, when a user tries to add another word like <strong>“Tomato”</strong>, the embedding model processes it, and it might get a numerical representation of 1.2.</p><p>Why 1.2? Because &quot;Tomato&quot; is still near to &quot;Vegetable&quot; in context, but it&#39;s more of a fruit than a vegetable from a botanical perspective, pulling its numerical representation closer to &quot;Fruit&quot;.</p><p>So, when we perform a vector search with the query “Tomato”, the system will result with “Fruit” because their numerical representations (1.2 and 1.0) are closer in the vector space than 1.2 and 2.0.</p><blockquote><strong><em>Note:</em></strong><em> This is a simplified analogy, as real embeddings are high-dimensional vectors, but the principle of numerical proximity representing semantic similarity holds true.</em></blockquote><h3>How Are Embeddings Generated?</h3><p>That’s where <strong>embedding models</strong> come in. In our accompanying code, I’ve simply used deepseek-r1 (a code-focused LLM) as both my embedding model and my LLM for querying.</p><p>This isn’t ideal, as deepseek-r1 isn&#39;t primarily meant for embedding, but due to hardware constraints and, to be honest, a bit of laziness, I&#39;ve found it can achieve a simple, working solution. This demonstrates that you can sometimes use the same model for both querying and embedding, though dedicated embedding models (like nomic-embed-text) are generally better.</p><h3>The RAG Chatbot Architecture: A Simple Flow</h3><p>Before we dive into any code, let’s understand the conceptual flow of our RAG chatbot. As a developer, grasping the architecture first often makes the implementation details fall into place more easily.</p><p>Our RAG system operates in two main phases: <strong>Ingestion (Indexing)</strong> and <strong>Retrieval &amp; Generation (Chatting)</strong>.</p><h3>Phase 1: Ingesting Your Knowledge (The Indexing Phase)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXHUoJ7XE2TcC6d6EBuiSw.png" /></figure><p>This phase is about preparing your custom knowledge base so that the LLM can later access relevant information.</p><h4>Step 1: User Uploads File</h4><p>First, you’ll upload a document (e.g., a Harry Potter book, a company manual, a research paper) to our system. This is your raw, unstructured knowledge.</p><h4>Step 2: Document Processing &amp; Chunking</h4><p>The system takes this large document and breaks it down into smaller, manageable pieces called <strong>“chunks.”</strong></p><p>Why chunking? Because LLMs have a limited “context window” — they can only process so much text at once. Smaller chunks also tend to be more semantically focused, which helps in retrieving highly relevant information later. We also add a small “overlap” between chunks to ensure that context isn’t lost at chunk boundaries.</p><h4>Step 3: Embedding Generation</h4><p>Each of these text chunks is then fed into an embedding model. This model transforms the text into a dense numerical vector (the “embedding”). As we discussed, these vectors capture the semantic meaning of the text, so chunks with similar meanings will have vectors that are numerically “close” to each other in a high-dimensional space.</p><h4>Step 4: Vector Database Storage</h4><p>Finally, these newly generated embeddings, along with their corresponding original text chunks and any useful metadata (like page numbers, original filename, line ranges), are stored in a vector database (like Weaviate). This database is optimized for storing and quickly searching these high-dimensional vectors.</p><p>This entire process happens once for each document you upload.</p><h3>Phase 2: Chatting with Your Knowledge (The Retrieval &amp; Generation Phase)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AECynnMAqB7MhFJUAsfZQg.png" /></figure><p>This phase occurs in real-time when a user interacts with the chatbot.</p><h4>Step 1: User Asks a Question</h4><p>A user types a question into the chatbot.</p><h4>Step 2: Query Embedding</h4><p>Just like with the document chunks, the user’s question is immediately converted into an embedding using the same embedding model. This allows us to compare the question’s meaning to the meaning of our stored document chunks.</p><h4>Step 3: Vector Search &amp; Retrieval</h4><p>The chatbot then performs a very fast similarity search in the vector database. It compares the embedding of the user’s question to all the stored document chunk embeddings. The goal is to find the top N most semantically similar chunks from your knowledge base.</p><h4>Step 4: Context Augmentation</h4><p>The actual text content from these N retrieved chunks is then extracted and combined into a single, comprehensive “context” string. This context contains the most relevant information from your documents related to the user’s question.</p><h4>Step 5: LLM Generation</h4><p>Finally, this augmented prompt (containing the user’s original question, the retrieved context, and specific instructions for the LLM on how to use this context) is sent to the Large Language Model (LLM). The LLM then generates a response, primarily drawing information from the provided context. Our prompt also instructs the LLM to cite its sources (page numbers, line ranges) from the retrieved context, and to indicate when it’s using general knowledge versus document-specific information.</p><p>This process allows the LLM to provide highly accurate, up-to-date, and attributable answers by “looking up” information in your custom knowledge base, overcoming the limitations of its original training data.</p><blockquote><em>It’s not rocket science, and honestly, even rocket science feels easier to understand in this AI world! 😄</em></blockquote><h3>Setting Up Our Environment and Implementation Details</h3><p>If you’re curious about the implementation details and want to jump straight into the code, this section is for you. Here, we’ll cover the necessary installations, environment variables, and the full Python code for our FastAPI application.</p><h3>Prerequisites</h3><p>Before you run the code, make sure you have:</p><ol><li><strong>Python 3.7+</strong> installed</li><li><strong>Ollama installed and running</strong>: Download Ollama from <a href="https://ollama.com/">ollama.com</a>. Once installed, pull the deepseek-r1 model by running ollama run deepseek-r1 in your terminal. This will download the model. Keep Ollama running (ollama serve) in the background.</li><li><strong>Weaviate Cloud account and API key</strong>: Sign up for a free sandbox cluster at <a href="https://console.weaviate.cloud/">console.weaviate.cloud</a></li><li><strong>Required Python packages</strong>: You can install them using pip:</li></ol><pre>pip install fastapi uvicorn httpx pypdf weaviate-client python-dotenv pydantic</pre><blockquote><strong><em>Note:</em></strong><em> </em><em>pydantic is usually a dependency of FastAPI, but explicitly listing it is good practice.</em></blockquote><ol><li><strong>Environment Variables</strong>: Create a file named .env in the same directory as your Python script and add your Weaviate credentials:</li></ol><pre>WEAVIATE_URL=&quot;https://YOUR_WEAVIATE_CLUSTER_URL.weaviate.network&quot;<br>WEAVIATE_API_KEY=&quot;YOUR_WEAVIATE_API_KEY&quot;</pre><h3>Creating the Streaming Response Handler</h3><p>First, let’s create a simple streaming response handler. Create a file called streaming.py:</p><pre># streaming.py<br>import json<br>from typing import AsyncGenerator, Optional, Dict<br>from starlette.responses import StreamingResponse</pre><pre>class StreamingJSONResponse(StreamingResponse):<br>    media_type = &quot;application/json&quot;<br>    <br>    def __init__(self, content: AsyncGenerator, status_code: int = 200, headers: Optional[Dict[str, str]] = None):<br>        super().__init__(content, status_code, headers)<br>        self.body_iterator = self.json_generator(content)<br>    <br>    async def json_generator(self, generator):<br>        async for data in generator:<br>            yield json.dumps(data) + &quot;\n&quot;</pre><h3>Core Application Setup and Helper Functions</h3><p>This section contains the initial setup for our FastAPI application, including imports, global variables, Pydantic models for data validation, and helper functions that abstract away common tasks like checking connections and processing text.</p><h3>Imports and Initial Setup</h3><pre>from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks<br>from fastapi.middleware.cors import CORSMiddleware<br>from pydantic import BaseModel<br>from typing import List, Optional, Dict, Union, Any, AsyncGenerator<br>import httpx<br>import numpy as np<br>from pathlib import Path<br>import os<br>from dotenv import load_dotenv<br>import json<br>import asyncio<br>from fastapi.responses import JSONResponse<br>import io<br>from PyPDF2 import PdfReader<br>import weaviate<br>import weaviate.classes as wvc<br>from weaviate.classes.config import Configure<br>import uuid<br>from streaming import StreamingJSONResponse</pre><pre># Load environment variables from .env file for sensitive info like API keys<br>load_dotenv()</pre><h3>Application Lifespan and CORS Setup</h3><pre>from contextlib import asynccontextmanager</pre><pre># Lifespan context manager for startup/shutdown tasks<br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    &quot;&quot;&quot;Lifespan event handler for FastAPI application&quot;&quot;&quot;<br>    # Startup: Initialize Weaviate schema<br>    if weaviate_client:<br>        setup_weaviate_schema()<br>    <br>    yield  # Application starts here<br>    <br>    # Shutdown: Close Weaviate connection<br>    if weaviate_client:<br>        weaviate_client.close()</pre><pre>app = FastAPI(lifespan=lifespan)</pre><pre># CORS middleware configuration for local development<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;http://localhost:3000&quot;, &quot;http://localhost:3001&quot;],  # Adjust as needed<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)</pre><h3>Weaviate Client Initialization</h3><pre># Weaviate configuration from environment variables<br>WEAVIATE_URL = os.getenv(&quot;WEAVIATE_URL&quot;, &quot;https://your-cluster.weaviate.network&quot;)<br>WEAVIATE_API_KEY = os.getenv(&quot;WEAVIATE_API_KEY&quot;, &quot;your-api-key&quot;)</pre><pre># Initialize Weaviate client<br>try:<br>    weaviate_client = weaviate.connect_to_weaviate_cloud(<br>        cluster_url=WEAVIATE_URL,<br>        auth_credentials=wvc.init.Auth.api_key(WEAVIATE_API_KEY),<br>    )<br>except Exception as e:<br>    print(f&quot;Failed to connect to Weaviate: {e}&quot;)<br>    weaviate_client = None  # Set to None if connection fails</pre><h3>Data Models and Global State</h3><pre># Global processing status for tracking document ingestion<br>processing_status = {<br>    &quot;total_chunks&quot;: 0,<br>    &quot;processed_chunks&quot;: 0,<br>    &quot;status&quot;: &quot;idle&quot;,  # idle, processing, completed, error<br>    &quot;current_document&quot;: None<br>}</pre><pre># Pydantic models for API request/response validation<br>class QueryRequest(BaseModel):<br>    question: str<br>    document_id: Optional[str] = None  # Optional: query specific document</pre><pre>class Reference(BaseModel):<br>    page: int<br>    start_line: int<br>    end_line: int<br>    content: str<br>    similarity_score: float</pre><pre>class QueryResponse(BaseModel):<br>    answer: str<br>    references: List[Reference]</pre><pre>class ProcessingStatus(BaseModel):<br>    status: str<br>    progress: float<br>    total_chunks: int<br>    processed_chunks: int<br>    current_document: Optional[str]</pre><pre>class DocumentInfo(BaseModel):<br>    id: str<br>    filename: str<br>    chunk_count: int<br>    upload_date: str</pre><h3>Key Helper Functions</h3><h3>Database Schema Setup</h3><pre>def setup_weaviate_schema():<br>    &quot;&quot;&quot;Setup Weaviate collection schema&quot;&quot;&quot;<br>    if not weaviate_client:<br>        print(&quot;Weaviate client not initialized. Cannot set up schema.&quot;)<br>        return False<br>    <br>    try:<br>        # Check if collection exists<br>        if weaviate_client.collections.exists(&quot;NovelChunk&quot;):<br>            print(&quot;NovelChunk collection already exists. Skipping schema creation.&quot;)<br>            return True<br>        <br>        # Create collection with schema<br>        weaviate_client.collections.create(<br>            name=&quot;NovelChunk&quot;,<br>            vectorizer_config=Configure.Vectorizer.none(),  # We&#39;ll provide our own vectors<br>            properties=[<br>                wvc.config.Property(<br>                    name=&quot;content&quot;,<br>                    data_type=wvc.config.DataType.TEXT,<br>                    description=&quot;Text content of the chunk&quot;<br>                ),<br>                wvc.config.Property(<br>                    name=&quot;page&quot;,<br>                    data_type=wvc.config.DataType.INT,<br>                    description=&quot;Page number&quot;<br>                ),<br>                wvc.config.Property(<br>                    name=&quot;start_line&quot;,<br>                    data_type=wvc.config.DataType.INT,<br>                    description=&quot;Starting line number&quot;<br>                ),<br>                wvc.config.Property(<br>                    name=&quot;end_line&quot;,<br>                    data_type=wvc.config.DataType.INT,<br>                    description=&quot;Ending line number&quot;<br>                ),<br>                wvc.config.Property(<br>                    name=&quot;document_id&quot;,<br>                    data_type=wvc.config.DataType.TEXT,<br>                    description=&quot;Document identifier&quot;<br>                ),<br>                wvc.config.Property(<br>                    name=&quot;filename&quot;,<br>                    data_type=wvc.config.DataType.TEXT,<br>                    description=&quot;Original filename&quot;<br>                ),<br>                wvc.config.Property(<br>                    name=&quot;chunk_index&quot;,<br>                    data_type=wvc.config.DataType.INT,<br>                    description=&quot;Index of chunk within document&quot;<br>                )<br>            ]<br>        )<br>        print(&quot;NovelChunk collection created successfully.&quot;)<br>        return True<br>    except Exception as e:<br>        print(f&quot;Error setting up Weaviate schema: {e}&quot;)<br>        return False</pre><h3>Connection Health Checks</h3><pre>async def check_ollama_connection() -&gt; bool:<br>    &quot;&quot;&quot;Check if Ollama is running and accessible&quot;&quot;&quot;<br>    try:<br>        async with httpx.AsyncClient() as client:<br>            response = await client.get(&quot;http://localhost:11434/api/tags&quot;)<br>            return response.status_code == 200<br>    except:<br>        return False</pre><pre>async def check_weaviate_connection() -&gt; bool:<br>    &quot;&quot;&quot;Check if Weaviate is accessible&quot;&quot;&quot;<br>    try:<br>        if not weaviate_client:<br>            return False<br>        return weaviate_client.is_ready()<br>    except Exception as e:<br>        print(f&quot;Weaviate connection check failed: {e}&quot;)<br>        return False</pre><h3>Embedding Generation with Retry Logic</h3><pre>async def get_embedding(text: str) -&gt; List[float]:<br>    &quot;&quot;&quot;Get embedding from Ollama API with retry logic&quot;&quot;&quot;<br>    max_retries = 3<br>    for attempt in range(max_retries):<br>        try:<br>            async with httpx.AsyncClient() as client:<br>                response = await client.post(<br>                    &quot;http://localhost:11434/api/embeddings&quot;,<br>                    json={<br>                        &quot;model&quot;: &quot;deepseek-r1&quot;,  # Our chosen model for embeddings<br>                        &quot;prompt&quot;: text<br>                    },<br>                    timeout=30.0  # Increased timeout for embedding calls<br>                )<br>                if response.status_code == 200:<br>                    return response.json()[&quot;embedding&quot;]<br>        except httpx.ConnectError as e:<br>            print(f&quot;Connection error to Ollama on attempt {attempt+1}: {e}&quot;)<br>            if attempt == max_retries - 1:<br>                raise HTTPException(<br>                    status_code=500,<br>                    detail=f&quot;Failed to connect to Ollama after {max_retries} attempts: {str(e)}&quot;<br>                )<br>            await asyncio.sleep(2 ** attempt)  # Exponential backoff<br>        except Exception as e:<br>            print(f&quot;Error getting embedding on attempt {attempt+1}: {e}&quot;)<br>            if attempt == max_retries - 1:<br>                raise HTTPException(<br>                    status_code=500,<br>                    detail=f&quot;Failed to get embeddings after {max_retries} attempts: {str(e)}&quot;<br>                )<br>            await asyncio.sleep(1)  # Simple delay for other errors<br>    <br>    raise HTTPException(status_code=500, detail=&quot;Failed to get embeddings from Ollama (unknown reason)&quot;)</pre><h3>Text Processing Functions</h3><pre>def chunk_text(text: str, lines_per_page: int = 30, overlap: int = 5) -&gt; List[dict]:<br>    &quot;&quot;&quot;Chunk text with overlap for better context preservation&quot;&quot;&quot;<br>    lines = text.split(&#39;\n&#39;)<br>    chunks = []<br>    page = 1<br>    start_line = 1<br>    i = 0</pre><pre>    while i &lt; len(lines):<br>        # Calculate end index with overlap<br>        end_idx = min(i + lines_per_page, len(lines))<br>        chunk_lines = lines[i:end_idx]<br>        <br>        # Add overlap from next chunk if available<br>        if end_idx &lt; len(lines):<br>            overlap_lines = lines[end_idx:min(end_idx + overlap, len(lines))]<br>            chunk_lines.extend(overlap_lines)<br>        <br>        if chunk_lines:<br>            chunks.append({<br>                &#39;text&#39;: &#39;\n&#39;.join(chunk_lines),<br>                &#39;page&#39;: page,<br>                &#39;start_line&#39;: start_line,<br>                &#39;end_line&#39;: start_line + len(chunk_lines) - 1<br>            })<br>        <br>        i += lines_per_page<br>        page += 1<br>        start_line += lines_per_page</pre><pre>    return chunks</pre><pre>async def process_pdf(file_content: bytes) -&gt; str:<br>    &quot;&quot;&quot;Extract text from PDF file&quot;&quot;&quot;<br>    pdf_reader = PdfReader(io.BytesIO(file_content))<br>    text_content = []<br>    <br>    for page in pdf_reader.pages:<br>        page_text = page.extract_text()<br>        if page_text:<br>            text_content.append(page_text)<br>    <br>    return &quot;\n&quot;.join(text_content)</pre><pre>async def process_file_content(file: UploadFile) -&gt; str:<br>    &quot;&quot;&quot;Process uploaded file content based on file type&quot;&quot;&quot;<br>    content = await file.read()<br>    <br>    if file.filename.endswith(&#39;.pdf&#39;):<br>        return await process_pdf(content)<br>    elif file.filename.endswith(&#39;.txt&#39;):<br>        return content.decode(&#39;utf-8&#39;)<br>    else:<br>        raise HTTPException(status_code=400, detail=&quot;Unsupported file format. Only .txt and .pdf files are supported&quot;)</pre><h3>API Endpoints Explained</h3><p>Now that you understand the conceptual flow and the helper functions, let’s look at how these pieces come together in our FastAPI endpoints.</p><h3>1. Health Check and Status Endpoints</h3><p>These endpoints provide insight into the operational status of our RAG system and the progress of document processing.</p><ul><li>/health: Checks if Ollama and Weaviate are reachable</li><li>/status: Provides real-time updates on background document processing</li></ul><pre>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    &quot;&quot;&quot;Endpoint to check the health of Ollama and Weaviate connections&quot;&quot;&quot;<br>    ollama_connected = await check_ollama_connection()<br>    weaviate_connected = await check_weaviate_connection()<br>    return {<br>        &quot;status&quot;: &quot;ok&quot; if (ollama_connected and weaviate_connected) else &quot;error&quot;,<br>        &quot;ollama_connected&quot;: ollama_connected,<br>        &quot;weaviate_connected&quot;: weaviate_connected,<br>        &quot;processing_status&quot;: processing_status<br>    }</pre><pre>@app.get(&quot;/status&quot;)<br>async def get_processing_status() -&gt; ProcessingStatus:<br>    &quot;&quot;&quot;Get the current processing status of document uploads&quot;&quot;&quot;<br>    progress = (processing_status[&quot;processed_chunks&quot;] / processing_status[&quot;total_chunks&quot;] * 100) if processing_status[&quot;total_chunks&quot;] &gt; 0 else 0<br>    return ProcessingStatus(<br>        status=processing_status[&quot;status&quot;],<br>        progress=round(progress, 2),<br>        total_chunks=processing_status[&quot;total_chunks&quot;],<br>        processed_chunks=processing_status[&quot;processed_chunks&quot;],<br>        current_document=processing_status[&quot;current_document&quot;]<br>    )</pre><h3>2. Document Management Endpoints</h3><p>These endpoints allow us to interact with the documents stored in our vector database.</p><ul><li>/documents: Lists all documents currently stored in Weaviate</li><li>/documents/{document_id}: Allows you to delete a specific document</li></ul><pre>@app.get(&quot;/documents&quot;)<br>async def list_documents() -&gt; List[DocumentInfo]:<br>    &quot;&quot;&quot;List all uploaded documents (grouped by document_id)&quot;&quot;&quot;<br>    if not weaviate_client:<br>        raise HTTPException(status_code=503, detail=&quot;Weaviate service is not available&quot;)<br>    <br>    try:<br>        collection = weaviate_client.collections.get(&quot;NovelChunk&quot;)<br>        response = collection.query.fetch_objects(limit=10000)<br>        <br>        document_map = {}<br>        for obj in response.objects:<br>            props = obj.properties<br>            doc_id = props.get(&quot;document_id&quot;)<br>            filename = props.get(&quot;filename&quot;)<br>            <br>            if doc_id and filename:<br>                if doc_id not in document_map:<br>                    document_map[doc_id] = {<br>                        &quot;id&quot;: doc_id,<br>                        &quot;filename&quot;: filename,<br>                        &quot;chunk_count&quot;: 0,<br>                        &quot;upload_date&quot;: &quot;Unknown&quot;<br>                    }<br>                document_map[doc_id][&quot;chunk_count&quot;] += 1<br>        <br>        documents = []<br>        for doc_data in document_map.values():<br>            documents.append(DocumentInfo(**doc_data))<br>        <br>        return documents<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=f&quot;Error retrieving documents: {str(e)}&quot;)</pre><pre>@app.delete(&quot;/documents/{document_id}&quot;)<br>async def delete_document(document_id: str):<br>    &quot;&quot;&quot;Delete a specific document and all its chunks from Weaviate&quot;&quot;&quot;<br>    if not await check_weaviate_connection():<br>        raise HTTPException(status_code=503, detail=&quot;Weaviate service is not available&quot;)<br>    <br>    try:<br>        collection = weaviate_client.collections.get(&quot;NovelChunk&quot;)<br>        result = collection.data.delete_many(<br>            collection.query.Filter.by_property(&quot;document_id&quot;).equal(document_id)<br>        )<br>        <br>        if result.successful:<br>            return {<br>                &quot;success&quot;: True, <br>                &quot;message&quot;: f&quot;Document {document_id} and its chunks deleted successfully. Objects affected: {result.matches}&quot;<br>            }<br>        else:<br>            raise HTTPException(status_code=500, detail=f&quot;Failed to delete document {document_id}: {result.errors}&quot;)<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=f&quot;Error deleting document: {str(e)}&quot;)</pre><h3>3. Document Upload Endpoint</h3><p>This is where the indexing phase is initiated. When a user uploads a file, this endpoint handles the initial reception and then offloads the heavy processing to a background task.</p><pre>@app.post(&quot;/upload&quot;)<br>async def upload_novel(<br>    background_tasks: BackgroundTasks,<br>    file: UploadFile = File(...),<br>    lines_per_page: int = 30<br>):<br>    &quot;&quot;&quot;Endpoint to upload a document for RAG indexing&quot;&quot;&quot;<br>    if not await check_ollama_connection():<br>        raise HTTPException(status_code=503, detail=&quot;Ollama service is not available&quot;)<br>    <br>    if not await check_weaviate_connection():<br>        raise HTTPException(status_code=503, detail=&quot;Weaviate service is not available&quot;)</pre><pre>    try:<br>        text = await process_file_content(file)  # Read and parse file content<br>        document_id = str(uuid.uuid4())  # Generate a unique ID for the document<br>        <br>        # Update global status for monitoring<br>        processing_status.update({<br>            &quot;status&quot;: &quot;processing&quot;,<br>            &quot;total_chunks&quot;: 0,  # Will be set in process_document<br>            &quot;processed_chunks&quot;: 0,<br>            &quot;current_document&quot;: file.filename<br>        })<br>        <br>        # Offload the heavy processing to a background task<br>        background_tasks.add_task(<br>            process_document,<br>            text,<br>            file.filename,<br>            document_id,<br>            lines_per_page<br>        )<br>        <br>        return {<br>            &quot;success&quot;: True,<br>            &quot;message&quot;: &quot;Document upload started. Use the /status endpoint to monitor progress.&quot;,<br>            &quot;document_id&quot;: document_id,<br>            &quot;filename&quot;: file.filename<br>        }<br>    <br>    except Exception as e:<br>        processing_status[&quot;status&quot;] = &quot;error&quot;<br>        raise HTTPException(status_code=500, detail=str(e))</pre><h3>4. Query Endpoint (The Chatbot’s Core)</h3><p>This is the runtime part where the RAG system processes a user’s question, retrieves relevant information, and generates a context-aware answer.</p><p>The most interesting part is our detailed prompt engineering that instructs the LLM on how to properly cite sources and combine book knowledge with general knowledge:</p><pre>@app.post(&quot;/query&quot;)<br>async def query_novel(query: QueryRequest):<br>    &quot;&quot;&quot;Query the novel with streaming response, incorporating RAG&quot;&quot;&quot;<br>    if not await check_weaviate_connection():<br>        raise HTTPException(status_code=503, detail=&quot;Weaviate service is not available&quot;)<br>    <br>    if not await check_ollama_connection():<br>        raise HTTPException(status_code=503, detail=&quot;Ollama service is not available&quot;)<br>    <br>    try:<br>        # Generate embedding for the user&#39;s question<br>        question_embedding = await get_embedding(query.question)<br>        <br>        # Search for similar chunks in Weaviate<br>        collection = weaviate_client.collections.get(&quot;NovelChunk&quot;)<br>        weaviate_query_builder = collection.query.near_vector(<br>            near_vector=question_embedding,<br>            limit=5,<br>            return_metadata=[&quot;distance&quot;]<br>        )<br>        <br>        # Optional: Filter by specific document<br>        if query.document_id:<br>            weaviate_query_builder = weaviate_query_builder.with_where_filter(<br>                collection.query.Filter.by_property(&quot;document_id&quot;).equal(query.document_id)<br>            )<br>            <br>        response = weaviate_query_builder.do()<br>        objects = response.objects if hasattr(response, &#39;objects&#39;) else []<br>        <br>        if not objects:<br>            async def empty_response():<br>                yield {<br>                    &quot;answer&quot;: &quot;No relevant information found in the uploaded documents. Please try a different query or upload more documents.&quot;,<br>                    &quot;references&quot;: [],<br>                    &quot;done&quot;: True<br>                }<br>            return StreamingJSONResponse(empty_response())<br>        <br>        # Process retrieved chunks<br>        context_chunks_for_llm = []<br>        references_for_frontend = []<br>        <br>        for obj in objects:<br>            try:<br>                props = obj.properties<br>                content = props.get(&quot;content&quot;, &quot;&quot;)<br>                <br>                if content and isinstance(content, str) and content.strip():<br>                    context_chunks_for_llm.append(content)<br>                <br>                distance = obj.metadata.distance if obj.metadata else 0<br>                similarity_score = 1 - (distance if distance is not None else 0)<br>                <br>                references_for_frontend.append(Reference(<br>                    page=props.get(&quot;page&quot;, 0),<br>                    start_line=props.get(&quot;start_line&quot;, 0),<br>                    end_line=props.get(&quot;end_line&quot;, 0),<br>                    content=content,<br>                    similarity_score=round(similarity_score, 3)<br>                ))<br>                <br>            except Exception as e:<br>                print(f&quot;Error processing retrieved object: {e}&quot;)<br>                continue<br>        <br>        # Create context string for the LLM<br>        context_string = &quot;\n\n&quot;.join(context_chunks_for_llm)<br>        <br>        # Here&#39;s our detailed prompt that instructs the LLM on proper citation<br>        prompt = f&quot;&quot;&quot;You are an intelligent book analysis assistant with access to both the provided book content and your general knowledge. Your primary role is to help users navigate and understand book content, but you can supplement with general knowledge when appropriate.</pre><pre>CONTEXT FROM BOOK:<br>{context_string}</pre><pre>USER QUESTION: {query.question}</pre><pre>INSTRUCTIONS:<br>1. **Primary Source Analysis**: Always prioritize information from the provided book content first.</pre><pre>2. **Reference Citation**: For every piece of information from the book, include specific references:<br>   - Page numbers where the information appears<br>   - Line ranges when available<br>   - Direct quotes with quotation marks when relevant</pre><pre>3. **Response Strategy**:<br>   - **If information IS in the book**: Provide comprehensive analysis with detailed citations<br>   - **If information is NOT in the book**: Clearly state &quot;I couldn&#39;t find information about [topic] in the provided book content, but here&#39;s what I know about it from my general knowledge:&quot; then provide relevant general information<br>   - **If partially in the book**: Provide book-based information first with citations, then add &quot;Additionally, from my general knowledge:&quot; for supplementary context</pre><pre>4. **Clear Source Attribution**:<br>   - **From the book**: &quot;(Page X, Lines Y-Z)&quot; <br>   - **From general knowledge**: &quot;Based on my general knowledge:&quot; or &quot;From what I know about [topic]:&quot;</pre><pre>Now analyze the context and provide your detailed response following these guidelines.&quot;&quot;&quot;</pre><pre>        # Stream the response back to the user<br>        async def generate_combined_response():<br>            &quot;&quot;&quot;Generate response with both streaming answer and references&quot;&quot;&quot;<br>            async for chunk_data in generate_streaming_response(prompt):<br>                if chunk_data.get(&quot;done&quot;, False):<br>                    chunk_data[&quot;references&quot;] = [ref.model_dump() for ref in references_for_frontend]<br>                yield chunk_data<br>        <br>        return StreamingJSONResponse(generate_combined_response())<br>    <br>    except Exception as e:<br>        print(f&quot;Exception in query_novel: {e}&quot;)<br>        raise HTTPException(status_code=500, detail=str(e))</pre><h3>Running the Application</h3><p>Finally, to run your FastAPI application:</p><h3>Step 1: Save the Code</h3><p>Save the entire code into a Python file (e.g., main.py).</p><h3>Step 2: Create Environment File</h3><p>Ensure your .env file is set up correctly in the same directory as main.py:</p><pre>WEAVIATE_URL=&quot;https://YOUR_WEAVIATE_CLUSTER_URL.weaviate.network&quot;<br>WEAVIATE_API_KEY=&quot;YOUR_WEAVIATE_API_KEY&quot;</pre><h3>Step 3: Start Ollama</h3><p>Make sure Ollama is running and you have the model ready:</p><pre># Start Ollama service<br>ollama serve</pre><pre># In another terminal, pull the model<br>ollama pull deepseek-r1</pre><h3>Step 4: Run the FastAPI Application</h3><p>Open your terminal in the directory where you saved main.py and run:</p><pre>uvicorn main:app --reload</pre><blockquote><em>Use </em><em>--reload for development to automatically restart on code changes. For production, omit </em><em>--reload and consider </em><em>uvicorn main:app --host 0.0.0.0 --port 8000.</em></blockquote><p>Your FastAPI RAG chatbot backend will now be running, typically accessible at http://localhost:8000. You can then interact with it using tools like curl, Postman, or a custom frontend application.</p><h3>Testing Your RAG Chatbot</h3><p>Once your application is running, you can test it using these example requests:</p><h3>Upload a Document</h3><pre>curl -X POST &quot;http://localhost:8000/upload&quot; \<br>  -H &quot;accept: application/json&quot; \<br>  -H &quot;Content-Type: multipart/form-data&quot; \<br>  -F &quot;file=@your_document.pdf&quot;</pre><h3>Check Processing Status</h3><pre>curl -X GET &quot;http://localhost:8000/status&quot;</pre><h3>Query Your Document</h3><pre>curl -X POST &quot;http://localhost:8000/query&quot; \<br>  -H &quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc44fbb0e77f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock Your AI Journey: Learn RAG & Agentic AI Without Breaking the Bank!]]></title>
            <link>https://medium.com/@somnath.muthukumaran/unlock-your-ai-journey-learn-rag-agentic-ai-without-breaking-the-bank-b97a9300cbbf?source=rss-190b44b30f19------2</link>
            <guid isPermaLink="false">https://medium.com/p/b97a9300cbbf</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Somnath Muthukumaran]]></dc:creator>
            <pubDate>Fri, 30 May 2025 14:01:08 GMT</pubDate>
            <atom:updated>2025-05-30T14:01:08.771Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EDOlG8bpga4V9I5yYK6fSA.png" /></figure><p>Are you fascinated by Large Language Models (LLMs) and eager to dive into concepts like Retrieval-Augmented Generation (RAG) and Agentic AI? Do you feel overwhelmed by the complexity or worried about the costs?</p><p>Here’s the truth: <strong>You don’t need a massive budget, or expensive cloud APIs to start your AI journey.</strong></p><p>As someone building practical AI solutions, I’ve discovered that the biggest barrier isn’t technical complexity — it’s the fear of getting started. Let me show you how simple it really is with <strong>Ollama</strong>.</p><h3>The Fear Factor: It’s Simpler Than You Think</h3><p>Let’s be honest — AI can feel intimidating. Terms like “Retrieval-Augmented Generation,” “vector embeddings,” and “agentic workflows” sound like they belong in a PhD thesis, not your weekend project.</p><p>But here’s what I learned: <strong>the concepts are actually straightforward once you start playing with them.</strong></p><ul><li><strong>RAG</strong> is just “give the AI some context before asking a question”</li><li><strong>Vector embeddings</strong> are just “turning text into numbers so computers can compare similarity”</li><li><strong>AI agents</strong> are just “AI that can use tools to accomplish tasks”</li></ul><p>The intimidating jargon hides surprisingly intuitive concepts.</p><h3>Why Go Local with Ollama?</h3><p>The typical approach involves paying for cloud-based AI APIs (like OpenAI, Gemini, etc.). While convenient, costs can quickly add up during experimentation, and honestly, this creates a psychological barrier. You hesitate to experiment because every API call costs money.</p><p>This is where Ollama changes everything. It allows you to run powerful open-source LLMs directly on your local machine, offering:</p><ul><li><strong>Zero API Costs</strong>: Experiment freely, iterate endlessly, fail fast, and learn without watching your wallet</li><li><strong>Enhanced Privacy</strong>: Your data never leaves your machine — no more worrying about sending sensitive information to third parties</li><li><strong>Full Control</strong>: Want to understand how these models really work? You can poke, prod, and customize to your heart’s content</li></ul><h3>Your Hardware is Already Ready!</h3><p>Here’s what might surprise you: that gaming laptop or desktop you already have? It’s probably more than capable of running sophisticated AI models.</p><p>I’m personally using my MSI Cyborg 14 with an RTX 3050 (just 6GB VRAM), and it runs powerful language models beautifully. Modern GPUs, even mid-range ones, can handle quantized LLMs that would have required enterprise hardware just a few years ago.</p><p>The magic word here is <strong>quantization</strong> — a clever technique that shrinks these massive models while keeping most of their intelligence intact. A model that originally needs 32GB of memory can run smoothly in 4–6GB with minimal quality loss.</p><h3>Getting Started is Literally This Easy</h3><p>Want to see how simple it really is? Here’s the complete process from zero to AI chatbot:</p><h3>Step 1: Install Ollama (30 seconds)</h3><pre># On macOS/Linux - just one command:<br>curl -fsSL https://ollama.ai/install.sh | sh</pre><pre># On Windows - download installer from ollama.ai</pre><h3>Step 2: Get Your AI Model (2 minutes)</h3><pre># Download a capable 8B parameter model<br>ollama pull llama3:8b-instruct-q4_K_M</pre><pre># Start the API server<br>ollama serve</pre><p>That’s it! Your AI is now running locally on <a href="http://localhost:11434/">http://localhost:11434</a></p><h3>Step 3: Chat with Your AI</h3><p>Here’s all the code you need to start having conversations:</p><pre>import requests</pre><pre>def chat_with_ai(question):<br>    response = requests.post(&#39;http://localhost:11434/api/generate&#39;, json={<br>        &quot;model&quot;: &quot;llama3:8b-instruct-q4_K_M&quot;,<br>        &quot;prompt&quot;: question,<br>        &quot;stream&quot;: False<br>    })<br>    return response.json()[&quot;response&quot;]</pre><pre># That&#39;s it. Seriously.<br>answer = chat_with_ai(&quot;Explain quantum computing in simple terms&quot;)<br>print(answer)</pre><p>Three steps to get here:</p><ol><li>Install Ollama (one command)</li><li>Download a model (one command)</li><li>Start coding (the snippet above)</li></ol><h3>Why This Matters More Than You Think</h3><p>When you remove the cost barrier and complexity fear, something magical happens: <strong>you start experimenting.</strong></p><p>Instead of carefully crafting the “perfect” prompt because each API call costs money, you iterate rapidly. You try crazy ideas. You build weird prototypes. You fail fast and learn faster.</p><p>This hands-on experimentation teaches you things that no tutorial or course ever could:</p><ul><li>How different models behave differently</li><li>Why prompt engineering actually matters</li><li>How to debug when AI gives weird responses</li><li>The intuitive understanding of what AI can and cannot do</li></ul><h3>The Skills You’ll Accidentally Master</h3><p>Working with local models forces you to become better at the fundamentals:</p><p><strong>Prompt Engineering</strong>: Local models are more sensitive to how you ask questions, so you naturally develop precision in your instructions. This skill transfers directly to working with any AI system.</p><p><strong>System Thinking</strong>: You’ll understand the entire pipeline — from text input to embeddings to retrieval to generation. No black boxes.</p><p><strong>Resource Management</strong>: You’ll learn about model sizes, quantization, and hardware optimization — knowledge that’s invaluable as AI becomes more prevalent in software development.</p><h3>From Chatbot to AI Agent: The Natural Progression</h3><p>Once you’re comfortable with basic interactions, the path to more advanced concepts becomes obvious:</p><ol><li><strong>Start with simple Q&amp;A</strong>: Get comfortable with the API</li><li><strong>Add context</strong>: Feed relevant documents to make responses more accurate (that’s RAG!)</li><li><strong>Give it tools</strong>: Let your AI search databases, make calculations, or call other APIs (that’s an agent!)</li></ol><p>Each step builds naturally on the previous one. No quantum leaps in complexity.</p><h3>The Bottom Line</h3><p>The AI revolution isn’t happening in some distant future or exclusive tech labs. It’s happening right now, on your laptop, with free tools and open-source models.</p><p>The only thing standing between you and building sophisticated AI applications is the decision to start.</p><p>Stop waiting for the “right time” or the “perfect tutorial.” Download Ollama, pull a model, and start experimenting. The future you’ve been reading about? You can build it this weekend.</p><p>The barrier to entry has never been lower. The tools have never been more accessible. And honestly, it’s never been more fun.</p><p><strong>Ready to stop being intimidated by AI and start building with it?</strong></p><p>Your local AI revolution starts with a single command: ollama pull llama3:8b-instruct-q4_K_M</p><p><em>What’s holding you back from starting your AI journey? Share your thoughts in the comments — I’d love to help you take that first step!</em></p><p>#AI #Ollama #RAG #AgenticAI #MachineLearning #OpenSource #LocalAI #LLM #TechLearning #Developers #NoFear</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b97a9300cbbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Title: Creating a Monochrome Image Filter in JavaScript using Web Workers]]></title>
            <link>https://medium.com/@somnath.muthukumaran/title-creating-a-monochrome-image-filter-in-javascript-using-web-workers-debc6a378b07?source=rss-190b44b30f19------2</link>
            <guid isPermaLink="false">https://medium.com/p/debc6a378b07</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[monochrome]]></category>
            <dc:creator><![CDATA[Somnath Muthukumaran]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 05:12:41 GMT</pubDate>
            <atom:updated>2023-07-31T05:12:41.176Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*Q6J7MbQbmePbSvn_9tjdHQ.jpeg" /></figure><p>In this two-part tutorial, we will explore how to create a monochrome image filter using JavaScript and leverage web workers to handle image processing efficiently. The monochrome filter will convert colored images into grayscale by averaging the RGB values of each pixel. We will divide the tutorial into two parts for better clarity and understanding.</p><p>Part 1 will cover the initial setup, the HTML structure, and the creation of a web worker responsible for applying the monochrome filter. Let’s get started!</p><p>Prerequisites: Basic knowledge of HTML, JavaScript, and the Canvas API would be beneficial.</p><p><strong>Step 1: Setting up the Project</strong></p><p>Before diving into the implementation, let’s set up the project structure. Create a new directory for the project and add the following files:</p><ol><li>index.html: This HTML file will provide the user interface for selecting and displaying images.</li><li>main.js: This JavaScript file will contain the code for handling user interactions and loading images.</li><li>worker.js: This JavaScript file will define the web worker responsible for image processing.</li></ol><p><strong>Step 2: HTML Structure (index.html)</strong></p><p>We’ll start by creating the basic HTML structure with an input element for file selection and a canvas element for displaying the image. Open index.html and add the following code:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Monochrome Image Filter - Part 1&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;input type=&quot;file&quot; id=&quot;fileInput&quot;&gt;<br>  &lt;canvas id=&quot;canvas&quot;&gt;&lt;/canvas&gt;<br>  &lt;script src=&quot;main.js&quot;&gt;&lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>The above code sets up the basic HTML page with an input field for selecting images and a canvas element for displaying the processed image.</p><p><strong>Step 3: Web Worker Setup (worker.js)</strong></p><p>Web workers provide a way to run JavaScript code in the background, separate from the main thread, allowing for parallel processing. We’ll create a web worker to handle the monochrome image filtering. In your project directory, create a file named worker.js and add the following code:</p><pre>// worker.js<br>self.addEventListener(&#39;message&#39;, (e) =&gt; {<br>  const imageData = e.data;<br>  const filteredData = monochromeFilter(imageData);<br>  self.postMessage(filteredData);<br>});<br><br>function monochromeFilter(imageData) {<br>  const data = imageData.data;<br>  for (let i = 0; i &lt; data.length; i += 4) {<br>    const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;<br>    data[i] = avg; // Red channel<br>    data[i + 1] = avg; // Green channel<br>    data[i + 2] = avg; // Blue channel<br>  }<br>  return imageData;<br>}</pre><p>In the above code, we define a listener for the message event, which receives the image data from the main thread. The monochromeFilter function calculates the average of the red, green, and blue channel values for each pixel and sets them to create a grayscale effect.</p><p><strong>Step 4: Handling User Interaction (main.js)</strong></p><p>Next, we’ll implement the JavaScript code that handles user interactions, file selection, and image processing. Create a file named main.js in your project directory and add the following code:</p><pre>// main.js<br>document.getElementById(&#39;fileInput&#39;).addEventListener(&#39;change&#39;, handleFileSelect);<br><br>function handleFileSelect(event) {<br>  const file = event.target.files[0];<br>  const reader = new FileReader();<br><br>  reader.onload = function (event) {<br>    // Image loading and processing code will be added in Part 2<br>  };<br><br>  reader.readAsDataURL(file);<br>}</pre><p>The code above adds an event listener to the file input element. When a user selects an image, the handleFileSelect function will be called. Inside this function, we use the FileReader API to read the selected image and initiate image processing</p><p><strong>Step 5: Image Loading and Web Worker Communication</strong></p><p>In the main.js file, let&#39;s continue by adding the image loading and web worker communication code:</p><pre>// main.js<br>document.getElementById(&#39;fileInput&#39;).addEventListener(&#39;change&#39;, handleFileSelect);<br><br>function handleFileSelect(event) {<br>  const file = event.target.files[0];<br>  const reader = new FileReader();<br><br>  reader.onload = function (event) {<br>    const img = new Image();<br>    img.onload = function () {<br>      const canvas = document.getElementById(&#39;canvas&#39;);<br>      canvas.width = img.width;<br>      canvas.height = img.height;<br><br>      const ctx = canvas.getContext(&#39;2d&#39;);<br>      ctx.drawImage(img, 0, 0, img.width, img.height);<br><br>      const imageData = ctx.getImageData(0, 0, img.width, img.height);<br><br>      // Create a worker to apply the monochrome filter<br>      const worker = new Worker(&#39;worker.js&#39;);<br>      worker.postMessage(imageData);<br><br>      worker.onmessage = function (e) {<br>        const filteredData = e.data;<br>        ctx.putImageData(filteredData, 0, 0);<br>      };<br>    };<br>    img.src = event.target.result;<br>  };<br><br>  reader.readAsDataURL(file);<br>}</pre><p>n the code above, we handle the file selection using the handleFileSelect function. When a user selects an image, we use the FileReader API to read the file data and convert it to a data URL (event.target.result). We create an HTML image element (img) and set its onload event handler.</p><p><strong>Step 6: Applying the Monochrome Filter</strong></p><p>nside the img.onload event handler, we create an HTML canvas element, set its dimensions to match the loaded image, and draw the image onto the canvas using the drawImage method. Next, we extract the image data from the canvas using ctx.getImageData.</p><p>To apply the monochrome filter, we create a new web worker using new Worker(&#39;worker.js&#39;) and send the extracted image data to the worker using worker.postMessage(imageData). The worker will process the image in the background, and when it&#39;s done, it will post a message back to the main thread with the filtered image data. We handle this message using the worker.onmessage event and display the filtered image on the canvas using ctx.putImageData(filteredData, 0, 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Oz8KSeOL-NBTQFNEm9oGw.png" /></figure><p><strong>Step 6: Completing the Project</strong></p><p>That’s it! With the code, you have successfully implemented a monochrome image filter using JavaScript and web workers. The filter converts colored images into grayscale, providing a sleek and stylish effect.</p><p><strong>Conclusion:</strong></p><p>In this tutorial, we successfully created a monochrome image filter using JavaScript and web workers. By utilizing the HTML5 Canvas API and web workers, we were able to process images efficiently on the client-side, converting colored images into grayscale with a sleek and stylish effect.</p><p>The project involved setting up the HTML structure with an input field for file selection and a canvas element for image display. We implemented a web worker that applied the monochrome filter by calculating the average of the RGB values for each pixel.</p><p>Upon user selection of an image, we loaded it into the canvas and communicated with the web worker to process the image data. The web worker executed the monochrome filter in the background, and once done, the filtered image was displayed on the canvas.</p><p>This example showcased the power of web workers for optimizing time-consuming tasks and enhancing the performance of image processing operations. With this knowledge, you can further explore and expand upon this foundation to create even more exciting image filters and applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=debc6a378b07" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>