<?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 Karan Gore on Medium]]></title>
        <description><![CDATA[Stories by Karan Gore on Medium]]></description>
        <link>https://medium.com/@karangore518?source=rss-a1abcd419c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*XYo1djmuyQncZ3Bb0NSyQw.jpeg</url>
            <title>Stories by Karan Gore on Medium</title>
            <link>https://medium.com/@karangore518?source=rss-a1abcd419c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 04:16:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karangore518/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[How I Built a Self-Correcting AI Workflow with LangGraph]]></title>
            <link>https://medium.com/@karangore518/how-i-built-a-self-correcting-ai-workflow-with-langgraph-3cb45fc2963d?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cb45fc2963d</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 21:10:06 GMT</pubDate>
            <atom:updated>2026-06-10T21:10:06.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_e-0ghYpo1ryBn0_ZN28-A.png" /></figure><h3>A fetch → evaluate → present pipeline with conditional retries</h3><p>Everyone talks about “AI agents”. Fewer people talk about what happens when the agent’s first attempt is bad.</p><p>Most tutorials show a single prompt with ten tools bolted onto it. But when moving from a demo to production, a single “mega-prompt” breaks easily, hallucinates fields, and is difficult to debug.</p><p>When I built <strong>Work Finder</strong> — an automated pipeline that helps job seekers discover real apply links across the web — I built a <strong>graph</strong>: shared state, focused nodes, and a conditional loop that automatically corrects itself when search quality is low.</p><p>Here is a high-level architectural overview of how this LangGraph workflow is wired and how the code is structured.</p><h3>Why a Graph Beats a Single Agent</h3><p>A naive version of a job discovery agent looks like this:</p><blockquote><strong><em>User Prompt</em></strong><em> -&gt; </em><strong><em>Single LLM</em></strong><em> -&gt; </em><strong><em>Search the Web</em></strong><em> -&gt; </em><strong><em>Return Jobs</em></strong></blockquote><p>In practice, this fails for three main reasons:</p><ul><li><strong>Planning and searching are entirely different skills.</strong> Query design is an LLM job, while hitting an API is a deterministic coding job. Mixing them creates muddy prompts.</li><li><strong>Quality isn’t binary on the first try.</strong> Web search is noisy. You need an explicit evaluate-and-retry step rather than just hoping the model “tries harder” the first time.</li><li><strong>Presentation is its own stage.</strong> Users don’t want raw, messy URLs. They want categorized, scannable opportunities.</li></ul><p>LangGraph solves this by treating these stages as distinct <strong>nodes</strong> connected by <strong>edges</strong> — including conditional loops.</p><h3>The Graph Topology</h3><p>The system relies on four focused nodes, one conditional loop, and a single shared State object passed between every step:</p><pre>START ──&gt; search_planner ──&gt; work_search ──&gt; search_qa<br>                                ▲               │<br>                                │               │<br>                             restart ─────── proceed<br>                                                ▼<br>                                        job_consolidation ──&gt; END</pre><p><strong>NodeRoleOutput Field</strong>search_plannerTurns user intent into optimized search taskssearch_planwork_searchExecutes searches and collects raw linksraw_jobssearch_qaEvaluates quality and decides whether to retry or proceedplanner_feedback, retry_countjob_consolidationOrganizes, normalizes, and filters final resultscurated_jobs</p><blockquote><strong><em>Note:</em></strong><em> Each node returns a </em>partial<em> state update. LangGraph merges it into the shared state automatically, so you never have to pass the entire state object around manually.</em></blockquote><h3>Code Overview: Shared State &amp; Routing</h3><p>The backbone of the application relies on defining a rigid contract for the data and a clear routing blueprint.</p><h3>1. The Shared State Contract</h3><p>The state is defined using Python’s TypedDict. This acts as the API contract that every node agrees to follow:</p><p>Python</p><pre>from typing import TypedDict, List, Annotated<br>from langchain_core.messages import AnyMessage<br>from langgraph.graph.message import add_messages</pre><pre>class State(TypedDict):<br>    messages: Annotated[list[AnyMessage], add_messages] # Appends chat history<br>    search_plan: List[SearchTask] | None                # Overwrites on retry<br>    raw_jobs: List[JobSearchResult] | None              # Overwrites on retry<br>    planner_feedback: SearchValidationOutput | None<br>    curated_jobs: OpportunityIntelligenceOutput | None<br>    user_query: str | None<br>    retry_count: int | None</pre><h3>2. Wiring the Graph Topology</h3><p>The entire workflow orchestration and routing logic are cleanly declared in a central builder file:</p><p>Python</p><pre>from langgraph.graph import StateGraph, START, END</pre><pre>builder = StateGraph(State)</pre><pre># 1. Define Nodes<br>builder.add_node(&quot;search_planner&quot;, search_planner_agent)<br>builder.add_node(&quot;work_search&quot;, search_jobs_node)<br>builder.add_node(&quot;search_qa&quot;, search_qa)<br>builder.add_node(&quot;job_consolidation&quot;, job_consolidation_agent)</pre><pre># 2. Connect Edges<br>builder.add_edge(START, &quot;search_planner&quot;)<br>builder.add_edge(&quot;search_planner&quot;, &quot;work_search&quot;)<br>builder.add_edge(&quot;work_search&quot;, &quot;search_qa&quot;)</pre><pre># 3. Conditional Routing (The Loop)<br>builder.add_conditional_edges(&quot;search_qa&quot;, should_proceed, {<br>    &quot;restart&quot;: &quot;search_planner&quot;,<br>    &quot;proceed&quot;: &quot;job_consolidation&quot;,<br>})<br>builder.add_edge(&quot;job_consolidation&quot;, END)</pre><pre>grph = builder.compile()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*lbcVO3AzEwlXSodGuHgB3g.png" /></figure><h3>High-Level Node Responsibilities</h3><p>Instead of large, nested blocks of code, each node functions as a standalone specialist:</p><h3>search_planner (LLM-based)</h3><p>Reads the user request and uses llm.with_structured_output() to generate optimized, structured search queries. If the state contains planner_feedback from a previous run, it automatically injects that history into the prompt context so the model knows how to adjust its strategy.</p><h3>work_search (Pure Python)</h3><p>A deliberately lightweight node that does not call an LLM. It extracts the query strings from the state, calls the Tavily search API programmatically, maps the vendor JSON into an internal Pydantic format, and normalizes and dedupes the URLs before passing them forward.</p><h3>search_qa (LLM + Code Logic)</h3><p>Uses an LLM to evaluate the quality of the results against the original user query. Crucially, it manages safety guardrails in raw code: if the system exceeds its max retry limit, code logic overrides the LLM’s feedback to force forward progress, guaranteeing the graph can never get stuck in an infinite loop.</p><h3>job_consolidation (LLM + Code Validation)</h3><p>The presentation stage. An LLM organizes and buckets the raw results into clean UI categories. However, to prevent model hallucinations, a Python validation layer compares the final output against an allowlist of URLs originally fetched by the API node, completely discarding any invented links.</p><h3>3 Core Takeaways for Production</h3><ul><li><strong>Orchestrated Specialists Win:</strong> Splitting responsibilities into independent nodes makes debugging simple. If queries are bad, edit the planner. If links are fake, harden your post-LLM validation layer.</li><li><strong>Code for Constraints, LLM for Judgment:</strong> Use LLMs for subjective tasks like planning or categorizing. Use deterministic code for limits, API orchestration, and strict data validation.</li><li><strong>State Semantics Matter:</strong> Use appending logic (add_messages) for tracking conversations, but use overwrite semantics for tasks like search plans so retries always work with a clean slate.</li></ul><p><em>How do you handle self-correcting loops and state management in your AI systems? Let’s discuss in the comments below!</em></p><h3>Let’s connect:</h3><p><a href="https://www.linkedin.com/in/karan-gore/">https://www.linkedin.com/in/karan-gore/</a></p><p><a href="https://karandevelop.netlify.app/">Karan Gore | Senior Software Engineer | Flutter &amp; Gen AI</a></p><h3>Recent AI AGENT &amp; LLM Posts:</h3><ul><li><a href="https://medium.com/@karangore518/building-mybot-a-personal-ai-assistant-with-rag-tooling-and-guardrails-839da734b687">Building “MyBot” - A Personal AI Assistant with RAG, Tooling, and Guardrails</a></li><li><a href="https://medium.com/@karangore518/i-built-an-ai-system-that-converts-brds-into-jira-tickets-heres-why-f8543871a79b">I Built an AI System That Converts BRDs into Jira Tickets, Here’s Why</a></li><li><a href="https://medium.com/@karangore518/building-an-ai-that-understands-tone-and-writes-better-replies-my-first-real-llm-project-4338c3253cd9">Building an AI That Understands Tone and Writes Better Replies (My First Real LLM Project)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cb45fc2963d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building “MyBot” - A Personal AI Assistant with RAG, Tooling, and Guardrails]]></title>
            <link>https://medium.com/@karangore518/building-mybot-a-personal-ai-assistant-with-rag-tooling-and-guardrails-839da734b687?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/839da734b687</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Mon, 04 May 2026 18:43:38 GMT</pubDate>
            <atom:updated>2026-05-04T19:32:06.397Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building “MyBot” — A Personal AI Assistant with RAG, Tooling, and Guardrails</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFmMKz7fbVvFOq9x9gVblw.png" /></figure><blockquote>Find the ChatBot in the link below :<br>Try asking “Can you schedule a meeting?”</blockquote><p><a href="http://karandevelop.netlify.app/?ai=open">Karan Gore | Senior Software Engineer | Flutter &amp; Gen AI</a></p><p>I built a personal AI assistant that:</p><ul><li>answers strictly from my profile data (RAG)</li><li>maintains conversation context</li><li>uses tools to take actions (schedule calls, capture leads)</li><li>enforces guardrails (scope, abuse, safety)</li></ul><p>Stack:<br><strong>FastAPI + OpenAI (function calling) + FAISS + Supabase + Flutter Web</strong></p><h3>The Problem</h3><p>Most “AI chatbots” today are:</p><ul><li>generic wrappers over GPT</li><li>prone to hallucination</li><li>unable to take real actions</li><li>not production-safe</li></ul><p>I wanted something different:</p><blockquote><em>A bot that behaves like </em>me<em>, answers only from real data, and can take actions — not just generate text.</em></blockquote><h3>System Architecture</h3><p>At a high level:</p><pre>User → FastAPI → Retrieval (FAISS)<br>     → LLM (OpenAI + tools)<br>     → Tool Execution Layer<br>     → Supabase (logs, leads)<br>     → Response</pre><h3>1. Retrieval (RAG with FAISS)</h3><p>All personal data is stored as:</p><ul><li>resume text</li><li>portfolio content</li><li>scraped links</li></ul><h3>Chunking</h3><pre>def chunking_text(text, chunk_size=400, overlap=100):<br>    words = text.split()<br>    chunks = []</pre><pre>    start = 0<br>    while start &lt; len(words):<br>        chunk = words[start:start + chunk_size]<br>        chunks.append(&quot; &quot;.join(chunk))<br>        start += chunk_size - overlap</pre><pre>    return chunks</pre><h3>Embedding + Indexing</h3><pre>embeddings = np.array(<br>    [get_embeddings(doc) for doc in documents]<br>).astype(&quot;float32&quot;)</pre><pre>index = faiss.IndexFlatL2(len(embeddings[0]))<br>index.add(embeddings)</pre><h3>Retrieval</h3><pre>D, I = index.search(query_embedding, k=3)<br>context = [documents[i] for i in I[0]]</pre><p>👉 Keeping k small was critical for latency.</p><h3>2. LLM Layer (With Tool Calling)</h3><p>Instead of pure text generation, I used <strong>function calling</strong>.</p><h3>Why?</h3><p>Because:</p><ul><li>structured outputs &gt; raw text</li><li>enables real actions</li><li>reduces hallucination</li></ul><h3>Example Tools</h3><h4>Capture Lead</h4><pre>def capture_lead(name: str, requirement: str):<br>    supabase.table(&quot;leads&quot;).insert({<br>        &quot;name&quot;: name,<br>        &quot;requirement&quot;: requirement<br>    }).execute()</pre><h4>Schedule Call</h4><pre>def schedule_call():<br>    return {<br>        &quot;message&quot;: &quot;You can schedule a call below&quot;,<br>        &quot;url&quot;: &quot;https://cal.com/...&quot;<br>    }</pre><h4>Failure Logging</h4><pre>def cant_answer(session_id, question):<br>    supabase.table(&quot;cant_answer&quot;).insert({<br>        &quot;session_id&quot;: session_id,<br>        &quot;question&quot;: question<br>    }).execute()</pre><h3>3. Guardrails (Critical Layer)</h3><p>This is where most bots fail.</p><p>I implemented <strong>3 levels of control</strong>:</p><h3>1. Scope Guard</h3><p>Only answer:</p><ul><li>skills</li><li>experience</li><li>projects</li></ul><p>Everything else:<br>→ trigger cant_answer</p><h3>2. Abuse Detection</h3><pre>def is_abusive(text):<br>    return any(word in text.lower() for word in [&quot;idiot&quot;, &quot;stupid&quot;, &quot;fuck&quot;])</pre><p>→ returns controlled response</p><h3>3. Strict Context Grounding</h3><p>Prompt enforces:</p><pre>Answer ONLY using provided context.<br>Do NOT assume.<br>Do NOT hallucinate.</pre><h3>4. Conversation Memory</h3><p>Stored in Supabase:</p><pre>def get_recent_history(session_id, email, limit=5):<br>    return (<br>        supabase.table(&quot;chat_logs&quot;)<br>        .select(&quot;*&quot;)<br>        .eq(&quot;session_id&quot;, session_id)<br>        .eq(&quot;user_mail&quot;, email)<br>        .order(&quot;created_at&quot;, desc=True)<br>        .limit(limit)<br>        .execute()<br>    ).data[::-1]</pre><p>👉 Only last few messages → avoids latency</p><h3>5. Performance Optimization</h3><p>Initial latency: <strong>10–20s</strong></p><p>After optimization:</p><h3>Parallel execution</h3><pre>context, history = await asyncio.gather(<br>    asyncio.to_thread(retrive_context, query),<br>    asyncio.to_thread(get_recent_history, session_id)<br>)</pre><h3>Background logging</h3><pre>asyncio.create_task(<br>    asyncio.to_thread(save_chat, ...)<br>)</pre><h3>Reduced context size</h3><pre>k = 3</pre><p>👉 Final latency: <strong>~2–5 seconds</strong></p><h3>6. Frontend (Flutter Web)</h3><ul><li>Chat UI</li><li>Action buttons (schedule call)</li><li>Clean UX</li><li>API-driven</li></ul><h3>Key Learnings</h3><h3>1. RAG alone is not enough</h3><p>You need:</p><ul><li>structure</li><li>tools</li><li>guardrails</li></ul><h3>2. LLMs should not do everything</h3><p>👉 Use LLM for:</p><ul><li>reasoning</li><li>actions</li><li>data retrieval</li></ul><h3>3. Guardrails &gt; intelligence</h3><p>A slightly less smart bot with:</p><ul><li>control</li><li>safety</li><li>reliability</li></ul><p>👉 is far more usable</p><h3>What’s Next</h3><ul><li>SaaS version (multi-user bots)</li><li>better semantic skill mapping</li><li>automated follow-ups</li><li>analytics dashboard</li></ul><h3>Final Thought</h3><p>This project started as:</p><blockquote><em>“Can I build a chatbot about myself?”</em></blockquote><p>It turned into:</p><blockquote><em>“Can AI represent you digitally and take actions on your behalf?”</em></blockquote><p>If you’re building in LLMs, RAG, or AI systems - happy to connect and exchange ideas.</p><p><a href="https://huggingface.co/spaces/karangore/mybot">Mybot - a Hugging Face Space by karangore</a></p><p>Github: <a href="https://github.com/itskgore/mybot_ui">https://github.com/itskgore/mybot_ui</a></p><p>LinkedIn: <a href="https://www.linkedin.com/in/karan-gore/">https://www.linkedin.com/in/karan-gore/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=839da734b687" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Built an AI System That Converts BRDs into Jira Tickets, Here’s Why]]></title>
            <link>https://medium.com/@karangore518/i-built-an-ai-system-that-converts-brds-into-jira-tickets-heres-why-f8543871a79b?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8543871a79b</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Tue, 28 Apr 2026 22:51:33 GMT</pubDate>
            <atom:updated>2026-04-28T22:52:09.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usRWC_RV2QAD1wz_e-hMPQ.png" /></figure><h3>The Problem I Kept Seeing</h3><p>If you’ve worked in a product or engineering team, you’ve probably experienced this:</p><ul><li>Business Analysts spend <strong>hours translating BRDs into Jira tickets</strong></li><li>Backend developers struggle to <strong>read long documents just to understand what to build</strong></li><li>Important details get missed between interpretation and execution</li></ul><p>And despite all the effort, sprint planning still feels… heavy.</p><p>I kept asking myself:</p><blockquote><strong><em>Why are we manually translating structured requirements into tasks, when AI can already understand context?</em></strong></blockquote><h3>💡 The Idea</h3><p>What if you could:</p><ul><li>Upload a BRD</li><li>Automatically break it into modules</li><li>Generate developer-friendly task details</li><li>And create Jira tickets instantly</li></ul><p>That’s how <strong>AI BRD Workflow Analyzer</strong> was born.</p><h3>🧠 What the System Does</h3><p>The system transforms a raw BRD into:</p><p>✅ Structured modules<br>✅ Feature-level breakdowns<br>✅ Backend implementation details<br>✅ API definitions<br>✅ Jira-ready tickets</p><p>And everything is <strong>editable before pushing to Jira</strong>.</p><h3>⚙️ Under the Hood (Real Engineering, Not Just Prompting)</h3><p>This isn’t just a “send prompt → get response” tool.</p><p>I built a full <strong>GenAI pipeline</strong>:</p><h3>1. 📄 BRD Processing</h3><p>The system first extracts text from uploaded PDFs and prepares it for understanding:</p><ul><li>PDF parsing</li><li>Text normalization</li><li>Chunking into smaller segments</li></ul><pre>def chunking(text, chunk_size=500, overlap=100):</pre><p>👉 This ensures large BRDs don’t overwhelm the model.</p><h3>2. 🔍 Smart Retrieval using RAG</h3><p>Instead of sending the entire document to the LLM:</p><ul><li>BRD is chunked</li><li>Embedded using OpenAI embeddings</li><li>Stored in <strong>FAISS vector index</strong></li></ul><pre>index = faiss.IndexFlatL2(dim)</pre><p>Then, for every query:</p><ul><li>Only <strong>relevant chunks</strong> are retrieved</li><li>Passed as context to the model</li></ul><p>👉 This makes responses:</p><ul><li>Faster</li><li>More accurate</li><li>Context-aware</li></ul><h3>3. 🧠 Feature Extraction</h3><p>The model first acts like a <strong>Product Analyst</strong>:</p><pre>&quot;You are a senior product analyst. Extract ALL modules...&quot;</pre><p>It converts BRDs into structured modules like:</p><pre>{<br>  &quot;module&quot;: &quot;Payments&quot;,<br>  &quot;features&quot;: [&quot;User validation&quot;, &quot;Payment redirection&quot;]<br>}</pre><h3>4. 🏗️ Developer-Focused Generation</h3><p>Then it switches roles:</p><pre>&quot;You are a senior backend architect...&quot;</pre><p>For each feature, it generates:</p><ul><li>Technical implementation details</li><li>Sub-features</li><li>Validations</li><li>API definitions</li><li>Jira tickets</li></ul><p>👉 This is where it becomes <strong>developer-friendly</strong>, not just descriptive.</p><h3>5. ⚡ Parallel Processing</h3><p>To make it fast:</p><pre>ThreadPoolExecutor(max_workers=5)</pre><p>Multiple features are processed <strong>in parallel</strong>, reducing response time significantly.</p><h3>6. 🔗 Jira Integration</h3><p>Finally, tickets are pushed directly into Jira:</p><ul><li>Summary</li><li>Description (ADF format)</li><li>Priority</li><li>Epic linking</li></ul><pre>requests.post(&quot;/rest/api/3/issue&quot;, json=jira_payload)</pre><h3>🎯 What This Solves</h3><h3>For Business Analysts:</h3><ul><li>No more manual ticket creation</li><li>Faster requirement breakdown</li></ul><h3>For Developers:</h3><ul><li>Shortcut to read entire BRDs</li><li>Clear, actionable implementation tasks</li></ul><h3>For Teams:</h3><ul><li>Faster sprint planning</li><li>Better clarity</li><li>Reduced miscommunication</li></ul><h3>⚠️ Challenges I Faced</h3><p>This wasn’t straightforward:</p><ul><li>Ensuring <strong>valid JSON output from LLMs</strong></li><li>Preventing empty or vague Jira tickets</li><li>Designing prompts that are both:</li><li>strict (for structure)</li><li>flexible (for reasoning)</li><li>Handling <strong>context overlap between BRD and knowledge base</strong></li></ul><h3>💡 Key Learning</h3><blockquote><strong><em>RAG + Structured prompting &gt; raw LLM calls</em></strong></blockquote><p>Without retrieval:</p><ul><li>The model guesses</li></ul><p>With retrieval:</p><ul><li>The model <em>understands</em></li></ul><h3>📬 Want Access or Curious to Try It?</h3><p>If you’d like to:</p><ul><li>Explore the full implementation</li><li>Get access to the repo</li><li>Or collaborate on something similar</li></ul><p>👉 <strong>DM me on LinkedIn to request access</strong></p><p>🔗 LinkedIn: <a href="https://www.linkedin.com/in/karangore">https://www.linkedin.com/in/karangore</a></p><h3>🌐 Check Out My Work</h3><p>I also build production-ready mobile apps and scalable systems.</p><p>👉 Explore my portfolio: <a href="https://karandevelop.netlify.app/">https://karandevelop.netlify.app/</a></p><h3>🚀 What’s Next</h3><p>I’m exploring:</p><ul><li>Effort estimation using AI</li><li>Auto sprint planning</li><li>Multi-team workflow intelligence</li><li>Feedback loops to improve outputs over time</li></ul><h3>🤔 Final Thought</h3><p>We don’t need AI just to “chat”.</p><p>We need AI to <strong>reduce friction in real workflows</strong>.</p><p>This project is one step toward that.</p><p>If you’re building in GenAI or solving similar workflow problems, I’d love to connect.</p><p>What would you automate next?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8543871a79b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI That Understands Tone and Writes Better Replies (My First Real LLM Project)]]></title>
            <link>https://medium.com/@karangore518/building-an-ai-that-understands-tone-and-writes-better-replies-my-first-real-llm-project-4338c3253cd9?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4338c3253cd9</guid>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tone-aware-ai-replies]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 10:10:59 GMT</pubDate>
            <atom:updated>2026-04-20T10:10:59.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QPwFQ_I5reuk5GD7vErSgA.png" /></figure><p>We’ve all been there.</p><p>You receive a message like:</p><ul><li><em>“Why is this still not done?”</em></li><li><em>“Wow, great job… 🙄”</em></li><li><em>“This is completely useless.”</em></li></ul><p>And you pause.</p><p>Not because you don’t know how to respond -<br> but because <strong>you don’t want to respond the wrong way</strong>.</p><p>That’s exactly the problem I wanted to solve.</p><h3>🚀 The Idea</h3><p>Instead of just building another chatbot, I wanted to build something more practical:</p><p>👉 An AI assistant that:</p><ul><li>Understands the <strong>tone</strong> of incoming messages</li><li>Interprets intent (even sarcasm or frustration)</li><li>Suggests a <strong>professional, emotionally intelligent reply</strong></li></ul><h3>🧠 The Problem with LLMs (What I Learned Early)</h3><p>At first, I thought:</p><blockquote><em>“I’ll just send the message to an LLM and ask it to reply.”</em></blockquote><p>It <em>worked</em>… but not reliably.</p><p>Sometimes it:</p><ul><li>Missed sarcasm</li><li>Responded too bluntly</li><li>Failed to handle abusive tone properly</li></ul><p>That’s when I realized something important:</p><pre>LLMs alone are not enough.<br>You need system design.</pre><h3>🏗️ The Architecture I Built</h3><p>I designed a <strong>two-stage system powered by RAG (Retrieval-Augmented Generation)</strong>:</p><pre>User Message<br>   ↓<br>Tone Detection (LLM + RAG)<br>   ↓<br>Context Retrieval (rules + examples)<br>   ↓<br>Response Generation (LLM)</pre><h3>🔍 Step 1: Tone Detection</h3><p>Instead of relying purely on the model, I used:</p><ul><li>A lightweight LLM (Qwen Instruct)</li><li>A <strong>RAG layer with tone-labeled examples</strong></li><li>Simple heuristics (for sarcasm/emojis/keywords)</li></ul><p>Example:</p><pre>&quot;Wow great job 🙄&quot; → sarcasm<br>&quot;You are useless&quot; → abusive</pre><p>This made tone detection much more <strong>grounded and reliable</strong>.</p><h3>📚 Step 2: RAG (The Game Changer)</h3><p>This is where things got interesting.</p><p>I built a <strong>custom knowledge base</strong> containing:</p><h3>1. Rules (Markdown)</h3><pre>Abusive tone → stay calm, set boundaries<br>Sarcasm → interpret intent, don’t respond literally</pre><h3>2. Examples (JSONL)</h3><pre>{<br>  &quot;message&quot;: &quot;You are useless&quot;,<br>  &quot;tone&quot;: &quot;abusive&quot;,<br>  &quot;response&quot;: &quot;Let’s keep the discussion respectful...&quot;<br>}</pre><p>Then I used:</p><ul><li><strong>Sentence Transformers</strong> for embeddings</li><li><strong>FAISS</strong> for fast retrieval</li></ul><p>So instead of guessing, the model now had <strong>contextual grounding</strong>.</p><h3>🤖 Step 3: Response Generation</h3><p>Once tone is detected and context is retrieved:</p><p>The model generates a reply that is:</p><ul><li>Calm</li><li>Professional</li><li>Situation-aware</li></ul><p>For example:</p><h3>Input:</h3><pre>&quot;You are useless&quot;</pre><h3>Output:</h3><pre>Let’s keep the discussion respectful and focus on resolving the issue.</pre><h3>⚠️ The Hardest Problem: Abusive Tone</h3><p>This was surprisingly tricky.</p><p>Most models either:</p><ul><li>Refuse to respond</li><li>Or give generic safe replies</li></ul><p>The fix wasn’t changing the model — it was <strong>changing the framing</strong>:</p><pre>The AI is NOT replying to abuse<br>It is helping the user respond professionally</pre><p>That small shift made a huge difference.</p><h3>🧠 Key Learnings</h3><h3>1. Prompting is not enough</h3><p>You need:</p><ul><li>structured data</li><li>examples</li><li>constraints</li></ul><h3>2. RAG &gt; Bigger Models</h3><p>A small model + good RAG:</p><pre>&gt; performs better than a large model without context</pre><h3>3. System design matters more than model choice</h3><p>This project made me realize:</p><pre>AI is not about models<br>It’s about how you use them</pre><h3>🔮 What’s Next</h3><p>I’m planning to take this further into a real-world assistant:</p><h3>📩 Gmail Integration</h3><ul><li>Auto-draft replies to emails</li><li>Handle professional communication</li></ul><h3>💬 WhatsApp Integration</h3><ul><li>Suggest responses in real-time</li><li>Maintain tone across conversations</li></ul><h3>🧠 Memory Layer</h3><ul><li>Understand previous messages</li><li>Maintain context over time</li></ul><h3>🤖 Automation</h3><ul><li>Generate updates for seniors</li><li>Assist with work communication</li></ul><h3>🎯 Final Thought</h3><p>Communication is not just about words -<br> it’s about <strong>tone, intent, and timing</strong>.</p><p>If AI can help us:</p><ul><li>avoid misunderstandings</li><li>respond more thoughtfully</li><li>reduce emotional friction</li></ul><p>That’s a meaningful use of this technology.</p><h4>Git Repo: <a href="https://github.com/itskgore/tone-recognizer">https://github.com/itskgore/tone-recognizer</a></h4><h3>Follow me on:</h3><p><a href="https://karandevelop.netlify.app/">https://karandevelop.netlify.app/</a></p><p><a href="https://www.linkedin.com/posts/karan-gore_ai-artificialintelligence-generativeai-activity-7451933298991374336-TkzC?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAACqhBmsBDJy74m-OEAlZPXVovZiFHeQk31A">https://www.linkedin.com/in/karan-gore/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4338c3253cd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everyone Is Using AI. Very Few Are Using It Correctly.]]></title>
            <link>https://medium.com/@karangore518/everyone-is-using-ai-very-few-are-using-it-correctly-bd1c3eca6f85?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd1c3eca6f85</guid>
            <category><![CDATA[flutter-app-development]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[sdk]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 13:17:40 GMT</pubDate>
            <atom:updated>2026-01-10T13:17:40.506Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEu17g73bH8e-A_ey44ijw.png" /></figure><p>Speech-to-text, meeting summaries, voice assistants, MoM generators — you name it.</p><p>But here’s the uncomfortable truth:</p><blockquote><em>Most teams are </em><strong><em>using AI</em></strong><em>, not </em><strong><em>engineering it</em></strong><em>.</em></blockquote><p>And that difference shows up very clearly in:</p><ul><li>❌ unstable voice features</li><li>❌ high OpenAI bills</li><li>❌ hacks that don’t scale</li></ul><p>This post is about <strong>doing it right</strong>, especially for <strong>voice-based features</strong>.</p><h3>The Real Problem With Voice-Based AI Features</h3><p>If you’ve ever tried to build <strong>meeting transcription or conversation recording</strong> in Flutter, you’ve probably faced this:</p><ul><li>Speech stops randomly</li><li>You need to manually restart listening</li><li>Long conversations break the flow</li><li>speech_to_text works fine… until you need <strong>continuous listening</strong></li></ul><p>The default approach is okay for:</p><ul><li>Short commands</li><li>Button-based voice input</li></ul><p>But it becomes a <strong>hassle</strong> when your use case is:</p><ul><li>Meetings</li><li>Interviews</li><li>Long conversations</li><li>Real-time MoM generation</li></ul><p>And that’s where most implementations fail.</p><h3>Why I Built a Flutter Plugin for Continuous Speech-to-Text</h3><p>I didn’t build another plugin to “add AI”.</p><p>I built it to <strong>fix a real engineering problem</strong>:<br>👉 <strong>Continuous, reliable speech-to-text for meetings and conversations.</strong></p><h3>What this plugin is designed for:</h3><ul><li>✅ Continuous speech reading (no manual restart loops)</li><li>✅ Long-duration sessions (1–2+ hours)</li><li>✅ Meeting &amp; conversation context</li><li>✅ Cleaner transcripts for AI summaries</li><li>✅ Offline-first support (when needed)</li></ul><p>In short:</p><blockquote><em>Built for </em><strong><em>real conversations</em></strong><em>, not demos.</em></blockquote><h3>The Cost Myth: “OpenAI Is Expensive Because of Tokens”</h3><p>This is where things get interesting.</p><p>Most people blame <strong>tokens</strong> for high AI costs.</p><p>That’s not true for voice features.</p><h3>Here’s how audio costing actually works:</h3><ul><li>🎙️ <strong>Audio is charged by time (minutes)</strong></li><li>❌ Audio is NOT charged by tokens</li><li>📝 Tokens are only used <strong>after audio becomes text</strong></li></ul><h3>Real example: 1-hour meeting</h3><p>StepCostAudio transcription~$0.36AI summary (ChatGPT)~$0.007</p><p>👉 <strong>90%+ of the cost comes from audio duration</strong>, not tokens.</p><p>So if your architecture is bad:</p><ul><li>Silence costs money</li><li>Long pauses cost money</li><li>Re-transcribing costs money</li></ul><h3>Why Architecture Matters More Than Models</h3><p>If you want AI features to scale, you must treat them like <strong>systems</strong>, not APIs.</p><h3>Correct flow:</h3><pre>Audio<br> → Speech-to-Text (once)<br> → Clean transcript<br> → AI summary</pre><h3>Common mistake:</h3><pre>Audio<br> → AI<br> → Retry<br> → Reprocess<br> → Higher bill</pre><h3>How to Reduce AI Cost by 10–50×</h3><p>These are not tricks — this is engineering discipline.</p><p>✔ Transcribe once, reuse text<br>✔ Remove filler words before summarizing<br>✔ Chunk long meetings<br>✔ Limit output tokens<br>✔ Never send raw audio to LLMs<br>✔ Store transcripts, not audio</p><p>This alone can reduce your OpenAI bill <strong>dramatically</strong>.</p><h3>Why Flutter Needed a Better Speech-to-Text Solution</h3><p>Flutter developers deserve tools that:</p><ul><li>Work reliably</li><li>Handle real-world use cases</li><li>Don’t require hacks for basic functionality</li></ul><p>That’s why this plugin focuses on:</p><ul><li><strong>Continuous listening</strong></li><li><strong>Meeting-grade stability</strong></li><li><strong>AI-ready output</strong></li></ul><p>Not just “speech recognition”, but <strong>speech recognition done right</strong>.</p><h3>Final Thought</h3><p>AI is easy to use.<br>AI done right is a <strong>skill</strong>.</p><p>If you’re building:</p><ul><li>Voice-based products</li><li>Meeting tools</li><li>Productivity apps</li><li>AI-powered summaries</li></ul><p>Then <strong>how</strong> you integrate AI matters more than <strong>which model</strong> you choose.</p><h3>🚀 Try the Flutter plugin in your next project</h3><p>Not to <em>add AI</em> — but to add it <strong>correctly</strong>.</p><p>If this helped you think differently about AI integration,<br>you’re already ahead of most teams.</p><p><a href="https://github.com/itskgore/continuous_speech_recognition">GitHub - itskgore/continuous_speech_recognition: This guide explains how to use the `continuous_speech_recognition` plugin in the main speechtextpoc app.</a></p><p>If you want next:</p><ul><li>A <strong>technical deep dive</strong> with code snippets</li><li>A <strong>cost calculator section</strong></li><li>A <strong>part 2</strong> on MoM prompt engineering</li></ul><p>Just tell me — happy to help you build this as a full series.</p><h3>Follow me on:</h3><p><a href="https://karandevelop.netlify.app/">https://karandevelop.netlify.app/</a></p><p><a href="https://www.linkedin.com/in/karan-gore/">https://www.linkedin.com/in/karan-gore/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd1c3eca6f85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Salaries with Linear Regression -A Simple & Powerful ML Exercise]]></title>
            <link>https://medium.com/@karangore518/predicting-salaries-with-linear-regression-a-simple-powerful-ml-exercise-2e17a2f68115?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e17a2f68115</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[business-solutions]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Sun, 23 Nov 2025 21:47:27 GMT</pubDate>
            <atom:updated>2025-11-23T22:23:29.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWKZAMopS6B_ngb-aJac-g.png" /></figure><p>Machine learning often feels intimidating when you’re just beginning… but some models are incredibly simple <em>and</em> extremely useful.<br> One of them is <strong>Linear Regression</strong> -a straight-line model that can predict numbers with surprising accuracy.</p><h3>Why Linear Regression for Salary Prediction?</h3><p>Most industries follow structured salary patterns.</p><p>For example:</p><ul><li>1 year experience → around X salary</li><li>5 years → Y salary</li><li>10 years → Z salary</li></ul><p>This means salary often grows <strong>linearly</strong> with experience — so a straight-line pattern works beautifully.</p><p>Linear Regression figures out:</p><ul><li><strong>Slope (coefficient)</strong> → “How much salary increases every year”</li><li><strong>Intercept</strong> → “What is the base salary of someone with 0 experience”</li></ul><p>Once the model learns this relationship, it can predict:</p><blockquote>“If a person has 10 years of experience, what should their salary be?”</blockquote><p>And that’s exactly what we build today.</p><h3>The Dataset</h3><p>Our dataset is very simple 2 columns for the Frontend (Flutter) dev in a company:</p><pre>YearsExperience,Salary<br>1.1,39343.00<br>1.3,46205.00<br>1.5,37731.00<br>2.0,43525.00<br>2.2,39891.00<br>2.9,56642.00<br>3.0,60150.00<br>3.2,54445.00<br>3.2,64445.00<br>3.7,57189.00<br>3.9,63218.00<br>4.0,55794.00<br>4.0,56957.00<br>4.1,57081.00<br>4.5,61111.00<br>4.9,67938.00<br>5.1,66029.00<br>5.3,83088.00<br>5.9,81363.00<br>6.0,93940.00<br>6.8,91738.00<br>7.1,98273.00<br>7.9,101302.00<br>8.2,113812.00<br>8.7,109431.00<br>9.0,105582.00<br>9.5,116969.00<br>9.6,112635.00<br>10.3,122391.00<br>10.5,121872.00</pre><p><strong>Step-by-Step Code Explained</strong></p><pre>import pandas as pd<br>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression<br>from sklearn.metrics import mean_squared_error<br>from sklearn.metrics import r2_score<br># load data<br>data = pd.read_csv(&#39;data.csv&#39;)<br><br># correct slicing<br>x = data.iloc[:, :-1].values          # YearsExperience<br>y = data.iloc[:, -1].values           # Salary<br><br># train test split<br>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)<br><br># train<br>regressor = LinearRegression()<br>regressor.fit(x_train, y_train)<br><br># predict<br>y_pred = regressor.predict(x_test)<br><br># mse<br>mse = mean_squared_error(y_test, y_pred)<br>print(&quot;MSE: &quot;, mse)<br>r2_score = r2_score(y_test, y_pred)<br>print(&quot;R2 :&quot;, r2_score)<br><br>print(&#39;1yr exp increase Salary increment: &#39;,regressor.coef_)<br>print(&#39;0yr exp Salary: &#39;,regressor.intercept_)<br><br>print(&#39;10yr exp Salary: &#39;,regressor.predict([[10]]))</pre><h3>1. Load the data</h3><pre>data = pd.read_csv(&#39;data.csv&#39;)</pre><p>Pandas loads the data into a DataFrame so we can work with it easily.</p><h3>2. Split features (X) and target (y)</h3><pre>x = data.iloc[:, :-1].values<br>y = data.iloc[:, -1].values</pre><ul><li>x = years of experience</li><li>y = salary</li></ul><p>This prepares our model’s inputs and outputs.</p><h3>3. Create training &amp; testing sets</h3><pre>x_train, x_test, y_train, y_test = train_test_split(<br>    x, y, test_size=0.2, random_state=0<br>)</pre><p>We give 80% data to training, 20% to testing.</p><p>This ensures the model is evaluated on unseen data.</p><h3>4. Train the Linear Regression model</h3><pre>regressor = LinearRegression()<br>regressor.fit(x_train, y_train)</pre><p>This is the “learning” step.</p><p>The model calculates:</p><ul><li><strong>Coefficient</strong> (slope)</li><li><strong>Intercept</strong> (base salary)</li></ul><p>These numbers define the salary line.</p><h3>5. Predict salary on test data</h3><pre>y_pred = regressor.predict(x_test)</pre><p>Now we get the predicted salaries.</p><h3>6. Evaluate the model</h3><pre>mse = mean_squared_error(y_test, y_pred)<br>r2_score = r2_score(y_test, y_pred)</pre><ul><li><strong>MSE</strong> → Error between actual &amp; predicted</li><li><strong>R2 Score</strong> → Accuracy level (closer to 1 is better)</li></ul><p>For salary data, the model usually performs very well (R2 &gt; 0.9).</p><h3>7. Understand the learned pattern</h3><pre>print(&#39;1yr exp increase Salary increment: &#39;, regressor.coef_)<br>print(&#39;0yr exp Salary: &#39;, regressor.intercept_)</pre><p>Example output:</p><pre>As each exp increase salary increment to: 9449.96<br>0yr salary: 25792.20</pre><p>Meaning:</p><ul><li>Every year adds about <strong>₹9,450</strong></li><li>Freshers start around <strong>₹25,792</strong></li></ul><h3>8. Predict salary for 10 years experience</h3><pre>print(regressor.predict([[10]]))</pre><p>Output example:</p><pre>[121292.8]</pre><p>So someone with <strong>10 years experience → ~₹1.21 LPA</strong> (just sample numbers).</p><h3>What Makes This So Powerful?</h3><p>If a company provides:</p><ul><li>employee experience data</li><li>historical salaries</li><li>yearly increments</li></ul><p>You can build:</p><ul><li>Salary estimator tools</li><li>HR dashboards</li><li>Offer letter automation</li><li>Career growth analysis</li><li>Market comparison reports</li></ul><p>All with <em>just a few lines of ML code</em>.</p><p>This is how many salary-prediction tools and HR analytics dashboards are built behind the scenes.</p><h3>Final Thoughts</h3><p>Linear Regression is one of the <strong>easiest ML models</strong>, but also one of the <strong>most practical</strong> -especially in finance, HR tech, and analytics.</p><p>If you’re starting your ML journey, this project is the perfect first step because:</p><ul><li>It uses simple math</li><li>Gives real business value</li><li>Helps you understand model training, prediction &amp; evaluation</li><li>Teaches you how to work with real datasets</li><li>And the results are immediately meaningful</li></ul><blockquote>I’m still new to Machine Learning, and I’m sharing what I learn so others can benefit too.<br>If you’re an ML practitioner or expert, I’d love to hear your thoughts, improvements, or suggestions!</blockquote><h3>Follow me on:</h3><p><a href="https://karandevelop.netlify.app/">https://karandevelop.netlify.app/</a></p><p><a href="https://www.linkedin.com/in/karan-gore/">https://www.linkedin.com/in/karan-gore/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e17a2f68115" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means Clustering With Scaled Data: A Complete Beginner-Friendly Walkthrough]]></title>
            <link>https://medium.com/@karangore518/k-means-clustering-with-scaled-data-a-complete-beginner-friendly-walkthrough-c6138062b30a?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6138062b30a</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ecommerce]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 19:48:54 GMT</pubDate>
            <atom:updated>2025-11-16T19:48:54.728Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi everyone! 👋<br>I’m currently learning Machine Learning and sharing my notes online so others can learn with me and so experts can guide me whenever needed.</p><p>Today’s topic is <strong>K-Means Clustering</strong>, one of the most popular unsupervised learning algorithms used for customer segmentation, pattern discovery, and grouping similar data points.</p><p>In this post, I’ll walk through:</p><ul><li>What K-Means does</li><li>Why scaling is important</li><li>How to apply the elbow method</li><li>How to train a K-Means model</li><li>How to visualize the clusters</li><li>complete reproducible Python code</li></ul><h3>🧠 What Is K-Means Clustering?</h3><p>K-Means is an unsupervised learning algorithm used to divide data into <strong>K groups</strong> based on similarity.</p><p>It works by:</p><ol><li>Choosing K cluster centers (centroids)</li><li>Assigning every data point to the nearest centroid</li><li>Recalculating the centroids</li><li>Repeating until the clusters stabilize</li></ol><p>It’s widely used in:</p><ul><li>customer segmentation</li><li>market analytics</li><li>image compression</li><li>anomaly detection</li></ul><h3>📏 Why Scaling Is Important</h3><p>K-Means relies on <strong>Euclidean distance</strong>.</p><p>If one feature has a larger numerical range than another, it will dominate the distance measurement.</p><p>Example:</p><ul><li>Income: 10–90</li><li>Score: 1–100</li></ul><p>Income has a higher variance → it affects clustering more.</p><p>To give all features equal weight, we use <strong>StandardScaler()</strong> to convert them into a uniform scale.</p><h3>📈 Finding the Optimal Number of Clusters: The Elbow Method</h3><p>The elbow method helps identify the best value for <strong>K</strong>.</p><p>Steps:</p><ol><li>Train K-Means for different values of K (1 to 10)</li><li>Compute WCSS (within-cluster sum of squares)</li><li>Plot WCSS vs. K</li><li>Look for the “elbow”- the point where improving K gives diminishing returns</li></ol><p>This elbow usually represents the optimal number of clusters.</p><h3>🧪 Complete Working Code (Beginner Friendly)</h3><p>Here is the full code for:</p><ul><li>Scaling the data</li><li>Finding optimal K</li><li>Xlustering</li><li>Visualizing the clusters</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0abb947039c51fad5ffe7f9608c8bae/href">https://medium.com/media/c0abb947039c51fad5ffe7f9608c8bae/href</a></iframe><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>from sklearn.preprocessing import StandardScaler<br>from sklearn.cluster import KMeans</pre><pre># Load data<br>data = pd.read_csv(&#39;data.csv&#39;)<br>x = data.iloc[:, 1:].values   # Selecting Income &amp; Score</pre><pre># Scale the features<br>sc = StandardScaler()<br>X_scaled = sc.fit_transform(x)</pre><pre># Elbow Method<br>wcss = []<br>for i in range(1, 11):<br>    kmeans = KMeans(n_clusters=i, random_state=0, init=&#39;k-means++&#39;)<br>    kmeans.fit(X_scaled)<br>    wcss.append(kmeans.inertia_)</pre><pre>plt.plot(range(1, 11), wcss)<br>plt.title(&#39;Elbow Method&#39;)<br>plt.xlabel(&#39;Number of clusters&#39;)<br>plt.ylabel(&#39;WCSS&#39;)<br>plt.show()</pre><pre># Train K-Means Model<br>kmeans = KMeans(n_clusters=3, random_state=42, init=&#39;k-means++&#39;)<br>y_kmeans = kmeans.fit_predict(X_scaled)</pre><pre># Plot clustering results<br>plt.scatter(X_scaled[y_kmeans == 0, 0], X_scaled[y_kmeans == 0, 1], s=100, c=&#39;red&#39;, label=&#39;Cluster 1&#39;)<br>plt.scatter(X_scaled[y_kmeans == 1, 0], X_scaled[y_kmeans == 1, 1], s=100, c=&#39;blue&#39;, label=&#39;Cluster 2&#39;)<br>plt.scatter(X_scaled[y_kmeans == 2, 0,], X_scaled[y_kmeans == 2, 1], s=100, c=&#39;green&#39;, label=&#39;Cluster 3&#39;)</pre><pre># Plot centroids<br>plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],<br>            s=300, c=&#39;yellow&#39;, label=&#39;Centroids&#39;)</pre><pre>plt.title(&#39;Clusters of Customers&#39;)<br>plt.xlabel(&#39;Annual Income (scaled)&#39;)<br>plt.ylabel(&#39;Spending Score (scaled)&#39;)<br>plt.legend()<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9CohDF1lnDhaDD2Mvl8sQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KeqSursPiu4tJf3S3lS92w.png" /></figure><h3>🎯 What This Solves</h3><p>This workflow helps in:</p><ul><li>Segmenting customers into meaningful groups</li><li>Identifying behavior patterns</li><li>Designing targeted marketing strategies</li><li>Understanding relationships between features</li></ul><p>By scaling the data and applying K-Means properly, we can uncover clear patterns and high-quality clusters.</p><h3>🙌 Final Note</h3><p>I’m still new to Machine Learning, and I’m sharing what I learn so others can benefit too.<br> If you’re an ML practitioner or expert, I’d love to hear your thoughts, improvements, or suggestions!</p><p>Let’s learn and grow together 🚀</p><h3>Connect me via:</h3><blockquote>karandevelop.netlify.app/</blockquote><blockquote><a href="https://www.linkedin.com/in/karan-gore/">https://www.linkedin.com/in/karan-gore/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6138062b30a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Your Own Camera in Flutter and Give Your App a Branded Feel]]></title>
            <link>https://medium.com/@karangore518/build-your-own-camera-in-flutter-and-give-your-app-a-branded-feel-4a5f892f2d3d?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a5f892f2d3d</guid>
            <category><![CDATA[flutter-ui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[cameras]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 21:04:12 GMT</pubDate>
            <atom:updated>2025-10-22T21:04:12.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QDFcjNPAAFnIhpO1nDr5Ew.png" /></figure><p>Have you ever opened an app and noticed how even the <strong>camera feels different</strong>? Think of Instagram, Snapchat, or TikTok — each has its own camera interface, its own touch. That’s no coincidence — it’s <em>branding through experience</em>.</p><p>If you’re still using the good old image_picker to capture images, you’re missing a golden chance to make your app stand out.</p><p>Today, let’s dive into how you can <strong>build your own custom camera in Flutter</strong> using the camera package and give your users a polished, on-brand experience that feels truly <em>yours</em>.</p><h3>Why Create a Custom Camera?</h3><p>The image_picker It&#39;s easy to use, but it’s also generic. It pops up the system UI — the same default camera that every other app uses.</p><p>That means:</p><ul><li>You lose control over how the camera looks and feels.</li><li>You can’t add overlays, filters, or branding.</li><li>You can’t customize buttons or user experience.</li></ul><p>By creating your own camera screen, you can:</p><ul><li>Add your logo, filters, or guides.</li><li>Match your brand’s color palette.</li><li>Integrate instant previews, cropping, and effects.</li><li>Create something memorable for users.</li></ul><p>Imagine a fashion app with a sleek purple gradient camera overlay, or a fitness app that adds a subtle frame to show proper form — that’s where experience meets design.</p><h3>Let’s Get Started — Setting Up the Camera Plugin</h3><p>Add the dependency to your pubspec.yaml:</p><pre>dependencies:<br>  flutter:<br>    sdk: flutter<br>  camera: ^0.10.5+5<br>  path_provider: ^2.1.2<br>  path: ^1.8.3</pre><p>Then run:</p><pre>flutter pub get</pre><p>Now, you’re ready to build your own camera UI.</p><h3>Basic Camera Implementation</h3><p>Here’s a simple example of a fully working custom camera screen in Flutter:</p><pre>import &#39;package:camera/camera.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:path/path.dart&#39;;<br>import &#39;package:path_provider/path_provider.dart&#39;;<br><br>class CustomCameraScreen extends StatefulWidget {<br>  @override<br>  _CustomCameraScreenState createState() =&gt; _CustomCameraScreenState();<br>}<br><br>class _CustomCameraScreenState extends State&lt;CustomCameraScreen&gt; {<br>  late CameraController _controller;<br>  late Future&lt;void&gt; _initializeControllerFuture;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _initializeCamera();<br>  }<br><br>  Future&lt;void&gt; _initializeCamera() async {<br>    final cameras = await availableCameras();<br>    final firstCamera = cameras.first;<br><br>    _controller = CameraController(<br>      firstCamera,<br>      ResolutionPreset.high,<br>      enableAudio: false,<br>    );<br><br>    _initializeControllerFuture = _controller.initialize();<br>    setState(() {});<br>  }<br><br>  @override<br>  void dispose() {<br>    _controller.dispose();<br>    super.dispose();<br>  }<br><br>  Future&lt;void&gt; _takePicture() async {<br>    try {<br>      await _initializeControllerFuture;<br>      final image = await _controller.takePicture();<br><br>      // You can save or process image.path here<br>      ScaffoldMessenger.of(context).showSnackBar(<br>        SnackBar(content: Text(&#39;Image saved at: ${image.path}&#39;)),<br>      );<br>    } catch (e) {<br>      print(e);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      body: FutureBuilder&lt;void&gt;(<br>        future: _initializeControllerFuture,<br>        builder: (context, snapshot) {<br>          if (snapshot.connectionState == ConnectionState.done) {<br>            return Stack(<br>              children: [<br>                CameraPreview(_controller),<br><br>                // Overlay with branding or gradient<br>                Container(<br>                  decoration: BoxDecoration(<br>                    gradient: LinearGradient(<br>                      colors: [Colors.black.withOpacity(0.3), Colors.transparent],<br>                      begin: Alignment.bottomCenter,<br>                      end: Alignment.topCenter,<br>                    ),<br>                  ),<br>                ),<br><br>                // Capture button<br>                Align(<br>                  alignment: Alignment.bottomCenter,<br>                  child: Padding(<br>                    padding: const EdgeInsets.only(bottom: 40.0),<br>                    child: GestureDetector(<br>                      onTap: _takePicture,<br>                      child: Container(<br>                        width: 80,<br>                        height: 80,<br>                        decoration: BoxDecoration(<br>                          color: Colors.white,<br>                          shape: BoxShape.circle,<br>                          border: Border.all(<br>                            color: Colors.deepPurple,<br>                            width: 5,<br>                          ),<br>                        ),<br>                      ),<br>                    ),<br>                  ),<br>                ),<br><br>                // Custom logo overlay<br>                Positioned(<br>                  top: 60,<br>                  left: 20,<br>                  child: Text(<br>                    &#39;TechStart Lens 📸&#39;,<br>                    style: TextStyle(<br>                      color: Colors.white,<br>                      fontWeight: FontWeight.bold,<br>                      fontSize: 20,<br>                    ),<br>                  ),<br>                ),<br>              ],<br>            );<br>          } else {<br>            return Center(child: CircularProgressIndicator());<br>          }<br>        },<br>      ),<br>    );<br>  }<br>}</pre><h3>Adding Your Brand Personality</h3><p>You can easily go beyond this basic setup:</p><ul><li>Add your logo watermark to the preview.</li><li>Include custom buttons that match your theme.</li><li>Overlay helpful guides (e.g., a frame or grid lines).</li><li>Apply filters or AR stickers with packages like camera_platform_interface.</li></ul><p>It’s not just a <em>camera</em> anymore, it’s your <strong>brand experience</strong>.</p><h3>The Impact: User Experience and Engagement</h3><p>In UX, <strong>small things make big differences</strong>.<br> A custom camera:</p><ul><li>Makes your app feel more professional.</li><li>Strengthens brand recall.</li><li>Builds trust, users feel they’re using a premium product.</li><li>Opens doors to creative features (e.g., branded selfies, AR effects).</li></ul><p>This approach turns an ordinary photo capture into a branded touchpoint, one that makes your app unforgettable.</p><h3>Final Thoughts</h3><blockquote>Next time you build an app that needs image capture, skip the default picker.<br>Instead, <strong>own the experience</strong>. Build your own camera with Flutter’s camera plugin — it’s simple, powerful, and 100% customizable.</blockquote><blockquote><em>Your camera isn’t just a tool, it’s a </em><strong><em>brand story in pixels</em></strong><em>.</em></blockquote><blockquote><strong>Know more about my work:</strong></blockquote><p><a href="https://karandevelop.netlify.app/">Karan Gore | Senior Software Engineer | Flutter &amp; Gen AI</a></p><p><a href="https://www.linkedin.com/in/karan-gore/">https://www.linkedin.com/in/karan-gore/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a5f892f2d3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reliable API Calls with dio_smart_retry]]></title>
            <link>https://medium.com/@karangore518/reliable-api-calls-with-dio-smart-retry-366366fa9a60?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/366366fa9a60</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 20:05:04 GMT</pubDate>
            <atom:updated>2025-03-19T20:05:04.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q7KcWpIOca3TiE5ygZuLyg.png" /></figure><p>When developing Flutter applications, we often focus on API calls but overlook <strong>one of the most powerful yet underutilized features — interceptors</strong>. They play a crucial role in enhancing API reliability, security, and performance. One such interceptor that every Flutter developer should consider using is <strong>dio_smart_retry</strong>.</p><h3>Why Do API Failures Matter?</h3><p>Imagine you are building an <strong>e-commerce app</strong>, and a user initiates a payment. Due to an unstable network, the API request fails. Without a retry mechanism, the user may assume the payment was unsuccessful and either leave the platform or make unnecessary repeated attempts.</p><p>This isn’t just frustrating for users — it directly impacts your business by increasing churn and reducing trust.</p><h3>Common Causes of API Failures</h3><ol><li><strong>Network Fluctuations</strong> — Poor connectivity can disrupt API requests.</li><li><strong>Timeout Issues</strong> — If the request takes too long, it may be terminated.</li><li><strong>Server Downtime</strong> — Temporary server failures can cause unexpected API failures.</li><li><strong>Rate Limits &amp; Throttling</strong> — APIs may block repeated requests in a short time frame.</li></ol><p>To mitigate these issues, we need a <strong>smart retry mechanism</strong>, and this is where dio_smart_retry comes in.</p><h3>What is dio_smart_retry?</h3><p>dio_smart_retry is a <strong>retry interceptor</strong> for <strong>Dio</strong>, Flutter’s most popular HTTP client. It allows failed requests to be retried <strong>automatically</strong> based on predefined conditions, reducing errors and improving reliability.</p><h3>Key Features:</h3><p>✅ <strong>Retries failed requests</strong> intelligently ✅ <strong>Prevents unnecessary retries</strong> for client-side errors (e.g., 400-series errors) ✅ <strong>Configurable retry count &amp; delays</strong> ✅ <strong>Works seamlessly with Dio</strong></p><h3>How to Implement dio_smart_retry in Your Flutter App</h3><p>First, install the package:</p><pre>flutter pub add dio_smart_retry</pre><p>Then, integrate it into your Dio client:</p><pre>import &#39;package:dio/dio.dart&#39;;<br>import &#39;package:dio_smart_retry/dio_smart_retry.dart&#39;;<br><br>void main() {<br>  final Dio dio = Dio();<br>  dio.interceptors.add(<br>    RetryInterceptor(<br>      dio: dio,<br>      retries: 3, // Number of retries<br>      retryDelays: [<br>        Duration(seconds: 1),<br>        Duration(seconds: 2),<br>        Duration(seconds: 3),<br>      ], // Delay intervals<br>      retryEvaluator: (error) =&gt; error.response?.statusCode == 500, // Retry on server errors<br>    ),<br>  );<br>}</pre><p>With just a few lines of code, your API requests become <strong>smarter and more resilient</strong>! 🚀</p><h3>Real-World Use Case: Payment Processing in an E-Commerce App</h3><p>Let’s say your app allows users to <strong>make payments</strong>, and you call an API to process them. A failed payment request can result in <strong>poor user experience</strong> or even <strong>financial loss</strong>. Instead of showing an error message and asking the user to retry, we can <strong>automatically retry</strong> the request:</p><pre>Future&lt;void&gt; processPayment() async {<br>  try {<br>    final response = await dio.post(&quot;https://api.example.com/payment&quot;, data: paymentData);<br>    print(&quot;Payment Successful: ${response.data}&quot;);<br>  } catch (error) {<br>    print(&quot;Payment Failed: ${error.message}&quot;);<br>  }<br>}</pre><p>With dio_smart_retry, the app will <strong>retry failed requests up to 3 times</strong>, reducing the likelihood of a failed payment due to temporary network issues.</p><h3>Interceptors Are More Than Just Retries!</h3><p>While dio_smart_retry is essential for handling retries, <strong>interceptors</strong> can be used for other crucial functionalities:</p><h3>1. Logging Requests &amp; Responses</h3><p>Logging API requests and responses is helpful for debugging and monitoring.</p><pre>dio.interceptors.add(<br>  InterceptorsWrapper(<br>    onRequest: (options, handler) {<br>      print(&quot;Request: ${options.uri}&quot;);<br>      return handler.next(options);<br>    },<br>    onResponse: (response, handler) {<br>      print(&quot;Response: ${response.data}&quot;);<br>      return handler.next(response);<br>    },<br>  ),<br>);</pre><h3>2. Adding Authentication Tokens</h3><p>Interceptors can <strong>dynamically inject authentication tokens</strong> before making API requests.</p><pre>dio.interceptors.add(<br>  InterceptorsWrapper(<br>    onRequest: (options, handler) {<br>      options.headers[&#39;Authorization&#39;] = &#39;Bearer your_access_token&#39;;<br>      return handler.next(options);<br>    },<br>  ),<br>);</pre><h3>3. Centralized Error Handling</h3><p>Instead of handling API errors in multiple places, interceptors can <strong>streamline error management</strong>:</p><pre>dio.interceptors.add(<br>  InterceptorsWrapper(<br>    onError: (DioException e, handler) {<br>      if (e.response?.statusCode == 401) {<br>        print(&quot;Unauthorized! Redirecting to login...&quot;);<br>      }<br>      return handler.next(e);<br>    },<br>  ),<br>);</pre><h3>Final Thoughts</h3><p>We often <strong>ignore interceptors</strong>, but they are a <strong>powerful tool</strong> in Flutter development. Using <strong>dio_smart_retry</strong> ensures that your API calls <strong>don’t fail unnecessarily</strong>, improving reliability and user experience.</p><h3>Key Takeaways:</h3><p>✔️ API failures can significantly impact user experience. <br>✔️ <strong>dio_smart_retry</strong> helps in auto-retrying failed requests. <br>✔️ Interceptors are not just for retries—they can handle logging, authentication, and error management. <br>✔️ Small changes in API handling can make a big difference in your app’s performance and stability.</p><p>If you haven’t used <strong>dio_smart_retry</strong>, give it a try in your next Flutter project! 🚀</p><h4>Connect with me on Social Networks:</h4><ul><li><a href="https://karandevelop.netlify.app/">Karan Gore | Senior Software Engineer | Flutter &amp; Gen AI</a></li><li><a href="https://github.com/itskgore">itskgore - Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=366366fa9a60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter with Mockito & flutter_test]]></title>
            <link>https://medium.com/@karangore518/flutter-with-mockito-flutter-test-29eb50a23409?source=rss-a1abcd419c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/29eb50a23409</guid>
            <category><![CDATA[appdev]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Karan Gore]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 17:31:40 GMT</pubDate>
            <atom:updated>2025-03-13T17:31:40.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>Writing Unit Tests in Flutter with Mockito &amp; flutter_test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ftXVPXUXRVMAr0j8eLG4Q.png" /></figure><p>Unit testing is an essential part of Flutter development. It helps ensure that your app’s logic, UI interactions, and API calls work correctly, reducing the risk of introducing bugs when making changes.</p><p>In this guide, we’ll explore:<br> 1. How to use flutter_test and Mockito for unit testing<br> 2. How to test <strong>business logic</strong> (mock API calls)<br> 3. How to write <strong>widget tests</strong> (testing UI interactions with API)</p><h3>Why Unit Testing?</h3><p>Unit tests help in:</p><ul><li><strong>Detecting bugs early</strong> before they reach production</li><li><strong>Ensuring refactoring doesn’t break functionality</strong></li><li><strong>Reducing manual testing time</strong></li><li><strong>Improving code quality</strong></li></ul><p>Flutter provides the flutter_test package for unit testing, and we can use <strong>Mockito</strong> to mock dependencies such as API calls.</p><h3>1️⃣ Testing Business Logic (Mocking API Calls)</h3><p>Let’s consider an authentication service that interacts with an API to log in a user.</p><h3>AuthService (Business Logic Layer)</h3><pre>class AuthService {<br>  final ApiClient apiClient;<br>  AuthService(this.apiClient);<br>  Future&lt;String&gt; login(String email, String password) async {<br>    final response = await apiClient.authenticate(email, password);<br>    return response.token;<br>  }<br>}</pre><p>This class takes an ApiClient dependency and calls authenticate(), returning a token if login is successful.</p><h3>Mocking API &amp; Writing Unit Test</h3><p>Instead of calling a real API (which would be slow and unreliable), we use <strong>Mockito</strong> to create a fake version of ApiClient.</p><h4>Step 1: Add Dependencies</h4><p>Add these dependencies in pubspec.yaml:</p><pre>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  mockito: ^5.4.0<br>  build_runner: ^2.4.0</pre><h4>Step 2: Generate Mocks</h4><p>Create a file auth_service_test.dart and add this:</p><pre>import &#39;package:mockito/annotations.dart&#39;;<br>import &#39;package:mockito/mockito.dart&#39;;<br>import &#39;auth_service.dart&#39;;</pre><pre>@GenerateMocks([ApiClient])<br>import &#39;auth_service_test.mocks.dart&#39;;</pre><p>Run the following command to generate the mock class:</p><pre>flutter pub run build_runner build</pre><h4>Step 3: Write the Unit Test</h4><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:mockito/mockito.dart&#39;;<br><br>void main() {<br>  late AuthService authService;<br>  late MockApiClient mockApiClient;<br>  setUp(() {<br>    mockApiClient = MockApiClient();<br>    authService = AuthService(mockApiClient);<br>  });<br>  test(&#39;Login returns token on success&#39;, () async {<br>    when(mockApiClient.authenticate(any, any))<br>        .thenAnswer((_) async =&gt; Response(token: &#39;12345&#39;));<br>    final token = await authService.login(&#39;test@email.com&#39;, &#39;password&#39;);<br>    expect(token, &#39;12345&#39;);<br>    verify(mockApiClient.authenticate(any, any)).called(1);<br>  });<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVqlz4q3Ax3PNTA1Ix03rw.png" /></figure><h3>💡 Key Takeaways:</h3><p>✅ <strong>Mocks help isolate dependencies</strong> — Your test only verifies AuthService, without hitting the real API.<br> ✅ <strong>Fast &amp; reliable</strong> – No external dependencies, making tests quick.</p><h3>2️⃣ Widget Testing (UI Interacting with API)</h3><p>Now, let’s test a <strong>login screen</strong> that interacts with AuthService.</p><h3>Login Screen UI</h3><pre>class LoginScreen extends StatefulWidget {<br>  final AuthService authService;<br>LoginScreen({required this.authService});<br>  @override<br>  _LoginScreenState createState() =&gt; _LoginScreenState();<br>}<br><br>class _LoginScreenState extends State&lt;LoginScreen&gt; {<br>  final _emailController = TextEditingController();<br>  final _passwordController = TextEditingController();<br>  String? _message;<br>  void _login() async {<br>    final token = await widget.authService.login(<br>        _emailController.text, _passwordController.text);<br>    setState(() {<br>      _message = token.isNotEmpty ? &quot;Login Successful!&quot; : &quot;Login Failed!&quot;;<br>    });<br>  }<br>  @override<br>  Widget build(BuildContext context) {<br>    return Column(<br>      children: [<br>        TextField(controller: _emailController, key: Key(&#39;emailField&#39;)),<br>        TextField(controller: _passwordController, key: Key(&#39;passwordField&#39;)),<br>        ElevatedButton(<br>          key: Key(&#39;loginButton&#39;),<br>          onPressed: _login,<br>          child: Text(&quot;Login&quot;),<br>        ),<br>        if (_message != null) Text(_message!, key: Key(&#39;messageText&#39;)),<br>      ],<br>    );<br>  }<br>}</pre><h3>Writing the Widget Test</h3><p>Now, let’s test if clicking the <strong>Login</strong> button correctly updates the UI after authentication.</p><pre>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:mockito/mockito.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br><br>void main() {<br>  late AuthService mockAuthService;<br>  setUp(() {<br>    mockAuthService = MockAuthService();<br>  });<br>  testWidgets(&#39;Login screen displays success message on valid login&#39;,<br>      (WidgetTester tester) async {<br>    when(mockAuthService.login(any, any))<br>        .thenAnswer((_) async =&gt; &#39;12345&#39;); // Mock success response<br>    await tester.pumpWidget(MaterialApp(home: LoginScreen(authService: mockAuthService)));<br>    // Enter email &amp; password<br>    await tester.enterText(find.byKey(Key(&#39;emailField&#39;)), &#39;test@email.com&#39;);<br>    await tester.enterText(find.byKey(Key(&#39;passwordField&#39;)), &#39;password&#39;);<br>    // Tap login button<br>    await tester.tap(find.byKey(Key(&#39;loginButton&#39;)));<br>    await tester.pump(); // Rebuild widget after login<br>    // Verify message displayed<br>    expect(find.text(&#39;Login Successful!&#39;), findsOneWidget);<br>  });<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oKIPlLZEbEbacWqOc%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNmxvbTBuMzBmeW5nMDUwajAzY2ZzbTRjN2U3MDdiYnBuc2hvaGtybCZlcD12MV9naWZzX3NlYXJjaCZjdD1n%2F3oKIPlLZEbEbacWqOc%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia4.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExYjU3MWF2cW5zNG5hb3prc2VpZXF0Z2p5b2JwcmR3bHR3Nmh0bGx1YSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F3oKIPlLZEbEbacWqOc%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/97e08ae5742393ef3b7b3dd53709441f/href">https://medium.com/media/97e08ae5742393ef3b7b3dd53709441f/href</a></iframe><h3>💡 Key Takeaways:</h3><p>✅ <strong>Tests both UI &amp; API integration</strong><br> ✅ <strong>Verifies UI updates correctly after user interaction</strong><br> ✅ <strong>Ensures app behavior is as expected before release</strong></p><h3>Final Thoughts</h3><p>Unit testing makes your app <strong>reliable, maintainable, and bug-free</strong> 🚀. Here’s what we covered:<br> 🔹 How to write <strong>unit tests for business logic</strong> using Mockito<br> 🔹 How to test <strong>UI interactions with API</strong> using flutter_test<br> 🔹 Why testing <strong>both logic &amp; UI together</strong> is crucial</p><h4>Connect with me on Social Networks:</h4><ul><li><a href="https://karandevelop.netlify.app/">Karan Gore | Senior Software Engineer | Flutter &amp; Gen AI</a></li><li><a href="https://github.com/itskgore">itskgore - Overview</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29eb50a23409" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>