<?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 Shrinidhi Kulkarni on Medium]]></title>
        <description><![CDATA[Stories by Shrinidhi Kulkarni on Medium]]></description>
        <link>https://medium.com/@kulkarnishreenidhi?source=rss-596b4db6b28a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Shrinidhi Kulkarni on Medium</title>
            <link>https://medium.com/@kulkarnishreenidhi?source=rss-596b4db6b28a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 08:01:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kulkarnishreenidhi/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[Open-Weight Models Are Winning on Volume. Here Is What Technology Leaders Must Decide]]></title>
            <link>https://kulkarnishreenidhi.medium.com/open-weight-models-are-winning-on-volume-here-is-what-technology-leaders-must-decide-dde7164d4d50?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/dde7164d4d50</guid>
            <category><![CDATA[open-weight-model]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[technology-leadership]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Tue, 24 Nov 2026 01:50:06 GMT</pubDate>
            <atom:updated>2026-11-24T01:50:06.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqeMIRpORKcZ6aTbw-uv6g.png" /></figure><p>Open-weight AI models are no longer a side project for developers. They are becoming part of how large organisations run AI every day.</p><p>An open-weight model is an AI model whose core files are published. A organisation can download it and run it on its own compute, instead of paying per use to send its data to an AI provider.</p><p>Adoption is moving fast. In a September 2026 survey by Enterprise Technology Research, open-weight models handled <a href="https://techstrong.ai/articles/open-weight-ai-models-expected-to-capture-41-of-enterprise-token-usage/">34 percent of enterprise AI usage</a>, up from 23 percent a year earlier.</p><p>But open models win on volume, not on spending. On Vercel’s AI Gateway, open models handled <a href="https://techstrong.ai/articles/open-weight-ai-models-seize-token-lead-but-proprietary-systems-still-make-the-money/">56 percent of the work</a> in August 2026 but only 14 percent of the spending. <strong>The same work on closed models cost about 7.8 times more.</strong> This covers one gateway, not the whole market, but the pattern is clear: companies use open models for large volumes of everyday work and pay a premium for closed models on hard problems. The quality gap is also small. Epoch AI estimates that the best open models are <a href="https://epoch.ai/data-insights/open-closed-eci-gap">about four months behind</a> the best closed ones.</p><p>For leaders, quality is no longer the main obstacle. Among companies testing open models, the top blockers were unfinished security and compliance reviews (62 percent) and the cost of running the models themselves (50 percent). Only 10 percent were worried about quality. The real questions are which work to move, how to govern it and who will run it. Cheap AI usage does not automatically mean cheap AI.</p><p>To keep this practical, we follow one example: a software company that receives about 20,000 customer support tickets a month. Each ticket must be tagged with a topic, an urgency level and the team that should handle it. Today the company sends every ticket to a paid AI service. The numbers in the example are illustrative.</p><h3>Know what “open” really means</h3><p>“Open” can mean different things, and the difference matters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ZN2BcDJmFvwH8lK8SPcvHQ.png" /></figure><p>Every model also comes with a license, a set of rules for how it can be used. Some allow almost any business use. Others restrict certain uses or the size of the company using them. Where a model comes from matters too: in the ETR survey, concerns about export controls and sanctions became three times more common.</p><p><em>In the support example,</em> one of the first models the team picks has a license that blocks one of the company’s uses. The legal team catches it before anything goes live.</p><p><strong>What leaders should do:</strong> treat AI models like any other software you bring in. Keep an approved list that shows what each model includes, its license and its country of origin, and require legal and security sign-off before use.</p><h3>Cost depends on size and memory, not the brand</h3><p>The cost of running a model comes down to one simple idea: how much memory it needs, and how quickly it can use that memory. Four terms explain most of it:</p><ul><li><strong>Parameters:</strong> the “settings” a model learned during training. More parameters usually means a more capable model, but also a bigger and costlier one. A model with 8 billion parameters needs about 16 GB of memory in its original form.</li><li><strong>Quantization:</strong> storing those settings in a compressed form, like saving a photo at a lower resolution. The same model can shrink to about 5 GB, usually with little loss on simple tasks.</li><li><strong>Mixture of experts:</strong> a model made of many specialist parts, where only a few are used for each answer. Think of a large hospital where each patient sees one or two specialists, not every doctor. The model needs room for all of them but works as fast as a small team.</li><li><strong>Context window:</strong> how much text the model can read at once. Reading more uses more memory, so a bigger window is not always better.</li></ul><p>In short, smaller and compressed models are faster and cheaper to run.</p><p><em>In the support example,</em> most tickets are only a few sentences long. So the team picks a small, compressed model and trims long email chains and error logs before the model reads them.</p><p><strong>What leaders should do:</strong> ask for cost estimates based on the busiest hour, measured on your own hardware, not on a model’s size or name. Match the model and how much it reads to your real work.</p><h3>Test on your own work, not on public scores</h3><p>Public rankings show how models do on general tests. They cannot tell you how a model will handle your products, your customers or what “urgent” means in your company. The only reliable test is a set of your own past work with known right answers. Teams call this an evaluation set.</p><p><em>In the support example,</em> the team takes 500 old tickets with known correct answers. The paid service gets 94 percent right. The open model, used as is, gets 78 percent. It sends billing questions to engineers and marks some outages as low priority. No public ranking predicted this.</p><p><strong>What leaders should do:</strong> build your own test set before choosing any model. A few hundred real examples is enough to start. Give it an owner, and rerun it whenever the model, its instructions or your data change. Once you have it, switching models becomes a quick decision instead of a guess.</p><h3>Teach the model your business</h3><p>One big advantage of open models is that you can train them further on your own examples, which most paid services do not fully allow. A common method, called LoRA, adds a small layer of new learning on top of the model instead of retraining all of it. It is like a new employee taking a short course on company processes rather than going back to university. It takes hours on one machine, not weeks on many.</p><p><em>In the support example,</em> the company has years of tickets that support staff already tagged correctly. After training on 3,000 of them, the open model scores 91 percent, close to the paid service. It did not become smarter in general. It learned this company’s topics, products and teams.</p><p><strong>What leaders should do:</strong> use this for narrow, repeated tasks where you already have good past examples. Do not use it to teach the model new general knowledge; connecting the model to your documents works better for that. Protect the training data as carefully as live customer data.</p><h3>Use both, and plan for the running costs</h3><p>Most companies are not swapping one kind of model for another. They are using both. The winning approach is to send each task to the cheapest model that is good enough for it.</p><p><em>In the support example,</em> 91 percent is close to 94 percent, but not the same. So the team splits the work. The trained open model handles tickets it is confident about. Unclear tickets, outages and security issues go to the paid service. Most tickets now go to the cheaper option, and the hardest ones still get the best model.</p><p>Then the operations team asks: who will run this? Running your own model brings costs a price list does not show:</p><ul><li><strong>Compute:</strong> enough capacity for the busiest hour, not the average one</li><li><strong>People:</strong> named owners for running, testing and governing the model</li><li><strong>Ongoing work:</strong> retesting when things change, such as a new product or a new team</li></ul><blockquote>There is also a benefit. The company decides when its model changes. With a paid service, the provider can update the model without warning, and results can shift overnight.</blockquote><p><strong>What leaders should do:</strong> connect all AI models through one central gateway, so no application depends on a single provider and switching becomes a simple setting change. Run models yourself only when you have clear owners and enough volume to save money on total cost, not just on price per use.</p><h3>The questions that matter now</h3><p><em>The support team</em> did not give up its paid AI service. It ended up with a mix: an open model for most of the work, a top model for the hard cases, and its own test set to decide when to change the balance. Expect the same pattern across many business functions as open models improve and prices fall.</p><p>Before the next discussion about open models, leaders should be able to answer five questions:</p><ol><li>What exactly are we getting, under what license, and from which country?</li><li>What will it cost to run at our busiest time, on our own compute?</li><li>What does our real work look like, and how much text does the model need to read?</li><li>How does it score on our own test set, compared with what we use today?</li><li>Who will run, test and secure it, and at what volume does it start saving money?</li></ol><p>The real question is not “open or closed?” It is “which work, at what volume, govern by whom?” With open models, control is not free. It has to be built.</p><h3>Sources</h3><ul><li>James Maguire, <a href="https://techstrong.ai/articles/open-weight-ai-models-expected-to-capture-41-of-enterprise-token-usage/">Open-Weight AI Models Expected to Capture 41% of Enterprise Token Usage</a>, Techstrong.ai, September 22, 2026 (Enterprise Technology Research survey of 200 respondents)</li><li>Steven Vaughan-Nichols, <a href="https://techstrong.ai/articles/open-weight-ai-models-seize-token-lead-but-proprietary-systems-still-make-the-money/">Open-Weight AI Models Seize Token Lead, but Proprietary Systems Still Make the Money</a>, Techstrong.ai, September 22, 2026 (Vercel AI Gateway data)</li><li>Ankit Bisht, Lareina Yee and Roger Roberts, <a href="https://www.mckinsey.com/capabilities/tech-and-ai/our-insights/open-source-technology-in-the-age-of-ai">Open source technology in the age of AI</a>, McKinsey, April 22, 2025</li><li>Epoch AI, <a href="https://epoch.ai/data-insights/open-closed-eci-gap">Open models lag state-of-the-art closed models by 4 months</a>, May 29, 2026</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dde7164d4d50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic Debt: The Hidden Bottleneck Between Your Data and Your AI Agents]]></title>
            <link>https://kulkarnishreenidhi.medium.com/semantic-debt-the-hidden-bottleneck-between-your-data-and-your-ai-agents-d2822c300cab?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2822c300cab</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ontology]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Sat, 12 Sep 2026 18:49:02 GMT</pubDate>
            <atom:updated>2026-09-12T18:49:02.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiCHVE-_iKKQGdh1G9pSYA.png" /></figure><h3>The story</h3><p>A revenue operations team wires an AI agent up to the warehouse. Leadership’s ask is simple: “Which enterprise accounts are showing early churn signals?” The team has done everything right — governed access, a well-documented warehouse, an agent framework with tool-calling into SQL. This is supposed to be the easy case, the one AI was built for.</p><p>The agent answers in four seconds. It’s confident, well-formatted, and wrong. It joined a “customer” table that means <em>logged-in user</em> to a “customer” table that means <em>billing entity</em>, because nothing told it those were different concepts with the same name. Nobody catches it for two weeks, until finance asks why the churn number in the generated report doesn’t match the number in their own dashboard — a dashboard built off a third, human-maintained definition that also disagrees with both.</p><p>Three definitions of the same word, and now a machine producing polished, board-ready answers from the wrong one, at machine speed, with machine confidence. This is worse than the version of this story where a human analyst spends three weeks confused — a confused human eventually asks someone. A confident agent doesn’t ask anyone. It just answers, and the wrong answer looks exactly as authoritative as the right one.</p><p>This is the failure mode defining this moment in enterprise AI: the constraint was never access. It’s whether the organization’s data carries enough <em>meaning</em> for a machine to use it correctly, unsupervised, at the speed machines operate.</p><h3>Discovery used to be a human-speed problem. Now it’s a machine-trust problem.</h3><p>For most of the last decade, “data discovery” meant helping a human find and understand data faster — a search bar over a catalog, a Slack channel to ask “does anyone know what this table is,” a tribal-knowledge relay from whoever built the pipeline to whoever needs to query it. Slow, but self-correcting: humans notice when something looks off, ask a colleague, and quietly patch the gap in their own understanding before shipping a number.</p><p>Agentic AI removes the self-correction. An agent doesn’t feel confused. It doesn’t pause to ask a Slack channel. It picks the most plausible-looking table, writes syntactically perfect SQL against it, and returns an answer with the same tone whether it’s right or catastrophically wrong. The cost of ambiguous, undocumented, dark data didn’t go away when agents arrived — it just stopped being visible in the form of lost analyst-hours and started being invisible inside a confident wrong answer.</p><p>The numbers back this up from every angle:</p><ul><li><strong>Discovery still eats most of the analytical workday.</strong> Anaconda’s <em>State of Data Science</em> survey puts data professionals at roughly 39–45% of their time on data preparation and cleansing — <strong>and most of that isn’t transformation work, it’s figuring out which data is even the right data to use.</strong></li><li><strong>Most enterprise data is functionally invisible.</strong> Gartner estimates 55–80% of enterprise data is “dark” — collected, stored, paid for, and never used, because nobody downstream knows it exists or what it means.</li><li><strong>This has become the defining reason AI projects die.</strong> Gartner projects organizations will abandon 60% of AI projects that aren’t backed by AI-ready data, and separately attributes 85% of AI failures to poor data quality or a lack of relevant, discoverable data — not model quality, not compute.</li><li><strong>Agentic analytics inherits the same failure, sharper.</strong> Gartner has predicted that 60% of agentic analytics projects relying solely on the Model Context Protocol (MCP) <strong>will fail specifically because they lack a consistent semantic layer underneath it</strong> — the protocol gives an agent a door, not an understanding of what’s behind it.</li></ul><p>Put together: the industry spent ten years building faster doors — self-service BI, warehouse permissions, federated ownership, data mesh — and is now discovering that a faster door onto an unlabeled room doesn’t help an agent that can’t tell one room from another. Access was the first bottleneck, and it’s solved. Meaning is the second bottleneck, and most organizations haven’t started on it.</p><h3>What “AI-ready” actually requires: five layers, not one</h3><p>Vendors sell “semantic layer” as if it’s a single product you can buy and bolt on. In practice, an AI-ready data product is built from five layers stacked on top of each other, and skipping any one of them collapses the whole thing back into the failure mode above. Each layer answers a question the one below it cannot.</p><h4>Layer 1: Access — “Can I reach it?”</h4><p>This is the layer the industry actually finished. Governed warehouses, role-based permissions, self-service BI — most organizations can already get a query or an API call to any dataset it’s entitled to see. This layer is necessary, table stakes, and no longer differentiating. If your AI strategy is still primarily about connecting agents to more data sources, you’re investing further in the layer that’s already solved.</p><h4>Layer 2: Inventory — “What exists?”</h4><p>This is what most “data catalogs” actually deliver: a list of tables, columns, types, and maybe some lineage. It answers “what exists” honestly, and that’s real value — but it’s a search problem, not a meaning problem. A table named evt_raw_v3 shows up in the inventory with its column list. Nothing about the inventory tells an agent — or a human — that this table happens to be the single best leading indicator of churn in the company. Keyword search over names and columns is exactly why so much genuinely valuable data stays dark even after it&#39;s been &quot;cataloged.&quot;</p><h4>Layer 3: Semantics — “What does it mean, and how does it relate?”</h4><p>This is the layer that’s actually new, and it’s where the real work of 2026 is happening. A semantic layer has to answer, for any concept an agent might need: what real-world entity does this represent, what does each state or status value actually mean, what’s it related to and through which keys, what are its known synonyms and aliases across teams, and what’s the specific, named gap or caveat a requester needs to know before trusting it.</p><p>This is also where the industry’s tooling is visibly maturing past the BI-era “metrics layer.” A semantic layer built for human dashboards defines a metric once and stops. A semantic layer built for agents has to also carry relationship mapping for multi-step reasoning, domain-scoped definitions for when the same word means different things in different parts of the business, and enough structure — whether that’s a knowledge graph, an OWL ontology, or a governed metrics store — that an agent can resolve ambiguity without guessing.</p><blockquote>Atlan’s AI Labs benchmarked this directly: adding this layer of business context improved text-to-SQL accuracy by 38%. That’s not a rounding error; that’s the difference between a usable agent and a liability.</blockquote><p><em>Example:</em> the two “customer” tables from the opening story stop being a landmine the moment each is tagged with what it actually represents — customer (billing entity, source: Stripe, grain: one row per paying account) versus app_user (logged-in identity, source: auth service, grain: one row per login credential) — plus an explicit note that &quot;churn&quot; as finance defines it and &quot;churn&quot; as product defines it are two different, equally valid, non-interchangeable metrics. An agent that can read that distinction stops guessing which one applies.</p><h4>Layer 4: Trust and contract — “Can I believe it, and who’s accountable if I’m wrong?”</h4><p>Meaning without trust signals is still dangerous — an agent can now correctly identify what a field means and still not know if it’s fresh, complete, or actively drifting. This layer is where data contracts, quality certifications, freshness SLAs, provenance, and ownership live. It’s the difference between an agent citing a number and an agent citing a number <em>with an audit trail back to a definition someone is accountable for</em> — which matters enormously the moment a wrong answer and a right answer arrive in exactly the same confident tone. Traceability isn’t a nice-to-have at this layer; it’s what makes the difference reviewable at all.</p><h4>Layer 5: Agent access — “Can a machine actually consume this safely, at scale?”</h4><p>The final layer is the interface itself. This is where the Model Context Protocol and interfaces like it matter — not as a replacement for the layers underneath, but as the standardized way an agent reaches them, with access control and row-level security enforced <em>before</em> a query runs rather than filtered after the fact, and with caching and pre-aggregation so production agent traffic doesn’t fall over the moment it stops being a demo. This is precisely the layer Gartner’s warning targets: MCP is a very good door. It is not, by itself, a semantic layer, and treating it as one is how the 60% failure rate happens.</p><p>Skip layer 3 and layer 5 becomes a fast, well-governed way to get a confidently wrong answer. Skip layer 4 and you get correct answers today with no way to know when they quietly become wrong tomorrow. The layers compound — each one is what makes the layer above it trustworthy rather than merely reachable.</p><h3>Why this is the actual unlock for AI use cases</h3><p>Every one of the headline AI-readiness numbers above — the 60% project abandonment, the 85% failure attribution — traces back to organizations trying to stand a Layer 5 capability (an agent, a copilot, an autonomous workflow) directly on top of Layer 1 or Layer 2 infrastructure, with nothing in between. It looks like it should work, because the agent <em>can</em> reach the data. It fails because reaching data and understanding it are different problems, and only one of them was solved.</p><p>The organizations getting real, compounding value from AI right now aren’t the ones with the most agents deployed. They’re the ones that treat layers 3 and 4 as durable infrastructure rather than a one-off project scoped to a single use case. Every entity definition, relationship, and known caveat captured for one agent becomes available to the next one — a support-sentiment gap documented for a churn-prediction agent is the same gap a forecasting agent needs to know about six months later. That compounding effect is what actually shrinks the discovery bottleneck over time: not faster search, but a growing body of machine-readable meaning that fewer and fewer new use cases have to rediscover from scratch.</p><h3>What to actually do about it</h3><p>Three moves, in order, for a team trying to close this gap without turning it into a multi-year program:</p><p><strong>Stop scoring your data platform on access and inventory alone.</strong> If your “AI readiness” dashboard measures catalog coverage and API uptime, it’s measuring the two layers that are already solved. Add a measure of semantic coverage — what percentage of the entities your agents actually touch have a governed definition, a known relationship map, and a documented caveat list.</p><p><strong>Build the semantic layer narrow and deep before wide and shallow.</strong> Pick the one or two AI use cases with real business pressure behind them, and fully instrument layers 3 and 4 for exactly the entities those use cases touch — don’t attempt an enterprise-wide ontology on day one. A precisely modeled slice beats a comprehensive but shallow one every time an agent actually has to reason across it.</p><p><strong>Treat MCP — or any agent-access layer — as the last step, not the first.</strong> If the plan is “give the agent MCP access to the warehouse” without a semantic layer underneath, that plan is statistically likely to be one of Gartner’s 60%. Sequence it: access exists already, inventory is quick, semantics and trust are the real build, and the protocol layer on top is what finally makes all of that reachable by any agent instead of one bespoke integration at a time.</p><p>The organizations that will look “AI-native” a year from now aren’t the ones who moved fastest on agents. They’re the ones who quietly did the unglamorous work of making their data mean something a machine could trust — before they asked a machine to use it.</p><p>Sources:</p><ul><li><a href="https://www.bigdatawire.com/2020/07/06/data-prep-still-dominates-data-scientists-time-survey-finds/">Data Prep Still Dominates Data Scientists’ Time, Survey Finds</a></li><li><a href="https://atlan.com/dark-data-101/">Dark Data: Concept, Challenges, and Ways to Manage It</a></li><li><a href="https://www.gartner.com/en/newsroom/press-releases/2025-02-26-lack-of-ai-ready-data-puts-ai-projects-at-risk">Lack of AI-Ready Data Puts AI Projects at Risk — Gartner</a></li><li><a href="https://atlan.com/know/ai-agent/semantic-layer-for-ai-agents/">What Is a Semantic Layer for AI Agents? A Complete 2026 Guide — Atlan</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2822c300cab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harness Engineering, Applied: Data Pipelines, Tested Under Failure]]></title>
            <link>https://kulkarnishreenidhi.medium.com/harness-engineering-applied-data-pipelines-tested-under-failure-199d8b139a37?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/199d8b139a37</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 23:59:44 GMT</pubDate>
            <atom:updated>2026-08-12T23:59:44.977Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>The follow-up to </em></strong><a href="https://kulkarnishreenidhi.medium.com/harness-engineering-the-anatomy-of-an-agent-harness-0efe10a596d0?sharedUserId=kulkarnishreenidhi"><strong><em>Harness Engineering: The Anatomy of an Agent Harness</em></strong></a><strong><em>.<br></em></strong><em>That post made the case that </em><em>Agent = Model + Harness — the harness being everything you configure around the model. This one builds all four pieces of that harness against a real data pipeline, breaks each one on purpose, and reports what actually happened — including the parts that didn&#39;t work the first time.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*spBUq7qEcyrBF6CcLsMj4A.png" /></figure><p>The project is txpipeline, (<a href="https://github.com/shree644/txpipeline.git">git-repo</a>) a batch ETL job that ingests transaction records, validates them, transforms them, and loads them into a database — the kind of pipeline most data teams run in some form. Every test below runs against the same synthetic batch, with a realistic mix of clean and messy data baked in. The point isn&#39;t the pipeline. It&#39;s what happens when each pattern meets a failure that actually costs something.</p><p>Four patterns, in the order you’d want to add them to your own project:</p><ol><li><strong>Agentfiles</strong> — encode your conventions before the agent has to guess them</li><li><strong>Skills</strong> — keep occasional workflows out of the agent’s default context</li><li><strong>Hooks</strong> — enforce your rules instead of just stating them</li><li><strong>Sub-agents</strong> — keep exploratory noise out of your main conversation</li></ol><h3>1. Agentfiles — what goes in CLAUDE.md, and what doesn&#39;t</h3><p><strong>The risk:</strong> a batch job that silently double-loads data on re-run. The trigger isn’t exotic — a process dies mid-run, someone re-runs it, and without an explicit rule against it, nothing stops the same batch loading twice.</p><p><strong>The rule:</strong> put a constraint in CLAUDE.md only if it&#39;s true on <em>every</em> task, without exception — a safety boundary, a data-integrity invariant, a testing convention. If a constraint only applies to one specific <em>kind</em> of task, it doesn&#39;t belong here — it belongs in a skill (section 2). This distinction is the difference between an agentfile that stays readable and one that turns into a 200-line wall nobody actually reads before acting.</p><p><strong>How to write yours:</strong></p><ol><li>Run a handful of real tasks with no agentfile present. Let the agent make its own default choices.</li><li>Log exactly what went wrong — not what <em>could</em> go wrong, what actually did.</li><li>Write one rule per failure, and note which failure it traces to. If you can’t point to an incident, don’t add the rule yet.</li><li>Re-run an equivalent task and confirm the rule actually changed the outcome.</li></ol><p><strong>The realistic trigger, in practice:</strong> a teammate uses Claude Code to fix a nightly batch job that choked halfway through. Instead of debugging why, they take the obvious shortcut — ask the agent to just re-run it against the same incoming/ files. <em>Nobody thinks twice about this; it&#39;s the normal instinct after a failed run</em>. That&#39;s the exact scenario tested here — the same batch, run twice against an already-loaded database, no code changes in between:</p><pre>before: 830 rows / $1,236,865.38<br>after:  1,660 rows / $2,473,730.76   (identical run summary printed both times)</pre><p>Every previously-loaded row got re-inserted. Nothing in the pipeline’s own output said so — the only way to catch it was to query the database directly.</p><p><strong>The actual rule that went into </strong><a href="https://github.com/shree644/txpipeline/blob/main/CLAUDE.md"><strong>CLAUDE.md</strong></a><strong>:</strong></p><pre>- Re-running the pipeline on a batch must never double-load a<br>  transaction_id already present in `transactions`. The run summary<br>  must report a `skipped_as_duplicate` count.</pre><p><strong>After</strong>, same scenario:</p><pre>first run:  loaded 810,  skipped as duplicate 10<br>re-run:     loaded 0,    skipped as duplicate 820   → 810 rows, $1,208,665.75, unchanged</pre><p>loaded: 0 is now visible in the run summary itself — no database query required to catch it.</p><h3>2. Skills — when a workflow graduates out of CLAUDE.md</h3><p><strong>The rule: the moment the same multi-step task has happened twice, in the same shape, extract it into a skill. Don’t wait for a third repetition, and don’t fold it into </strong><strong>CLAUDE.md.</strong> The reason is mechanical, not stylistic: everything in CLAUDE.md loads into context on <em>every single turn</em>, whether or not that turn needs it. A skill&#39;s content only loads when the agent&#39;s own matching decides the current task actually calls for it. If you catch yourself writing &quot;if you&#39;re doing X, follow these five steps&quot; inside your agentfile, that&#39;s a skill trying to happen — move it out.</p><p><strong>Put it in </strong><strong>CLAUDE.md if:</strong></p><ul><li>It’s true on every task, no exceptions</li><li>It’s a hard constraint or safety boundary</li><li>It’s short — a rule, not a procedure</li></ul><p><strong>Put it in a skill if:</strong></p><ul><li>It’s only relevant to one recognizable kind of task</li><li>It’s a repeatable, multi-step workflow</li><li>It can be as long as it needs to be, because it’s not loaded by default</li></ul><p><strong>Anatomy of a skill file (</strong><a href="https://github.com/shree644/txpipeline/blob/main/.claude/skills/add-validation-rule/SKILL.md"><strong>skill.md</strong></a><strong>):</strong></p><pre>---<br>name: add-validation-rule<br>description: Use when adding a new business-rule validation check to<br>  txpipeline — a rejection condition beyond basic schema shape. Use<br>  whenever asked to add, change, or remove a rejection rule.<br>---<br><br>1. Add the check to schema.validate(), same place/shape as existing checks.<br>2. Reason code: lowercase snake_case.<br>3. Add a pytest test.<br>4. Verify against the real batch, not just the unit test.</pre><p><strong>The </strong><strong>description field is the whole mechanism — get it wrong and the skill never fires.</strong> It&#39;s what the agent matches against an incoming task at the start of a session, before deciding whether to invoke it. Write it the way you&#39;d describe the task to a teammate (&quot;use when adding a new validation rule&quot;), not as a title. A vague or overly narrow description means the skill exists on disk and never actually gets used.</p><p><strong>The realistic trigger, in practice:</strong> you ask coding agent — “add a rule to reject anything over $4,500, needs manual review” — the third time this exact shape of request has landed this month, each time worded a little differently. This is what makes it a skill candidate rather than a one-off: the <em>request</em> varies, but the <em>steps</em> to satisfy it don’t. Demonstrated live on exactly that ask, on a third rule:</p><pre>records loaded:  737<br>skipped as duplicate: 8<br>records rejected: 155<br>  - amount_exceeds_limit: 77<br>  - future_dated: 8<br>  ...</pre><p>future_dated dropped from 10 to 8 in this run — not a regression. Two records tripped both rules and landed under whichever check ran first. Read in isolation, a dropping counter looks like a bug; step 4 of the skill (verify against the real batch, not just the unit test) is specifically what surfaces the real explanation instead of a false alarm. Inlining these four steps into CLAUDE.md would have added roughly 30 lines to a file meant to stay short enough to actually be read carefully on every turn — that&#39;s the concrete cost progressive disclosure avoids.</p><h3>3. Hooks — turning a rule into an enforced check</h3><p><strong>The risk:</strong> “run the tests before declaring done” is easy to state and easy to skip under pressure. An agentfile rule is a request; nothing mechanically stops it from being ignored.</p><p><strong>The rule: any instruction phrased as “always do X before Y” is a hook candidate, not an agentfile line.</strong> If skipping it would ever be a real problem, don’t rely on the agent choosing to comply — make compliance a precondition for finishing.</p><p><strong>Anatomy of the </strong><a href="https://github.com/shree644/txpipeline/blob/main/.claude/hooks/run-tests.sh"><strong>hook</strong></a><strong> :</strong></p><pre>{<br>  &quot;hooks&quot;: {<br>    &quot;Stop&quot;: [{<br>      &quot;hooks&quot;: [{<br>        &quot;type&quot;: &quot;command&quot;,<br>        &quot;command&quot;: &quot;.claude/hooks/run-tests.sh&quot;<br>      }]<br>    }]<br>  }<br>}</pre><pre># .claude/hooks/run-tests.sh<br>output=$(.venv/bin/pytest -q 2&gt;&amp;1)<br>[ $? -ne 0 ] &amp;&amp; echo &quot;$output&quot; &gt;&amp;2 &amp;&amp; exit 2</pre><p>Stop fires when the agent tries to end its turn — the right lifecycle point for a &quot;must pass before you&#39;re done&quot; check. Exit 0 lets the turn end silently. Exit 2 blocks it and feeds the script&#39;s stderr back into context, so the agent sees the real failure, not just &quot;blocked.&quot;</p><p><strong>The realistic trigger this catches, concretely:</strong> say your teammate schedules a nightly cron job that runs Claude Code unattended to reprocess whatever failed overnight and auto-merge the fix:</p><pre>0 2 * * * claude -p &quot;Re-run last night&#39;s failed batch, fix any test<br>failures, and merge when done.&quot; &gt;&gt; /var/log/txpipeline-nightly.log 2&gt;&amp;1</pre><p>That -p flag runs Claude Code in headless/print mode — no terminal, no one watching.</p><p><strong>Before — hook doesn’t fire (the exact failure mode a headless job hits):</strong> a test was deliberately left broken, and the agent tried to end its turn declaring the task done anyway, with no manual test run first:</p><pre>Turn ended with: &quot;The rule is implemented. Task done.&quot;<br><br><br>Next turn began with: a plain continue from the operator — no pytest<br>output, no hook-related text, nothing surfaced into context at all.<br><br>tests/test_schema.py confirmed still broken afterward.</pre><p>Nothing stopped it. In the cron scenario above, this is the version where the overnight merge goes through with a broken test still in the codebase, and the log shows a clean exit, because nothing ever ran to catch it.</p><p><strong>After — hook fires (same break, same task, run interactively instead):</strong></p><pre>[.claude/hooks/run-tests.sh]: ......F  [100%]<br>&gt; assert result.reason == &quot;invalid_amount&quot;<br>E AssertionError: assert &#39;invalid_currency&#39; == &#39;invalid_amount&#39;<br>1 failed, 6 passed in 0.04s</pre><p>The turn was blocked, not completed — the agent saw the real failure and fixed it before trying again. Once the suite was actually green, ending the turn the same way produced no interruption at all:</p><pre>$ pytest -q<br>.......  [100%]<br>7 passed in 0.03s</pre><p><strong>The difference between “before” and “after” here isn’t the hook configuration — it’s identical in both cases.</strong> It’s whether Claude Code was running interactively (hook enforced) or headlessly via -p (hook not enforced). Same script, same settings file, opposite outcome, depending entirely on how the session was invoked. That&#39;s the trap: a hook that works perfectly in your terminal can be silently inert in exactly the unattended context — cron, CI, a background script — where you&#39;d want it enforced the most.</p><p><strong>How to actually validate one before you trust it — two steps, not one:</strong></p><ol><li><strong>Verify the mechanics directly first.</strong> Run the hook script by hand against a deliberately broken test:</li></ol><pre>$ .claude/hooks/run-tests.sh; echo &quot;exit code: $?&quot;<br>.FFFFF  [100%]<br>5 failed, 1 passed in 0.04s<br>exit code: 2</pre><p>This confirms the script and config are correct — but it does <strong>not</strong> confirm Claude Code will actually run it in the mode you plan to use.</p><ol><li><strong>Then confirm it in whichever mode you’ll actually run it in — interactive and headless are not interchangeable.</strong> If your real usage is a cron job or CI script (headless, -p), test it that way specifically, not just in a terminal session — a pass in one mode tells you nothing about the other.</li></ol><p><strong>Take this as a standing rule, not a one-off gotcha: a hook that passes a manual script test is not proven — it’s only proven once you’ve watched it fire in the actual mode you’ll run it in.</strong> A hook validated only in an interactive terminal tells you nothing about whether it’ll protect an unattended cron job, and vice versa.</p><h3>4. Sub-agents — delegate the search, not the decision</h3><p><strong>The risk:</strong> understanding how a field flows through a pipeline before changing its schema takes a lot of looking, and almost none of that looking is worth keeping in your working context afterward.</p><p><strong>The rule: delegate to a sub-agent when the task is “go find out,” not “make a judgment call.”</strong> A bounded, gradable lookup — map every reference to a field, check whether a path is tested, confirm a pattern is followed consistently — is a good fit. A decision that needs your context and priorities isn’t; keep that in the main thread.</p><p><strong>Delegate to a sub-agent when the question is:</strong></p><ul><li>“Find every place X is referenced”</li><li>“Map what touches this field before I modify it”</li><li>Checkable against the code, objectively — no judgment call needed</li></ul><p><strong>Keep it in the main thread when the question is:</strong></p><ul><li>“Should we change X”</li><li>“Design the migration for this field”</li><li>Dependent on your own context or trade-offs, not just a lookup</li></ul><p><strong>Invocation:</strong></p><pre>Agent(subagent_type: &quot;Explore&quot;, prompt: &quot;find every place amount and<br>currency are read, transformed, validated, or persisted across this<br>pipeline&quot;)</pre><p><strong>The realistic trigger, in practice:</strong> right before a schema change ships, a teammate needs to know everywhere amount and currency get touched — without burning an hour grepping eight files themselves, or filling their own context window doing it while they&#39;re mid-task on something else. Delegated exactly that — the sub-agent returned a condensed report and volunteered three findings nobody asked for directly, all confirmed against the actual code:</p><ol><li>No test existed for the invalid-currency rejection path.</li><li>The USD-converted amount field was entirely untested — nothing would catch the currency list and the conversion-rate table drifting out of sync into a runtime error.</li><li>Rejected records had no structured amount/currency columns, only the raw line.</li></ol><p>None of the sub-agent’s intermediate searching — the files it opened, the dead ends — entered the main conversation. Reading those files directly would have pulled roughly 400 lines into context; the report was a few hundred words.</p><h3>Checklist for your own pipeline</h3><ol><li><strong>Agentfile:</strong> one rule per real incident. If you can’t name the incident, don’t add the rule yet.</li><li><strong>Skill:</strong> the second time a workflow repeats in the same shape, pull it out — and write the description field like you&#39;re briefing a teammate, since that&#39;s what determines whether it ever actually fires.</li><li><strong>Hook:</strong> any “always do X before Y” becomes a Stop hook, not an agentfile line — and validate it in a real interactive session, not a headless one.</li><li><strong>Sub-agent:</strong> “find everywhere this happens” gets delegated. “Should we change this” stays with you.</li></ol><p>None of these four patterns are exotic. Each one is a small amount of configuration and a few minutes of deliberately breaking something to see what happens.</p><p>It’s worth being direct about why that configuration is necessary at all, rather than something a better model eventually makes unnecessary. None of the failures in this post were reasoning failures. The duplicate-load bug wasn’t a model failing to understand idempotency — it’s a model doing exactly what was asked, correctly, against a schema with no uniqueness constraint. The Stop hook not firing wasn’t a lapse in judgment — it’s a property of <em>how a session was invoked</em>, something no amount of model capability touches, because the model was never even asked the question. A smarter model still can’t tell you the five-step shape of your team’s validation-rule convention unless something puts that in front of it at the right moment, and it still can’t enforce a test suite on itself if there’s nothing external checking its own claim of “done.”</p><p>That’s the actual argument for Agent = Model + Harness:A better model gives you a better collaborator inside whatever structure you’ve built. It does not build the structure for you, and it will not notice the structure is missing until something has already gone wrong inside the gap. The harness is what turns “the model is smart enough to know better” into “it doesn’t matter whether it does — the system won’t let it happen anyway.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199d8b139a37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harness Engineering : The Anatomy of an Agent Harness]]></title>
            <link>https://kulkarnishreenidhi.medium.com/harness-engineering-the-anatomy-of-an-agent-harness-0efe10a596d0?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/0efe10a596d0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Fri, 24 Apr 2026 20:47:18 GMT</pubDate>
            <atom:updated>2026-04-29T00:52:04.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ghGo6_sOz92OS9Cn_ZpXFw.png" /><figcaption>Harness Engineering</figcaption></figure><h3>Introduction: The Promise vs. The Reality</h3><p>The software industry has spent the last two years intensely arguing about models: which one is the smartest, which one writes the cleanest React components, and which one hallucinates the least. The promise of the AI software engineer is incredibly tantalizing, but the reality often falls short.</p><p>If you have tried incorporating these tools into a complex workflow, you have likely watched coding agents fail in every conceivable way: ignoring explicit instructions, executing dangerous commands unprompted, and going in circles on the simplest of tasks. As software engineers, we have a natural trust barrier with AI-generated code. LLMs are inherently non-deterministic, they do not intrinsically know our specific business context, and ultimately, they do not really understand the code — they think in tokens.</p><p>In the modern AI ecosystem, an autonomous developer is defined by a simple equation: <strong>Agent = Model + Harness</strong>. The model is just one input into a running agent; the rest is the harness. <strong>If you are not the model, you are the harness. </strong><br>This is the frontier of <strong>Harness Engineering</strong>: the discipline of treating the scaffolding around the model — the prompts, tools, context policies, hooks, sandboxes, and feedback loops — as a real, primary artifact. It is the practice of leveraging these configuration points to customize and dramatically improve your coding agent’s output quality and reliability.</p><h3>The Problem: The Chaos of the Unbound Agent</h3><p>A raw model is not an agent. Without a harness, you do not have an automated workflow; you essentially just have a chat window where you are forced to copy and paste code back and forth. When developers attempt to give these raw models more autonomy by simply providing them with <strong>massive prompts or full repository access</strong>, they inevitably collide with several fundamental failure modes.</p><h4>1. Context Rot and the “Dumb Zone”</h4><p>The most common instinct when an agent fails is to simply give it a larger context window so it can “see” more of the codebase. However, research into “context rot” proves that models actually perform worse as their context length increases.When you stuff every possible instruction, tool description, and file into the system prompt, you rapidly push the model out of its “smart zone” and deep into the “dumb zone”. Extended context windows do not magically make the model better at finding the exact code snippet it needs; they just make the haystack bigger. Every irrelevant tool description and massive log file becomes a distractor that degrades the agent’s reasoning capabilities</p><h4>2. The Long-Horizon Breakdown</h4><p>While models are great at answering single questions, autonomous long-horizon work is notoriously difficult. When tasked with complex, multi-step problems, unbound models consistently suffer from early stopping, poor decomposition of the problem, and general incoherence as the work stretches across multiple context windows.They end up going in circles on the simplest of tasks. Furthermore, a raw model is incredibly bad at verifying its own success; agents reliably skew positive when grading their own work, meaning they will confidently claim a broken feature is finished.</p><h4>3. Safety and Trust Barriers</h4><p>We have a natural trust barrier with AI-generated code because LLMs are non-deterministic. An unbound agent will easily ignore instructions or execute dangerous commands unprompted.Running agent-generated code directly on your local machine is inherently risky. Worse, if an agent is simply given unstructured access to external tools via Model Context Protocol (MCP) servers, it opens up severe security vulnerabilities: because tool descriptions populate the prompt, a sloppy or malicious MCP can prompt-inject your agent before you have even typed a command.</p><blockquote>Solving these fundamental breakdowns requires more than just increasing context windows or waiting for smarter models. We must actively design the environment that surrounds and controls the AI — a discipline known as <strong>harness engineering</strong>. Let’s dive in to understand exactly what it is and how it works.</blockquote><h3>What is Harness Engineering?</h3><p>In the modern AI ecosystem, the definition of a coding agent boils down to a single, fundamental equation: <strong>Agent = Model + Harness</strong>. Simply put, if you are not the model itself, you are the harness.</p><p>A raw model is essentially just a text-prediction engine. It only becomes an autonomous agent when a harness surrounds it with state, tool execution, feedback loops, and enforceable constraints. The harness encompasses everything else in the system: the system prompts, APIs, memory policies, isolated sandboxes, sub-agents, and recovery paths.</p><p><strong>Harness engineering</strong> is the discipline of treating this scaffolding as a primary, first-class engineering artifact. While AI providers supply a default, built-in harness (like a base system prompt or standard orchestration logic) , the true leverage lies in building the <strong>User Harness</strong>. This is the custom layer of controls you build explicitly for your specific system. Harness engineering is driven by a simple, uncompromising philosophy: anytime your agent makes a mistake, you engineer a solution into the harness so it <em>never</em> makes that exact mistake again</p><h3>Deep Dive: The Anatomy of an Agent Harness</h3><p>To successfully tame a non-deterministic model, your harness must rely on anticipating unwanted outputs (feedforward) and providing mechanisms for the agent to self-correct (feedback). It is not just about giving the model tools; it is about expertly designing both the tools and the loop in which they operate.When we break down a mature, production-grade harness, we find four primary pillars of configuration that deliver the highest leverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*4NmHf9bOWBwA5SW1_omdpw.png" /></figure><h4>1. Agentfiles (The Baseline)</h4><p>Before touching complex orchestration or external integrations, you must configure your CLAUDE.md or AGENTS.md files. These are markdown files at the root of your repository that get deterministically injected into the agent&#39;s system prompt by the harness.</p><p>The golden rule here is to treat these files like a pilot’s checklist, not a comprehensive style guide.</p><ul><li><strong>Keep it incredibly concise:</strong> The best agentfiles are often under 60 lines. Every line competes for the model’s attention.</li><li><strong>Earn each rule:</strong> Rules should trace back directly to a specific past failure or a hard external constraint. If a rule doesn’t solve a known problem, it is just noise.</li><li><strong>Do not auto-generate them:</strong> A study by ETH Zurich tested 138 agentfiles and found that LLM-generated agentfiles actually hurt performance and increased costs by over 20%. Carefully craft these instructions yourself.</li></ul><blockquote><strong>Industry Review:</strong><br>This aligns with what Thoughtworks sees in the field too — they have independently validated hand-crafted instructions at Adopt level, while flagging auto-generated ones as Caution. Read more from <a href="https://www.thoughtworks.com/radar/techniques/summary/agent-instruction-bloat">Thoughtworks Tech Radar.</a></blockquote><h4>2. Skills and Progressive Disclosure</h4><p>A common trap is stuffing every possible tool description and instruction into the system prompt. If you do this, you will blow through your model’s “instruction budget” before the agent even begins its work. Furthermore, adding too many Model Context Protocol (MCP) servers clutters the prompt with tool schemas, rapidly pushing the model into the “dumb zone”.</p><p>The solution is <strong>progressive disclosure</strong> via <strong>Skills</strong>. Instead of front-loading everything, the harness keeps instructions and tools hidden until the exact moment the task calls for them. The agent is only informed of specific workflows or files when it actively decides it needs that knowledge, preserving the context window for actual problem-solving.</p><blockquote><strong>Industry Review:</strong><br>The broader industry is catching up to this pattern — Thoughtworks has trialled Progressive Context Disclosure and moved it to Trial in their latest <strong>Tech Radar</strong>. Read more from <a href="https://www.thoughtworks.com/radar/techniques/summary/progressive-context-disclosure">Thoughtworks Tech Radar</a>.</blockquote><h4>3. Hooks and Back-Pressure (The Enforcement Layer)</h4><p>Your coding agent’s likelihood of success is strongly correlated with its ability to verify its own work. <strong>Hooks</strong> are the enforcement layer that makes this possible. They are user-defined scripts that run automatically at specific points in the agent’s lifecycle (e.g., before a tool call, after a file edit, or when the agent attempts to finish).</p><p>Hooks create “back-pressure,” forcing the agent to deal with reality. For example, you can wire a hook to run your TypeScript type checks every time the model pauses.</p><ul><li><strong>Success is silent:</strong> If the typecheck passes, the script exits silently, and nothing ends up in the agent’s context.</li><li><strong>Failures are verbose:</strong> If it fails, the hook intercepts the stop, surfaces the exact compiler errors into the context, and forces the agent to fix them before it is allowed to finish.</li></ul><blockquote><strong>Industry Review:</strong><br>This is not just theory — Thoughtworks has trialled this pattern, listing Feedback Sensors for Coding Agents at Trial in their latest Tech Radar. Read more from <a href="https://www.thoughtworks.com/radar/techniques/summary/feedback-sensors-for-coding-agents">Thoughtworks Tech Radar</a>.</blockquote><h4>4. Sub-Agents: The Context Firewall</h4><p>Sub-agents are arguably the most powerful — and most misunderstood — harness configuration point. Many teams try to use them as roleplaying personas, like a “frontend engineer” sub-agent or a “data analyst” sub-agent, which simply does not work well.</p><p>Instead, sub-agents should be used strictly for <strong>context control</strong>. They act as a “context firewall” against context rot.</p><ul><li>When a primary agent delegates a task (like “find where the XYZ schema is defined”), the sub-agent receives a completely fresh, isolated context window with its own instruction budget.</li><li>The sub-agent might make 40 different grep and bash tool calls, stumbling around the codebase to find the answer.</li><li>Because of the context firewall, none of that intermediate noise pollutes the parent agent’s thread. The parent only receives the final, highly condensed answer.</li><li><strong>Cost Control:</strong> Because sub-agents handle discrete, smaller tasks, you can confidently run them on cheaper, faster models (like Claude 3.5 Haiku) while reserving your expensive models (like Opus) for the parent orchestration session.</li></ul><h3>Why It Pays Off</h3><p>Investing time in configuring a harness might feel like a distraction from actually writing code. But teams that treat harness engineering as a primary practice consistently report outsized returns — and the advantage compounds as models improve.</p><p><strong>The harness scales with model intelligence.</strong> A common fear is that better models will make harness investment obsolete. The opposite is true. A well-designed harness does not just compensate for model weaknesses — it amplifies model strengths. As models get smarter, the same hooks and sub-agent architecture unlock capabilities that were previously impossible, rather than simply becoming redundant.</p><p><strong>Token costs drop significantly.</strong> Progressive disclosure prevents the model from processing irrelevant context on every turn. Sub-agents route simple lookup tasks to cheaper models instead of burning expensive tokens on your orchestration model. Teams routinely see 30–50% reductions in token spend after implementing these two patterns alone.</p><p><strong>Review toil shrinks.</strong> When hooks enforce type checks, linting, and test suites automatically, the agent catches its own errors before they reach human eyes. The result is that code reviews shift from “did the agent break something obvious” to “is this the right architectural decision” — which is where human time is actually well spent.</p><p><strong>It becomes a transferable asset.</strong> A mature harness configuration is not throwaway scaffolding. It encodes your team’s engineering standards, failure history, and domain constraints in a format that onboards every new team member — human or AI — instantly. It is institutional knowledge made executable.</p><blockquote>This creates a compounding effect over time — Thoughtworks calls this the Feedback Flywheel, a meta-technique where teams capture successes and failures from agent sessions to continuously improve the harness, making future sessions more predictable. Thoughtworks has independently assessed this pattern in their latest Tech Radar. Read more from <a href="https://www.thoughtworks.com/radar/techniques/summary/feedback-flywheel">Thoughtworks Tech Radar</a>.</blockquote><h3>Conclusion: The Irreplaceable Human</h3><p>As foundational models become more capable, the differentiator between competing AI coding tools will not just be the LLM they use — it will be the environment designed around it. Look at the top coding agents today; their underlying models differ, but their harness patterns are converging.</p><p>However, even the best harness cannot entirely replace the human developer. We bring an implicit harness to every codebase: we understand organizational alignment, we know which technical debt is tolerated for business reasons, and we know our name is on the commit.</p><p>Harness engineering is our attempt to externalize that human experience and make it explicit for the machine. We are not building these environments to eliminate human input, but to direct our input to where it is most critical.</p><p>The next time your autonomous agent fails to resolve a ticket, look at your tools, tighten your hooks, update your agentfile, and engineer the failure out of existence. The model is probably fine — it is just a harness issue.</p><blockquote>Thanks for reading…</blockquote><blockquote>Stay tuned for my next post , where I will dive into a practical, real-world example of harness engineering in action.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0efe10a596d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Agent Systems : A Practical Implementation Guide]]></title>
            <link>https://kulkarnishreenidhi.medium.com/building-multi-agent-systems-a-practical-implementation-guide-b09d815cd328?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b09d815cd328</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[multiagent-system]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 03:31:45 GMT</pubDate>
            <atom:updated>2025-12-20T03:43:17.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Multi AI Agents: A Practical Implementation Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WPdxBLnTK0znkVCmQCblsA.png" /></figure><p>In the evolving landscape of Artificial Intelligence, we are moving beyond simple chatbots. We are entering the era of <strong>Agentic AI</strong> — systems that can use tools, think through steps, and solve complex problems autonomously.</p><p>In my <a href="https://medium.com/@kulkarnishreenidhi/building-a-local-ai-agent-with-python-a-practical-implementation-guide-b45f71cffdfb">previous blog</a> we tried to understand about Agentic AI with practical implementation of an agent capable of analyzing airlines dataset. But what happens when a task is too complex for one AI agent and want to orchestrate complete trip itinerary ? That is where the <strong>Multi-Agent</strong> <strong>Supervisor Architecture</strong> comes in.</p><h3>What is a <strong>Multi-Agent </strong>Supervisor Solution?</h3><p>A <strong>Multi-Agent Supervisor Solution</strong> mimics a professional team. Instead of one AI trying to do everything, you have a <strong>Manager (the Supervisor)</strong> and several <strong>Specialists (the Workers)</strong>.</p><ul><li><strong>The Supervisor</strong>: Orchestrates the work. It listens to your request, decides which specialist is best for the job, and delegates the task.</li><li><strong>The Workers</strong>: These are specialized agents. Once a worker finishes, they report back to the Supervisor, who reviews the result and decides if more work is needed or if the task is complete.</li></ul><h4>Advantages Compared to Single Agents</h4><ul><li><strong>Specialization</strong>: You can have one agent expert in web searching and another in technical writing, ensuring high-quality output in each domain.</li><li><strong>Efficiency</strong>: Single agents often get overwhelmed by long, complex instructions. In a supervisor model, each worker only receives the specific task they are an expert in.</li><li><strong>Scalability</strong>: You can easily add more specialists (like a “Data Analyst”) without rewriting the entire logic of your system.</li></ul><h3>Example: Smart Travel Concierge</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4P2SlsILEYWKvlEbPAUcw.png" /></figure><p>The above diagram illustrates how the Supervisor manages the flow of information between the user and the specialized agents.</p><p>We will take an example of <strong>Smart Travel Concierge</strong> which demonstrates a sophisticated <strong>Supervisor Agentic Architecture </strong>by simulating a real-world team environment.</p><p><strong>The Core Intention: Orchestration and Routing</strong></p><p>The primary goal of this setup is to show how a Supervisor node uses an LLM to act as an intelligent router. Even with mocked responses, the architecture proves its capability in below areas:</p><ul><li><strong>Request Analysis</strong>: The Supervisor evaluates the raw “User Request” to determine intent — detecting if you need a flight, a hotel, or both.</li><li><strong>State Verification</strong>: After an agent finishes its task, control returns to the Supervisor. The Supervisor reviews the <strong>Shared State</strong> (the memory) to see if the job is truly done or if another specialist needs to be called.</li></ul><p><em>Let’s Dive-in</em></p><h3>Step 1: Getting Your OpenAI API Key</h3><p>To run this solution locally, you need an API key to power your agents.</p><ol><li>Visit the <a href="https://platform.openai.com/">OpenAI Platform</a> and create an account.</li><li>Navigate to the <strong>API Keys</strong> section in the side menu.</li><li>Click <strong>“Create new secret key”</strong>.</li><li><strong>Copy and save it immediately</strong>, as it will only be shown once.</li><li>In your terminal, set it as an environment variable: export OPENAI_API_KEY=&#39;your-key-here&#39;.</li></ol><h3>Step 2: Setting Up the Code</h3><p>Install the necessary libraries for building graphs and using OpenAI models:</p><pre>pip install langgraph langchain_openai langchain</pre><h4>A. Defining the State</h4><p>The “State” is the shared memory that tracks conversation history and the Supervisor’s next decision.</p><pre>from typing import Annotated, TypedDict, List<br>from langchain_openai import ChatOpenAI<br>from langgraph.graph import StateGraph, START, END<br>from pydantic import BaseModel, Field<br><br>class AgencyState(TypedDict):<br>    messages: Annotated[List[str], &quot;The history&quot;]<br>    next_agent: str  # Tracks who acts next<br>    flight_data: str # Shared data from Flight Agent<br>    hotel_data: str  # Shared data from Hotel Agent</pre><h4>B. Defining the Specialist Workers</h4><p>These functions represent your expert employees, each equipped with a “real-world” dataset.</p><p>By using these specific entries for flights (ranging from “Budget” to “Business Class”) and hotels (sorted by neighborhoods like “Le Marais” or “Montmartre”), the example simulates a <strong>Specialized Knowledge Base</strong>.</p><pre>def flight_agent(state: AgencyState):<br>    print(&quot;--- Flight Agent: Finding Cheapest Options ---&quot;)<br>    # Real-world dataset: 5 entries<br>    flights = [<br>        {&quot;route&quot;: &quot;NYC -&gt; Paris&quot;, &quot;price&quot;: 450, &quot;type&quot;: &quot;Budget&quot;},<br>        {&quot;route&quot;: &quot;NYC -&gt; Paris&quot;, &quot;price&quot;: 1200, &quot;type&quot;: &quot;Direct&quot;},<br>        {&quot;route&quot;: &quot;NYC -&gt; Paris&quot;, &quot;price&quot;: 380, &quot;type&quot;: &quot;Last Minute Deal&quot;},<br>        {&quot;route&quot;: &quot;NYC -&gt; Paris&quot;, &quot;price&quot;: 950, &quot;type&quot;: &quot;Business Class Upgrade&quot;},<br>        {&quot;route&quot;: &quot;NYC -&gt; Paris&quot;, &quot;price&quot;: 510, &quot;type&quot;: &quot;One-Stop Economy&quot;}<br>    ]<br>    # Finding the cheapest option for the user<br>    cheapest = min(flights, key=lambda x: x[&#39;price&#39;])<br>    return {<br>        &quot;flight_data&quot;: f&quot;Deal Found: {cheapest[&#39;route&#39;]} for ${cheapest[&#39;price&#39;]} ({cheapest[&#39;type&#39;]}).&quot;,<br>        &quot;next_agent&quot;: &quot;supervisor&quot; # Report back to manager<br>    }<br><br>def hotel_agent(state: AgencyState):<br>    print(&quot;--- Hotel Agent: Searching Specific Areas ---&quot;)<br>    # Real-world dataset: 5 entries in different districts<br>    hotels = [<br>        {&quot;name&quot;: &quot;Hotel Le Marais&quot;, &quot;price&quot;: 180, &quot;area&quot;: &quot;Le Marais&quot;},<br>        {&quot;name&quot;: &quot;Eiffel View Suites&quot;, &quot;price&quot;: 350, &quot;area&quot;: &quot;7th Arrondissement&quot;},<br>        {&quot;name&quot;: &quot;Budget Stay Bastille&quot;, &quot;price&quot;: 95, &quot;area&quot;: &quot;Bastille&quot;},<br>        {&quot;name&quot;: &quot;Luxury Louvre&quot;, &quot;price&quot;: 500, &quot;area&quot;: &quot;1st Arrondissement&quot;},<br>        {&quot;name&quot;: &quot;Montmartre Boutique&quot;, &quot;price&quot;: 150, &quot;area&quot;: &quot;Montmartre&quot;}<br>    ]<br>    # Simulation: Finding an option based on &quot;Le Marais&quot; area<br>    result = next(h for h in hotels if h[&quot;area&quot;] == &quot;Le Marais&quot;)<br>    return {<br>        &quot;hotel_data&quot;: f&quot;Top Pick: {result[&#39;name&#39;]} in {result[&#39;area&#39;]} at ${result[&#39;price&#39;]}/night.&quot;,<br>        &quot;next_agent&quot;: &quot;supervisor&quot;<br>    }</pre><p>In a production environment, you would simply replace the mocked Python lists with actual API calls to services like Skyscanner or Expedia. The Supervisor’s logic remains exactly the same: it doesn’t need to know <em>how</em> to find a flight; it only needs to know <em>who</em> to ask and <em>when</em> they have provided a valid answer</p><h4>C. Building the Supervisor (The Manager)</h4><p>The Supervisor uses an LLM to “route” the conversation based on what the user is asking</p><pre>class Router(BaseModel):<br>    next_node: str = Field(description=&quot;Next: &#39;FlightAgent&#39;, &#39;HotelAgent&#39;, or &#39;FINISH&#39;&quot;)<br><br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;)<br><br>def supervisor_node(state: AgencyState):<br>    prompt = f&quot;&quot;&quot;You are a Travel Manager. <br>    Current State: Flights={state.get(&#39;flight_data&#39;)}, Hotels={state.get(&#39;hotel_data&#39;)}.<br>    Based on the user&#39;s request, decide who works next. <br>    Pick &#39;FINISH&#39; only if all requested information has been found.&quot;&quot;&quot;<br>    <br>    decision = llm.with_structured_output(Router).invoke(prompt)<br>    return {&quot;next_agent&quot;: decision.next_node}</pre><h4>D. Connecting the Workflow Graph</h4><p>We now build the graph, setting the Supervisor as the entry point</p><pre>builder = StateGraph(AgencyState)<br>builder.add_node(&quot;supervisor&quot;, supervisor_node)<br>builder.add_node(&quot;FlightAgent&quot;, flight_agent)<br>builder.add_node(&quot;HotelAgent&quot;, hotel_agent)<br><br>builder.add_edge(START, &quot;supervisor&quot;) <br>builder.add_conditional_edges(<br>    &quot;supervisor&quot;,<br>    lambda state: state[&quot;next_agent&quot;], <br>    {&quot;FlightAgent&quot;: &quot;FlightAgent&quot;, &quot;HotelAgent&quot;: &quot;HotelAgent&quot;, &quot;FINISH&quot;: END}<br>)<br>builder.add_edge(&quot;FlightAgent&quot;, &quot;supervisor&quot;)<br>builder.add_edge(&quot;HotelAgent&quot;, &quot;supervisor&quot;)<br><br>graph = builder.compile()</pre><h3>Step 3: Execution &amp; Output</h3><p>Because the Supervisor evaluates the user’s specific intent, it only invokes the agents that are actually needed.</p><h4>Example 1: Full Trip Request</h4><blockquote>User Query: <em>“Find me the cheapest flight to Paris and a hotel in Le Marais.”</em></blockquote><pre># The supervisor will call both Flight and Hotel agents<br>inputs = {&quot;messages&quot;: [&quot;Plan a trip to Paris including flights and hotels.&quot;]}<br>print(graph.invoke(inputs))</pre><p><strong>Output Trace</strong>:</p><pre>--- Flight Agent: Finding Cheapest Options ---<br>--- Hotel Agent: Searching Specific Areas ---<br><br>Final Result: <br>Flights: Deal Found: NYC -&gt; Paris for $380 (Last Minute Deal).<br>Hotels: Top Pick: Hotel Le Marais in Le Marais at $180/night.</pre><h3>Summary</h3><p>The Supervisor architecture is the gold standard for multi-agent systems because it provides <strong>centralized intelligence</strong>.</p><ul><li><strong>Intelligent Routing</strong>: It only consumes resources for the agents required for the specific query.</li><li><strong>Specialization</strong>: Each expert agent focuses on a narrow task, leading to fewer errors and more “real-world” accurate results.</li><li><strong>Stateful Memory</strong>: The system remembers what it has already found, allowing it to complete complex multi-part requests seamlessly.</li></ul><p><em>Thanks for reading…</em></p><p><em>If you like reading this article then please hold the clap button!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b09d815cd328" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Local AI Agent with Python: A Practical Implementation Guide]]></title>
            <link>https://kulkarnishreenidhi.medium.com/building-a-local-ai-agent-with-python-a-practical-implementation-guide-b45f71cffdfb?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b45f71cffdfb</guid>
            <category><![CDATA[local-llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 08:43:48 GMT</pubDate>
            <atom:updated>2025-06-08T17:15:57.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*po0n3ufxLgkcc0LWgaP_kw.png" /></figure><p>This blog presents a comprehensive guide to developing a local AI agent using Python. The implementation will utilize <strong>Ollama, LangChain, and ChromeDB as the vector search database.</strong></p><p>Furthermore, this blog will outline the integration of retrieval-augmented generation, a technique that facilitates the extraction of relevant data from sources such as CSV files for seamless incorporation into the model.</p><p>Notably, the entire setup is accessible at no cost. There is no requirement for an OpenAI account, cloud subscription, or external infrastructure — everything can be executed directly on a local machine.</p><p>Lets’s begin…</p><p>We will download Airlines <a href="https://www.kaggle.com/datasets/sujalsuthar/airlines-reviews?resource=download">dataset</a> from Kaggle and which has Airline reviews in CSV format, featuring evaluations of the top 10 highest-rated airlines in 2023, sourced from Airline Quality. The file includes various attributes such as <strong>Title, Name, Review Date, Reviews, Seat Comfort, Staff Service, Food &amp; Beverages, Inflight Entertainment, Value for Money, Overall Rating, and Recommendation Status</strong> — all of which contribute to identifying top-performing airlines.</p><p>Next, we will explore the process of constructing an AI agent capable of analyzing this dataset. The agent will be designed to retrieve relevant reviews from the document, enabling it to answer queries related to airline performance and customer satisfaction.</p><p>For instance, if a user is looking for recommendations on the best airline for business class travel, the AI agent can extract and analyze pertinent reviews to provide an informed response. This will be a straightforward process, so stay with me as I walk you through how it’s done.</p><h4>Python Setup and Installation</h4><p>To begin, a few preliminary setup steps are required before diving into the coding process.</p><p><strong>Prepare the Necessary Files</strong> The first essential component is the previously mentioned CSV file. Start by creating a new folder named <strong>Local AI Agent</strong>. Within this folder, add:</p><ul><li>The CSV file</li><li>A requirements.txt file containing the three dependencies required for installation in Python</li></ul><p><strong>Create a Virtual Environment</strong> To ensure an isolated environment for dependency management, create a virtual environment using the following command:</p><pre>python -m venv venv</pre><p>This will generate a environment where various dependencies can be installed without interfering with system-wide configurations.</p><p><strong>Activate the Virtual Environment</strong> Once the virtual environment is created, it needs to be activated:</p><ul><li>On <strong>Windows</strong>, use the following command:</li></ul><pre>.\venv\Scripts\activate</pre><ul><li>On <strong>Mac/Linux</strong>, use:</li></ul><pre>source venv/bin/activate</pre><p>After activation, the environment is ready for package installation and further development.<br>If you have a requirements.txt file, you can run the following command:</p><pre>pip install -r requirements.txt</pre><p>This will automatically install all required packages into the virtual environment.<br>However, if the requirements.txt file is not available, you can manually install the dependencies using the following commands:</p><pre>pip install langchain<br>pip install langchain-llama<br>pip install langchain-chroma</pre><p>These commands will ensure that all essential libraries are properly set up within the virtual environment, allowing you to proceed with development seamlessly.</p><h4>Ollama Setup</h4><p>Now that the required dependencies have been installed, the next step is to set up <strong>Ollama</strong>.<br>Ollama enables running AI models locally on a personal computer using our own hardware, eliminating the need for external services such as an OpenAI API key. This ensures complete local execution without reliance on cloud-based solutions.<br>To install Ollama, visit<a href="http://ollama.com/"> ollama.com</a> and download the software. Once installed, open a terminal or command prompt and enter the following command to verify the setup:</p><pre>Ollama</pre><h4>Downloading AI Models</h4><p>Next, we will retrieve two models for local execution.</p><ul><li><strong>Retrieving the Llama 3.2 Model</strong> First, we will download <strong>Llama 3.2</strong>, a compact yet efficient AI model suitable for various tasks. While multiple models are available, we will use version <strong>3.2</strong> for this demonstration. You may explore the available models in the directory and select one that fits your needs.</li></ul><pre>ollama pull llama3.2</pre><ul><li><strong>Downloading an Embedding Model</strong> Once Llama 3.2 is successfully installed, the next step is to retrieve an embedding model. This model is crucial for converting documents into vector representations for efficient search and retrieval.<br>For this setup, we will use <strong>mxbai-embed-large</strong>, although several other embedding models are available. If needed, alternative models can be selected based on specific use cases.</li></ul><pre>ollama pull mxbai-embed-large</pre><p>Now that the models are in place, we’re ready to begin writing the code. Let’s dive in!</p><p>Let’s import <strong>OllamaLLM</strong> — A locally hosted language model (Llama 3.2) that generates responses. <strong>ChatPromptTemplate - </strong>A tool that formats prompts for AI interaction.<br>I am loading the Llama 3.2 model using <strong>OllamaLLM </strong>which will enable the Agent to process natural language and provide responses.<br>Next, I created a template, which was a simple string defining the model’s task. Within this string, I specified the intended functionality — designating the model as an expert in answering questions related to airline reviews. Additionally, I included a collection of relevant reviews to guide the model’s responses effectively.</p><pre>from langchain_ollama.llms import OllamaLLM<br>from langchain_core.prompts import ChatPromptTemplate<br>from vector import retriever<br><br>model = OllamaLLM(model=&quot;llama3.2&quot;)<br><br>template = &quot;&quot;&quot;<br>You are an expert in answering questions about airlines reviews.<br><br>Here are some relevant reviews: {reviews}<br><br>Here is the question to answer: {question}<br>&quot;&quot;&quot;</pre><p>We have now created a chat prompt template that enables us to pass in both a <strong>reviews</strong> variable and a <strong>question</strong> variable, allowing the model to generate relevant responses accordingly.<br>Next, we will build a <strong>chain</strong>, which serves as a structured process for invoking the entire sequence efficiently.</p><pre>from langchain_ollama.llms import OllamaLLM<br>from langchain_core.prompts import ChatPromptTemplate<br>from vector import retriever<br><br>model = OllamaLLM(model=&quot;llama3.2&quot;)<br><br><br><br>template = &quot;&quot;&quot;<br>You are an expert in answering questions about airlines reviews.<br><br>Here are some relevant reviews: {reviews}<br><br>Here is the question to answer: {question}<br>&quot;&quot;&quot;<br><br>prompt = ChatPromptTemplate.from_template(template)<br>chain = prompt | model<br></pre><h4>Vector Store Database Setup</h4><p>In this step, we will implement the logic for embedding documents and performing efficient lookups through vectorization.<br>For those unfamiliar with vector search, it functions as a specialized database designed for rapid retrieval of relevant information. This database will be hosted locally on our computer using <strong>ChromaDB</strong>, which was installed earlier.<br>By leveraging this setup, we can quickly retrieve relevant data, pass it to our model, and enhance its ability to generate informed responses based on the embedded information.<br>Large Language Models (LLMs) excel at synthesizing text and generating responses, but they often lack direct access to accurate, structured data. To address this limitation, we will utilize a vector-enabled database to store and retrieve relevant information efficiently.<br>In this case, we will import the entire CSV file into the vector database. When a query is made, the system will search for relevant documents within the database and pass them to the model as a list of reviews. The model will then analyze these reviews and generate a well-informed response based on the retrieved data.<br>This is the fundamental concept behind vector search — now, let’s walk through the implementation process.</p><pre>from langchain_ollama import OllamaEmbeddings<br>from langchain_chroma import Chroma<br>from langchain_core.documents import Document<br>import os<br>import pandas as pd<br><br>airlines_df = pd.read_csv(&quot;airlines_reviews.csv&quot;)<br>model = OllamaEmbeddings(model=&quot;mxbai-embed-large&quot;)<br><br>db_location = &quot;./chrome_langchain_db&quot;<br>db_path = not os.path.exists(db_location)<br><br>if db_path:<br>    documents = []<br>    ids = []<br><br>    for i, row in airlines_df.iterrows():<br>        document = Document(<br>            page_content=row[&quot;Title&quot;] + &quot; &quot; + row[&quot;Reviews&quot;],<br>            metadata={&quot;Airline&quot;: row[&quot;Airline&quot;], &quot;date&quot;: row[&quot;Review Date&quot;]},<br>            id=str(i)<br>        )<br>        ids.append(str(i))<br>        documents.append(document)<br><br>vector_store = Chroma(<br>    collection_name=&quot;airline_reviews&quot;,<br>    persist_directory=db_location,<br>    embedding_function=model<br>)<br><br>if db_path:<br>    vector_store.add_documents(documents=documents, ids=ids)<br><br>retriever = vector_store.as_retriever(<br>    search_kwargs={&quot;k&quot;: 5}<br>)</pre><ul><li>This code loads airline reviews, embeds them into a vector store, and creates a retriever to find relevant reviews when users ask questions.</li><li>ChromaDB enables fast local searches without relying on cloud-based APIs.</li><li>Ollama embeddings convert text into searchable vector formats, improving AI-generated responses.</li></ul><h4><strong>Connecting LLM &amp; Vector Store</strong></h4><pre>from langchain_ollama.llms import OllamaLLM<br>from langchain_core.prompts import ChatPromptTemplate<br>from vector import retriever<br><br>model = OllamaLLM(model=&quot;llama3.2&quot;)<br><br><br><br>template = &quot;&quot;&quot;<br>You are an expert in answering questions about airlines reviews.<br><br>Here are some relevant reviews: {reviews}<br><br>Here is the question to answer: {question}<br>&quot;&quot;&quot;<br>prompt = ChatPromptTemplate.from_template(template)<br>chain = prompt | model<br><br>while True:<br>    print(&quot;\n\n-------------------------------&quot;)<br>    question = input(&quot;Ask your question (q to quit): &quot;)<br>    print(&quot;\n\n&quot;)<br>    if question == &quot;q&quot;:<br>        break<br><br>    reviews = retriever.invoke(question)<br>    result = chain.invoke({&quot;reviews&quot;: reviews, &quot;question&quot;: question})<br>    print(result)</pre><p>The above code block will implements an <strong>interactive loop</strong> where the user can continuously ask questions about airline reviews. The program fetches <strong>relevant reviews</strong> based on the user’s query and processes them through an AI model to generate a response.</p><h4><strong>Demo</strong></h4><p>Let’s ask agent few questions</p><figure><img alt="ive me airlines which are good for business class travel" src="https://cdn-images-1.medium.com/max/1024/1*QDxrLHn7hi9jm6k6j1oRUw.png" /><figcaption><strong>Give me airlines which are good for business class travel</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JWQqoADFQlqdWtJmV369BQ.png" /><figcaption><strong>Which is the most cost effective airline</strong></figcaption></figure><p>For first question — <strong>give me airlines which are good for business class</strong> <strong>travel</strong> <br>Agent has effectively <strong>retrieved relevant reviews</strong>, <strong>analyzed passenger sentiment</strong>, and <strong>generated a well-informed recommendation</strong> for Business Class travellers.</p><p>For second question — which is the most cost effective airline<br>Agent has<strong> retrieved relevant reviews</strong>, <strong>analyzed customer sentiment</strong>, and <strong>provided an informed assessment</strong> of cost-effective airline choices, <strong>while acknowledging the need for further research.</strong></p><h3>Summary</h3><p>In this blog post we focused on the development of a <strong>local AI agent</strong> using <strong>Python, LangChain, Ollama, and ChromaDB</strong>, allowing users to interact with an AI chatbot that retrieves <strong>airline reviews</strong> for informed decision-making. The setup involved <strong>creating a virtual environment</strong>, <strong>installing dependencies</strong>, and configuring <strong>Ollama</strong> to enable local execution without relying on cloud-based APIs. After selecting <strong>Llama 3.2</strong> as the primary language model and using an embedding model (mxbai-embed-large), to integrate <strong>vector search capabilities</strong> with <strong>ChromaDB</strong> to enable efficient review retrieval. A <strong>structured prompt template</strong> was created, allowing users to ask questions about airline services, which the AI could respond to by fetching relevant review data.</p><p>Also We have seen demo where Agent tried to evaluate <strong>business class airlines</strong>, highlighting Qatar Airways, Singapore Airlines, and Turkish Airlines as top choices based on customer feedback. It also attempted to identify <strong>cost-effective airlines</strong>, though some confusion arose between affordability and service quality in the analysis.</p><p><em>Thanks for reading…</em></p><p><em>If you like reading this article then please hold the clap button!!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b45f71cffdfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Databricks Liquid Clustering]]></title>
            <link>https://kulkarnishreenidhi.medium.com/databricks-liquid-clustering-a57273e707d1?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a57273e707d1</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[spark-optimization]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[delta-lake]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Fri, 14 Feb 2025 06:37:18 GMT</pubDate>
            <atom:updated>2025-02-18T08:47:50.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*p2GgYBxIaO0xZbUy.jpg" /><figcaption>simplifying data layouts</figcaption></figure><h3><strong>What is Liquid clustering?</strong></h3><p>Delta Lake liquid clustering replaces table partitioning and ZORDER to simplify data layout decisions and optimize query performance. Liquid clustering provides flexibility to redefine clustering keys without rewriting existing data, allowing data layout to evolve alongside analytic needs over time. Liquid clustering accomplishes these by leveraging a <strong>tree-based algorithm</strong> to incrementally map the data layout and maintain the associated metadata as part of the table’s Delta Lake logs.</p><h3><strong>Why Liquid Clustering?</strong></h3><p>Before dive deep into Liquid Clustering lets try to understand what are the limitation of Hive-Style Partitioning and Z-Order indexing.</p><p><strong>Hive-style partitioning</strong></p><p>Hive-style partitioning clusters data such that every file contains exactly one distinct combination of partition column values. Although Hive-style partitioning works well if tuned correctly, there are limitations:</p><ul><li>Since partition values are physical boundaries for files, Hive-style partitioning by high cardinality columns will create many small files that cannot be combined, resulting in poor scan performance.</li><li>In Spark/Delta, once a table is partitioned, its partition strategy cannot be changed, thus being unable to adapt to new use cases such as query pattern changes, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*PYirc1yfSvFzip5xu8oAwQ.jpeg" /></figure><p><strong>Z-Order clustering</strong></p><p>ZORDER is a multi-dimensional clustering technique used in Delta tables. The OPTIMIZE ZORDER BY command applies ZORDER clustering and improves the performance of queries that utilize ZORDER BY columns in their predicates. However, it has the following limitations:</p><ul><li>OPTIMIZE ZORDER BY is an operation that rewrites all data in the table, resulting in high write amplification. Also, no partial results are saved when execution fails.</li><li>ZORDER BY columns are not persisted and the user is required to remember the previous ZORDER BY columns, often causing user errors.</li><li>Z-Order curve has some locality preservation issues.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*1oCuENpFfNG8GSdUAbvFZw.jpeg" /></figure><p>Now we understand the limitations of hive style partitioning and z-order indexing. Its time to deep dive on Liquid clustering!!</p><h3><strong>How Liquid clustering works in background?</strong></h3><p><strong>Note: You can skip this and jump on to </strong><a href="#d809"><strong>liquid clustering usage</strong></a><strong> if you are only interested in liquid clustering usage and benefits.</strong></p><p><strong>Liquid clustering </strong>uses Hilbert curve, a continuous fractal space-filling curve as a multi-dimensional clustering technique for Liquid, which significantly improves data skipping over ZORDER.</p><p>Similar to how ZORDER works, Hilbert curve maps multidimensional data onto a 1D space by fitting them on the curve. This preserves the locality very well meaning points that are close in the 1D space should also be close in multi-dimensional space. We can leverage this property to do efficient data skipping. Take the following example of a simple two-column table, with 64 distinct records. Each dotted rectangle represents a single file, and each file contains 4 records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AH3SDWVbaOMxiXkpXIl4sw.png" /></figure><p>In this example, Liquid clustering first translate the two columns A and B into a numeric range of [0, 7] by range partitioning the value distribution. The Hilbert curve gives us a nice property that adjacent points on the curve always have a distance of 1. To make use of this, we partition the data by the points of the curve, and then pack the nearby points into good-size files. This means each file contains points that are close to each other on the curve, which means they’ll have close min/max ranges for each of the clustering dimensions.</p><p>Liquid clustering<strong> </strong>is incremental clustering capability with Liquid, which allows users to run OPTIMIZE <strong>without rewriting all data</strong>. OPTIMIZE will also be completed in batches, where each batch will produce a single OPTIMIZE commit, so that not all progress is lost when something goes wrong.</p><p>Incremental clustering is built around the concept of ZCubes. A ZCube is a group of files produced by the same OPTIMIZE job. Since Liquid clustering only want to rewrite fresh/unoptimized files, it distinguish between already optimized files (that are part of some ZCubes) from unoptimized files using the ZCUBE_ID tag in AddFile. It will generate a unique ZCUBE_ID using UUID for each new ZCube.</p><p>Liquid Clustering introduces two configs to provide flexibility for controlling which files to consider for clustering:</p><ul><li><strong>MIN_CUBE_SIZE</strong>: ZCube size for which new data will no longer be merged with it during incremental OPTIMIZE. Defaults to 100 GB.</li><li><strong>TARGET_CUBE_SIZE</strong>: Liquid Cluster creates target size of the ZCubes. This is not a hard max; we will continue adding files to a ZCube until their combined size exceeds this value. This value must be greater than or equal to MIN_CUBE_SIZE. Defaults to 150 GB.</li></ul><p>Any ZCubes with a size less than <em>MIN_CUBE_SIZE</em> a <strong>partial ZCube</strong>. All new files will be considered for OPTIMIZE but, also consider any existing partial ZCubes. Once a partial ZCube accumulates enough data and crosses the <em>MIN_CUBE_SIZE</em> threshold, it becomes a <strong>stable ZCube</strong>, at which point ZCube no longer considered it for rewriting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0p80ZQidNVDpeqv3rC8rAg.png" /><figcaption><em>ZCube-based incremental clustering</em></figcaption></figure><p>Stable ZCubes may become partial again if DML operations delete too many files, at which point files for partial ZCubes will be considered for clustering.</p><h3><strong>When to use liquid clustering?</strong></h3><ul><li>Tables often filtered by high cardinality columns.</li><li>Tables with significant skew in data distribution.</li><li>Tables that grow quickly and require maintenance and tuning effort.</li><li>Tables with concurrent write requirements.</li><li>Tables with access patterns that change over time.</li><li>Tables where a typical partition key could leave the table with too many or too few partitions</li></ul><blockquote><strong>What happens to the tables that are already z-ordered? Can you still apply liquid clustering.</strong></blockquote><blockquote>Yes, we can apply Liquid clustering on tables which are currently using z-order index. Use same columns used for Z-order indexing(max 4) and Liquid clustering will cluster the data as per column specified.</blockquote><h3><strong>Where/How to use liquid clustering?</strong></h3><p>To enable liquid clustering, add the <strong>CLUSTERBY</strong> phrase to a table creation or while saving dataframe as table</p><pre>-- SQL <br>-- Create an empty table<br>CREATE TABLE Country(country_id int, country_name string) CLUSTER BY (country_id);<br><br>-- Using a CTAS statement<br>CREATE EXTERNAL TABLE Country CLUSTER BY (country_id)  -- specify clustering after table name, not in subquery<br>LOCATION &#39;path/to/location&#39;<br>AS SELECT * FROM Geo;<br><br></pre><pre>#pyspark code <br><br>df = spark.read.table(&quot;non_cluster_country&quot;)<br>df.write.clusterBy(&quot;country_id&quot;).saveAsTable(&quot;Country&quot;)</pre><p><strong>Choose clustering keys</strong><br>Databricks recommends choosing clustering keys based on the columns most frequently used in query filters. Clustering keys can be defined in any order. If two columns are highly correlated, you only need to include one of them as a clustering key.</p><p>You can specify up to <strong>four clustering keys</strong>. For smaller tables (under 10 TB), using more clustering keys (for example, four) can degrade performance when filtering on a single column compared to using fewer clustering keys (for example, two). However, as table size increases, the performance difference with using more clustering keys for single-column queries becomes negligible.</p><p><strong>Trigger clustering table</strong></p><p>To trigger clustering, you must use Databricks Runtime 13.3 LTS or above. Use the <strong>OPTIMIZE</strong> command on your table.</p><pre>spark.sql(&quot;OPTIMIZE Country&quot;)</pre><blockquote>We have used this liquid clustering for one of our job and tried to compare the monthly cost on before and after using Liquid clustering. Here are the results. We are able to save 900 dollars per month i.e, <strong>~11k dollars per year.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nsC98B8JbGDxpr_ZoFmu1Q.png" /></figure><h3>Summary</h3><p>In this post we have discussed about What is Liquid Clustering, Why we need it, how it works in the background and how we can leverage liquid clustering to cluster data to simplify data layouts.</p><p>Now We know how to implement liquid clustering. With this we can increase the performance of data pipelines and reduce overall job duration.</p><p><em>Thanks for reading.</em></p><p>If you like this article, please hold the clap button!</p><h3>Happy Clustering !!!</h3><p>References:</p><ul><li><a href="https://learn.microsoft.com/en-us/azure/databricks/delta/clustering">https://learn.microsoft.com/en-us/azure/databricks/delta/clustering</a></li><li><a href="https://www.youtube.com/watch?v=5t6wX28JC_M">https://www.youtube.com/watch?v=5t6wX28JC_M</a></li><li><a href="https://docs.google.com/document/d/1FWR3odjOw4v4-hjFy_hVaNdxHVs4WuK1asfB6M6XEMw/edit?tab=t.0">https://docs.google.com/document/d/1FWR3odjOw4v4-hjFy_hVaNdxHVs4WuK1asfB6M6XEMw/edit?tab=t.0</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a57273e707d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cache using Caffeine in spring boot webflux]]></title>
            <link>https://kulkarnishreenidhi.medium.com/cache-using-caffeine-in-spring-boot-webflux-326618bd32aa?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/326618bd32aa</guid>
            <category><![CDATA[aop]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[caffiene]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot-webflux]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 11:28:03 GMT</pubDate>
            <atom:updated>2022-11-29T11:46:16.280Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I am sharing my experience with caffeine caching in spring boot webflux application. Let’s begin with a basic understanding of what is caching ?</p><p><strong>What is Caching?</strong></p><p>Caching is the process of storing data in the cache. A cache is a high-speed data storage layer which stores a subset of data, typically transient in nature, so that future requests for that data are served up faster than is possible by accessing the data’s primary storage location.</p><p>Great !! Now we have a basic understanding of what caching is. Let’s see <strong>caching patterns</strong></p><ol><li><strong>Cache-Aside</strong></li></ol><p>Load data on demand into a cache from a data store. This can improve performance and also helps to maintain consistency between data held in the cache and data in the underlying data store.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bl1dU7mDfy_A_FODk9mng.png" /></figure><p>2. <strong>Read-Through</strong></p><p>When the cache is asked for the value associated with a given key and such an entry does not exist within the cache, the cache retrieves the data from the db, then caches the value, then returns it to the caller.</p><p>3. <strong>Write-Through</strong></p><p>In this write strategy, data is first written to the cache and then to the database. The cache sits in-line with the database and writes always go through the cache to the main database. This helps cache maintain consistency with the main database.</p><p>4. <strong>Write-Back/Behind</strong></p><p>Here, the application writes data to the cache which stores the data and acknowledges the data that is read makes its way into the cache.</p><p>Now let’s dive into the main agenda of this article. That is we’re going to learn how to use the Caching Abstraction using caffeine in Spring boot Webflux, and generally improve the performance of our system.</p><p>For reactive streams, you can’t reliably use a LoadingCache because it’s blocking by default. Thankfully, tapping into a couple of basic features of reactive streams and caffeine can get us there.</p><p><a href="https://github.com/ben-manes/caffeine"><strong>Caffeine</strong></a></p><p>Caffeine is a high-performance Java 8 based caching library providing a near-optimal hit rate. It provides an in-memory cache very similar to the Google Guava API. Spring Boot Cache starters are auto-configured CaffeineCacheManager if it finds the Caffeine in the classpath. The Spring Framework provides support for transparently adding caching to an application.</p><p><em>Let’s Dive in….</em></p><p>Let’s consider the need to display a list of books to the user. For this our API has to make different calls to upstream services to collate all data. It takes around 500 to 600 MS per request, but SLA is below 80 MS at 99 percentile. How are we going to achieve this ????</p><p>In this scenario caching is much more handy.</p><p>Let’s create custom annotation to enable caching. To do that we need to create an interface with Target as method and retention as runtime policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*DFDCV8JJRLcESEAdIZkInw.png" /></figure><p>Now we can create AOP, before that let us create a bean which serves configured caffeine object. There you can set maximum size and expiry time.. etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*Ul1kk-Qlu9-DpQHMEtT-dQ.png" /></figure><p>Let’s create AOP class to enable custom caching functionality using caffeine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*eefGSKFuyQQXPGb1DwlHvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7SCo-BXOC4qQzBMTxAdgow.png" /></figure><p>Now we are almost there. let’s add this annotation to book service method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*MVpZSm82IeFxW2XGX8a12A.png" /></figure><p>Voila.. that is it. Now you can see the magic where book service <strong>takes 0 milliseconds.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*jleX0EQxvS4N46rsdlkPYQ@2x.jpeg" /></figure><h3><strong>Summary</strong> :</h3><p>In this post, we have discussed all about Caching, patterns of Cache, Caching annotations, Caffeine Caching and its configuration and how to add caching in Spring Boot webflux application with example.</p><p>Now you have learned how to implement caching in Spring Boot applications. With the help of caching we can increase the performance of applications and reduce the application host.</p><p><em>Thanks for reading.</em></p><p>If you like reading this article then please hold the clap button!</p><h4>Happy Caching !!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=326618bd32aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serverless Architecture]]></title>
            <link>https://kulkarnishreenidhi.medium.com/serverless-architecture-a742212abfc9?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a742212abfc9</guid>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless-architecture]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Thu, 20 Jan 2022 11:47:28 GMT</pubDate>
            <atom:updated>2022-01-20T12:38:44.758Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re developing software before the term serverless came into picture you know how hard it is to maintain servers and manage them. With the recent advancements in the cloud computing ecosystem, Serverless is one of the major contributions for some innovative solutions. In this article we are going to see what is serverless computing with the use case with which we create our application architectures. This is the agenda for this article :</p><ul><li>what is serverless</li><li>serverless offerings from major cloud providers</li><li>Use cases for web applications</li><li>Future of serverless</li></ul><p>Throughout this article I’ll be using AWS as the cloud platform. However I will compare the different offerings provided by the other cloud providers as well.</p><h4><strong>What is Serverless ??</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*nMZLgbiFwgWKSrrtX4bhAg@2x.jpeg" /></figure><p>The name serverless itself is a misnomer. serverless is generally made of servers and people think serverless doesn’t have servers. Essentially we need a server to run or compute. The only difference is we don’t see the compute and we don’t manage them, Because we don’t essentially create them ourselves. however you still need a server to run your compute. So why is it called serverless ?? Serverless is essentially a managed offering which is provided by different cloud providers.</p><p>Imagine you are in a cloud provider or you are using a platform which could be providing some cloud offerings for serverless, in this case let’s say I have a mobile application and I have my cloud provider who is having lot of servers I’m not essentially renting anything right now but I have a mobile application which I have pushed into an app store and people are start using the mobile application now, the moment the request comes from the mobile application to my back-end, though I don’t have my servers started or I don’t have any server up and running in the backend. However based on the usage of my application, I provision these servers instantaneously and if I need to process anything with respect to maintaining a state I can use a relational database or no sql database. Now more users are using this particular application and I get more volume in a traditional cloud computing paradigm we will have to configure the auto scaling capability on how many machines we need to provision or how much load can our application with Stan. However in the serverless is offering scalability is added by default, So if there are more loads there will be more instances of machines and the applications. So that I don’t have to manually configure them when I create my application because the complete ownership of provisioning these machines is taken care by the cloud platform. Obviously more compute means more data if we need to scale our database we should be able to scale that as well so it’s not just with respect to scaling the application or the compute.</p><p>Imagine a pricing model where people come back and say you can have your application deployed but don’t pay me if nobody is using it that’s where serverless computing is placed. So the major features of the serverless paradigm is the event triggers, based on my incoming requests my instances were provisioned instantaneously and based on trigger my compute has been provisioned. Once the compute has been provisioned I was able to scale by default so scalability is provided in the serverless offering by default and this is managed by the cloud provider so I don’t have to manually maintain these servers and I don’t have to bring them up and bring them down because these are by default.</p><p>if there are no triggers obviously there is no compute running so I don’t have to pay – so the pricing model is also tied up with these factors and you’ll be able to pay only for the requests and the time of compute which you are running.</p><p>Every technology comes with this pros and cons, there are a lot of things which we need to consider before getting into serverless computing world. The major ones are cold start time we need to have an application which should be able to start instantaneously if the vendor is going to provide our underlying compute and if he starts the application we should be able to immediately serve the request based on the triggers which we get. So the cold start time should be reduced and we should have a faster start-up time.</p><p>The next one is event based triggers not every application can react to humans there could be synchronous applications however you need to make sure that your application is event based and stateless and it is cloud vendor based so if you are creating a serverless architecture you cannot use the same architecture in every cloud platform you need to use the corresponding cloud platforms offering so if you are integrating with AWS you might not be able to easily lift and shift into other platforms because the other platforms might have similar offerings but with a different product so you might have to work with these vendor specific products so it is vendor based most of the time.</p><h4>Serverless Offerings</h4><p>Now let’s see what are the different service offerings provided by the different cloud platforms. So I am picking up the three major ones the AWS cloud Google cloud platform and the Microsoft Azure cloud platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*YA4SbaGkLzXSTdBMKyHZuA@2x.jpeg" /></figure><p>https://aws.amazon.com/serverless/</p><p>Function as Service :</p><p>Serverless has evolved into popularity with the introduction of function as a service the first offering which came as a function as a service was from Amazon and it was called a AWS lambda. The same offering is available in the other cloud platforms in the name as cloud functions and Azure cloud functions. However it is just a part of the serverless offering because its functions as a service. you can run a particular function as a service and it also falls into this server as ecosystem because you don’t have to keep on running your compute.</p><p>Serverless containers :</p><p>The next predominant one is the container based serverless offering. Amazon provides something called a AWS fargate using which you can have serverless containers running on elastic container service or elastic kubernetes service.</p><p>So Amazon provides two container service in the container service which is their proprietary and the kubernetes service and you can use Fargate to schedule your containers on these based on your events. Google cloud provides something called cloud run using which you can run containers in a serverless mode, so it can spin off a new container from a docker image based on the event it could be a http event or a event from a queue the same applies to the azure cloud platform there is something called Azure cloud instances which can be triggered based on events.</p><p>With that I hope you understand what is serverless and what are the different cloud offerings in order to explain the use case I’m gonna pick up a AWS as our primary cloud provider.</p><h4>Example :</h4><p>To Understand more on these concepts, let’s try with the Use case for creating and hosting web application in AWS.</p><p>Now let’s look at how to create a web application by leveraging the serverless offering. imagine we have a website and hosted in AWS. So let’s see how I would design the web application so that I can serve requests to the clients. Now somebody from the browser is hitting our website that will hit my Cloud front servers, I have my static files stored inside a S3 bucket so that geographically my users are able to load the website faster because all my images are stored inside the s3 bucket and cloud front is distributing my static files via its CDN and cloud front is the Amazon version of the CDN.</p><p>Imagine somebody’s loading the website and I have static files it just gets from the s3 bucket and then it just provides that to the user. So if you look at it I don’t have any compute involved here. Now let’s say one part of the website needs to dynamically retrieve something and I have to run some logic which is in python so in order to get the python code I have created a python lambda which I have deployed in my server side. This will be invoked only when the user clicks that particular category or a feature from the website, this particular lambda need to be triggered once the user clicks that particular feature. The request from the cloud front needs to come into the lambda so how can I achieve that ? I can achieve that using a API gateway which can act as a interface. Please refer below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-vgadwjIpXHLgFldylXnQw@2x.jpeg" /></figure><p>API gateway creates a trigger to the lambda and this is HTTP trigger which I am going to trigger from the cloud front into the lambda.</p><p>I need to have it secured, so I’m going to use the Amazon Cognito for securing this particular endpoint along with the data retrieval from the dynamo DB. So the lambda is going to retrieve the data from the DynamoDB dynamically and serve to the CloudFront distribution and it is secured by a Cognito and the lambda is triggered using a api gateway so i don’t have to worry about how many people are going to use website because my lambda is a managed service and amazon will scale it up and down based on the need and if people are not going to use the dynamic feature inside the website and I won’t be charged because my lambdas won’t be triggered until or unless somebody uses that particular feature so this is a classic example of how we can use lambdas or serverless architecture for creating a web application.</p><h4>Serverless is a FUTURE</h4><p>As day by day the serverless framework is getting evolved you might be able to see more and more tools getting added to this particular cloud native landscape. I would say serverless is going to be the future because most of us would like to save cost in running compute so for us serverless plays a major role in achieving these by leveraging the cloud native platform capabilities with reducing the cost. I hope you learned something new as always.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a742212abfc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Service Bus]]></title>
            <link>https://kulkarnishreenidhi.medium.com/azure-service-bus-83fefccffb31?source=rss-596b4db6b28a------2</link>
            <guid isPermaLink="false">https://medium.com/p/83fefccffb31</guid>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[json]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[aspdotnetcore]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Shrinidhi Kulkarni]]></dc:creator>
            <pubDate>Sun, 14 Feb 2021 12:19:48 GMT</pubDate>
            <atom:updated>2021-02-14T12:19:48.444Z</atom:updated>
            <content:encoded><![CDATA[<p>Message buses and queues are a powerful tool for communicating between applications they are used extensively in microservices. But they can be useful in larger applications as well. In this article we’re going to look at how to implement azure service bus queues into our applications to both send and receive messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kov3_LcY9QajywwL" /><figcaption>Photo by <a href="https://unsplash.com/@robinpierre?utm_source=medium&amp;utm_medium=referral">Robin Pierre</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before making our hands dirty let’s understand what is Azure service bus with real time example.</p><p>let’s pretend that our sender is a website that captures information about Employees so employee can come in here to log in and create account and it’s going to email you and say hey thanks for joining and some cool information about what we do well. Here I could put that &lt;email code&gt; in the same site that captures all of your information but then what if I have to take down the email service or change the email service ? I have to take the whole site down including the rest of the website that’s not ideal for micro services — the idea is we break out a piece of our application and make it an entire application that does one thing and so we can say well our microservice would be that email system where all it does is send an email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*kgTHk2jINN0WJtSeonfClQ.png" /></figure><p>It doesn’t know who or when you give us all the information in the input — it’d be a little service that sit out there and all it’s going to do is listen for new emails that need to be sent. When a person signs up then we’re going to send them an email so we’d have to some way to tell this micro service that go ahead and send an email but how do we do that without being directly connected to it ? I could add this as a reference and then trigger some kind of method but that is not the right way to do it and again if I want to update this micro service, then we have to hit the website down, because it’s tied together. Now how can we solve this problem ? and the answer is message buses or queues. And the idea is sender is going to send a message and it’s going to a queue and receiver – its job is to look at that message queue and wait for new messages to come. So with a message bus you can listen for changes and the receiver is going to listen to the queue and say when something comes in I’m going to do work .</p><p>So now we understood how message bus helps in real time scenario. Now will do small hands-on to understand azure service bus bit more. Let’s get back to the business.</p><p>I am going to create a new .Net 5 blazer server project. This kicks off the queue that creates the queue message — the basic structure of our application is we’ll have a blazer server app where we have a web form you fill in the web form with some information you hit submit that’s going to send a message to the queue. we’re going to have a different application we’ll use a console app for the other application that listens for queue messages and then it will do something with those queue messages which is just display on the screen that’s all we’re going to do.</p><p>We will create a new blazer project and name it MessageSender</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b16CnzbwoID9wKeZC-fGUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*qxAL_FaU-ziRnUmgucsHow.png" /></figure><p>We will add new class library to the solution and name it Common and will add reference to MessageSender project</p><p>Let’s create Console app project and name it MessageReceiver.</p><p>So those are our three pieces we’re gonna have our Sender ,Common and Receiver.</p><p>Now in the sender right click on dependencies manage new get packages add microsoft azure service bus.</p><p>Let’s add a class file in Common project and call it Employee make it public employeeID, first name last name. Please refer side image for solution structure and dependencies.</p><p>In MessageSender project, let’s create folder and call this services and add a class and let’s call this class the QueueService please refer side image.</p><p>Add constructor with IConfiguration — we’ll call this config control to create and assign the fields of appsettings.json. Let’s create and implement SendMessageAsync</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eIpEzw_G3T5HGNweNqLCgA.png" /></figure><p>We’re going to serialize our service bus message. Serialization what it does is it turns your object into a json. what a serializer does is it takes our object and turns it into a string now we can take the same that string and then deserialize it back to an object kind of like you know dehydrating rehydrating our objects.</p><p>Let’s go and create azure service bus. if you’re not familiar with azure subscription, you can get azure for free <a href="https://www.googleadservices.com/pagead/aclk?sa=L&amp;ai=DChcSEwiQhqy-7ujuAhVJ15YKHa7pBm4YABAAGgJ0bA&amp;ae=2&amp;ohost=www.google.com&amp;cid=CAESQeD2lmdWrT4GrlFkh2RdBT3QlzdLg20QW7b6Oma7qrVWS_3I5i3jfD6w84X-W_QJe4hMgp4KkkkcY3E0lFcqs69J&amp;sig=AOD64_2e3qZeN_76mnO_xTwRNIPOlNirjw&amp;q&amp;adurl&amp;ved=2ahUKEwjV0aG-7ujuAhW273MBHfhSBaAQ0Qx6BAghEAE">azure.microsoft.com/account/free</a></p><p>You can get first 30 days hundred dollars in credit or something like that to try pretty much anything you want out but then you also have 12 months of free services and then you also have 25 plus things that are free forever.</p><p>Let’s create a resource and we’re going to search for service bus hit create. provide all details hit create or review and create as shown in below picture.please refer below images for references.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jhIl6CbpBgsllSxfkCWecQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xe2_acOhQ3gIwFnnuxXH8g.png" /></figure><p>We’re ready it’s validated hit create and that’s going to create our service bus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9DHoJRxsskc7iOCkXcrrEA.png" /></figure><p>Then go to your resource group, in my case it is AzureBlogs and go inside your namespace (ShreeMediumBlog). Then access Shared access policies and copy from primary connection string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5jCL3fECj75DO0kztdL0g.png" /></figure><p>Let’s go back to visual studio and paste that connection string in appsettings.json.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*LLxwKlFHoUlvnKZYdIFB5Q.png" /></figure><p>Let’s go back to Azure and create queues and call it employeequeue. Please refer below images for queue creation in azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*Ab00l5vr_940-amEoqMwMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*tOqWDieTJF2SgmbMQCiJPQ.png" /></figure><p>Let’s go back to visual studio and create UI with some basic code to set basic fields.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*IG6Oijc1ZfZJBKAuaQ2Cog.png" /></figure><p>We will run this application and add some items to the Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l3QsfRjxsd7XP1tcQNdPXw.png" /></figure><p>In azure if we open up the employee queue we’ll see that we have one active message and you can see message without reading by clicking on peek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ixmjOWiR6lAQ2e-iJMhyaA.png" /></figure><p>Let’s try to understand, how we can consume these messages from the Azure service bus. So our messagereceiver going to do that job.</p><p>Let’s make Void main async by adding async keyword prior to that. Now will implement below code to consume messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*bSIQvHrd-PnRRdJIG_8UdQ.png" /></figure><p>We’re going to pass in our connection string and our queue name so this establishes the connection to our queue and we’re going to pass in a exception received handler object and then autocomplete equals false what autocomplete equals false — autocomplete equals false will not mark the message as complete so when it triggers and we’re not going to just say and it’s complete we’re going to wait until we read the message and as long as they successfully read. The message we’re going to say yes complete this message and that’s where that 30 second lock timer comes in where we have 30 seconds to do it before it gets unlocked and allowed to get pulled down by somebody else so that’s our options. And now we’re going to say queueclient.register messagehandler and let’s say process messages async that’s a method name and we’re gonna pass in our message handler options.</p><p>So what this is doing is it’s going to create a new queue client which talks to the message queue in the azure service bus and it’s going to register a message handler — a message handler is the method that’s going to accept messages. when messages come in it listens and decodes byte array and deserializes into Employee object. We will print message response in console window.</p><p>Note : will set startup projects as multiple as shown below :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*-M6sAUbgNNgOn11weQxg_g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83fefccffb31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>