<?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 Chandan Singh on Medium]]></title>
        <description><![CDATA[Stories by Chandan Singh on Medium]]></description>
        <link>https://medium.com/@chandanpsingh?source=rss-8b86fb661c9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*c_bKPK4GMOZHmoDXby9fnA.jpeg</url>
            <title>Stories by Chandan Singh on Medium</title>
            <link>https://medium.com/@chandanpsingh?source=rss-8b86fb661c9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:00:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chandanpsingh/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[My First Real LLM Project: The Same Chatbot Built with 5 Different Context Strategies]]></title>
            <link>https://chandanpsingh.medium.com/my-first-real-llm-project-the-same-chatbot-built-with-5-different-context-strategies-9f96de474f50?source=rss-8b86fb661c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f96de474f50</guid>
            <category><![CDATA[context]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[chat-model]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Chandan Singh]]></dc:creator>
            <pubDate>Fri, 22 May 2026 05:59:19 GMT</pubDate>
            <atom:updated>2026-05-22T05:59:19.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XqIrtEZ8XMFBHcY4leBWug.png" /></figure><p>When I started learning about LLMs, I assumed the hard part was getting the model to <em>understand</em> the user. Turns out, the hard part is getting the model to <em>remember the right things at the right time</em> — without going broke on token costs.</p><p>My first real project: a doctor’s assistant chatbot. Users describe symptoms, the bot checks real-time doctor availability, and books appointments.</p><p>I built <strong>5 versions</strong> of the same bot, each with a different context strategy. Here’s exactly what worked, what failed, and what I’d never do again.</p><h3>The Project in One Paragraph</h3><p>A chat assistant for a clinic. Match symptoms to specialties (rash → dermatologist), check live doctor availability from a database, book appointments, and mark slots as taken. Implemented in Python with XAI’s Grok Completion API + function calling.</p><p>The core question: <strong>What should the LLM see with each request?</strong></p><h3>Strategy 1: Rule-Based (No LLM) + Intent-First Flow</h3><p><strong>How it works:</strong> Regex + keyword mapping. “Rash” → dermatology. “Fever” → general physician. Slot filling for date/time. No LLM anywhere.</p><p><strong>Pros:</strong> Zero cost, lightning fast, perfectly predictable.</p><p><strong>Cons:</strong> “My skin feels like sandpaper” → no match. User gets frustrated. Typos break everything.</p><p><strong>When it failed:</strong> A caller said, “I fell playing badminton — my ankle is swollen.” No keyword for “orthopedic.” The bot asked, “Which doctor would you like?” Wrong answer.</p><p><strong>Verdict:</strong> Fine for a rigid IVR system. Useless for natural conversation.</p><h3>Strategy 2: LLM + Full History + Strong System Prompt</h3><p><strong>How it works:</strong> Send <em>every</em> previous message — user and assistant — with each API call. System prompt sets rules: “You are a clinic assistant. Always verify availability before booking.”</p><p>python</p><pre>messages = [<br>    {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_prompt},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Hi, I have a rash&quot;},<br>    {&quot;role&quot;: &quot;assistant&quot;, &quot;content&quot;: &quot;Let me help...&quot;},<br>    {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Tomorrow at 10 AM&quot;}<br>]</pre><p><strong>Pros:</strong> The model never forgets anything. Perfect for short conversations. Trivial to implement.</p><p><strong>Cons:</strong> Token cost explodes after 5–6 turns. Latency grows linearly. In a 12-turn conversation, I paid for ~4,000 tokens just to remind the model about the rash mentioned on turn 2.</p><p><strong>When it failed:</strong> A user rescheduled three times. By turn 15, the prompt was massive. The model hallucinated availability that didn’t exist because it got lost in its own history.</p><p><strong>Verdict:</strong> Works for demos. Not production-ready.</p><h3>Strategy 3: LLM + Summarized History + Strong System Prompt</h3><p><strong>How it works:</strong> After each interaction, summarize the conversation so far. Store only the summary. Next call = system prompt + summary + latest user message.</p><p>python</p><pre># After each turn<br>summary = summarize_with_llm(conversation_so_far)<br># Next call uses only the summary</pre><p><strong>Pros:</strong> Fixed token cost per turn (~500–800). No runaway growth. Forces focus.</p><p><strong>Cons:</strong> Information loss is inevitable. Doubles latency (summarization call + response call). Summaries can introduce subtle errors.</p><p><strong>When it failed:</strong> User said “rash on inner thigh” on turn 2. By turn 6, summary said “skin issue.” The LLM recommended a general physician instead of a dermatologist. The detail loss mattered.</p><p><strong>Verdict:</strong> Good for low-stakes, linear conversations. Risky when details matter.</p><h3>Strategy 4: LLM + Summarized History + Last N Messages + Strong System Prompt</h3><p><strong>How it works:</strong> Keep a rolling window of the last 3–5 raw messages <em>plus</em> a summary of everything before that. Best of both worlds.</p><p>python</p><pre>context = {<br>    &quot;long_term_summary&quot;: &quot;User has rash, wants appointment this week&quot;,<br>    &quot;recent_messages&quot;: [<br>        &quot;User: Can I do 11 AM?&quot;,<br>        &quot;Assistant: Let me check...&quot;,<br>        &quot;User: Actually, make it 2 PM&quot;<br>    ]<br>}</pre><p><strong>Pros:</strong> Recent details preserved perfectly. Older context compressed. Sweet spot for medium-length conversations.</p><p><strong>Cons:</strong> Still two LLM calls per turn (summarize + respond). Choosing N is trial and error (3 works? 5? depends on your use case). The summary can still miss connections between recent and old info.</p><p><strong>When it worked well:</strong> A 10-turn conversation where the user changed time slots twice. The last 3 messages captured the rescheduling dance. The summary remembered the original symptom. Both needed, neither lost.</p><p><strong>When it struggled:</strong> A user said, “Actually, back to what I said earlier about Thursday…” The model couldn’t connect “back to earlier” because the detail wasn’t in the last N messages <em>or</em> the summary. It was lost.</p><p><strong>Verdict:</strong> Best of the “memory-based” approaches. But still has fundamental limits.</p><h3>Strategy 5: LLM + Schema / Slots + Strong System Prompt</h3><p><strong>How it works:</strong> No conversation history at all. Instead, maintain a structured schema (slots) that gets updated after each user message. The LLM sees only:</p><ul><li>Current intent</li><li>Filled slots (specialty, doctor, date, time)</li><li>Missing slots</li><li>Database results (available doctors)</li></ul><p>python</p><pre>context = {<br>    &quot;intent&quot;: &quot;book_appointment&quot;,<br>    &quot;slots&quot;: {<br>        &quot;patient_id&quot;: None,<br>        &quot;patient_phone&quot;: None,<br>        &quot;patient_name&quot;: None,<br>        &quot;patient_email&quot;: None,<br>        &quot;patient_date_of_birth&quot;: None,<br>        &quot;patient_address&quot;: None,<br>        &quot;symptoms&quot;: None<br>        &quot;specialty&quot;: &quot;dermatology&quot;,<br>        &quot;doctor_name&quot;: &quot;Dr. Smith&quot;,<br>        &quot;doctor_id&quot;: None,<br>        &quot;date&quot;: None,<br>        &quot;time&quot;: None<br>    },<br>    &quot;missing_slots&quot;: [&quot;date&quot;, &quot;time&quot;],<br>    &quot;db_results&quot;: {<br>        &quot;Dr. Smith&quot;: [&quot;11 AM&quot;, &quot;2 PM&quot;, &quot;4 PM&quot;]<br>    }<br>}<br># That&#39;s it. No conversation history.</pre><p><strong>Pros:</strong></p><ul><li>Tiny token cost (~300 per call)</li><li>Flat latency regardless of conversation length</li><li>No information decay — you control the schema</li><li>Perfect for function calling</li></ul><p><strong>Cons:</strong></p><ul><li>Requires building a state machine alongside the LLM</li><li>The LLM can’t refer to verbatim user phrasing anymore</li><li>More initial code</li></ul><p><strong>When it worked best:</strong> A 20-turn conversation where the user changed time slots four times. Token cost? Flat. Accuracy? Perfect. The LLM wasn’t doing memory — it was doing reasoning on clean, structured data.</p><p><strong>Verdict:</strong> Production-ready. The extra engineering pays for itself in a week.</p><h3>Quick Comparison Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*5irv6W43G_AjN_gC1RSDcA.png" /></figure><h3>Which One Won and Why</h3><p><strong>Winner: Strategy 5 (Schema/Slots)</strong></p><p>By a good margin. Here’s why:</p><ul><li><strong>Cost:</strong> approximately 0.02 per session vs 0.15 for full history</li><li><strong>Accuracy:</strong> Near 100% on appointment booking because the LLM never hallucinated availability — it only read real DB results from the schema</li><li><strong>Latency:</strong> Flat at ~600ms regardless of conversation length</li><li><strong>Maintainability:</strong> Adding a new specialty or rule meant updating the schema, not re-prompting</li></ul><p>Strategy 4 (summary + last N) was second place. It handled medium conversations well but broke when users referred to “earlier” details outside the window.</p><h3>Key Lessons Learned</h3><p><strong>1. LLMs are terrible at memory.</strong> They’re reasoning engines, not databases. If you need to remember a fact, store it in a variable or schema. Give the LLM only what it needs for the <em>next action</em>.</p><p><strong>2. Full history is a trap for beginners.</strong> It works beautifully in your first demo. Then you scale to 100 users and your API bill arrives. Start with schema thinking from day one.</p><p><strong>3. Summaries sound elegant but lose signal.</strong> Every summarization is lossy compression. For healthcare (or any domain where details matter), that’s dangerous.</p><p><strong>4. The hybrid approach always wins.</strong> Use LLMs for understanding messy language and generating natural responses. Use traditional code for state, validation, and DB queries.</p><h3>What’s Next</h3><p>This project taught me the limits of manual context handling. For my next experiment, I’m planning to rebuild the similar bot using <strong>LangChain</strong> — specifically exploring its memory modules and chain-based state management. I’m curious whether LangChain’s built-in abstractions would have saved me from building that schema state machine from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f96de474f50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Networks Explained in the Easiest Way Possible: No PhD Required, Just Curiosity]]></title>
            <link>https://chandanpsingh.medium.com/neural-networks-explained-in-the-easiest-way-possible-no-phd-required-just-curiosity-9bf8326c6406?source=rss-8b86fb661c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bf8326c6406</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Chandan Singh]]></dc:creator>
            <pubDate>Thu, 07 May 2026 05:23:08 GMT</pubDate>
            <atom:updated>2026-05-07T05:23:08.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C1ORZY0dtgmjwOEwdRDBjg.jpeg" /></figure><p>Hey there! like many of you, I recently jumped into the world of <strong>AI and Large Language Models (LLMs)</strong>. I added Python to my skill set and started digging into what actually powers tools like ChatGPT.</p><p>If you’re new to AI, the term “Neural Network” can sound scary. Don’t worry! In this blog, I’ll explain everything using simple English, everyday analogies, and what I learned from the excellent <strong>3Blue1Brown</strong> YouTube series. Think of this as your friendly starting point.</p><h3>What is a Neural Network? (It’s Not Magic!)</h3><p>Imagine a big group of friends trying to decide whether a photo shows a cat or a dog.</p><ul><li>Each friend looks at different things: one checks the ears, another the whiskers, another the tail shape.</li><li>They all give their opinion (yes/no/maybe).</li><li>One smart friend combines all these opinions and makes the final decision.</li></ul><p>A <strong>neural network</strong> works exactly like this team of friends.</p><ul><li>The “friends” are called <strong>neurons</strong>.</li><li>They are organized in <strong>layers</strong>: input layer (what goes in), hidden layers (the thinking part), and output layer (the answer).</li><li>Each neuron takes inputs, does a small calculation, and passes the result forward.</li></ul><p><strong>Key Point for Beginners</strong>: A neural network is just a bunch of mathematical equations connected in a smart way. No magic involved!</p><h3>How Do Neural Networks Learn? (The Training Process)</h3><p>This is where it gets exciting.</p><p>When the network makes a wrong prediction (e.g., says a cat is a dog), it needs to improve. This improvement happens through two main ideas:</p><ol><li><strong>Gradient Descent</strong> (Finding the best path downhill)</li><li><strong>Backpropagation</strong> (Learning from mistakes efficiently)</li></ol><p><strong>Simple Analogy for Gradient Descent:</strong></p><p>Imagine you are on a foggy mountain and want to reach the lowest point (the best solution). You can’t see far, so you take small steps in the direction where the ground is going down the most. That’s gradient descent — the network slowly adjusts its internal numbers (called <strong>weights</strong>) to reduce errors.</p><p><strong>Backpropagation — The Real Hero:</strong></p><p>This is the clever algorithm that tells each neuron: “Hey, you contributed to the mistake. Here’s how much you should change.”</p><p>It works backwards through the network (from output to input), calculating responsibility for the error. This is why neural networks can learn from millions of examples.</p><h3>Step-by-Step Learning Process</h3><ol><li><strong>Forward Pass</strong>: Data goes in → Network makes a guess.</li><li><strong>Calculate Error</strong>: Compare guess with correct answer.</li><li><strong>Backward Pass (Backpropagation)</strong>: Figure out which neurons caused the error.</li><li><strong>Update Weights</strong>: Slightly adjust the connections using gradient descent.</li><li><strong>Repeat</strong>: Do this thousands or millions of times until the network becomes really good.</li></ol><p>This whole process is called <strong>training</strong> the model.</p><h3>Why Should Care?</h3><ul><li>Neural networks are like massive, trainable functions. Instead of you writing every rule, the network learns the rules from data.</li><li>Modern tools and libraries make it surprisingly approachable..</li><li>LLMs like ChatGPT, Gemini, and others are built on giant neural networks (Transformers, which are an advanced type of neural network). Understanding the basics helps you go deeper.</li></ul><h3>Key Takeaways for New Learners</h3><ul><li>Neural networks are <strong>layered mathematical functions</strong> that learn patterns from data.</li><li>They improve through <strong>trial and error</strong> (gradient descent + backpropagation).</li><li>You don’t need to be a math genius to start — visual intuition is enough in the beginning.</li><li>Start small: Play with simple classification problems (e.g., handwritten digit recognition).</li></ul><h3>My Learning Tips</h3><ul><li>Watch the 3Blue1Brown videos (highly recommended):<br>- <a href="https://www.youtube.com/watch?v=aircAruvnKk">But what is a neural network?</a><br>- <a href="https://www.youtube.com/watch?v=IHZwWFHWa-w">Gradient Descent</a><br>- <a href="https://www.youtube.com/watch?v=Ilg3gGewQ5U">Backpropagation</a><br>- <a href="https://www.youtube.com/watch?v=tIeHLnjs5U8">Calculus of Backpropagation</a></li><li>Code along in Python (start with simple notebooks on Google Colab — no setup needed).</li><li>Build tiny projects: Iris flower classification, spam detection, or image recognizer.</li><li>Don’t rush the math. Understand the “why” first.</li><li><a href="https://www.youtube.com/watch?v=Ilg3gGewQ5U">Backpropagation</a></li><li><a href="https://www.youtube.com/watch?v=tIeHLnjs5U8">Calculus of Backpropagation</a></li></ul><ol><li>Don’t rush the math. Understand the “why” first.</li></ol><p><strong>Final Words</strong></p><p>AI is not as complicated as it first seems. It’s just clever mathematics and lots of data + computation.</p><p>The same logical thinking you use in everyday problem-solving applies here — you’re just learning a new, powerful paradigm. The journey is incredibly rewarding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bf8326c6406" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exception Handling in Python AI Code: What Java Taught Me About Graceful Failures]]></title>
            <link>https://chandanpsingh.medium.com/exception-handling-in-python-ai-code-what-java-taught-me-about-graceful-failures-33151272eef8?source=rss-8b86fb661c9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/33151272eef8</guid>
            <category><![CDATA[python-exception]]></category>
            <category><![CDATA[python-ai]]></category>
            <category><![CDATA[python-vs-java]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[python-ai-project]]></category>
            <dc:creator><![CDATA[Chandan Singh]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 05:46:53 GMT</pubDate>
            <atom:updated>2026-04-20T05:46:53.534Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZqUb4wtbIuYYgYHNh-UPeQ.png" /></figure><h3>The Day My CSV Parser Met an LLM</h3><p>Three weeks into my AI journey, I wrote what I thought was a simple script. Take a user’s document, ask an LLM to extract key information, save it to a database. Basic stuff.</p><p>My Python script crashed 47 times on the first 100 documents.</p><p>Coming from 10+ years of Java development, I was used to try-catch-finally, checked exceptions, and the comforting predictability of NullPointerException. But AI code? It fails in <em>creative</em> new ways I never imagined.</p><p>Let me share what those failures taught me — and how Java’s exception handling philosophy (with some Python twists) saved my AI project.</p><h3>The Problem: AI Doesn’t Just Throw Exceptions. It Throws Chaos.</h3><p>In traditional Java development, failures are predictable:</p><ul><li>File not found? FileNotFoundException</li><li>Database down? SQLException</li><li>Null value? NullPointerException</li></ul><p>In AI development, failures look like this:</p><p>python</p><pre># You expect: {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30}<br># You get: &quot;John is 30 years old&quot;  (plain text, not JSON)<br># Or: {&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: &quot;thirty&quot;}  (string instead of int)<br># Or: {&quot;name&quot;: &quot;John&quot;}  (missing field)<br># Or: &quot;&quot;  (empty response)<br># Or: None  (API timeout)<br># Or: &quot;I&#39;m sorry, I cannot process this request&quot;  (refusal)</pre><p>The LLM doesn’t throw exceptions. It returns <em>garbage</em> and keeps running like nothing happened.</p><h3>Lesson 1 from Java: Fail Fast, But Fail Gracefully</h3><p>In Java, we learn to validate early:</p><p>java</p><pre>// Java mindset<br>public void processUser(User user) {<br>    if (user == null) throw new IllegalArgumentException(&quot;User cannot be null&quot;);<br>    if (user.getName() == null) throw new IllegalStateException(&quot;Name required&quot;);<br>    // proceed confidently<br>}</pre><p>Apply this to AI responses:</p><p>python</p><pre>def extract_user_info(llm_response: str) -&gt; dict:<br>    &quot;&quot;&quot;Parse LLM response with validation at EVERY step&quot;&quot;&quot;</pre><pre>    # Fail fast on obvious garbage<br>    if not llm_response or not isinstance(llm_response, str):<br>        raise ValueError(f&quot;Invalid response type:{type(llm_response)}&quot;)</pre><pre>    if len(llm_response.strip()) &lt; 10:<br>        raise ValueError(f&quot;Response too short:{llm_response[:50]}&quot;)</pre><pre>    # Try parsing<br>    try:<br>        data = json.loads(llm_response)<br>    except json.JSONDecodeError as e:<br>        # This is where Java&#39;s checked exceptions would be helpful<br>        raise ValueError(f&quot;LLM didn&#39;t return JSON. Got:{llm_response[:200]}&quot;) from e</pre><pre>    # Validate required fields (like Java&#39;s @NotNull)<br>    required_fields = [&quot;name&quot;, &quot;age&quot;, &quot;department&quot;]<br>    for field in required_fields:<br>        if field not in data:<br>            raise KeyError(f&quot;Missing required field:{field}. Got:{data.keys()}&quot;)</pre><pre>    # Validate types (like Java generics)<br>    if not isinstance(data[&quot;age&quot;], int):<br>        # Try to convert - AI often returns string numbers<br>        try:<br>            data[&quot;age&quot;] = int(data[&quot;age&quot;])<br>        except (ValueError, TypeError):<br>            raise TypeError(f&quot;Age must be number, got{type(data[&#39;age&#39;])}:{data[&#39;age&#39;]}&quot;)</pre><pre>    return data</pre><p>The key insight? <strong>Don’t trust the AI output one inch.</strong> Validate like you’re parsing untrusted user input from the internet.</p><h3>Lesson 2: The Try-Except-Finally Pattern (But Make It AI-Friendly)</h3><p>Java’s try-catch-finally is beautiful for resource cleanup. Python&#39;s try-except-finally works the same way, but for AI, we need <em>retries</em> and <em>fallbacks</em>.</p><p>Here’s my battle-tested pattern:</p><p>python</p><pre>def call_llm_with_graceful_failure(user_query: str, context_document: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Three attempts, three different fallback strategies.<br>    Like Java&#39;s retry libraries, but homegrown.<br>    &quot;&quot;&quot;<br>    max_retries = 3</pre><pre>    for attempt in range(max_retries):<br>        try:<br>            # Attempt 1: Normal call<br>            response = llm_api_call(user_query, context_document)</pre><pre>            # Validate response quality (critical step!)<br>            if is_valid_response(response):<br>                return response<br>            else:<br>                raise ValueError(f&quot;Low quality response on attempt{attempt + 1}&quot;)</pre><pre>        except NetworkError as e:<br>            # Like Java&#39;s IOException - retry with backoff<br>            wait_time = 2 ** attempt  # exponential backoff<br>            print(f&quot;Network error (attempt{attempt + 1}), retrying in{wait_time}s:{e}&quot;)<br>            time.sleep(wait_time)</pre><pre>        except RateLimitError as e:<br>            # LLM-specific - need longer wait<br>            wait_time = 10 * (attempt + 1)<br>            print(f&quot;Rate limited, waiting{wait_time}s:{e}&quot;)<br>            time.sleep(wait_time)</pre><pre>        except (ValueError, KeyError, TypeError) as e:<br>            # Parsing error - maybe the format changed<br>            print(f&quot;Parse error:{e}&quot;)<br>            if attempt == max_retries - 1:<br>                # Last attempt - use fallback<br>                return generate_fallback_response(user_query)<br>            # Otherwise, retry with stricter prompting<br>            context_document = add_format_instructions(context_document)</pre><pre>    # If all retries fail (Java&#39;s finally block equivalent)<br>    log_failure(user_query, context_document)<br>    return &quot;Unable to process request. Please rephrase or contact support.&quot;</pre><pre>def is_valid_response(response: str) -&gt; bool:<br>    &quot;&quot;&quot;Like Java&#39;s validation methods - be strict!&quot;&quot;&quot;<br>    if not response or len(response) &lt; 20:<br>        return False<br>    if &quot;I cannot&quot; in response or &quot;sorry&quot; in response.lower():<br>        return False<br>    if response.count(&quot;{&quot;) != response.count(&quot;}&quot;):  # unbalanced JSON<br>        return False<br>    return True</pre><p>The big difference from Java? <strong>You always need a Plan B.</strong> In Java, failure means throw an exception and let the user know. In AI, failure means try again, try differently, or return <em>something</em> useful.</p><h3>Lesson 3: Use Python’s Specific Exceptions (Don’t Just Print and Pray)</h3><p>In Java, we love our exception hierarchy. Python has one too — use it!</p><p>python</p><pre># Don&#39;t do this (generic except)<br>try:<br>    result = process_with_ai(doc)<br>except:  # catches everything - terrible!<br>    print(&quot;Something failed&quot;)<br>    return None</pre><pre># Do this instead<br>try:<br>    result = process_with_ai(doc)<br>except json.JSONDecodeError as e:<br>    # AI gave malformed JSON<br>    logger.error(f&quot;JSON parse failed for doc{doc.id}:{e}&quot;)<br>    result = repair_json_with_fallback(doc)</pre><pre>except requests.exceptions.Timeout as e:<br>    # API took too long<br>    logger.warning(f&quot;Timeout on{doc.id}, retrying with shorter context&quot;)<br>    result = retry_with_truncated_context(doc)</pre><pre>except openai.RateLimitError as e:<br>    # Need to slow down<br>    logger.info(f&quot;Rate limited, backing off for{doc.id}&quot;)<br>    time.sleep(5)<br>    result = retry_with_backoff(doc)</pre><pre>except Exception as e:<br>    # Catch-all for UNEXPECTED failures (log and escalate)<br>    logger.critical(f&quot;Unknown error on{doc.id}:{type(e).__name__}:{e}&quot;)<br>    raise  # Re-raise because I don&#39;t know how to handle this</pre><p>The Pythonic way: <strong>Be specific about what you can handle, and let unexpected failures crash loudly.</strong> You’ll thank yourself when debugging at 2 AM.</p><h3>Lesson 4: The “Circuit Breaker” Pattern (Borrowed from Enterprise Java)</h3><p>In distributed systems, we use circuit breakers to stop calling a failing service. AI APIs fail <em>differently</em> — they might succeed but return garbage.</p><p>Here’s a simple circuit breaker for AI quality:</p><p>python</p><pre>class AICircuitBreaker:<br>    &quot;&quot;&quot;Like Netflix Hystrix, but for LLM hallucinations&quot;&quot;&quot;</pre><pre>    def __init__(self, failure_threshold=5, timeout_seconds=60):<br>        self.failure_count = 0<br>        self.failure_threshold = failure_threshold<br>        self.last_failure_time = None<br>        self.timeout_seconds = timeout_seconds<br>        self.state = &quot;CLOSED&quot;  # CLOSED = normal, OPEN = failing, HALF_OPEN = testing</pre><pre>    def call(self, func, *args, **kwargs):<br>        if self.state == &quot;OPEN&quot;:<br>            if time.time() - self.last_failure_time &gt; self.timeout_seconds:<br>                self.state = &quot;HALF_OPEN&quot;<br>                print(&quot;Circuit half-open - testing if AI recovered&quot;)<br>            else:<br>                raise Exception(&quot;Circuit breaker OPEN - AI service appears degraded&quot;)</pre><pre>        try:<br>            result = func(*args, **kwargs)</pre><pre>            # Validate result quality (critical!)<br>            if not self.is_quality_result(result):<br>                raise ValueError(&quot;Low quality result&quot;)</pre><pre>            if self.state == &quot;HALF_OPEN&quot;:<br>                self.state = &quot;CLOSED&quot;<br>                self.failure_count = 0<br>                print(&quot;Circuit closed - AI recovered&quot;)</pre><pre>            return result</pre><pre>        except Exception as e:<br>            self.failure_count += 1<br>            self.last_failure_time = time.time()</pre><pre>            if self.failure_count &gt;= self.failure_threshold:<br>                self.state = &quot;OPEN&quot;<br>                print(f&quot;Circuit OPEN after{self.failure_count} failures&quot;)</pre><pre>            raise e</pre><pre>    def is_quality_result(self, result):<br>        # Check for common AI failure modes<br>        if not result or len(result) &lt; 10:<br>            return False<br>        if &quot;error&quot; in result.lower() and &quot;sorry&quot; in result.lower():<br>            return False<br>        # Add your quality checks here<br>        return True</pre><p>This pattern alone reduced my failure rate from 30% to under 5%.</p><h3>Lesson 5: Logging Like You Mean It (Java’s SLF4J, Python’s Logging)</h3><p>In Java, we log everything. In Python AI, you need to log <em>failures</em> with enough context to debug:</p><p>python</p><pre>import logging<br>import traceback<br>from datetime import datetime</pre><pre>logging.basicConfig(level=logging.INFO)<br>logger = logging.getLogger(__name__)</pre><pre>def safe_ai_extraction(document_text: str, doc_source: str):<br>    try:<br>        result = llm_extract(document_text)<br>        return result</pre><pre>    except Exception as e:<br>        # Log like a senior dev - include ALL context<br>        logger.error(<br>            f&quot;AI extraction failed\\n&quot;<br>            f&quot;Document source:{doc_source}\\n&quot;<br>            f&quot;Document length:{len(document_text)} chars\\n&quot;<br>            f&quot;Document preview:{document_text[:200]}...\\n&quot;<br>            f&quot;Error type:{type(e).__name__}\\n&quot;<br>            f&quot;Error message:{str(e)}\\n&quot;<br>            f&quot;Traceback:{traceback.format_exc()}\\n&quot;<br>            f&quot;Timestamp:{datetime.now().isoformat()}&quot;<br>        )</pre><pre>        # Store failed doc for manual review<br>        with open(f&quot;failed_docs/{doc_source}_{datetime.now().timestamp()}.txt&quot;, &quot;w&quot;) as f:<br>            f.write(document_text)</pre><pre>        # Return a safe default (not None!)<br>        return {<br>            &quot;status&quot;: &quot;failed&quot;,<br>            &quot;error&quot;: str(e),<br>            &quot;document_source&quot;: doc_source<br>        }</pre><p>In Java, you’d throw. In AI, you <em>can’t</em> throw — you need to return something that won’t crash the next step.</p><h3>The Golden Rules I Learned (The Hard Way)</h3><p>After 47 crashes on 100 documents, I distilled everything into one rule:</p><p><strong>“In Java, exceptions mean your code is wrong. In AI, exceptions mean the world is messy.”</strong></p><p>You can’t fix the world. You can only build systems that survive it.</p><p>Here’s my survival checklist for every AI function:</p><ul><li><strong>Validate inputs</strong> (even if they came from another AI)</li><li><strong>Catch specific exceptions</strong> (JSONDecodeError, Timeout, RateLimit)</li><li><strong>Implement retries</strong> (with exponential backoff)</li><li><strong>Have fallbacks</strong> (simpler prompt, default values, human review queue)</li><li><strong>Log with context</strong> (document ID, length, timestamp, error type)</li><li><strong>Never return None</strong> (return a dict with a “status” field)</li><li><strong>Test with garbage</strong> (empty strings, random text, API errors)</li></ul><p><em>P.S. — The day my Python script processed all 100 documents without a single crash — I felt the same pride as deploying my first stable Java microservice.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33151272eef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>