<?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 Swati Verma on Medium]]></title>
        <description><![CDATA[Stories by Swati Verma on Medium]]></description>
        <link>https://medium.com/@swatisv11?source=rss-23060b44a4c5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Swati Verma on Medium</title>
            <link>https://medium.com/@swatisv11?source=rss-23060b44a4c5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 10:37:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swatisv11/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[Designing an AI System That Learns and Improves in Production]]></title>
            <link>https://medium.com/@swatisv11/designing-an-ai-system-that-learns-and-improves-in-production-39ed3853524b?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/39ed3853524b</guid>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 07:07:04 GMT</pubDate>
            <atom:updated>2026-07-08T07:07:04.285Z</atom:updated>
            <content:encoded><![CDATA[<p>Say you’re running a shopping assistant in production — something that recommends a jacket, checks order status. A shopper asks it for “a waterproof jacket under $100.” It recommends one. Thirty seconds later, the same session comes back with almost the same question, one word added — “…that isn’t polyester.” Then the session ends. No purchase, no error, no exception thrown anywhere.</p><p>What happened there?</p><p>Nothing dramatic, from the system’s point of view. The bot didn’t crash, didn’t say anything wrong, didn’t get flagged for anything. It just missed. Maybe it didn’t know material mattered here. Maybe the first answer was technically fine but not actually useful. A static system has no way to notice any of this — it’ll answer the next person’s near-identical question exactly the same way, no better informed than it was an hour ago.</p><p>This kind of thing happens constantly, and it’s almost always invisible from the outside. Nothing about it trips an alert or shows up as a dip on a dashboard you’d know to check. No exception, no failed request, no 500. It just sits there as a slightly worse answer that nobody’s instrumented a way to catch. Multiply that across a few thousand sessions a week, and you’ve got a system quietly degrading quality in production, with nothing telling you it’s happening.</p><p>That’s really why self-improvement matters. A system that can’t learn from what just happened has no way of getting better than it was on day one. And nothing about the underlying model fixes this for you — it doesn’t remember the last session, and it definitely doesn’t know that the follow-up message was the one that actually mattered.</p><p>So what does actually learning from that look like?</p><h3><strong>The trap most people fall into</strong></h3><p>Here’s the usual setup: log everything the bot does, look at the logs every week, notice it keeps recommending a shoe that’s out of stock, go fix and ship it, repeat next Friday.</p><p>That’s a person doing all the improving. The system itself just sits there, waiting to be noticed and fixed. It works, but it’s slow, and it completely depends on someone actually reading the report that week. Nothing about the system detects and fixes on its own — which means it’s not really self-improving; it’s a organized to-do list with a person attached.</p><p>What we actually want is a bot that notices this stuff itself — watches what shoppers do after it answers, figures out on its own that something’s off, and quietly builds and tests a better version in the shadow. A person still gets final say before anything ships, but nobody has to be the one who spots the problem in the first place.</p><p>This is basically the idea behind <a href="https://github.com/Gen-Verse/OpenClaw-RL">OpenClaw-RL</a> — a project that trains a personal AI agent just from talking to it, where your next message is the signal for whether the last response was any good.</p><h3>The four-part architecture</h3><p>The idea is splitting flow into four things that don’t wait on each other:</p><p>The bot <strong>serves</strong> shoppers like normal, answering questions live. Separately, something is <strong>collecting</strong> what happens after each answer — not just the response, but whether the shopper bought the thing, asked again in a different way, or gave up. Separately again, something is <strong>judging</strong> those moments — a model looking at “here’s what the bot said, here’s what the shopper did next” and deciding if that went well or not. And somewhere in the background, something is <strong>adapting</strong> — taking the patterns where things kept going badly and drafting a fix: a clearer instruction, a different tool description, whatever.</p><p>None of these four blocks each other. The bot keeps answering people while last week’s conversations get scored and a fix quietly gets drafted and tested somewhere else. The live system only changes at one moment — when a fix has actually proven itself better and approved, not before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2x0vdsXitVKHrn8khD8oeA.png" /></figure><pre>def serve_node(state):<br>    return {&quot;response&quot;: bot.answer(state[&quot;policy&quot;], state[&quot;query&quot;])}<br><br>def collect_node(state):<br>    return shopper_sim.react(state[&quot;query&quot;], state[&quot;response&quot;])  # what happened next<br><br>def judge_node(state):<br>    return {&quot;verdict&quot;: judge.score(state)}<br><br>graph = StateGraph(RolloutState)<br>graph.add_node(&quot;serve&quot;, serve_node)<br>graph.add_node(&quot;collect&quot;, collect_node)<br>graph.add_node(&quot;judge&quot;, judge_node)<br>graph.set_entry_point(&quot;serve&quot;)<br>graph.add_edge(&quot;serve&quot;, &quot;collect&quot;)<br>graph.add_edge(&quot;collect&quot;, &quot;judge&quot;)<br>graph.add_edge(&quot;judge&quot;, END)<br>app = graph.compile()</pre><p>That’s one rollout — serve, collect, judge, in that order. The “adapting” step lives outside this graph on purpose: it runs across a batch of rollouts like this one, not inside a single conversation, which is why it’s a separate step below rather than another node here.</p><h3>Figuring out what “good” even means here</h3><p>This is the hard part; in some cases, it can be simple — did your next message sound annoyed or fine? whereas some cases require more details</p><p>Someone rephrasing the same question a few seconds later means the first answer was missed. Someone abandoning their cart right after a recommendation is a hint, not proof, but a hint. An order going through with no more questions is a good sign. A return that shows up right after purchase, especially about something the bot should’ve mentioned — sizing, material — is a bad one. And someone asking for a human instead of the bot is about as clear a “no” as you’re going to get.</p><p>None of that needs a person tagging examples by hand. It just needs you to actually track what happens <em>after</em> the bot answers and something to turn that into a score.</p><p><strong>Strong, unambiguous signals — trust these the most.</strong> Someone asking for a human instead of the bot is about as clear a “no” as you’re going to get; treat every escalation as a bad rollout by default. A flat correction — “no,” “that’s wrong,” “not what I asked for” — is just as clear and just as cheap to catch with a keyword check before anything fancier runs. A return that shows up within a day or two of purchase, especially tied to something the bot could have mentioned up front (sizing, material, compatibility), is a strong negative too — it’s just a delayed one, which matters for how you use it (more on that below).</p><p><strong>Weaker signals — real, but only mean something in combination.</strong> Someone rephrasing the same question a few seconds later usually means the first answer was missed, but not always — sometimes people think out loud. Cart abandonment right after a recommendation is a hint, not proof; plenty of people add something and reconsider for reasons unrelated to the bot.</p><p><strong>The clean positive.</strong> An order going through with no more questions is the good case — the bot handled it; the shopper didn’t need to work for it. Worth noting, this is where it’s tempting to stop looking, and exactly where the Amazon example from a minute ago matters: a recommendation can convert and still be a worse pick for the shopper than it should’ve been, if the thing driving the conversion is more “this felt easy to click” than “this was actually the right product.” Conversion rate alone doesn’t tell you which one happened.</p><p><strong>Not every turn deserves a verdict at all.</strong> A shopper saying “thanks” or “cool, that works” isn’t reacting to quality one way or the other — it’s just conversational filler. Score every turn, and you’re mostly training the judge to pattern-match on noise and burning judge calls on messages that were never going to move anything. Filter these out before they even reach the judging</p><p>Putting the strong/weak distinction into code, rather than just a flat outcome check, looks something like this — strong signals decide the verdict outright, weak ones only tip it when there’s nothing stronger to go on</p><h3>Turning “this went badly” into an actual fix</h3><p>This is the part where it’s tempting to write one function that turns every bad rollout into a prompt addition and call it done. Don’t — the wrong kind of fix for the wrong kind of failure either does nothing or actively makes things worse. Worth going through the actual cases, because each one calls for a different move.</p><p><strong>Case 1: the bot knows the answer but doesn’t say it.</strong> This is the return-window example — the information exists, the bot just doesn’t volunteer it. This is the one case where a plain instruction is the right fix, because the gap really is “the model wasn’t told to.” Say fifteen sessions this week asked about a jacket’s return window right after the bot recommended one, and every time the answer was vague:</p><p><strong>Case 2: the bot confidently says something that isn’t true.</strong> Recommending a shoe that’s actually out of stock, or quoting last week’s price, is different. Adding “double-check availability before recommending” to the prompt is a bandaid — the model can’t check anything, it can only be told to claim it did. The actual fix lives one layer down, in the harness: the recommendation step needs to call the inventory tool and filter candidates by live availability <em>before</em> generating a response, not after. If your pattern-finder turns up “recommended an out-of-stock item,” that’s a signal to go patch the tool-calling sequence, not the wording</p><pre>def classify_failure(bad_rollout):<br>    if bad_rollout.get(&quot;recommended_item_unavailable&quot;):<br>        return &quot;harness&quot;   # fix the tool call order, not the prompt<br>    if bad_rollout.get(&quot;missing_expected_detail&quot;):<br>        return &quot;context&quot;   # the model just needs to be told<br>    return &quot;unclear&quot;<br><br></pre><p><strong>Case 3: nothing to patch yet.</strong> Sometimes a pattern shows up in the bad-rollout pile, but the underlying cause is different every time — “I want something like the other one” fails for five unrelated reasons across five sessions. Forcing a single instruction out of a cluster that isn’t actually one pattern gives you a vague, low-value addition to the prompt that doesn’t fix any of the five cases properly. The right move here is to <em>not</em> patch yet</p><h3>Why we still need a gate</h3><p>A fix shouldn’t go live just because it looks good by the same measure that produced it — that’s circular. It needs to prove itself against stuff it wasn’t built around: a small set of queries you already trust, plus a slice of real, recent traffic it’s never seen.</p><p>The gate itself doesn’t need to be fancy — it just needs to say no more often than you’d like:</p><pre>def should_promote(candidate_policy, current_policy, golden_set, held_out_traffic):<br>    candidate_golden = run_and_score(candidate_policy, golden_set)<br>    current_golden = run_and_score(current_policy, golden_set)<br>    candidate_held_out = run_and_score(candidate_policy, held_out_traffic)<br>    current_held_out = run_and_score(current_policy, held_out_traffic)<br><br>    return (candidate_golden &gt;= current_golden) and (candidate_held_out &gt;= current_held_out)</pre><p>Both numbers had to say yes before the fix was allowed to ship — if the candidate had only won on the golden set and lost on held-out traffic, it would’ve stayed on the baseline policy instead.</p><h3>Two flows, not one</h3><p>Everything above happens slowly and on purpose — it waits for a batch of conversations, checks a pattern is real, tests a fix, then ships it to everyone. That’s the right pace for something permanent. It’s way too slow for the person the system is talking to right now, who just rejected its third suggestion in a row.</p><p>So there’s a second, faster version of this worth having too: something that adjusts <em>within</em> the current conversation, before it even ends. Not a system-wide change — just a note for this one chat. If someone’s skipped past every polyester jacket without saying anything, that’s worth noticing this session, not in next month’s fix. If someone’s giving one-word answers and rejecting everything, that’s worth backing off and offering fewer, more direct picks right now, not waiting for a pattern across a thousand other shoppers.</p><p>The nice part is this doesn’t need the gate, the slow loop needs. Get it wrong, and the damage is one bad conversation, not a regression everyone gets. The two together cover different problems — the fast one catches “this shopper’s getting annoyed right now”; the slow one catches “shoppers keep hitting the same wall; let’s actually fix it.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MWKT1gmcGQfvePxnwxrZjw.png" /></figure><h3>Where this can go wrong</h3><p>The biggest one: the system gets good at whatever you’re measuring, not necessarily at what you meant. If “resolved quickly, no complaints” is the only signal, you’ll get fast, confident, occasionally wrong answers — because nothing’s checking for actual correctness, just for “nobody complained in the next five minutes.” Worth having a person spot-check some of the conversations the system rated as <em>good</em>, not just the bad ones, since that’s where a confidently wrong answer hides.</p><p>The fixes pile up over time if nobody prunes them. Six months of “when X happens, mention Y” turn into a prompt that half-contradicts itself. Give old instructions an expiry — if a pattern hasn’t shown up in a while, drop it instead of leaving it in forever.</p><p>And take the data seriously. You’re capturing order history, maybe payment details, addresses — treat that data store the same way you’d treat the actual order database, not like a debugging scratchpad.</p><h3>Build order, roughly</h3><p>Start by actually tracking what happens after the bot answers — not just the query and response. Get that collection running as its own thing, separate from serving. Get a judge model working and sanity-check it against a small set you trust before relying on it with real traffic. Build the part that turns bad patterns into a fix. Build the gate — new fix has to beat the old one on stuff it wasn’t built around. Then, and only then, let it ship changes automatically, with a log of what changed and why every single time.</p><h3>Where this leaves you</h3><p>The real difference between a good eval setup and something actually self-improving isn’t better metrics — it’s whether a person has to notice the problem before anything changes. Watching what happens after the bot answers, scoring that automatically, and shipping a tested fix without someone hand-editing a prompt is what gets you a system that’s quietly better next month than it is today. The shopping assistant is just the example — swap in whatever you’re actually building, the shape doesn’t change much.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39ed3853524b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Production Engineer’s Playbook for Taming LLM Hallucinations]]></title>
            <link>https://medium.com/@swatisv11/a-production-engineers-playbook-for-taming-llm-hallucinations-85e0679eb987?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/85e0679eb987</guid>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 09:17:49 GMT</pubDate>
            <atom:updated>2026-04-19T09:17:49.411Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>The invoice was wrong. The contract clause didn’t exist. The regulation the chatbot cited had been repealed two years ago. And every answer came with the same unwavering confidence.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RmV-5oicPoVyWiBakNPtwQ.jpeg" /></figure><p>Somewhere right now, an enterprise chatbot is inventing facts — and nobody upstream knows it yet. Not the product team. Not the ML engineers. Not the users, until the damage is done.</p><p>The frustrating part? The model was never “broken.” It did exactly what it was designed to do: produce fluent, contextually plausible text. The failure wasn’t in the weights — it was in the walls, or rather, the complete absence of them. <strong>Production LLM systems don’t fall apart because of bad models. They fall apart because of missing architecture.</strong></p><p>This article is a hands-on walkthrough of four engineering strategies that keep hallucinations out of your users’ hands: RAG done properly (hybrid search + reranking), a guardrails pipeline, confidence calibration, and a continuous eval loop.</p><h3>The Anatomy of a Hallucination</h3><p>Before reaching for solutions, it’s worth understanding what’s actually breaking.</p><p>An LLM doesn’t retrieve facts the way a database does. It compresses patterns from billions of tokens into a dense numerical structure — its weights — and at inference time, it reconstructs plausible-sounding text from those patterns. That reconstruction is probabilistic, not deterministic. This is <strong>parametric memory drift</strong>: the model learned something, but the exact form of that knowledge shifts unpredictably at generation time.</p><p>The second problem is <strong>lack of grounding</strong>. A model with no connection to external data has no choice but to answer from its internal representation of the world. When that representation doesn’t hold a confident answer, it doesn’t say “I don’t know” — it interpolates. It was trained to be helpful, and silence isn’t helpful.</p><p>Then there’s <strong>temperature</strong>. Dial it past 0.7 and the model starts picking lower-probability tokens — useful for creative tasks, but a direct lever for fabrication in factual ones.</p><p>Finally, <strong>RLHF feedback artifacts</strong>. If human annotators during training rewarded answers that <em>sounded</em> authoritative — regardless of accuracy — those patterns get baked into the model’s defaults. The result: a system that has learned confident tone earns better scores, truth optional.</p><p>Two beliefs worth discarding before moving on: that frontier models have solved this (they haven’t — GPT-4 and Claude hallucinate, just less visibly), and that fine-tuning is a cure (it narrows the problem to a domain, it doesn’t fix the underlying architecture). Adding a legal disclaimer to your chatbot is the engineering equivalent of putting a sign on a faulty bridge. It moves the liability. It doesn’t fix the bridge.</p><h3>Strategy 1: Stop Trusting Your Retriever — Fix It</h3><p>RAG is the right instinct. Giving the LLM access to your actual documents beats asking it to remember things from training data. But the version of RAG most teams ship in a prototype — embed, store in a vector DB, retrieve by cosine similarity — quietly fails in production without making much noise.</p><p>The root issue: semantic similarity is not the same as relevance. Two pieces of text can share meaning without one being useful for answering the other. Ask a question about “Q3 2023 penalty clauses” in a 10,000-document legal corpus and cosine similarity will cheerfully return chunks about penalty clauses from 2019, from different contracts, from different jurisdictions — all semantically on-topic, none of them what you needed.</p><h3>Layer 1: Hybrid Search</h3><p>The fix is to blend semantic retrieval with keyword-based retrieval (BM25). Semantic search understands concepts; keyword search ensures that specific terms in the query actually appear in the chunks. The weighted combination outperforms either method alone, especially in high-precision domains like finance, law, and healthcare.</p><pre>from langchain.retrievers import BM25Retriever, EnsembleRetriever<br>from langchain_community.vectorstores import Chroma<br>from langchain_openai import OpenAIEmbeddings<br><br>embeddings = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>vectorstore = Chroma.from_documents(documents=docs, embedding=embeddings)<br><br># Semantic arm<br>semantic_retriever = vectorstore.as_retriever(search_kwargs={&quot;k&quot;: 10})<br><br># Keyword arm<br>bm25_retriever = BM25Retriever.from_documents(docs)<br>bm25_retriever.k = 10<br><br># 60/40 blend — tune this ratio for your domain<br>hybrid_retriever = EnsembleRetriever(<br>    retrievers=[semantic_retriever, bm25_retriever],<br>    weights=[0.6, 0.4]<br>)<br><br>candidates = hybrid_retriever.invoke(&quot;Q3 2023 late payment penalty rate&quot;)</pre><p>For domains where exact terminology matters (contract law, medical dosing, tax codes), push the BM25 weight toward 0.5 or higher. For open-ended conversational queries, keep semantic dominant.</p><h3>Layer 2: Cross-Encoder Reranking</h3><p>Hybrid search improves recall — you get better candidates in your top-10. But you still need to distill those 10 down to the 2–3 chunks actually worth injecting into your prompt.</p><p>Where a bi-encoder computes query and document representations separately, a cross-encoder evaluates both simultaneously. It catches subtle relevance signals that independent embeddings miss. The downside: it’s significantly more expensive per call. That’s why you run it only on already-filtered candidates, never on the full corpus.</p><pre>from sentence_transformers import CrossEncoder<br><br>reranker = CrossEncoder(&quot;cross-encoder/ms-marco-MiniLM-L-6-v2&quot;)<br><br>def rerank(query: str, chunks: list[str], top_k: int = 3) -&gt; list[str]:<br>    scored = reranker.predict([(query, chunk) for chunk in chunks])<br>    ranked = sorted(zip(scored, chunks), key=lambda x: x[0], reverse=True)<br>    return [chunk for _, chunk in ranked[:top_k]]<br><br>query = &quot;Q3 2023 late payment penalty rate&quot;<br>raw_chunks = [doc.page_content for doc in hybrid_retriever.invoke(query)]<br>final_context = rerank(query, raw_chunks, top_k=3)</pre><h3>Layer 3: Metadata Filtering</h3><p>Every chunk in your vector store should carry metadata: source document, date, category, owning team. This lets you apply hard filters <em>before</em> semantic search runs, slashing the search space and ruling out stale data entirely.</p><pre>from langchain.schema import Document<br><br>docs_with_meta = [<br>    Document(<br>        page_content=&quot;Q3 2023 penalty rate for late invoices is 1.5% per month.&quot;,<br>        metadata={&quot;year&quot;: 2023, &quot;quarter&quot;: &quot;Q3&quot;, &quot;category&quot;: &quot;finance&quot;}<br>    ),<br>    Document(<br>        page_content=&quot;Q3 2020 penalty rate was 0.8% per month under legacy terms.&quot;,<br>        metadata={&quot;year&quot;: 2020, &quot;quarter&quot;: &quot;Q3&quot;, &quot;category&quot;: &quot;finance&quot;}<br>    ),<br>]<br><br>vectorstore = Chroma.from_documents(docs_with_meta, embedding=embeddings)<br><br># Hard filter: only documents from 2023 enter the search<br>retriever = vectorstore.as_retriever(<br>    search_kwargs={<br>        &quot;k&quot;: 10,<br>        &quot;filter&quot;: {&quot;year&quot;: {&quot;$eq&quot;: 2023}}<br>    }<br>)</pre><p>Without this filter, your LLM might blend the 2020 rate with the 2023 rate and return a confident figure that matches neither. With it, the 2020 documents never enter the picture.</p><h3>Strategy 2: Build Walls Around Your LLM</h3><p>Think of your LLM as a highly capable but slightly unpredictable analyst sitting in a soundproof room. You pass notes in, notes come out. Guardrails are the person reviewing both stacks before anything moves.</p><pre>User → [Input Check] → RAG + LLM → [Output Check] → User</pre><h3>Input Guardrails: Control What Goes In</h3><p>Three categories to intercept before a query reaches your model:</p><p><strong>Prompt injections and jailbreaks</strong> — adversarial inputs designed to override your system prompt and make the model ignore its instructions.</p><p><strong>Off-domain queries</strong> — questions your system was never built for. An airline chatbot being asked about derivatives trading isn’t being helpful by trying.</p><p><strong>Sensitive personal data</strong> — users casually including phone numbers, account IDs, or medical details in their queries, which can end up in LLM logs, prompt traces, or third-party API calls.</p><pre>import re<br>from guardrails import Guard<br>from guardrails.hub import ToxicLanguage<br><br>class InputGuardrail:<br>    def __init__(self, allowed_topics: list[str]):<br>        self.allowed_topics = allowed_topics<br>        self.guard = Guard().use(ToxicLanguage(threshold=0.5))<br><br>    def is_on_topic(self, query: str) -&gt; bool:<br>        return any(topic in query.lower() for topic in self.allowed_topics)<br><br>    def scrub_pii(self, text: str) -&gt; str:<br>        text = re.sub(r&#39;\b\d{10}\b|\b\d{3}[-.\s]\d{3}[-.\s]\d{4}\b&#39;, &#39;[PHONE REDACTED]&#39;, text)<br>        text = re.sub(r&#39;[\w.+-]+@[\w-]+\.[a-zA-Z]{2,}&#39;, &#39;[EMAIL REDACTED]&#39;, text)<br>        return text<br><br>    def process(self, query: str) -&gt; dict:<br>        if not self.is_on_topic(query):<br>            return {<br>                &quot;pass&quot;: False,<br>                &quot;reply&quot;: &quot;This assistant handles finance queries only. I can&#39;t help with that.&quot;<br>            }<br>        return {&quot;pass&quot;: True, &quot;query&quot;: self.scrub_pii(query)}<br><br>gate = InputGuardrail(allowed_topics=[&quot;invoice&quot;, &quot;payment&quot;, &quot;contract&quot;, &quot;revenue&quot;, &quot;penalty&quot;])<br>result = gate.process(&quot;My phone is 9876543210 — what&#39;s the Q3 penalty rate?&quot;)<br><br>final_query = result[&quot;query&quot;] if result[&quot;pass&quot;] else None</pre><h3>Output Guardrails: Control What Goes Out</h3><p>The LLM produced an answer. Before it reaches the user, run two checks.</p><p><strong>Grounding verification</strong> — does the answer derive from the retrieved context, or did the model draw on parametric memory? A fast secondary model can score this reliably.</p><p><strong>Toxicity</strong> — does the response contain harmful, offensive, or legally problematic language? Critical in consumer-facing applications.</p><pre>from openai import OpenAI<br>import json<br><br>client = OpenAI()<br><br>def verify_grounding(answer: str, context: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Ask a lightweight model to audit whether the answer<br>    is traceable to the provided context or fabricated.<br>    &quot;&quot;&quot;<br>    prompt = f&quot;&quot;&quot;<br>You are a factual auditor. Given a context and an AI-generated answer,<br>determine if the answer is grounded in the context or invented.<br><br>CONTEXT:<br>{context}<br><br>ANSWER:<br>{answer}<br><br>Return ONLY this JSON:<br>{{<br>  &quot;grounding_score&quot;: &lt;integer 1-5&gt;,<br>  &quot;is_grounded&quot;: &lt;true or false&gt;,<br>  &quot;fabricated_claims&quot;: [&quot;&lt;any claim not in context&gt;&quot;],<br>  &quot;verdict&quot;: &quot;&lt;PASS or FAIL&gt;&quot;<br>}}<br><br>Score 5 = every claim comes from the context. Score 1 = mostly fabricated.<br>&quot;&quot;&quot;<br>    resp = client.chat.completions.create(<br>        model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>        response_format={&quot;type&quot;: &quot;json_object&quot;},<br>        temperature=0<br>    )<br>    return json.loads(resp.choices[0].message.content)<br><br><br>llm_answer = your_rag_chain.invoke(query)<br>grounding = verify_grounding(llm_answer, retrieved_context)<br><br>if not grounding[&quot;is_grounded&quot;] or grounding[&quot;grounding_score&quot;] &lt; 3:<br>    user_response = (<br>        &quot;I wasn&#39;t able to find a reliable answer in the available documents. &quot;<br>        &quot;Please consult the source material directly or reach out to your account team.&quot;<br>    )<br>else:<br>    user_response = llm_answer</pre><p><strong>Guardrail libraries to know:</strong></p><p>ToolTypeBest fitguardrails-aiPython OSSCustom validators, structured output enforcementNeMo GuardrailsNVIDIA frameworkConversational flow control, topic railsLlama GuardMeta OSSHarm and safety classificationAWS / Azure / GCP nativeCloud-managedEnterprise deployments with compliance requirements</p><h3>Strategy 3: Give Your System a Way to Say “I’m Not Sure”</h3><p>The most dangerous hallucinations aren’t the obvious ones — they’re answers that are <em>almost</em> right, delivered with identical confidence to answers that are completely right. The solution isn’t to make the model smarter. It’s to give your system a mechanism to measure its own uncertainty and act on that signal.</p><h3>Log Probabilities as a Confidence Proxy</h3><p>Every token the model generates has an underlying probability. When the model is uncertain, those probabilities drop. The OpenAI API exposes these as log probabilities — a reliable proxy for answer confidence you can threshold on.</p><p>Start your threshold between 0.25–0.35 and calibrate it against your golden dataset (covered in Strategy 4).</p><h3>Self-Consistency: Ask Five Times, Trust the Consensus</h3><p>Here’s a less-obvious but highly effective signal: sample the same answer multiple times at a slightly elevated temperature, then check if the responses agree. When a model genuinely knows the answer, it says the same thing five different ways. When it’s guessing, the answers scatter.</p><pre>from collections import Counter<br>from openai import OpenAI<br><br>client = OpenAI()<br><br>def consistent_answer(query: str, context: str, samples: int = 5) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Sample the model N times and return the majority answer.<br>    Consistency score = fraction of samples matching the plurality.<br><br>    Note: costs N × your normal token budget. Reserve for high-stakes queries.<br>    &quot;&quot;&quot;<br>    answers = []<br>    for _ in range(samples):<br>        resp = client.chat.completions.create(<br>            model=&quot;gpt-4o-mini&quot;,<br>            messages=[<br>                {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;Answer only from the context. Be concise.&quot;},<br>                {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: f&quot;Context:\n{context}\n\nQuestion: {query}&quot;}<br>            ],<br>            temperature=0.6,<br>            max_tokens=200<br>        )<br>        answers.append(resp.choices[0].message.content.strip())<br><br>    majority, count = Counter(answers).most_common(1)[0]<br>    consistency = count / samples<br><br>    return {<br>        &quot;answer&quot;: majority,<br>        &quot;consistency&quot;: consistency,<br>        &quot;reliable&quot;: consistency &gt;= 0.6   # 3 of 5 agree<br>    }<br><br>result = consistent_answer(<br>    query=&quot;What is the interest rate on overdue invoices per the 2023 MSA?&quot;,<br>    context=retrieved_context,<br>    samples=5<br>)<br><br>if result[&quot;reliable&quot;]:<br>    print(f&quot;Answer ({result[&#39;consistency&#39;]:.0%} consistent): {result[&#39;answer&#39;]}&quot;)<br>else:<br>    print(&quot;Inconsistent responses detected. Routing to human review.&quot;)<br></pre><p>Expensive — use it as a precision instrument on high-value queries, not as a blanket policy.</p><h3>Retrieval Score Threshold: The Earliest Kill Switch</h3><p>If your best retrieved chunk barely correlates with the query, the LLM is being handed poor material and asked to do its best. It will. Badly.</p><pre>def retrieve_or_reject(query: str, vectorstore, min_score: float = 0.72, k: int = 5):<br>    results = vectorstore.similarity_search_with_score(query, k=k)<br><br>    if not results or results[0][1] &lt; min_score:<br>        return {<br>            &quot;proceed&quot;: False,<br>            &quot;message&quot;: (<br>                f&quot;No sufficiently relevant documents found &quot;<br>                f&quot;(best match: {results[0][1]:.2f}). &quot;<br>                &quot;I can&#39;t answer this reliably.&quot;<br>            )<br>        }<br><br>    return {&quot;proceed&quot;: True, &quot;chunks&quot;: [doc for doc, _ in results]}</pre><p>A retrieval score gate prevents the LLM from ever seeing low-quality context — which means there’s nothing to hallucinate <em>from</em>.</p><h3>Strategy 4: Measure Hallucination Like You Measure Everything Else</h3><p>“We think it’s performing well” is not a metric. Without a measurement harness, you have no idea whether your changes are helping or hurting, and no way to catch quality regressions before users do.</p><h3>The Golden Dataset</h3><p>The foundation of any hallucination testing harness is a curated set of questions with known-good answers. Aim for 100–500 entries. Don’t just include typical queries — cover edge cases, adversarial inputs, questions the system should <em>refuse</em>, and queries with subtle ambiguity.</p><pre>golden_dataset = [<br>    {<br>        &quot;question&quot;: &quot;What is the penalty rate for overdue invoices in the 2023 MSA?&quot;,<br>        &quot;expected_answer&quot;: &quot;1.5% per month on outstanding balances after 30 days.&quot;,<br>        &quot;source_doc&quot;: &quot;msa_2023_v2.pdf&quot;,<br>        &quot;should_refuse&quot;: False<br>    },<br>    {<br>        &quot;question&quot;: &quot;What did our CEO say at last year&#39;s board meeting?&quot;,<br>        &quot;expected_answer&quot;: None,<br>        &quot;should_refuse&quot;: True   # Out of scope or not in available documents<br>    },<br>    # ... expand to 100–500 items, covering diverse query types<br>]</pre><h3>Automated Scoring with RAGAS</h3><p>RAGAS gives you four metrics that together cover where your system can fail:</p><ul><li><strong>Faithfulness</strong> — Does the answer trace to the retrieved context, or did the model invent it?</li><li><strong>Answer Relevance</strong> — Does the answer actually address what was asked?</li><li><strong>Context Precision</strong> — Was the retrieved context genuinely useful?</li><li><strong>Answer Correctness</strong> — Does the answer match the ground truth?</li></ul><pre>from ragas import evaluate<br>from ragas.metrics import faithfulness, answer_relevancy, answer_correctness, context_precision<br>from datasets import Dataset<br><br>def run_eval(golden_dataset: list[dict], rag_chain, retriever) -&gt; dict:<br>    records = []<br><br>    for item in golden_dataset:<br>        q = item[&quot;question&quot;]<br>        docs = retriever.invoke(q)<br>        contexts = [d.page_content for d in docs]<br>        answer = rag_chain.invoke({&quot;question&quot;: q, &quot;context&quot;: &quot;\n\n&quot;.join(contexts)})<br><br>        records.append({<br>            &quot;question&quot;: q,<br>            &quot;answer&quot;: answer,<br>            &quot;contexts&quot;: contexts,<br>            &quot;ground_truth&quot;: item.get(&quot;expected_answer&quot;, &quot;&quot;)<br>        })<br><br>    return evaluate(<br>        Dataset.from_list(records),<br>        metrics=[faithfulness, answer_relevancy, answer_correctness, context_precision]<br>    )<br><br>results = run_eval(golden_dataset, rag_chain, hybrid_retriever)<br># {&#39;faithfulness&#39;: 0.89, &#39;answer_relevancy&#39;: 0.92, &#39;answer_correctness&#39;: 0.85, ...}</pre><p>A faithfulness score below 0.80 is a red flag that warrants immediate investigation. Treat it like a failing test suite — stop the deployment and dig in.</p><h3>LLM-as-Judge: Scaled Human-Quality Review</h3><p>For nuanced cases — where a technically correct answer is misleading, or a slightly wrong answer is mostly harmless — automated metrics fall short. LLM-as-judge bridges that gap at scale.</p><pre>def llm_judge(question: str, answer: str, context: str, ground_truth: str) -&gt; dict:<br>    prompt = f&quot;&quot;&quot;<br>You are an impartial evaluator for an enterprise Q&amp;A system.<br>Score the response across three dimensions. Return ONLY valid JSON.<br><br>QUESTION: {question}<br>RETRIEVED CONTEXT: {context}<br>GENERATED ANSWER: {answer}<br>GROUND TRUTH: {ground_truth}<br><br>{{<br>  &quot;faithfulness&quot;:          {{&quot;score&quot;: &lt;1-5&gt;, &quot;note&quot;: &quot;&lt;brief explanation&gt;&quot;}},<br>  &quot;relevance&quot;:             {{&quot;score&quot;: &lt;1-5&gt;, &quot;note&quot;: &quot;&lt;brief explanation&gt;&quot;}},<br>  &quot;correctness&quot;:           {{&quot;score&quot;: &lt;1-5&gt;, &quot;note&quot;: &quot;&lt;brief explanation&gt;&quot;}},<br>  &quot;hallucination_present&quot;: &lt;true|false&gt;,<br>  &quot;verdict&quot;:               &quot;&lt;PASS|FAIL&gt;&quot;<br>}}<br>&quot;&quot;&quot;<br>    resp = client.chat.completions.create(<br>        model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: prompt}],<br>        response_format={&quot;type&quot;: &quot;json_object&quot;},<br>        temperature=0<br>    )<br>    return json.loads(resp.choices[0].message.content)</pre><p>Run this on a sample of live production traffic — not just your golden dataset — to catch distribution shift between what users actually ask and what you tested for.</p><h3>Continuous Monitoring with W&amp;B</h3><p>Eval scores are only useful if you track them over time. Log every deployment. Alert on regressions. Treat your hallucination rate the way you’d treat p99 latency in a backend service.</p><pre>import wandb<br>from datetime import datetime<br><br>wandb.init(project=&quot;llm-hallucination-monitor&quot;, name=f&quot;eval-{datetime.now().date()}&quot;)<br><br>def log_metrics(results: dict, version: str):<br>    wandb.log({<br>        &quot;faithfulness&quot;:       results[&quot;faithfulness&quot;],<br>        &quot;answer_relevancy&quot;:   results[&quot;answer_relevancy&quot;],<br>        &quot;answer_correctness&quot;: results[&quot;answer_correctness&quot;],<br>        &quot;hallucination_rate&quot;: round(1 - results[&quot;faithfulness&quot;], 4),<br>        &quot;model_version&quot;:      version,<br>    })<br><br>    if results[&quot;faithfulness&quot;] &lt; 0.80:<br>        wandb.alert(<br>            title=&quot;⚠️ Hallucination Rate Elevated&quot;,<br>            text=(<br>                f&quot;Faithfulness dropped to {results[&#39;faithfulness&#39;]:.1%}. &quot;<br>                &quot;Review recent prompt or retrieval changes before next release.&quot;<br>            ),<br>            level=wandb.AlertLevel.WARN<br>        )<br><br>log_metrics(results, version=&quot;v2.4.0&quot;)<br>wandb.finish()<br></pre><p><strong>Other observability tools worth having on your radar:</strong> LangSmith (tight LangChain integration, excellent tracing), TrueLens (purpose-built for RAG evaluation), Arize Phoenix (strong for detecting data drift over time).</p><h3>The Full Stack at a Glance</h3><pre>User Input<br>    │<br>    ▼<br>┌─────────────────────────┐<br>│     Input Guardrail     │  ← PII scrubbing · topic filter · jailbreak detection<br>└────────────┬────────────┘<br>             │<br>    ▼<br>┌─────────────────────────┐<br>│     Hybrid Retriever    │  ← Semantic (60%) + BM25 (40%) + metadata pre-filter<br>└────────────┬────────────┘<br>             │<br>    ▼<br>┌─────────────────────────┐<br>│        Reranker         │  ← Cross-encoder scores top-10, passes top-3<br>└────────────┬────────────┘<br>             │<br>    ▼<br>┌─────────────────────────┐<br>│     LLM Generation      │  ← Grounded prompt · citation required · temp ≤ 0.2<br>└────────────┬────────────┘<br>             │<br>    ▼<br>┌─────────────────────────┐<br>│    Confidence Check     │  ← Log prob threshold · self-consistency on critical paths<br>└────────────┬────────────┘<br>             │<br>    ▼<br>┌─────────────────────────┐<br>│    Output Guardrail     │  ← Grounding verification · toxicity filter<br>└────────────┬────────────┘<br>             │<br>    ▼<br>┌─────────────────────────┐<br>│   Observability Logger  │  ← Every query scored · RAGAS metrics tracked nightly<br>└────────────┬────────────┘<br>             │<br>    ▼<br>  User Response</pre><h3>Six Things to Walk Away With</h3><p><strong>1. The model is rarely the root cause.</strong> Hallucination in production is almost always an architecture failure. Design your system to compensate for it — don’t wait for a better model to save you.</p><p><strong>2. Vanilla RAG will disappoint you.</strong> Cosine similarity retrieves what’s <em>related</em>, not what’s <em>useful</em>. Hybrid search and reranking are the upgrade that separates prototypes from production systems.</p><p><strong>3. Guard both ends of the pipeline.</strong> Input guardrails protect your system from misuse. Output guardrails protect your users from fabricated answers. You need both — neither is optional at scale.</p><p><strong>4. Uncertainty is a feature, not a failure.</strong> A system that says “I don’t know” is more trustworthy than one that guesses with confidence. Log probabilities and self-consistency give you the tooling to make that call programmatically.</p><p><strong>5. You can’t improve what you don’t measure.</strong> Build a golden dataset before you go live. Track faithfulness, relevance, and correctness on every deployment the same way you track error rates.</p><p><strong>6. When in doubt, escalate.</strong> For queries your system can’t handle with confidence, the correct move is to route to a human or refuse cleanly — not to fabricate politely and hope nobody checks.</p><p>Found this useful? Clap, follow, or drop a comment with what hallucination issues you’ve run into in production</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85e0679eb987" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DSPy — Programming vs Prompting LLMs]]></title>
            <link>https://medium.com/@swatisv11/dspy-programming-vs-prompting-llms-01c8a10eaeef?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/01c8a10eaeef</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[dspy]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 16:36:58 GMT</pubDate>
            <atom:updated>2025-07-06T17:19:58.232Z</atom:updated>
            <content:encoded><![CDATA[<h3>DSPy — Prompting vs Programming LLMs</h3><p>I came across DSPy while searching for a framework to build an agentic system. This approach to prompting caught my attention. If you’ve been working with Large Language Models (LLMs) for any significant time, you’ve probably known the efforts that go behind crafting a prompt.</p><p>Another option to prompt engineering is DSPy (Declarative Self-improving Python), a framework designed for programming language models instead of prompting them. With DSPy, you can quickly iterate on structured code. Instead of manually creating prompts, you write modular, declarative code, and DSPy takes care of optimizing.</p><p>Before diving into the technicalities of DSPy, let&#39;s cover the problem statements that we face with Prompt Engineering</p><h3>The Problem with Prompt Engineering</h3><p><strong>LLM Bais: </strong>Prompt engineering is heavily biased towards LLM and changing the model will require prompt changes</p><p><strong>Maintenance issues:</strong> Every time you modify your pipeline, add new features, or update your data, you need to manually adjust prompts across your entire system.</p><p><strong>High Iteration Cost</strong>: Most of us optimize prompts through trial and error, since it is unclear what change could lead to what result, we normally spend multiple iterations</p><p>DSPy changes the game by letting you write code that works with any LLM instead of writing specific prompts for each one.</p><h3>How DSPy works</h3><p>The backbone of DSPy programming consists of two classes:</p><p>dspy.Signature</p><p>dspy.Module</p><p><strong>dspy.Signature</strong></p><p>Think of Signature as contracts that define what you want your LLM to accomplish. Instead of writing lengthy prompts with instructions, examples, and formatting guidelines, you simply declare the inputs and outputs you expect. DSPy then handles the underlying prompt construction, formatting, and LLM communication.</p><p>They can be as simple as strings, and you can also specify type. This shorthand notation is your declarative replacement of a prompt for a simple task. Here are a few examples of shorthand notations:</p><pre>&#39;question -&gt; answer&#39;<br>&#39;sentence -&gt; sentiment: bool&#39;</pre><p>For more complex scenarios where you need precise control over input and output formats, you can create custom Class-based Signatures:</p><pre>class SentimentClassifier(dspy.Signature):<br>    &quot;&quot;&quot;Classify the sentiment of a text.&quot;&quot;&quot;<br><br>    text: str = dspy.InputField(desc=&quot;input text to classify sentiment&quot;)<br>    sentiment: int = dspy.OutputField(<br>        desc=&quot;sentiment, the higher the more positive&quot;, ge=0, le=10<br>    )</pre><p>To use this signature, you simply instantiate a predictor and call it:</p><pre>predict = dspy.Predict(SentimentClassifier) <br>output = predict(text=&quot;I am feeling pretty happy!&quot;)<br>print(output) </pre><p>Output was 8 here.</p><p>What’s happening behind the scenes is that DSPy automatically generates an appropriate prompt based on your signature, sends it to the configured LLM, parses the response, and returns a structured output object. You can even inspect the generated prompt using dspy.inspect_history(n=1) to see exactly how DSPy translated your signature into LLM instructions</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2PKeRXxRWDSVbUcki5Nzw.png" /></figure><p><strong>dspy.Module</strong></p><p>While Signatures define what you want to accomplish, Modules provide the way to utilize these signatures to interact with LLMs. They encapsulate the logic of LLM interaction and can be composed together to create complex workflows.</p><p>DSPy provides several built-in modules for different prompting techniques:</p><p><strong>dspy.Predict</strong></p><p>This is the most basic module for simple LLM interaction, like we saw in the previous example. It takes a Signature, handles instruction formatting, manages demonstrations, and sends the generated prompt to the LLM. It’s perfect for straightforward input-output transformations.</p><p><strong>dspy.ChainOfThought</strong></p><p>This module instructs the LLM to think step by step before providing the final output. It automatically adds reasoning prompts to your signature and includes the LLM’s reasoning process along with the final answer. This is particularly useful for complex reasoning tasks where you want to understand the model’s decision-making process.</p><p><strong>dspy.ReAct</strong></p><p>It allows the development of agent-like capabilities by supporting iterative reasoning and action cycles, making it ideal for building systems that need to interact with external tools or APIs.</p><p>DSPy also allows you to develop your custom modules for complex operations by extending the <strong>dspy.Module </strong>class, giving you the flexibility to create sophisticated workflows.</p><p>With enough context, let&#39;s dive into a practical example to understand how we can make use of DSPy</p><h3>Using DSPy to Classify Customer Query Intents</h3><p>To illustrate how we can program our system instead of prompting, I’m using a customer query intent classification problem for the banking domain. This example demonstrates the power of DSPy’s declarative approach compared to traditional prompt engineering.</p><p>I’m using the PolyAI/banking77 dataset from Hugging Face, which contains online banking queries annotated with their corresponding intents. This dataset provides a realistic scenario where we need to classify customer inquiries into specific banking-related categories.</p><p><strong>Configure DSPy</strong></p><pre>import dspy<br>dspy.settings.configure(lm=dspy.LM(&quot;openai/gpt-4o-mini&quot;))</pre><p><strong>Creating the Intent Classification Signature</strong></p><p>Next, I create a class-based Signature, given the customer query, I want to both the predicted intent and a confidence score as output:</p><pre>class IntentClassification(dspy.Signature):<br>    &quot;&quot;&quot;Classify the intent of a banking customer query with confidence score&quot;&quot;&quot;<br>    query: str = dspy.InputField(desc=&quot;The customer&#39;s banking query or question&quot;)<br><br>    intent: str = dspy.OutputField(desc=&quot;The predicted intent category that best matches the query&quot;)<br><br>    confidence: float = dspy.OutputField(desc=&quot;Confidence score between 0.0 and 1.0 for the prediction&quot;)</pre><p><strong>Building the Intent Classification Module</strong></p><p>Now I create a custom module that encapsulates the intent classification logic:</p><pre><br>class ConfidenceIntentModule(dspy.Module):<br>    &quot;&quot;&quot;DSPy module for banking intent classification with confidence scoring&quot;&quot;&quot;<br>    <br>    def __init__(self, intent_labels: List[str]):<br>        super().__init__()<br>        self.intent_labels = intent_labels<br>        self.classify = dspy.ChainOfThought(IntentClassification)<br>        <br>    def forward(self, query: str):<br>        &quot;&quot;&quot;Forward pass for intent classification with confidence&quot;&quot;&quot;<br>        # Add context about available intents<br>        context = &quot;Available banking intents :\n&quot;<br>        context += f&quot;{&#39;,&#39;.join(self.intent_labels)}&quot;<br>        enhanced_query = f&quot;{context}\n\nCustomer query: {query}&quot;<br>        prediction = self.classify(query=enhanced_query)    <br>        return prediction</pre><p>This module does several important things: it stores the list of available intent labels, uses ChainOfThought to get reasoning along with the prediction, and enhances the input query with context about available intents. The forward method defines how data flows through the module, combining the available intents with the customer query to provide better context for classification.</p><p>When I run this module with a sample query:</p><pre>module  = ConfidenceIntentModule(intent_labels=label_names)<br>output = module.forward(query=&quot;Can I track my card while it is in the process of delivery?&quot;)<br>print(output)</pre><p>And the output I got for the query “<em>Can I track my card while it is in the process of delivery</em>?”</p><p><em>Prediction( reasoning=”The query is related to tracking the delivery process of a card, which falls under the ‘card_delivery_estimate’ intent.”, intent=’card_delivery_estimate’, confidence=0.95 )</em></p><p>This is already a huge win. Instead of writing complex prompts with examples and formatting instructions, I just declared what I wanted the system to do, and DSPy handled the rest.</p><h3>The Optimization Process: Where DSPy Shines</h3><p>The most powerful aspect of DSPy is its ability to automatically optimize your modules. Traditional prompt engineering requires manual iteration and guesswork, but DSPy provides systematic optimization based on your training data and metrics.</p><p><strong>Defining Success Metrics</strong></p><p>To optimize our system, we need to define what success looks like. In DSPy, metrics are functions that compare your system’s output to the ideal output:</p><pre>def validate_intent(example, prediction, trace=None):<br>    &quot;&quot;&quot;Validate intent classification&quot;&quot;&quot;<br>    return prediction.intent == example.intent or prediction.intent.lower() == example.intent.lower() or prediction.intent.replace(&#39;_&#39;, &#39; &#39;) == example.intent.replace(&#39;_&#39;, &#39; &#39;)</pre><p>This validation function checks if our predicted intent matches the ground truth, handling variations in capitalization and formatting. It’s flexible enough to account for minor differences in how intents might be expressed.</p><p><strong>Baseline Evaluation</strong></p><p>Before we improve on our intent detection classification, let&#39;s first evaluate the existing module using DSPy’s evaluator functions:</p><pre>evaluator = Evaluate(devset=train_subset, num_threads=1, display_progress=True, display_table=5)<br>evaluator(module, metric=validate_intent)</pre><p>The evaluation framework runs our module on a subset of training data and measures performance using our validation metric. This gives us a baseline to compare against after optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nit6jhHpsR5sfRECpCe_iw.png" /></figure><p>To improve our system, we specify an <a href="https://dspy.ai/learn/optimization/optimizers/">optimizer</a> and ask DSPy to run it on our function with using our training dataset :</p><p><strong>Automatic Optimization</strong></p><p>Here’s where DSPy’s magic happens. Instead of manually tweaking prompts, I specify an optimizer and let DSPy improve the system automatically:</p><pre>optimizer = dspy.BootstrapFewShot(<br>            metric=lambda gold, pred, trace=None: gold.intent == pred.intent,<br>            max_bootstrapped_demos=4,<br>            max_labeled_demos=8<br>        )<br>        <br># Optimize the module<br>optimized_module = optimizer.compile(module,trainset=train_subset)</pre><p>The BootstrapFewShot optimizer analyzes our training data, identifies patterns in successful predictions, and automatically generates few-shot examples that improve performance. It creates demonstrations that help the LLM better understand the task and make more accurate predictions.</p><p>Now running the evaluations on this optimised module using the same validation metric for intent comparison</p><pre>evaluator(optimized_module, metric=validate_intent)<br></pre><p>The results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8C83PuVJSLZqdNuD4-2tQ.png" /></figure><p>The optimizer raised our evaluation from 41.4% to 77.2%.</p><p><strong>Before DSPy</strong>: Manual iteration cycles</p><p>Write prompt → Test → Analyze failures → Rewrite prompt → Repeat</p><p><strong>With DSPy</strong>: Systematic optimization</p><p>Define signature → Build module → Collect training data → Optimize automatically</p><p>The framework handles the complexity of prompt construction, optimization, and model interaction, allowing you to focus on defining what you want to accomplish rather than how to ask for it. This shift from prompting to programming represents a fundamental change in how we build LLM-powered systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01c8a10eaeef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prompting Secrets: Tips and Tricks to Get the Best from AI]]></title>
            <link>https://blog.dtdl.in/prompt-engineering-for-everyone-77d6dabafb76?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d6dabafb76</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Tue, 15 Apr 2025 07:35:11 GMT</pubDate>
            <atom:updated>2025-04-21T11:41:42.643Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever asked a question to ChatGPT or Claude? The text that you type is prompt and the secret to get better answers lies in something called “prompt engineering”</p><h3><strong>What is a Prompt?</strong></h3><p>Think of a prompt as simply the way you ask a LLM for help.</p><p><strong>Example:</strong> Instead of typing “weather Delhi,” you might say “How’s the weather in Delhi today?” The clearer and specific you are, the better results you’ll get.</p><p>Many aspects of prompt affect its efficacy: the model you use, the model’s training data, the model configurations, word choice, style and tone, structure, and context all these things matter.</p><h3>Prompt Engineering</h3><p>As we know how LLM works, it takes sequential text as input and then predicts what the following token should be, based on the data it was<br>trained on. The next token prediction is based on the relationship between what’s in the previous tokens and what the LLM has seen during its training.</p><p>When we write a prompt, basically it&#39;s an attempt to set up the LLM to predict the right sequence of tokens. Prompt engineering is the process of designing high-quality prompts that guide LLMs to produce accurate outputs. In the context of natural language processing and LLMs, a prompt is an input provided to the model to generate a response or prediction.</p><p>In this article, we will together see different techniques that can be used to create prompts to get the desired answers from LLM</p><h3>Zero-Shot Prompting: Just Ask!</h3><p>Zero-shot prompting is the most straightforward approach — you just ask a direct question without providing examples.</p><pre><strong>Goal</strong>: Classify product(Shirt) reviews as positive, neutral or negative.<br><strong>Prompt</strong>: Classify product reviews as POSITIVE, NEUTRAL or NEGATIVE.Review:I <br>recently purchased this &quot;shirt&quot;. The material is soft and breathable,<br> making it perfect for all-day wear. The stitching is flawless, and <br>the attention to detail is truly impressive<br><strong>Output</strong>: POSTIVE</pre><p>This works well for straightforward questions.</p><h3><strong>Few-Shot Prompting: Show and Tel</strong>l</h3><p>When creating prompts for AI models, it is helpful to provide examples. These examples can help the model understand what you are asking for. Examples are especially useful when you want to steer the model to a certain output structure or pattern.</p><p>One Shot prompt: Provide a single example</p><p>Few Shot prompt: provide multiple examples to the model,multiple examples of desired pattern increases chance the model follows the pattern.</p><p><strong>Example:</strong></p><pre>Goal: Convert the user&#39;s shirt preference into valid JSON<br>Prompt: Convert the user&#39;s shirt preference into valid JSON<br>EXAMPLE:<br>I prefer a slim-fit cotton shirt in white, size M.<br>JSON Response<br>```<br>{<br>  &quot;fit&quot;: &quot;slim&quot;,<br>  &quot;material&quot;: &quot;cotton&quot;,<br>  &quot;color&quot;: &quot;white&quot;,<br>  &quot;size&quot;: &quot;M&quot;<br>}<br>```<br>EXAMPLE:<br>I&#39;m looking for a relaxed-fit shirt made of linen, blue color, size L.<br>JSON Response<br>```<br>{<br>  &quot;fit&quot;: &quot;relaxed&quot;,<br>  &quot;material&quot;: &quot;linen&quot;,<br>  &quot;color&quot;: &quot;blue&quot;,<br>  &quot;size&quot;: &quot;L&quot;<br>}<br>```<br>Now I want a regular-fit polyester shirt in black, size XL.<br>JSON Response:<br>Output: <br>{<br>  &quot;fit&quot;: &quot;regular&quot;,<br>  &quot;material&quot;: &quot;polyester&quot;,<br>  &quot;color&quot;: &quot;black&quot;,<br>  &quot;size&quot;: &quot;XL&quot;<br>}<br></pre><h3>System Prompting</h3><p>This is a way to set the overall context and purpose for the LLM. It<br>defines the ‘big picture’ of what the model should be doing, like translating a language, classifying a review, etc. Unlike user-input examples in few-shot prompting, system prompts set the rules, tone, context, or guidelines for how the LLM should interpret and respond to queries.</p><pre><strong>Goal</strong>: Parse a user’s shirt preference into valid JSON.<br><strong>Prompt</strong>: You are a JSON parser for shirt preferences. <br>Always respond with valid JSON containing keys: fit, material, color, and size.<br> If any preference is missing, use null as the value.<br><strong>User</strong> <strong>Input</strong>:I want a cotton shirt in black, size M.<br><strong>Output</strong>: <br>{<br>  &quot;fit&quot;: null,<br>  &quot;material&quot;: &quot;cotton&quot;,<br>  &quot;color&quot;: &quot;black&quot;,<br>  &quot;size&quot;: &quot;M&quot;<br>}</pre><h3>Role prompting</h3><p>Role prompting is a technique in prompt engineering that involves assigning a specific role to the LLM. This can help the model to generate more relevant and informative output, as the model can generate its responses to the specific role that it has been assigned. You could role prompt an LLM to be a travel agent, a teacher, or a motivational speaker, and then give it prompts that are specific to that role</p><pre><strong>Goal</strong>: Act as travel guide and provide 3 travel suggestions<br><strong>Prompt</strong>: I want you to act as a travel guide. I will write to you<br>about my location and you will suggest 3 places to visit near<br>me. In some cases, I will also give you the type of places I<br>want to  visit.<br>My suggestion: &quot;I am in Delhi and I want to visit<br>only monuments.&quot;<br>Travel Suggestions:<br><strong>Output</strong>: Here are three iconic monuments to visit in Delhi:<br>1)Qutub Minar<br>A UNESCO World Heritage Site, Qutub Minar is a magnificent 73-meter tall <br>minaret made of red sandstone and marble. It dates back to the 12th century <br>and is surrounded by lush gardens and historical ruins.<br>2)Humayun’s Tomb<br>This stunning Mughal mausoleum is considered a precursor to the Taj Mahal&#39;s <br>architecture. Its symmetrical gardens and intricate craftsmanship make it a <br>must-visit monument.<br>2)Red Fort (Lal Qila)<br>A symbol of India&#39;s rich history, this red sandstone fort was the main <br>residence of Mughal emperors for over 200 years. The fort is vast and offers <br>a glimpse into the grandeur of Mughal architecture.<br></pre><p>Here are some styles you can choose from that I find effective:<br>Confrontational, Descriptive, Direct, Formal, Humorous, Influential, Informal, Inspirational, Persuasive</p><p>you can change the above prompt to include a humorous style and observe differences in LLM response</p><pre><strong>Prompt</strong>:<br>I want you to <strong>act as a travel guide.</strong> I will write to you<br>about my location and you will suggest 3 places to visit near<br>me. In some cases, I will also give you the type of places I<br>want to  visit <strong>in a humorous style.</strong><br>My suggestion: &quot;I am in Delhi and I want to visit<br>only monuments.&quot;<br>Travel Suggestions:<br><strong>Output</strong>:<br>1)Qutub Minar<br>Welcome to the OG skyscraper of Delhi! This 73-meter-tall beauty has been <br>standing tall since the 12th century. Bonus: You get to say you visited<br>the tallest minaret in the world made of bricks. <br>No elevators, though—bring your cardio spirit!&quot;<br><br>2)Humayun’s Tomb<br>Think of it as the Mughal emperor’s version of a super-luxe Airbnb. <br>With gardens, water channels, and majestic domes, it’s basically a <br>16th-century ad for royal real estate. You&#39;ll leave feeling like you&#39;ve <br>walked into a Mughal Pinterest board.&quot;<br><br>3)Red Fort (Lal Qila)<br>Ah, the Red Fort—a palace so cool, even the British decided to crash here <br>for a bit. Stroll through the massive walls, imagine yourself as royalty, <br>and don’t miss the sound and light show. History with a side of drama!<br><br></pre><h3>Step back prompting</h3><p>This aims to guide the LLM in generating better, more accurate, or more creative responses by asking it to take a “step back” and reconsider or evaluate its prior output.</p><p>How it works:</p><ol><li><strong>Initial Prompt</strong>: The user gives the AI an initial task or question.</li><li><strong>LLM Response</strong>: The LLM generates a response based on the initial input.</li><li><strong>Step Back Prompt</strong>: The user asks the LLM to take a “step back” by either: reviewing or critiquing the initial response, offering alternative solutions or perspectives, or refining or improving the initial output.</li></ol><pre><strong>Prompt</strong>: Summarize the main themes of The Lion King<br><strong>Output</strong>: The main themes of The Lion King are the circle of life, responsibility, and the importance of family.<br><br><strong>Step Back Prompt:</strong><br>&quot;Take a step back and expand on how these themes are explored in the movie.&quot;<br><strong>Output</strong>:<br>The themes of The Lion King include:<br><br>The Circle of Life: The movie opens and closes with the iconic &quot;Circle of Life&quot; sequence, emphasizing the interconnectedness of all living things and the inevitability of birth, growth, death, and rebirth. This is reflected in Simba&#39;s journey as he steps into his role as king, continuing the cycle.<br><br>Responsibility: Simba initially runs away from his responsibilities after the death of his father, Mufasa. Through guidance from Rafiki, Nala, and the memory of Mufasa, he learns that true leadership means facing challenges and protecting those you love.<br><br>The Importance of Family and Legacy: The bond between Simba and Mufasa forms the emotional core of the film. Mufasa&#39;s lessons echo throughout Simba’s life, guiding him back to his rightful place in the Pride Lands. The movie also highlights the contrast between Simba&#39;s sense of family and Scar&#39;s betrayal.</pre><h3>Chain of Thought Prompting: Thinking Step by Step</h3><p>This technique encourages the LLM to work through problems one step at a time instead of rushing to an answer.</p><p>The LLM response includes the chain of thought reasoning, which means more output tokens, which means predictions cost more money and take longer.</p><pre><strong>Prompt</strong>: When I was 3 years old, my partner was 3 times my age. Now, I<br>am 20 years old. How old is my partner? Let&#39;s think step<br>by step.<br><strong>Output</strong>:<br>1. Let’s assume my current age is “x” years.<br>2. When I was 3 years old, my age was 3 years.<br>3. My partner’s age at that time was 3 times my age, which means my partner’s<br>age was 3 * 3 = 9 years.<br>4. Now, I am 20 years old, which means my age has increased by 20 - 3 = 17<br>years since I was 3 years old.<br>5. Since my partner’s age was 9 years when I was 3 years old, and my age has<br>increased by 17 years, my partner’s age must have also increased by 17 years.<br>6. Therefore, my partner’s current age is 9 + 17 = 26 years.<br>So, my partner is 26 years old.</pre><p>Chain of thought can be useful for various use cases, like this prompting can be used for writing prompts for coding assistants to explain the logic behind the code generated.</p><h3>Tips for Better Results</h3><ol><li><strong>Be specific:</strong> “Give me 3 easy pasta recipes that use chicken” will work better than “I need dinner ideas.”</li><li>Provide examples: It’s like giving the model a reference point or<br>target to aim for, improving the accuracy, style, and tone of its response to better match your expectations.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d6dabafb76" width="1" height="1" alt=""><hr><p><a href="https://blog.dtdl.in/prompt-engineering-for-everyone-77d6dabafb76">Prompting Secrets: Tips and Tricks to Get the Best from AI</a> was originally published in <a href="https://blog.dtdl.in/">Deutsche Telekom Digital Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Reactive Programming with Spring WebFlux]]></title>
            <link>https://medium.com/@swatisv11/mastering-reactive-programming-with-spring-webflux-5ed72345109f?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed72345109f</guid>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[spring-boot-webflux]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Mon, 10 Mar 2025 13:10:32 GMT</pubDate>
            <atom:updated>2025-03-10T13:10:32.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Reactive programming is revolutionizing the way we build high-performance, scalable, and resilient applications. If you’re looking to dive into this paradigm and explore the power of <strong>Spring WebFlux</strong>, this blog will guide you through a structured learning roadmap. By the end, you’ll have a solid understanding of the fundamentals and practical experience to start building reactive applications.</p><h3>Understanding Reactive Programming Basics</h3><p>Before diving into Spring WebFlux, it’s essential to understand the principles of reactive programming.</p><h4>What is Reactive Programming?</h4><p>Reactive programming is a paradigm that focuses on handling asynchronous data streams and reacting to changes in real time. It’s built around the concept of streams that emit data over time and provides operators to transform, filter, and combine these streams.</p><h4>Key Concepts:</h4><ol><li><strong>Reactive Streams Specification: </strong>Defines four main interfaces to manage asynchronous data:</li></ol><ul><li><strong>Publisher</strong>: Produces data and sends it to subscribers.</li><li><strong>Subscriber</strong>: Consumes data from a publisher.</li><li><strong>Subscription</strong>: Represents the relationship between publisher and subscriber, allowing the subscriber to request a specific number of items.</li><li><strong>Processor</strong>: Both a publisher and a subscriber, used to transform data.</li></ul><pre>Flux&lt;Integer&gt; flux = Flux.just(1, 2, 3, 4);<br>flux.subscribe(System.out::println); // Prints 1, 2, 3, 4</pre><p><strong>2. Push vs. Pull Models:</strong></p><ul><li><strong>Push Model</strong>: The producer pushes data to the consumer as it becomes available.</li><li><strong>Pull Model</strong>: The consumer requests data when needed.</li><li>Reactive programming blends these models by allowing the consumer to request data (pull) while the producer pushes it asynchronously.</li></ul><p>3. <strong>Backpressure: </strong>A mechanism to ensure the producer does not overwhelm the consumer.</p><p><strong>4. Mono and Flux:</strong></p><p><strong>Mono</strong>: Represents 0 or 1 item. Example:</p><pre>Mono&lt;String&gt; mono = Mono.just(&quot;Hello Mono&quot;);<br>mono.subscribe(System.out::println); // Prints &quot;Hello Mono&quot;</pre><p><strong>Flux</strong>: Represents 0 to N items. Example:</p><pre>Flux&lt;String&gt; flux = Flux.just(&quot;Hello&quot;, &quot;Flux&quot;);<br>flux.subscribe(System.out::println); // Prints &quot;Hello&quot; and &quot;Flux&quot;</pre><h3>Getting Started with Spring WebFlux</h3><p>Spring WebFlux is the reactive alternative to Spring MVC, designed to handle asynchronous and non-blocking operations.</p><p><strong>Comparison with Spring MVC:</strong></p><ul><li>Spring MVC is thread-blocking and based on the servlet API.</li><li>Spring WebFlux is non-blocking and built on the reactive streams specification.</li><li>WebFlux uses <strong>Netty</strong>, a non-blocking event-driven server, by default instead of Tomcat.</li></ul><h4>Setting Up a WebFlux Project</h4><ol><li><strong>Create a Spring Boot Application:</strong></li></ol><ul><li>Use Spring Initializr (https://start.spring.io/).</li><li>Add dependencies: spring-boot-starter-webflux and optionally spring-boot-starter-data-mongodb-reactive.</li></ul><p><strong>2. Basic Project Structure:</strong></p><ul><li>Controller layer handles HTTP requests.</li><li>Service layer contains business logic.</li><li>Repository layer interacts with the database.</li></ul><h4>Building Reactive Controllers</h4><ol><li><strong>Example of a Simple Controller:</strong></li></ol><pre>@RestController<br>public class HelloController {<br>    @GetMapping(&quot;/hello&quot;)<br>    public Mono&lt;String&gt; sayHello() {<br>        return Mono.just(&quot;Hello, Reactive World!&quot;);<br>    }<br>}</pre><p><strong>2.Return Types:</strong></p><ul><li>Use Mono for single responses and Flux for lists. Example:</li></ul><pre>@GetMapping(&quot;/numbers&quot;)<br>public Flux&lt;Integer&gt; getNumbers() {<br>    return Flux.range(1, 10);<br>}</pre><h3>Exploring Reactive Data Access and Advanced Features</h3><p>Now lets focus on integrating reactive data sources and exploring advanced WebFlux capabilities.</p><h4>Reactive Data Access- <strong>Using Reactive MongoDB:</strong></h4><p>Add dependency: spring-boot-starter-data-mongodb-reactive. Create, read, update, and delete data reactively using Mono and Flux.</p><pre>@Repository<br>public interface UserRepository extends ReactiveMongoRepository&lt;User, String&gt; {<br>    Flux&lt;User&gt; findByAge(int age);<br>}</pre><h4>Error Handling</h4><ul><li>Use operators to handle errors:</li></ul><pre>Flux&lt;String&gt; data = Flux.just(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)<br>    .concatWith(Flux.error(new RuntimeException(&quot;Error!&quot;)))<br>    .onErrorResume(e -&gt; Flux.just(&quot;Default Value&quot;));</pre><h4>Functional Endpoints</h4><ul><li>Functional endpoints provide an alternative to annotations for defining routes. The configuration is done programmatically using RouterFunctions and HandlerFunction.</li><li>They offer an alternative to traditional annotation-based controllers (e.g., @RestController and @RequestMapping) by allowing to define routes and their corresponding request handlers programmatically.</li><li><strong>Router Configuration</strong>: Defines the mapping of HTTP requests (routes) to specific handler functions. It acts like a dispatcher for incoming requests.</li></ul><pre>@Configuration<br>public class RouterConfig {<br>    @Bean<br>    public RouterFunction&lt;ServerResponse&gt; routes() {<br>        return RouterFunctions.route()<br>            .GET(&quot;/hello&quot;, request -&gt; ServerResponse.ok().bodyValue(&quot;Hello, Functional Endpoint!&quot;))<br>            .build();<br>    }<br>}</pre><ul><li><strong>Handler Function</strong>: Contains the logic to process the request and generate a response. It replaces annotated controller methods.</li></ul><pre>@Component<br>public class HelloHandler {<br>    public Mono&lt;ServerResponse&gt; sayHello(ServerRequest request) {<br>        return ServerResponse.ok().bodyValue(&quot;Hello, Handler Function!&quot;);<br>    }<br>}</pre><p><strong>Unit Testing with StepVerifier</strong></p><pre>@Test<br>public void testMono() {<br>    Mono&lt;String&gt; mono = Mono.just(&quot;test&quot;);<br>    StepVerifier.create(mono)<br>                .expectNext(&quot;test&quot;)<br>                .verifyComplete();<br>}</pre><p><strong>Integration Testing: </strong>Use WebTestClient to test WebFlux endpoints:</p><pre>@Test<br>public void testEndpoint() {<br>    webTestClient.get().uri(&quot;/hello&quot;)<br>                 .exchange()<br>                 .expectStatus().isOk()<br>                 .expectBody(String.class).isEqualTo(&quot;Hello, Reactive World!&quot;);<br>}</pre><h3>Conclusion</h3><p>Reactive programming with Spring WebFlux offers a approach to building scalable and efficient applications. I curated both theoretical knowledge and practical experience in this article to help in developing reactive systems.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed72345109f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How AI Can Be Integrated Into a Spring Boot Applications: Spring AI]]></title>
            <link>https://medium.com/@swatisv11/how-ai-can-be-integrated-into-a-spring-boot-applications-spring-ai-779f88438a65?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/779f88438a65</guid>
            <category><![CDATA[spring-ai]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Thu, 02 Jan 2025 14:35:03 GMT</pubDate>
            <atom:updated>2025-01-02T14:40:19.129Z</atom:updated>
            <content:encoded><![CDATA[<p>In recent years, artificial intelligence (AI) has revolutionized various industries, offering smart solutions that make tasks more efficient, personalized, and automated. One of the key areas where AI has made a significant impact is in the development of applications that offer personalized experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1gYNzoErjXMSzutIKDhIw.jpeg" /></figure><p><strong>What is Spring AI?</strong><br>Spring AI is an emerging integration within the Spring ecosystem that allows developers to interact with AI models directly from their Spring applications. It simplifies the process of integrating pre-built AI models, such as OpenAI’s GPT series, by providing utilities and abstractions that fit seamlessly with Spring’s architecture.</p><p><strong>Key Features of Spring AI:</strong><br><strong>Model Integration</strong>: Spring AI supports integration with various AI models, such as OpenAI’s GPT, and can be extended to other machine learning services.<br><strong>Prompt Management</strong>: Provides tools to structure and manage prompts efficiently, making it easier to generate meaningful outputs.<br>Seamless Spring Integration: Leverages Spring Boot’s dependency injection, configuration management, and other features to streamline AI interactions.<br><strong>Understanding AI Models and Prompts</strong><br><strong>AI Models</strong><br>An AI model is a pre-trained system capable of performing specific tasks, such as generating text, answering questions, or making predictions. In this project, we will use OpenAI’s GPT model, which excels in natural language processing tasks.</p><p><strong>GPT (Generative Pre-trained Transformer):</strong> This model generates text based on the input prompt provided. It predicts the next word or sentence by analyzing the context of the input.<br><strong>Prompts</strong><br>A prompt is the input provided to an AI model to guide its response. Crafting effective prompts is crucial for obtaining accurate and relevant outputs. For example:</p><p><strong>Prompt</strong>: “Create an Italian recipe using chicken, garlic, and butter.”<br><strong>Response</strong>: “Here is an Italian recipe: Chicken Alfredo with garlic butter sauce…”<br>The model’s response depends on the clarity and detail of the prompt. Complex tasks may require iterative refinement of prompts to achieve desired results.</p><p>For this integration we will build a diet plan generator that takes user preferences as input and returns a personalized diet plan. We’ll use <strong>OpenAI’s GPT </strong>to generate the diet plan based on a prompt that includes user parameters like calorie target, diet type, and cuisine preference.</p><p>Let’s break down the process:</p><ol><li><strong>Frontend (React.js):</strong> The user inputs their preferences (calories, diet type, etc.) in a form on the React frontend.</li><li><strong>Backend (Spring Boot):</strong> The Spring Boot backend receives the input from the frontend and sends a request to the OpenAI API to generate the diet plan based on the given parameters.</li><li><strong>OpenAI API:</strong> OpenAI processes the prompt and returns a detailed diet plan.</li><li><strong>Display:</strong> The backend sends the response to the frontend, which then formats and displays the diet plan to the user.</li></ol><p><strong>Setting Up the Environment</strong></p><p>Here are the steps to set up your development environment:</p><ol><li><strong>Install Java and Spring Boot</strong>: Make sure you have Java 8 or higher installed. You can download the Spring Boot setup from <a href="https://start.spring.io/">Spring Initializr</a>.</li><li><strong>Set up Node.js and React.js</strong>: Install <strong>Node.js</strong> from <a href="https://nodejs.org/">nodejs.org</a>, and create a new React application using:</li><li><strong>Obtain OpenAI API Key</strong>: Go to <a href="https://beta.openai.com/signup/">OpenAI’s official website</a> and sign up to get your API key.</li></ol><p><strong>Lets begin:</strong></p><p>Once you have downloaded the Spring Boot setup from <a href="https://start.spring.io/">Spring Initializr</a>. Unzip and open it in your IDE and add following dependencies to pom.xml</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.ai&lt;/groupId&gt;<br>    &lt;artifactId&gt;spring-ai-openai-spring-boot-starter&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Next define a configuration property named spring.ai.openai.api-key that you should set to the value of the API Key obtained from openai.com</p><p>The <a href="https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-openai/src/main/java/org/springframework/ai/openai/OpenAiChatOptions.java">OpenAiChatOptions.java</a> class provides model configurations such as the model to use, the temperature, the frequency penalty, etc.</p><p>On start-up, the default options can be configured with the spring.ai.openai.chat.options.* properties.</p><p>At run-time, this can also be overriden by adding new, request-specific options to the Prompt call. For example, to override the default model and temperature for a specific request:</p><pre>ChatResponse response = chatModel.call(<br>    new Prompt(<br>        &quot;What is the capital of Inida.&quot;,<br>        OpenAiChatOptions.builder()<br>            .model(&quot;gpt-4-o&quot;)<br>            .temperature(0.4)<br>        .build()<br>    ));</pre><p>here model is open ai model to use such as: gpt-4o, gpt-4o-mini, gpt-4-turbo, gpt-3.5-turbo, and more and sampling temperature, higher values will make output more random while lower values will make results more focused.</p><p>Here in this case prompt is to create diet plan as per user preferences so dynamic values to be passed in prompt using placeholders and Map. Notice in prompt I also added Expected output so that output remains same for each API Call</p><pre>@Service<br>public class GenDietPlanService {<br><br> @Autowired<br> private ChatModel chatModel;<br><br>public String getDietPlanAsResponseOptions(String calories, String dietType, String cuisine, String considerations){<br>String prompt = &quot;&quot;&quot;<br>        Create a detailed 7-day diet plan tailored to my preferences and goals. Consider the following parameters:<br>                       \s<br>        - Total daily calorie target: {calories}.<br>        - Diet type: {dietType}.<br>        - Cuisine preference: {cuisine}.<br>        - Additional considerations: {considerations}.<br>        - Meal breakdown: Include breakfast, lunch, dinner, and snacks for each day.<br>        - Ingredients list: Provide a summarized ingredients list for easy shopping.<br>        - Ensure the plan is balanced, includes variety, and meets the calorie and nutritional requirements.<br>        &quot;&quot;&quot;;<br>PromptTemplate promptTemplate = new PromptTemplate(prompt);<br>Map&lt;String, Object&gt; params = Map.of(<br>        &quot;calories&quot;, calories,<br>        &quot;dietType&quot;, dietType,<br>        &quot;cuisine&quot;, cuisine,<br>        &quot;considerations&quot;, considerations<br>);<br>return chatModel.call(promptTemplate.create(params));<br>}</pre><p>Now create a rest `controller and call this service and API to get diet plan is ready which accepts user preferences in request params.</p><pre>private final GenDietPlanService genDietPlanService;<br><br>public GenDietPlanController(GenDietPlanService genDietPlanService) {<br>    this.genDietPlanService = genDietPlanService;<br>}<br><br>@GetMapping(&quot;/generate-diet-plan&quot;)<br>@CrossOrigin(origins = &quot;http://localhost:3002&quot;)<br>public String createDietPlan(@RequestParam String calories, @RequestParam String dietType, @RequestParam String cuisine, @RequestParam String considerations) {<br>    return genDietPlanService.getResponseOptions(calories, dietType, cuisine, considerations);<br>}<br><br></pre><p>Note: The @CrossOrigin annotation enables cross-origin resource sharing only for this specific method.</p><p>API response validated from Postman</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvGC-Xr3W6JUKHGhsaiHsg.png" /></figure><p>Thats it. The open ai integration is setup and working !!!</p><p>Additionally offering a UI to user where these details are entered and UI can call the API we just developed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiVDw-S6wh6k7uSxdF381g.png" /></figure><p>and upon submission result can be seen on the same page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06YJAmcQQqy69pd7fCemIw.png" /></figure><pre>import React, { useState } from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br><br>const App = () =&gt; {<br>  const [inputs, setInputs] = useState({<br>    calories: &#39;&#39;,<br>    dietType: &#39;Vegetarian&#39;,<br>    cuisine: &#39;Mediterranean&#39;,<br>    considerations: &#39;&#39;,<br>  });<br>  <br>  const [response, setResponse] = useState(&quot;&quot;);<br>  const [formattedResponse, setFormattedResponse] = useState(null);<br><br>  const handleInputChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setInputs({ ...inputs, [name]: value });<br>  };<br><br>  const fetchDietPlan = async () =&gt; {<br>    setFormattedResponse(null);<br>    try {<br>      const res = await axios.get(&quot;http://localhost:8080/generate-diet-plan&quot;, {<br>        params: inputs,<br>      });<br>      setResponse(res.data);<br>      formatResponse(res.data);<br>    } catch (error) {<br>      console.error(&quot;Error fetching diet plan:&quot;, error);<br>    }<br>  };<br><br>  const formatResponse = (data) =&gt; {<br>    const lines = data.split(&quot;\n&quot;);<br>    const formatted = lines.map((line, index) =&gt; {<br>      if (line.startsWith(&quot;###&quot;)) {<br>        return &lt;h3 key={index}&gt;{line.replace(&quot;###&quot;, &quot;&quot;).trim()}&lt;/h3&gt;;<br>      } else if (line.startsWith(&quot;**&quot;)) {<br>        const [label, value] = line.split(&quot;:&quot;);<br>        return (<br>          &lt;p key={index}&gt;<br>            &lt;strong&gt;{label.replace(&quot;**&quot;, &quot;&quot;).trim()}&lt;/strong&gt;: {value?.trim()}<br>          &lt;/p&gt;<br>        );<br>      } else if (line.startsWith(&quot;- &quot;)) {<br>        return &lt;p key={index}&gt;{line.replace(&quot;- &quot;, &quot;&quot;).trim()}&lt;/p&gt;;<br>      } else {<br>        return &lt;p key={index}&gt;{line}&lt;/p&gt;;<br>      }<br>    });<br>    setFormattedResponse(formatted);<br>  };<br><br>  return (<br>    &lt;div style={{ maxWidth: &#39;600px&#39;, margin: &#39;auto&#39;, padding: &#39;20px&#39;, fontFamily: &#39;Arial, sans-serif&#39; }}&gt;<br>       &lt;h2&gt;Generate Your Diet Plan&lt;/h2&gt;<br>      &lt;div style={{ marginBottom: &quot;20px&quot; }}&gt;<br>        &lt;form<br>          onSubmit={(e) =&gt; {<br>            e.preventDefault();<br>            fetchDietPlan();<br>          }}&gt;<br>        &lt;label htmlFor=&quot;calories&quot;&gt;Total Daily Calories:&lt;/label&gt;<br>        &lt;input<br>          type=&quot;number&quot;<br>          id=&quot;calories&quot;<br>          name=&quot;calories&quot;<br>          value={inputs.calories}<br>          onChange={handleInputChange}<br>          placeholder=&quot;e.g., 2000&quot;<br>          required<br>          style={{ display: &#39;block&#39;, marginBottom: &#39;10px&#39;, width: &#39;100%&#39;, padding: &#39;8px&#39; }}<br>        /&gt;<br>      <br>       {/* Diet Type */}<br>        &lt;label htmlFor=&quot;dietType&quot;&gt;Diet Type:&lt;/label&gt;<br>        &lt;select<br>          id=&quot;dietType&quot;<br>          name=&quot;dietType&quot;<br>          value={inputs.dietType}<br>          onChange={handleInputChange}<br>          style={{ display: &#39;block&#39;, marginBottom: &#39;10px&#39;, width: &#39;100%&#39;, padding: &#39;8px&#39; }}<br>        &gt;<br>          &lt;option value=&quot;Vegetarian&quot;&gt;Vegetarian&lt;/option&gt;<br>          &lt;option value=&quot;Non-Vegetarian&quot;&gt;Non-Vegetarian&lt;/option&gt;<br>          &lt;option value=&quot;Includes Eggs&quot;&gt;Includes Eggs (Ovo-Vegetarian)&lt;/option&gt;<br>        &lt;/select&gt;<br><br><br>        {/* Cuisine Preference */}<br>        &lt;label htmlFor=&quot;cuisine&quot;&gt;Cuisine Preference:&lt;/label&gt;<br>        &lt;select<br>          id=&quot;cuisine&quot;<br>          name=&quot;cuisine&quot;<br>          value={inputs.cuisine}<br>          onChange={handleInputChange}<br>          style={{ display: &#39;block&#39;, marginBottom: &#39;10px&#39;, width: &#39;100%&#39;, padding: &#39;8px&#39; }}<br>        &gt;<br>          &lt;option value=&quot;Mediterranean&quot;&gt;Mediterranean&lt;/option&gt;<br>          &lt;option value=&quot;Indian&quot;&gt;Indian&lt;/option&gt;<br>          &lt;option value=&quot;Mexican&quot;&gt;Mexican&lt;/option&gt;<br>          &lt;option value=&quot;American&quot;&gt;American&lt;/option&gt;<br>        &lt;/select&gt;<br><br>         {/* Additional Considerations */}<br>         &lt;label htmlFor=&quot;considerations&quot;&gt;Additional Considerations:&lt;/label&gt;<br>        &lt;textarea<br>          id=&quot;considerations&quot;<br>          name=&quot;considerations&quot;<br>          value={inputs.considerations}<br>          onChange={handleInputChange}<br>          placeholder=&quot;e.g., High-protein, Low-carb, Gluten-free&quot;<br>          style={{ display: &#39;block&#39;, marginBottom: &#39;10px&#39;, width: &#39;100%&#39;, padding: &#39;8px&#39; }}<br>        /&gt;<br><br>        {/* Submit Button */}<br>        &lt;button<br>          type=&quot;submit&quot;<br>          style={{<br>            backgroundColor: &#39;#4CAF50&#39;,<br>            color: &#39;white&#39;,<br>            padding: &#39;10px 20px&#39;,<br>            border: &#39;none&#39;,<br>            borderRadius: &#39;5px&#39;,<br>            cursor: &#39;pointer&#39;,<br>          }}<br>        &gt;<br>          Submit<br>        &lt;/button&gt;<br>        &lt;/form&gt;<br>      &lt;/div&gt;<br>      {formattedResponse &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;h2&gt;Generated Diet Plan:&lt;/h2&gt;<br>          &lt;div style={{ whiteSpace: &quot;pre-wrap&quot; }}&gt;{formattedResponse}&lt;/div&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p><strong>Conclusion</strong><br>You’ve successfully built a Spring Boot application that integrates with OpenAI to generate recipes based on ingredients and cuisine type. This project demonstrates how to leverage AI capabilities in your applications using Spring AI and OpenAI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=779f88438a65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring applications: Prometheus and Grafana]]></title>
            <link>https://medium.com/@swatisv11/monitoring-applications-prometheus-and-grafana-b1f5b92cf59f?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1f5b92cf59f</guid>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 16:56:18 GMT</pubDate>
            <atom:updated>2024-06-05T16:56:18.701Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post we will set how to set up application monitoring using Prometheus and Grafana</p><h3>Prometheus</h3><p>Prometheus is an open-source software application used for event monitoring and alerting. It records real-time metrics in a time series database with flexible queries.</p><p>First we will set up prometheus on machine, for that we can create a yml config file named prometheus.yml</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff2015a01d863e313538de36c69da509/href">https://medium.com/media/ff2015a01d863e313538de36c69da509/href</a></iframe><p>Run the prometheus docker container</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cd0b0af26cd238ce425de1d0ad03cee/href">https://medium.com/media/5cd0b0af26cd238ce425de1d0ad03cee/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0o5F1LzVsHhddEGZYdXo3g.png" /></figure><p><strong>Grafana</strong></p><p>Now, lets integrate Prometheus metrics to Grafana dashboard. To do that, first, pull the Grafana docker image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/265a8566ee47fb56d546833266d0c5c5/href">https://medium.com/media/265a8566ee47fb56d546833266d0c5c5/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1f5b92cf59f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secrets : Storing sensitive information]]></title>
            <link>https://medium.com/@swatisv11/secrets-storing-sensitive-information-5347569e514a?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5347569e514a</guid>
            <category><![CDATA[kubernetes-security]]></category>
            <category><![CDATA[kubernetes-secret]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Wed, 10 Aug 2022 07:29:37 GMT</pubDate>
            <atom:updated>2022-08-23T08:38:07.407Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Secrets Manager or Kubernetes Secrets: Storeing application confidential data</h3><p>A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key.</p><p>Using a Secret means that you don’t need to include confidential data in your application code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*Rj37NTrcGTxfdgOyO96dTQ.jpeg" /></figure><h3>Kubernetes secrets</h3><p>We can externalise our application config in ConfigMaps and it aid with separation of concerns. However configMaps don’t offer security.</p><p>Kubernetes Secrets let us store and manage sensitive data. They are great for storing credentials, tokens, keys etc.</p><p>Kubernetes secrets are stored as unencrypted, base64-encoded strings, in order to safely use Secrets, take at least the following steps:</p><ol><li>Enable Encryption at Rest for Secrets.</li><li>Enable or configure RBAC rules that restrict reading data in Secrets (including via indirect means).</li><li>Where appropriate, also use mechanisms such as RBAC to limit which principals are allowed to create new Secrets or replace existing ones.</li></ol><p>Here we are looking how Kubernetes Secrets can be used to store sensitive information</p><h3>How Kubernetes Secrets can be used to store sensitive information</h3><p>Here we are going create datasource configuration as Secret in Kubernetes and pass the values to our application via environment variables from our Pod.</p><h3>Creating the Secret using Kubectl</h3><p>There are several ways to create Secrets; via yaml files or using kubectl. I find it useful to create Secrets using kubectlinitially, outputting the result of the command to a yaml file for later usage. To create the Secret we can run the following command:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a5b36965240ef174dcfe1fc8f24912e/href">https://medium.com/media/4a5b36965240ef174dcfe1fc8f24912e/href</a></iframe><p>The above command creates us a Secret named datasource-credentials, from the literal values root for username and password for password. Notice the generic parameter as well, this is the default Secret type in Kubernetes and refers to an Opaque Secret.</p><h3>Creating the secret using configuration file</h3><p>Create the config file for secret, in our case the config file will look like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8205b835b7c4ce1a6f730ecee9aaed18/href">https://medium.com/media/8205b835b7c4ce1a6f730ecee9aaed18/href</a></iframe><p>to prepare this config file we can add the following two parameters onto the end of the command:</p><ul><li>o yaml — dry-run</li></ul><p>These parameters tell kubectl to output the results of the command in yaml format and not to apply to changes to our Kubernetes environment, this way we can copy the results into config file. The full command would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa5302edf1b7b265a0f53761241a9952/href">https://medium.com/media/fa5302edf1b7b265a0f53761241a9952/href</a></iframe><p>After you save the yaml config, run following to create secret</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9ab7f731984da96a76abdcba022f07e/href">https://medium.com/media/f9ab7f731984da96a76abdcba022f07e/href</a></iframe><p>Now we can check the Secret has been created successfully:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33caf048a1daaf4b48af4b68a35ed5dd/href">https://medium.com/media/33caf048a1daaf4b48af4b68a35ed5dd/href</a></iframe><h3>Using Kubernetes secret</h3><p>Now we have our Secret created within our Kubernetes environment, we can use it within our application and Pod configuration.</p><p>The changes to the Spring Boot application are minimal, and involve changing the reference values within the application.yml file</p><p>username and password properties can be referenced from environment variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b64359a029fa1d167ff67da001cf0ef/href">https://medium.com/media/6b64359a029fa1d167ff67da001cf0ef/href</a></iframe><p>The environment variables are set within the Kubernetes Pod manifest, the values for which are pulled from the Secret we created earlier. Our Pod manifest needs some additional entries to create those environment variables:</p><p>The key changes are these two env entries:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a30887a857ea20d1508e16d9bec96b8e/href">https://medium.com/media/a30887a857ea20d1508e16d9bec96b8e/href</a></iframe><p>The above approach is to use Secrets as environment variables within the Pod. We create two environment variables, one for DB_USERNAME and one for DB_PASSWORD, each of these gets assigned the values username and password from the datasource-credentials secret respectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5347569e514a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Excessive liquibase connections- keeps 10 open connections]]></title>
            <link>https://medium.com/@swatisv11/excessive-liquibase-connections-keeps-10-open-connections-441f8e8c677b?source=rss-23060b44a4c5------2</link>
            <guid isPermaLink="false">https://medium.com/p/441f8e8c677b</guid>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[custom-datasource]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[liquibase]]></category>
            <dc:creator><![CDATA[Swati Verma]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 08:16:34 GMT</pubDate>
            <atom:updated>2020-04-17T08:16:34.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Excessive liquibase connections- spring-boot liquibase keeps 10 open connections</h3><p>There is no doubt that liquibase is a great database migration tool. It enables you to write your create schema in database agnostic way. There are n numbers of benefits that it offers for making database changes.</p><p>However while utilizing the benefit of liquibase to specify your change once and then moving it from various environments to production you might get alarmed for having too many inactive sessions.</p><p>If you are using spring boot 2.x.x by adding spring-boot-starter-data-jpa application uses Hikari connection pooling. Lets assume you have not configured any Hikari configurations then it picks up default configurations. Default value for <em>maximumPoolSize </em>is 10 (this determines the maximum number of actual connections to database backend). Default value for <em>minimumIdle </em>is value of <em>maximumPoolSize which is 10 </em>(determines minimum number of idle connections that HikariCP tries to maintain in pool).</p><p>Now for one microservice you have 10 open connections and as soon you write <em>spring.liquibase.url </em>or <em>spring.liquibase.user</em> in your properties file, liquibase creates is own datasource which perfectly make sense. Although intention was good but here started the big problem for 1 microservice you have 10 default datasource connections and 10 liquibase datasource connections so has total of 20 connections. Assuming you have 10 microservice (I know it is quite less than compared to real world scenario), even if we go by this number we have 200 connections.</p><p>Obliviously HikariCP default properties can be manipulated by adding <em>spring.datasource.hikari.minimumIdle</em> in properties file but it only controls you default datasource connection pool not the one which is being used by liquibase. So even if you added s<em>pring.datasource.hikari.minimumIdle=2</em> you will still have 10 (liquibase connections) + 2 connections.</p><h3><strong>Solution:</strong></h3><p><strong>Alternative 1:</strong> <em>Liquibase autoconfiguration </em>uses <em>DataSourceClosingSpringLiquibase </em>which closes liquibase datasource after applying all change sets unless you have enabled liquibase actuator endpoint. If you can compromise on liquibase actuator endpoints then go ahead and disable it by adding and datasource will shutdown and hence no more connctions.</p><p><em>management.endpoints.liquibase.enabled =false</em></p><p><strong>Alternative 2</strong>: create your own custom liquibase datasource by using @LiquibaseDataSource and then add HikariCP properties. Now point to note here is since we are configuring datasource explicitly for liquibase then default datasource also needs to be configured explicitly and dont’t forget to mark it as primary datasource.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d8057e997fbd277c9a256148ce2ab0a/href">https://medium.com/media/4d8057e997fbd277c9a256148ce2ab0a/href</a></iframe><p>HAPPY LIQUIBASE DEPLOYMENTS!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=441f8e8c677b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>