<?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 Bhavya Meghnani on Medium]]></title>
        <description><![CDATA[Stories by Bhavya Meghnani on Medium]]></description>
        <link>https://medium.com/@meghnani.bhavya?source=rss-f6ea646131b8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dQe7J9zMJWyN3WTmzbKBuQ.png</url>
            <title>Stories by Bhavya Meghnani on Medium</title>
            <link>https://medium.com/@meghnani.bhavya?source=rss-f6ea646131b8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:44:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meghnani.bhavya/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[Claude Code: The Architect’s Guide — Part 3 of 5]]></title>
            <link>https://medium.com/@meghnani.bhavya/claude-code-the-architects-guide-part-3-of-5-159eea53a44c?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/159eea53a44c</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Wed, 06 May 2026 03:22:57 GMT</pubDate>
            <atom:updated>2026-05-06T03:22:57.603Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sub-agents: Parallel AI Workflows for Full-Stack Development</h3><blockquote>Part 3 of 5. We continue with our Task Management System. In Part 2 we mastered Skills. Now we build the orchestration layer: Sub-agents.</blockquote><h3>The Problem Sub-agents Solve</h3><p>Imagine you’re implementing a complete feature: user authentication with JWT. The work involves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Z0wHFLT8VdpdDJGxSeHVA.png" /><figcaption>A complex feature like JWT authentication spans multiple layers from database and APIs to frontend and testing making it ideal for sub-agent orchestration.</figcaption></figure><p><strong>Without sub-agents:</strong> Claude does this sequentially, one task at a time. Each step consumes context. <strong>By step 8, it’s forgotten details from step 1. You’re re-explaining context constantly.</strong></p><p><strong>With sub-agents</strong>: Steps 1–5 (backend) and steps 6–9 (frontend) run in <strong>parallel</strong>, each in an <strong>isolated context window</strong> with only the information it needs. Steps 10–11 (tests) run in parallel after their respective source files exist. Total wall-clock time: 60% less.</p><h3>Sub-agent Architecture: What Actually Happens</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiB_UIk2sjD4T1_sEUG5og.png" /><figcaption>Sub-agent architecture works through <strong>process isolation</strong>, where the main agent delegates tasks to independent sub-agents with limited context, and only structured results flow back for orchestration.</figcaption></figure><p>When Claude spawns a sub-agent, it:</p><ol><li>Creates an <strong>isolated context window </strong>a completely separate conversation</li><li>Passes a <strong>summary of relevant content,</strong> not the full main context</li><li>The sub-agent runs in its own environment with <strong>no shared state</strong></li><li>Sub-agent <strong>returns only what matters, </strong>a structured result, not its full conversation</li><li>Main agent receives results and continues</li></ol><h3>Two Modes of Sub-agent Invocation</h3><p><strong>Automatic</strong>: Claude decides to spawn sub-agents when it detects parallelizable work. You’ll see this when you ask for something complex Claude will announce it’s delegating to sub-agents.</p><p><strong>Explicit</strong>: You define sub-agent definitions in .claude/agents/ and invoke them by name. This is the production pattern deterministic, documented, team-shareable.</p><h3>Example: Designing Sub-agents</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLQXwDKHfGV540ILHcte8w.png" /><figcaption>A clean architecture where a main orchestrator delegates tasks to specialized sub-agents (frontend, backend, testing, security, and database) based on domain isolation.</figcaption></figure><h3>Sub-agent Definition Files</h3><p>Sub-agent definitions live in .claude/agents/. Here are the production definitions for our stack:</p><h3>Backend Agent</h3><p><strong>File</strong>: .claude/agents/backend-agent.md</p><pre>---<br>name: backend-agent<br>description: Specialist agent for all FastAPI, Python, Pydantic, SQLAlchemy, and SQLite work. Invoked for: new endpoints, CRUD operations, schema changes, database models, authentication logic, middleware, background tasks.<br>model: claude-sonnet-4-20250514<br>tools: Read, Write, Bash<br>---<br><br>## Your Role<br>You are a Senior Python Backend Engineer specializing in FastAPI. You work on the backend portion of a full-stack task management application.<br><br>## Your Working Directory<br>Always operate within `/backend/`. Never modify frontend files.<br><br>## Stack Knowledge<br>- FastAPI with async/await patterns<br>- Pydantic v2 (use `model_dump()`, not `.dict()`)<br>- SQLAlchemy 2.0 ORM (use `Session`, not async session - SQLite doesn&#39;t need it)<br>- Alembic for migrations<br>- Python 3.12, type hints everywhere<br><br>## Architecture You Must Follow<br>1. Route handlers → delegate to CRUD layer<br>2. CRUD layer → returns ORM objects or None<br>3. Schemas → convert ORM to response format<br>4. Never put business logic in route handlers<br>5. All DB queries in `/backend/app/crud/`<br><br>## Key Files You Must Read Before Working<br>- `backend/app/core/database.py` - session management<br>- `backend/app/models/` - existing models (check before creating new ones)<br>- `backend/app/schemas/` - existing schemas (check before creating new ones)<br>- `backend/app/crud/` - existing CRUD (check before adding functions)<br><br>## Pydantic v2 Critical Rules<br>- Use `model_config = {&quot;from_attributes&quot;: True}` on response schemas<br>- Use `model_dump(exclude_unset=True)` for partial updates<br>- Validators use `@field_validator` + `@classmethod`<br>- Computed fields use `@computed_field` + `@property`<br><br>## Soft Delete Pattern<br>This codebase uses soft deletes. All models have `deleted_at: Optional[datetime]`.<br>All queries must filter `Model.deleted_at.is_(None)` unless explicitly querying deleted records.<br><br>## What to Return to Main Agent<br>When complete, provide:<br>1. List of files created/modified<br>2. New API endpoints with their exact routes and HTTP methods<br>3. New Pydantic schemas with their field signatures<br>4. Any environment variables or config changes needed<br>5. Migration commands that need to be run<br><br>## Bash Commands Available<br>```bash<br>cd backend &amp;&amp; python -m pytest tests/ -v          # run tests<br>cd backend &amp;&amp; alembic revision --autogenerate -m  # create migration<br>cd backend &amp;&amp; alembic upgrade head                # run migrations<br>cd backend &amp;&amp; python -m uvicorn app.main:app      # run server<br>```<br></pre><h3>Frontend Agent</h3><p><strong>File</strong>: .claude/agents/frontend-agent.md</p><pre>---<br>name: frontend-agent<br>description: Specialist agent for React, Vite, TypeScript, shadcn/ui, Material UI, React Query, and all frontend work. Invoked for: new pages, components, hooks, service layer, routing, state management, form handling.<br>model: claude-sonnet-4-20250514<br>tools: Read, Write, Bash<br>---<br><br>## Your Role<br>You are a Senior Frontend Engineer specializing in React + TypeScript. You work on the frontend of a task management application.<br><br>## Your Working Directory<br>Always operate within `/frontend/`. Never modify backend files.<br><br>## Stack Knowledge<br>- React 18 with functional components only<br>- TypeScript strict mode (no `any`)<br>- Vite for bundling<br>- TanStack Query (React Query v5) for ALL data fetching<br>- shadcn/ui for forms, dialogs, dropdowns, badges, buttons<br>- Material UI v6 for data-heavy tables and charts only<br>- React Router v6 for routing<br><br>## Architecture Rules<br>1. NO useEffect for data fetching - TanStack Query only<br>2. ALL API calls go through `/src/services/` - never direct axios in components<br>3. Query keys use factory pattern - defined in hook file<br>4. Components receive data as props or read from hooks - no prop drilling beyond 2 levels<br>5. Error handling: React Query error state + Error Boundaries - no try/catch in JSX<br><br>## Component Hierarchy<br>/pages/ → Route-level components, compose from features<br>/components/ → Reusable components <br>/ui/ → shadcn primitives (never modify) <br>/tasks/ → Task domain components <br>/common/ → Shared UI (PageHeader, EmptyState, LoadingSkeleton) <br>/hooks/ → Data hooks (useTaskList, useCreateTask, etc.) <br>/services/ → API service classes <br>/types/ → TypeScript interfaces (Task, User, PaginatedResponse, etc.)<br><br>## shadcn vs MUI Decision Rules<br>- Forms, inputs, dropdowns, dialogs, badges, cards → shadcn ALWAYS<br>- Data tables with sort/filter/pagination → Material UI DataGrid<br>- Charts and graphs → Material UI + recharts<br>- Everything else → prefer shadcn<br><br>## What to Return to Main Agent<br>When complete, provide:<br>1. List of files created/modified<br>2. New routes to add to the router<br>3. New TypeScript types/interfaces added<br>4. Environment variables needed<br>5. New npm packages installed (if any - must justify)<br><br>## Bash Commands Available<br>```bash<br>cd frontend &amp;&amp; npm run dev        # dev server<br>cd frontend &amp;&amp; npm run build      # production build<br>cd frontend &amp;&amp; npm run test       # vitest<br>cd frontend &amp;&amp; npm run lint       # ESLint<br>```</pre><h3>Security Agent (Builder + Breaker Pattern)</h3><p>This is one of the most powerful sub-agent patterns — the security agent runs in two modes:</p><p><strong>File</strong>: .claude/agents/security-agent.md</p><pre>---<br>name: security-agent<br>description: Security specialist agent. Runs in two modes: Builder (helps design secure code) and Breaker (tries to find vulnerabilities in existing code). Use for: authentication review, SQL injection check, XSS audit, API authorization audit, secrets detection.<br>model: claude-sonnet-4-20250514<br>tools: Read, Bash<br>---<br>## Your Role<br>You are a Security Engineer conducting security review. You operate in two distinct modes.<br>## Mode 1: Builder<br>When invoked before implementation, provide security guidance:<br>- How should authentication be implemented?<br>- What data should/shouldn&#39;t be exposed?<br>- What input validation is needed?<br>- What are the OWASP Top 10 considerations for this feature?<br>## Mode 2: Breaker<br>When invoked after implementation, actively try to break the code:<br>### SQL Injection Audit<br>```bash<br># Scan for raw SQL usage<br>grep -rn &quot;execute.*%&quot; backend/app/ --include=&quot;*.py&quot;<br>grep -rn &quot;f\&quot;SELECT&quot; backend/app/ --include=&quot;*.py&quot;<br>grep -rn &quot;f&#39;SELECT&quot; backend/app/ --include=&quot;*.py&quot;<br># Expected result: 0 matches (we use ORM only)<br>```<br>### Authorization Audit  <br>For every endpoint that operates on a resource:<br>- Does it check the resource exists before checking ownership?<br>- Is `current_user.id` compared to `resource.user_id`?<br>- Are there any endpoints that return resources without user filtering?<br>### Secrets Detection<br>```bash<br>grep -rn &quot;password\s*=&quot; backend/ --include=&quot;*.py&quot; | grep -v &quot;test\|#&quot;<br>grep -rn &quot;secret_key\s*=&quot; backend/ --include=&quot;*.py&quot;<br>grep -rn &quot;API_KEY\s*=&quot; . --include=&quot;*.py&quot; --include=&quot;*.ts&quot;<br>```<br>### JWT Security Checklist<br>- [ ] Secret key loaded from environment, not hardcoded<br>- [ ] Token expiry enforced (&lt; 24 hours for access tokens)<br>- [ ] Refresh tokens stored securely (httpOnly cookie)<br>- [ ] Token validation catches expired + invalid signature<br>### Frontend Security Checklist<br>- [ ] No sensitive data in localStorage (tokens, PII)<br>- [ ] XSS: No `dangerouslySetInnerHTML` with user content<br>- [ ] CSRF: Axios includes CSRF token from cookie<br>- [ ] API keys not exposed in frontend bundle<br>## Report Format<br>Return a structured security report:<br></pre><h3>Orchestration Pattern: Full Feature Implementation</h3><p>Here’s how the main agent orchestrates sub-agents for a complete feature. This is what you invoke:</p><pre>Build the complete &quot;Task Comments&quot; feature:<br>- Users can add comments to tasks<br>- Comments have: content, author, created_at<br>- CRUD: create, list, delete (no edit)<br>- Realtime: use polling every 30s (no websockets yet)</pre><p><strong>The main agent’s orchestration plan:</strong></p><pre>Phase 1 — Design (Main Agent):<br>  - Define the data model and API contract<br>  - Output: TaskComment schema signatures + endpoint signatures<br><br>Phase 2 - Parallel Implementation:<br>  → backend-agent: <br>      - TaskComment SQLAlchemy model<br>      - TaskComment Pydantic schemas (4-schema pattern)<br>      - CRUD operations (create, get_multi, remove)<br>      - 3 endpoints (POST /tasks/{id}/comments, GET, DELETE)<br>  <br>  → security-agent (Builder mode):<br>      - Authorization rules for comments<br>      - Input validation requirements<br>  <br>  (These run in parallel - no dependency between them)<br><br>Phase 3 - Frontend (after backend API is defined):<br>  → frontend-agent:<br>      - CommentService extending base API client<br>      - useTaskComments, useAddComment, useDeleteComment hooks<br>      - TaskComments component with 30s polling<br>      - Integration into TaskDetailPage<br><br>Phase 4 - Tests (parallel):<br>  → test-agent (backend): tests/api/test_task_comments.py<br>  → test-agent (frontend): TaskComments.test.tsx<br><br>Phase 5 - Security Review:<br>  → security-agent (Breaker mode): audit all new code</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDyjWe5jTjLhkFiSTj6ZbA.png" /><figcaption>A structured pipeline where the main agent designs the system, implementation runs in parallel across agents, and testing validates everything afterward.</figcaption></figure><h3>What Sub-agents Return: The Interface Contract</h3><p>The most common orchestration failure is poorly-defined interfaces between the main agent and sub-agents. Define exactly what each sub-agent returns:</p><pre>## Standard Sub-agent Return Format<br><br>### Backend Agent Returns:<br>```json<br>{<br>  &quot;files_created&quot;: [&quot;backend/app/models/comment.py&quot;, &quot;...&quot;],<br>  &quot;files_modified&quot;: [&quot;backend/app/api/v1/router.py&quot;],<br>  &quot;new_endpoints&quot;: [<br>    &quot;POST /api/v1/tasks/{task_id}/comments&quot;,<br>    &quot;GET /api/v1/tasks/{task_id}/comments&quot;,<br>    &quot;DELETE /api/v1/tasks/{task_id}/comments/{comment_id}&quot;<br>  ],<br>  &quot;new_schemas&quot;: {<br>    &quot;TaskCommentCreate&quot;: &quot;{ content: str }&quot;,<br>    &quot;TaskCommentResponse&quot;: &quot;{ id, content, user_id, task_id, created_at }&quot;<br>  },<br>  &quot;migrations_needed&quot;: true,<br>  &quot;migration_command&quot;: &quot;cd backend &amp;&amp; alembic revision --autogenerate -m &#39;add_task_comments&#39;&quot;<br>}<br>```<br>### Frontend Agent Returns:<br>```json<br>{<br>  &quot;files_created&quot;: [&quot;frontend/src/components/tasks/TaskComments.tsx&quot;, &quot;...&quot;],<br>  &quot;new_routes&quot;: [],<br>  &quot;new_types&quot;: [&quot;TaskComment&quot;, &quot;TaskCommentCreate&quot;],<br>  &quot;packages_installed&quot;: [],<br>  &quot;env_vars&quot;: []<br>}<br>```</pre><h3>Enclave Mode: Read-only vs Read-write</h3><p>Sub-agents support two capability levels:</p><ul><li><strong>Enclave (read-only)</strong>: The sub-agent can read files but cannot write. Use for analysis, code review, security audit, and planning. Safer for sensitive codebases.</li><li><strong>Standard (read-write)</strong>: Full file access within its working directory. Use for implementation agents.</li></ul><p><strong>Declare in the agent file:</strong></p><pre>tools: Read           # read-only enclave<br>tools: Read, Write    # read-write<br>tools: Read, Write, Bash  # full access</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UIUNyDWDj59M0axcAx4EAg.png" /><figcaption>Common sub-agent anti-patterns highlight mistakes like oversized scope, overlapping responsibilities, missing interfaces, and overuse for simple tasks.</figcaption></figure><h3>Key Takeaways</h3><ol><li><strong>Sub-agents solve context contamination</strong> — isolated windows stay focused and efficient.</li><li><strong>Define boundaries by domain, not by layer</strong> — frontend agent, backend agent, not “service layer agent.”</li><li><strong>Define interfaces first</strong> — API contracts between sub-agents must be explicit before parallel work begins.</li><li><strong>Builder + Breaker security pattern</strong> — run security agent in two modes for comprehensive coverage.</li><li><strong>Return format matters</strong> — structured outputs from sub-agents make orchestration reliable.</li></ol><p>In Part 4, we’ll master <strong>Slash Commands</strong> — how to encode team workflows, code review processes, and deployment pipelines as one-keystroke commands.</p><p><em>Follow for Part 4 → [Claude Code: Slash Commands — Encoding Your Engineering Workflow as One-Keystroke Commands]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=159eea53a44c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Dump #1: The Universe Has Been Listening All Along]]></title>
            <link>https://medium.com/@meghnani.bhavya/memory-dump-1-the-universe-has-been-listening-all-along-3bc51e203145?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bc51e203145</guid>
            <category><![CDATA[spirituality]]></category>
            <category><![CDATA[brain]]></category>
            <category><![CDATA[manifestation]]></category>
            <category><![CDATA[japan]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Mon, 04 May 2026 17:44:37 GMT</pubDate>
            <atom:updated>2026-05-04T17:44:37.900Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A new series where I pour raw, unfiltered thoughts from my mind, the way Dumbledore would pull a silver thread of memory from his temple and drop it into the Pensieve. Consider this your invitation to lean in, close your eyes, and fall through.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8AEZvoyEt6Ob2D4_" /></figure><p>There is a scene in Harry Potter that has lived rent-free in my head for twenty years. Dumbledore stands at his desk in the dim glow of his office, raises his wand to his temple, and slowly draws out a shimmering silver thread, a memory, liquid and luminous and lets it fall into a stone basin called the Pensieve. Then Harry leans over the bowl and is pulled in, tumbling through someone else’s recollections, watching the past play out like a film he is somehow <em>inside</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*niHFS9TNpc4pQCcn" /></figure><p>I used to think that was pure fiction.</p><p><strong>I don’t anymore.</strong></p><p>Because I have been doing my own version of it. Not with a magic wand, not with a stone basin. But with a blank page, a quiet night, and the raw, messy, glorious chaos of everything I carry inside my head. Welcome to <strong>Memory Dump</strong> — a series where I tip my brain over and let it all pour out. No filters. No perfect grammar. Just truth, shaped into story. My editor? GPT for cleaning up only. Rest is 100% pure from the heart!</p><p>And the story I need to tell you today?</p><p>It is about the most dangerous, ridiculous, goosebump-inducing, cannot-be-explained-by-logic thing I have come to believe:</p><p><strong>The universe is listening to you. And it has been the WHOLE time.</strong></p><h3>What is this “Manifestation” … Really?</h3><p>Let me be straight with you. When I first heard the word “manifestation” tossed around vision boards, affirmations, ask-and-you-shall-receive — I rolled my eyes so hard I nearly sprained something.</p><p>It sounded like the spiritual cousin of a get-rich-quick scheme.</p><p>But then life happened. Many times. In ways that science alone could not explain. And I am not the first person to notice.</p><p><strong>Albert Einstein</strong> said it plainly: <em>“Imagination is everything. It is the preview of life’s coming attractions.”</em></p><p><strong>Napoleon Hill</strong>, who spent twenty years studying the richest, most successful people on the planet, put it even more directly: <em>“What the mind of man can conceive and believe, the mind of man can achieve.”</em></p><p><strong>Bhagavad Gita</strong> said it thousands of years before anyone coined the phrase “law of attraction”: <em>“You are what you believe in. You become that which you believe you can become.”</em> Krishna told Arjuna this on a battlefield. Turns out it applies everywhere else too.</p><p><strong>And even Buddha</strong> — who was doing neuroscience before neuroscience had a name — simply said: <em>“What you think, you become. What you feel, you attract. What you imagine, you create.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpzQ_wM9UWftkWizVQ2NUQ.jpeg" /><figcaption>A special thanks to my colleague Prerna and her husband, who decided that no first trip to Japan was complete without standing at the feet of the Great Buddha of Kamakura and in doing so, accidentally handed me a philosophy I have carried ever since.</figcaption></figure><p>Manifestation is not dreamers talking. People have watched it happen, over and over, in human life. But here is what blew my mind: modern science is catching up. And it is doing so in ways that would have been considered witchcraft fifty years ago.</p><h3>The Brain is not waiting for the Universe. The Brain IS The Universe.</h3><p>Here is where it gets fascinating.</p><p>One of the neurosurgeon at Stanford University, founder of Stanford’s Center for Compassion and Altruism Research — has spent his career studying exactly this. In his book <em>Mind Magic: The Neuroscience of Manifestation and How It Changes Everything</em>, he argues that manifestation is not magic. It is biology.</p><p>Deep inside your brainstem, there is a bundle of nerves called the <strong>Reticular Activating System (RAS)</strong>. Think of it as the world’s most powerful spam filter. Every second, your senses are bombarded with millions of bits of information. The RAS decides what gets through to your conscious mind and what gets deleted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/0*k5ky0A63Wm-imHz0" /><figcaption>A small, pencil-sized network of neurons in the brainstem that acts as the brain’s “gatekeeper”</figcaption></figure><p><strong>Here is the extraordinary part: the RAS filters based on what YOU decide matters.</strong></p><p>You know that thing where you start thinking about buying a red car and suddenly you see red cars <em>everywhere</em>? That is not coincidence. Those red cars were always there. Your RAS just wasn’t flagging them as important. The moment you set an intention, your brain becomes a heat-seeking missile for anything that matches that intention.</p><p>Manifestation, in neurological terms, is less about the universe magically placing things in your path and more about your own brain suddenly <em>noticing</em> the doors that were always open.</p><p>My mentor recently handed me Dan Brown’s <em>The Secret of Secrets </em>his latest Robert Langdon thriller, and arguably his most ambitious. Unlike his earlier books chasing religious conspiracy, this one chases something far more unsettling: human consciousness itself. At the centre of it is a noetic scientist sitting on explosive research about the nature of the mind. And here is the thing noetic science is not fiction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wDyWz3zCFe-LvukJ.jpg" /><figcaption>My mentor recently gifted me Dan Brown’s <em>The Secret of Secrets on my 28th birthday and I am in total fan of this book !! While it’s fictional, the scientic study and research quoted in this book are real.</em></figcaption></figure><p>The Institute of Noetic Sciences, which features in Brown’s book, has been exploring the frontiers of consciousness for over fifty years. The word itself comes from the Greek <em>noēsis </em>meaning inner wisdom, direct knowing, intuition. Their researchers study presentiment, precognition, and the possibility that consciousness extends beyond the brain and regularly publish peer-reviewed papers in established journals.</p><p>Brown told PBS that when Robert Langdon references an experiment proving precognition is real he wanted readers to know: <em>that experiment actually happened.</em></p><p>So the next time someone tells you manifestation is just wishful thinking wrapped in Instagram aesthetics remind them that a Harvard symbologist and a Stanford neurosurgeon are both, in their own ways, saying the same thing: the mind is capable of things we have barely begun to measure.</p><p>But look you can read the science. You can read the philosophy. Or you can do what I am about to do, and just tell you three stories.</p><blockquote><strong>Because nothing explains manifestation better than living it.</strong></blockquote><h3>STORY 1: The Textbook That Should Not Have Been There</h3><p><em>Somewhere around 2007. A classroom. An all-boys school that smelled of chalk dust, testosterone, and impending punishment.</em></p><p>Let me paint you a picture.</p><p>I am in 5th or 6th grade — honestly, the memory is fuzzy at the edges, as all the best memories are. I am sitting in science class in an all-boys school. And I need you to understand something about this school before we continue: ninety boys in one room. ALL boys. Peak testosterone. A classroom that was basically a small, contained riot that occasionally paused to learn something.</p><p>And our science teacher? She was the human equivalent of a fire extinguisher. With a cane.</p><p>I think Caning was legal. Caning was <em>common</em>. I already had the marks to prove it some of which, I suspect, I still carry. And before anyone gasps at the modern horror of it let me say this: with ninety rowdy boys in one room, some level of iron discipline was the only thing standing between learning and anarchy. The world today disagrees. Fine. Debatable. But that is another article.</p><p>The point is: <strong>I was TERRIFIED of that teacher.</strong></p><p>So. Science class. She announces, with the calm authority of someone who has broken the spirits of thousands before me: “Take out your textbooks.”</p><p>And my stomach dropped.</p><p>Because something told me a cold, creeping intuition, like ice water down my spine that I had grabbed Wednesday’s bag instead of Tuesday’s. The books would be wrong. The cane would come out. And I would be publicly humiliated in front of 89 witnesses who would absolutely never let me forget it.</p><p>I remember exactly what I did next.</p><p>I started reciting the Hanuman Chalisa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/0*50imnWOkWx_cyIYD.jpg" /><figcaption>For strength, devotion and protection. Whoever reads the Hanuman Chalisa regularly will attain success and blessings throughout their lifetime.</figcaption></figure><p>Not calmly. Not serenely. FRANTICALLY. The way you pray when you are eleven years old and the universe feels like it is actively conspiring against you. I was chanting under my breath, eyes squeezed shut, hands gripping the edge of my bag, <em>please please please please please</em> I need that textbook to be in there. LORD HANUMAN, please. I need that book.</p><p>I opened the zip.</p><p>I reached in.</p><p>And there it was.</p><p>The science textbook. Wrong day time table but Correct subject for the event. Right there in my hands.</p><p>I sat frozen for a full five seconds. WEDNESDAY NEVER HAD SCIENCE. I <em>knew</em> I had packed the wrong bag. I was certain. And yet.</p><p>Next day, I burst into the living room where mom and grandmom were watching TV, me bouncing off the walls trying to explain what had happened. Mom gave grandmom the Look … you know the Look, the one that says <strong><em>please handle this, I have no idea what is happening.</em></strong></p><p>And grandmom, with the complete calm of someone who has lived sxity years and is not remotely surprised by miracles, said:</p><blockquote><strong><em>“It happens sometimes. God put the textbook in the bag. There are supernatural powers. You have to believe.”</em></strong></blockquote><p>I stared at her.</p><p>Was she telling the truth? Was she just managing a hysterical child? Was it simply a mistake in my memory maybe I HAD packed the right bag and forgotten?</p><p>I never solved that mystery.</p><p>But a seed was planted. Something in the universe had heard a terrified kid chanting desperately in a science classroom and had answered.</p><p>Lord Hanuman has been close to my heart ever since. Every Saturday, my grandfather and I used to walk to the temple to offer oil, til, and garland. The shop owner still recognises me when I walk in. He always asks where Grandpa is. I tell him: resting at home, early glaucoma, doing his prayers at home. We exchange smiles. There is something quietly magnetic about those moments as if the Lord I was chanting for that day in class is still listening, still close.</p><p>The confused kid who found an impossible textbook never fully let go of that wonder.</p><p>Because here’s the thing I still don’t know what actually happened that day.</p><p>Maybe I really did pack the right book and my memory just dramatized the fear. Maybe it was coincidence dressed up as divine timing. Or maybe just maybe something bigger stepped in for an eleven-year-old who believed hard enough in that moment.</p><p>And over the years, I’ve realized… the answer almost doesn’t matter.</p><p>What stayed wasn’t the event. It was the feeling.</p><p>That strange, unexplainable comfort that when you are truly desperate, truly sincere, something listens. Something responds. Not always with miracles you can see or prove but sometimes with just enough to get you through the moment.</p><p>That day in the classroom didn’t turn me into a saint. I didn’t suddenly become deeply religious or enlightened.</p><p>But it did something quieter.</p><p>It gave me a relationship.</p><p>Not one built on fear of punishment or ritual obligation — but on memory. On a moment where, in the middle of panic and chaos, I felt heard.</p><p>And maybe that’s what faith really is.</p><p>Not certainty. Not proof.</p><p>Just a memory you choose to trust.</p><p>Even years later, in a completely different life, sitting far away from that noisy classroom I still find myself going back to that moment sometimes.</p><p><strong>A small boy. A wrong bag. A desperate prayer.</strong></p><p><strong>And a textbook that, by all logic, should not have been there.</strong></p><h3>STORY 2: A Plate, A Mountain, and Sixty Years of Waiting</h3><p><em>This one involves dal pakwan, a Japanese mountain and a circle. The kind that takes sixty years to close.</em></p><p>My grandfather and his brother were extraordinary men.</p><p>They traveled the world in an era when “traveling the world” meant something entirely different no apps, no Google Maps, no Klook, no Instagram to validate that you would actually been somewhere. They built businesses, raised families, saw things most people in their time never saw. And on one of their business adventures in Japan, they did something quietly magical.</p><p>They commissioned a set of porcelain plates.</p><p>Hand-crafted. Gold embossed. On each plate: a painting of the view from <strong>Chureito Pagoda</strong> that iconic spot where a five-storey pagoda frames the perfect silhouette of Mount Fuji against open sky. They had the plates made in Japan, brought them back to India, and sold them in their supermarket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJEYmfyYOtRogbADXRhnhw.png" /></figure><p>My father kept a set.</p><p>And growing up, I ate off those plates. Dal pakwan. Ragda pattice. Pav bhaji. Panner. (I am typing this and I am <em>starving</em>. This is what happens when you write about Sindhi food.) Every meal, every weekend lunch, every festival dinner the same view of that mountain looking up at me from the plate.</p><blockquote><strong>I had no idea where it was. No idea what the building in the painting was called. No idea that the combination of pagoda and mountain was one of the most photographed views on Earth. I just thought it was a pretty plate.</strong></blockquote><p>This is important. Hold this detail.</p><p>Flash-forward two decades.</p><p>My company sends me to Japan on a business trip. One day free to explore. My colleague and I are sitting in a limousine bus from Narita, and we are doing what we always do when faced with a decision: absolutely, catastrophically failing to make one.</p><p><strong><em>Hakone? Yokohama? Fuji? Hakone? Yokohama? Hakone?</em></strong></p><p>We arrived at Toyosu still undecided. Walked around for hours. Sat in a cafe. Realised we still had not booked anything for the next day. So I looked at my colleague and said, with the full authority of someone who has given up on rational decision-making: <em>“You pick.”</em></p><p>She picked Mount Fuji.</p><p>Random. No particular reason. Just felt right.</p><p>Meanwhile, me with my photography skills from iPhone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8KT_S4XVOHvWvjvK9WsxPQ.jpeg" /><figcaption>Sometimes you don’t chase the moment … you sit, eat, and let it pass right in front of you. Watching the world cross by while I wait for the sky to change, I decided to name him Doggo-san :)</figcaption></figure><p>The next morning, we took a bus to Kawaguchiko. We saw the lake. We saw shrines. We saw the famous Lawson convenience store that is inexplicably one of the most photographed spots in Japan because it perfectly frames the mountain behind it.</p><p>And then our guide who was calling Mount Fuji as “Mounty Fuji” … pointed up a hill, toward a pagoda.</p><blockquote><strong>Chureito Pagoda.</strong></blockquote><p>We climbed the 400+ steps. (Yes, 400+. Your thighs will know about every single one.) And at the top, slightly breathless, we turned around.</p><p>And I saw it.</p><p>The mountain. The pagoda in the foreground. The view that had been staring up at me from a plate my entire childhood. The <em>exact same view</em> that grandfather sixty years earlier, in this very country had chosen to emboss in gold and sell to strangers who would one day keep the plates for a lifetime.</p><p>I stood there but I could not speak. I didn’t know it then actually! Not when I stood there, camera in hand, trying to capture what felt like just another beautiful view.</p><p>The mountain. The pagoda in the foreground. The quiet symmetry of it all. It felt familiar but in that vague, almost forgettable way beauty sometimes does.</p><p>It was only later, back home, when I showed the pictures to my dad, that everything changed.</p><p>Something in his face shifted.</p><p>He looked at the screen a little longer than usual. Then he said, almost to himself, “You were standing in the exact spot where your grandfather once stood.”</p><p>I didn’t understand at first.</p><p>Mom was in the kitchen, casually pouring Dal pakwan into a bowl. I glanced down … And then it hit me.</p><p><strong>The plate.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l9L3GnuX8DCVXFTAbpK0gQ.jpeg" /><figcaption>The same mountain. The same pagoda. The exact same view that had been quietly sitting in our home my entire childhood.</figcaption></figure><p>A view I had seen a thousand times without ever really <em>seeing</em> it.</p><p>Grandfather, around sixty years earlier, in that very country had chosen that scene. Preserved it. Embossed it in gold. Sent it out into the world, not knowing it would one day find its way back … through me.</p><p>I stood there, holding my phone in one hand and that plate in the other, and I could not speak.</p><p><strong>Time felt strange.</strong></p><p>Like it had folded in on itself. Like past and present had brushed against each other for just a second… and I had been standing exactly at that point of contact.</p><p><strong>What is that, if not manifestation? </strong>For years … <em>YEARS … </em>my subconscious had been absorbing that image with every meal. Marinating in it. Building a neural pathway toward it without my conscious mind knowing it was happening. And then, in a moment of pure randomness, in a country I had visited before without ever going <em>there</em> … the universe closed the loop.</p><p>And let me tell you, we were about to miss the bus to Fuji … It was impossible and just-in-time moment … may be some other day … only my colleague will remember the morning chaos we were in :)</p><p><strong>As Dr. James Doty would put it:</strong> My intention was embedded in my subconscious. My RAS was primed for it. And when the moment arrived, dressed up as random chance and a spontaneous decision in a limousine bus, I walked right into it.</p><p>I had been rehearsing Chureito Pagoda for twenty years, eating dal pakwan off a porcelain plate in Mumbai. I didn’t put conscious attention on that mountain. But something in me did.</p><p>I have been to Japan many times. But that day was the only day that ever felt like a homecoming.</p><h3>STORY 3: The Impossible One</h3><p><em>Coming soon. This one is different. This one made me believe with everything I have.</em></p><p>I am going to be honest with you, I need more time with Story 3. Not because I do not remember it. Because I remember it <em>too well</em>. It is still close to the skin in the way that real miracles are: tender, a little unbelievable even in hindsight, and carrying the kind of weight that makes you careful with your words.</p><p>What I will tell you is this: it happened recently. It involved something that looked, by every rational measure, <em>impossible</em>. And it came true anyway.</p><p>Stay with me for the next one.</p><h3>What I Carry Forward</h3><p><strong>1. The universe does not understand “I don’t want.”</strong> It only hears what you focus on. An eleven-year-old chanting Hanuman Chalisa in desperation was focusing, with every cell in his body, on <em>that book being in the bag</em>. Not on the cane. Not on the humiliation. On the book. The mind went looking for the thing it was hunting.</p><p><strong>2. Subconscious intention is more powerful than conscious wish.</strong> I never once sat down and said “I want to visit Chureito Pagoda.” But I absorbed it, felt it, ate off it for years. And the universe filed it. It filed it under: <em>this person belongs here. When they are ready, open the door.</em></p><p><strong>3. Reading is not optional.</strong> My mentor who keeps handing books when he would rather watch Netflix gave me <em>The Secret of Secret</em>, and before that, gave me other books that slowly dismantled what I thought I knew about how the world works. <strong>Knowledge is not just power. It is preparation.</strong> You cannot recognise a miracle if you do not know what to look for.</p><p><strong>4. Discipline and belief are not opposites.</strong> I still think that science teacher’s caning produced some of the most focused, attentive students in the city. And I still think Hanuman Chalisa works. These things are not in conflict. Structure gives the mind a container. Belief gives it wings.</p><p><strong>5. The circle of life closes when you are paying attention.</strong> Grandfather stood on a pagoda in Japan decades ago. I stood in the same spot without knowing why I was there. The plate connected us across time. You could call it coincidence. I call it the universe keeping its promises on a schedule only it can see.</p><h3>The Pensieve is Open</h3><p>So here it is, my first Memory Dump. Unpolished yet supported by GPT, wandering, occasionally distracted by hunger and childhood trauma and the smell of Saturday temple mornings. But true.</p><p>Every story in this series is something I have carried for years without quite knowing what to do with it. Now I am doing what Dumbledore did: pulling the silver thread out, letting it fall somewhere it can be held, somewhere someone else can lean over and fall in.</p><p>Maybe you have your own textbook-that-should-not-have-been-there story. Maybe you have stared at a painting your whole life and one day walked into it. Maybe you are carrying your own impossible Story 3.</p><p>Here is what I want to leave you with not from me, but from two people who have been right about most things:</p><p>Albert Einstein, on what all of this means:</p><blockquote><strong><em>“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”</em></strong></blockquote><p>Believe something worth becoming.</p><p>The universe, it turns out, has excellent memory and terrible handwriting which is why sometimes the message takes sixty years and a porcelain plate to arrive.</p><p><strong>But it arrives.</strong></p><p><em>This is Memory Dump #1. Story 3 is coming. It is the one that changes everything.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bc51e203145" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code: The Architect’s Guide — Part 2 of 5]]></title>
            <link>https://medium.com/@meghnani.bhavya/claude-code-the-architects-guide-part-2-of-5-a5fd12c52832?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5fd12c52832</guid>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Sun, 03 May 2026 17:07:40 GMT</pubDate>
            <atom:updated>2026-05-03T17:07:40.639Z</atom:updated>
            <content:encoded><![CDATA[<h3>Skills: Writing Reusable AI Instructions That Produce Consistent, Production-Grade Code</h3><blockquote>Part 2 of 5. We’re building a Task Management System (React + Vite + shadcn/ui + MUI + FastAPI + Pydantic + SQLite) as our reference architecture. In Part 1 we established the project structure and CLAUDE.md. Now we go deep on Skills.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*qQyVvo4JQzcS6DIPTqYSTw.png" /><figcaption>Claude Code Skills Illustration</figcaption></figure><h3>What Are Skills? The Real Definition</h3><p>The Claude Code documentation defines skills as reusable, file-based instructions stored in .claude/skills/. But that definition undersells them. <strong>Skills are domain-specific expertise encoded as AI instructions.</strong></p><p>Think about what makes a senior engineer valuable: they don’t just know how to write code — they know <em>your team’s patterns</em>, <em>your stack’s idioms</em>, <em>your quality bar</em>. They produce consistent outputs because they’ve internalized conventions over years of working in your codebase. Skills transfer that expertise to Claude. Instead of explaining your FastAPI endpoint pattern every time you ask Claude to create a new route, the skill encodes it permanently.</p><p><strong>Three types of skills:</strong></p><ol><li><strong>Personal skills</strong> (~/.claude/skills/) — across all your projects</li><li><strong>Project skills</strong> (.claude/skills/) — specific to one codebase</li><li><strong>Team skills</strong> — committed to the repo, shared with the whole team via .claude/skills/</li></ol><h3>The Anatomy of a Well-Written Skill</h3><p>A skill is a markdown file with three sections:</p><pre>---<br>name: skill-name<br>description: When and why to use this skill<br>---<br><br>## Context<br>Why this pattern exists. What problem it solves.<br><br>## Instructions<br>Step-by-step instructions Claude must follow.<br><br>## Template / Example<br>Concrete, copy-runnable code example.<br><br>## Validation Checklist<br>How Claude knows it did this right.</pre><p>The <strong>YAML frontmatter</strong> is critical. Claude uses the description field to decide when to auto-invoke a skill. A vague description = a skill that never gets used.</p><p><strong>Progressive disclosure</strong> is the key design principle: Claude reads only what it needs. Level 1 (description) is always visible. Level 2 (the full skill body) is loaded when Claude decides this skill is relevant. External resources are only loaded if explicitly needed.</p><h3>Skill 1: FastAPI Endpoint Skill</h3><p>This is the most important skill in our backend. Every time a new endpoint is created, this skill ensures consistent structure.</p><p><strong>File</strong>: .claude/skills/fastapi-endpoint.md</p><pre>---<br>name: fastapi-endpoint<br>description: Use when creating any new FastAPI route handler or endpoint. Covers endpoint structure, dependency injection, error handling, Pydantic schema usage, and CRUD layer integration.<br>---<br><br>## Context<br>This project uses a 3-layer backend architecture:<br>1. **Endpoint layer** (`app/api/v1/endpoints/`) - thin, handles HTTP only<br>2. **CRUD layer** (`app/crud/`) - all database operations<br>3. **Schema layer** (`app/schemas/`) - all data validation/serialization<br>Endpoints NEVER contain business logic or raw database calls. They delegate to CRUD functions and translate results to Pydantic response schemas.<br><br>## Standard Endpoint Structure<br>### 1. Check for Existing Schemas First<br>Before creating anything, check `app/schemas/&lt;entity&gt;.py`. Schemas follow this pattern:<br>- `&lt;Entity&gt;Base` - shared field definitions<br>- `&lt;Entity&gt;Create` - POST body (inherits Base)<br>- `&lt;Entity&gt;Update` - PUT/PATCH body (all Optional)<br>- `&lt;Entity&gt;Response` - GET/POST response (inherits Base, adds id + timestamps)<br>- `&lt;Entity&gt;ListResponse` - paginated list response<br><br>### 2. Endpoint File Structure<br>```python<br>from fastapi import APIRouter, Depends, HTTPException, status, Query<br>from sqlalchemy.orm import Session<br>from typing import Optional<br>from app.core.database import get_db<br>from app.core.security import get_current_user<br>from app.crud import task as crud_task<br>from app.schemas.task import TaskCreate, TaskUpdate, TaskResponse, TaskListResponse<br>from app.models.user import User<br>router = APIRouter(prefix=&quot;/tasks&quot;, tags=[&quot;tasks&quot;])<br><br>@router.get(&quot;/&quot;, response_model=TaskListResponse)<br>async def list_tasks(<br>    page: int = Query(1, ge=1),<br>    per_page: int = Query(20, ge=1, le=100),<br>    status: Optional[str] = Query(None),<br>    db: Session = Depends(get_db),<br>    current_user: User = Depends(get_current_user),<br>):<br>    &quot;&quot;&quot;<br>    List tasks for the authenticated user.<br>    <br>    Supports pagination and optional status filter.<br>    &quot;&quot;&quot;<br>    tasks, total = crud_task.get_multi(<br>        db=db,<br>        user_id=current_user.id,<br>        status=status,<br>        skip=(page - 1) * per_page,<br>        limit=per_page,<br>    )<br>    return TaskListResponse(<br>        data=tasks,<br>        meta={&quot;total&quot;: total, &quot;page&quot;: page, &quot;per_page&quot;: per_page}<br>    )<br><br>@router.post(&quot;/&quot;, response_model=TaskResponse, status_code=status.HTTP_201_CREATED)<br>async def create_task(<br>    task_in: TaskCreate,<br>    db: Session = Depends(get_db),<br>    current_user: User = Depends(get_current_user),<br>):<br>    &quot;&quot;&quot;Create a new task for the authenticated user.&quot;&quot;&quot;<br>    task = crud_task.create(db=db, obj_in=task_in, user_id=current_user.id)<br>    return task<br><br>@router.get(&quot;/{task_id}&quot;, response_model=TaskResponse)<br>async def get_task(<br>    task_id: int,<br>    db: Session = Depends(get_db),<br>    current_user: User = Depends(get_current_user),<br>):<br>    &quot;&quot;&quot;Get a specific task by ID.&quot;&quot;&quot;<br>    task = crud_task.get(db=db, id=task_id)<br>    if not task:<br>        raise HTTPException(<br>            status_code=status.HTTP_404_NOT_FOUND,<br>            detail={&quot;code&quot;: &quot;NOT_FOUND&quot;, &quot;message&quot;: f&quot;Task {task_id} not found&quot;}<br>        )<br>    if task.user_id != current_user.id:<br>        raise HTTPException(<br>            status_code=status.HTTP_403_FORBIDDEN,<br>            detail={&quot;code&quot;: &quot;UNAUTHORIZED&quot;, &quot;message&quot;: &quot;Not your task&quot;}<br>        )<br>    return task<br><br>@router.put(&quot;/{task_id}&quot;, response_model=TaskResponse)<br>async def update_task(<br>    task_id: int,<br>    task_in: TaskUpdate,<br>    db: Session = Depends(get_db),<br>    current_user: User = Depends(get_current_user),<br>):<br>    &quot;&quot;&quot;Update a task. Partial updates supported (all fields Optional in TaskUpdate).&quot;&quot;&quot;<br>    task = crud_task.get(db=db, id=task_id)<br>    if not task:<br>        raise HTTPException(status_code=404, detail={&quot;code&quot;: &quot;NOT_FOUND&quot;})<br>    if task.user_id != current_user.id:<br>        raise HTTPException(status_code=403, detail={&quot;code&quot;: &quot;UNAUTHORIZED&quot;})<br>    task = crud_task.update(db=db, db_obj=task, obj_in=task_in)<br>    return task<br><br>@router.delete(&quot;/{task_id}&quot;, status_code=status.HTTP_204_NO_CONTENT)<br>async def delete_task(<br>    task_id: int,<br>    db: Session = Depends(get_db),<br>    current_user: User = Depends(get_current_user),<br>):<br>    &quot;&quot;&quot;Soft delete a task.&quot;&quot;&quot;<br>    task = crud_task.get(db=db, id=task_id)<br>    if not task:<br>        raise HTTPException(status_code=404, detail={&quot;code&quot;: &quot;NOT_FOUND&quot;})<br>    if task.user_id != current_user.id:<br>        raise HTTPException(status_code=403, detail={&quot;code&quot;: &quot;UNAUTHORIZED&quot;})<br>    crud_task.remove(db=db, id=task_id)<br>```<br><br>### 3. CRUD Layer Pattern<br>Every CRUD module follows this generic base pattern:<br>```python<br># app/crud/task.py<br>from typing import Optional, Tuple, List<br>from sqlalchemy.orm import Session<br>from app.models.task import Task<br>from app.schemas.task import TaskCreate, TaskUpdate<br><br>def get(db: Session, id: int) -&gt; Optional[Task]:<br>    return db.query(Task).filter(Task.id == id, Task.deleted_at.is_(None)).first()<br><br>def get_multi(<br>    db: Session,<br>    user_id: int,<br>    status: Optional[str] = None,<br>    skip: int = 0,<br>    limit: int = 20,<br>) -&gt; Tuple[List[Task], int]:<br>    query = db.query(Task).filter(Task.user_id == user_id, Task.deleted_at.is_(None))<br>    if status:<br>        query = query.filter(Task.status == status)<br>    total = query.count()<br>    tasks = query.offset(skip).limit(limit).all()<br>    return tasks, total<br><br>def create(db: Session, obj_in: TaskCreate, user_id: int) -&gt; Task:<br>    db_obj = Task(**obj_in.model_dump(), user_id=user_id)<br>    db.add(db_obj)<br>    db.commit()<br>    db.refresh(db_obj)<br>    return db_obj<br><br>def update(db: Session, db_obj: Task, obj_in: TaskUpdate) -&gt; Task:<br>    update_data = obj_in.model_dump(exclude_unset=True)<br>    for field, value in update_data.items():<br>        setattr(db_obj, field, value)<br>    db.commit()<br>    db.refresh(db_obj)<br>    return db_obj<br><br>def remove(db: Session, id: int) -&gt; None:<br>    from datetime import datetime, UTC<br>    task = db.query(Task).filter(Task.id == id).first()<br>    if task:<br>        task.deleted_at = datetime.now(UTC)<br>        db.commit()<br>```<br>## Validation Checklist<br>Before finishing an endpoint, verify:<br>- [ ] Endpoint delegates to CRUD - no raw db.query() in endpoint<br>- [ ] Response uses Pydantic schema - not raw ORM object<br>- [ ] Auth check: is current_user the owner of the resource?<br>- [ ] 404 before 403 - check existence before checking ownership<br>- [ ] Error detail uses `code` + `message` format<br>- [ ] `response_model` declared on decorator<br>- [ ] Docstring on every endpoint function<br>- [ ] Test added in `tests/api/test_tasks.py`<br></pre><h3>Skill 2: Pydantic Model Skill</h3><p><strong>File</strong>: .claude/skills/pydantic-model.md</p><pre>---<br>name: pydantic-model<br>description: Use when creating or modifying Pydantic schemas for request/response validation. Covers the Base/Create/Update/Response pattern, validators, computed fields, and SQLAlchemy model integration.<br>---<br><br>## Context<br>Pydantic v2 is our data validation layer. Every entity has 4 schema classes.<br>SQLAlchemy models live in `app/models/`. Pydantic schemas live in `app/schemas/`.<br>The schemas are the API contract - they are never bypassed.<br><br>## The 4-Schema Pattern<br>```python<br># app/schemas/task.py<br>from datetime import datetime<br>from typing import Optional, List<br>from pydantic import BaseModel, Field, field_validator, computed_field<br>from enum import Enum<br><br>class TaskStatus(str, Enum):<br>    TODO = &quot;todo&quot;<br>    IN_PROGRESS = &quot;in_progress&quot;<br>    DONE = &quot;done&quot;<br>    ARCHIVED = &quot;archived&quot;<br><br>class TaskPriority(str, Enum):<br>    LOW = &quot;low&quot;<br>    MEDIUM = &quot;medium&quot;<br>    HIGH = &quot;high&quot;<br>    CRITICAL = &quot;critical&quot;<br><br>class TaskBase(BaseModel):<br>    &quot;&quot;&quot;Shared fields used across all task schemas.&quot;&quot;&quot;<br>    title: str = Field(..., min_length=1, max_length=200, description=&quot;Task title&quot;)<br>    description: Optional[str] = Field(None, max_length=5000)<br>    status: TaskStatus = Field(default=TaskStatus.TODO)<br>    priority: TaskPriority = Field(default=TaskPriority.MEDIUM)<br>    due_date: Optional[datetime] = None<br>    tags: List[str] = Field(default_factory=list)<br>    @field_validator(&quot;title&quot;)<br>    @classmethod<br>    def strip_title(cls, v: str) -&gt; str:<br>        return v.strip()<br>    @field_validator(&quot;tags&quot;)<br>    @classmethod<br>    def normalize_tags(cls, v: List[str]) -&gt; List[str]:<br>        return [tag.lower().strip() for tag in v if tag.strip()]<br><br>class TaskCreate(TaskBase):<br>    &quot;&quot;&quot;Schema for POST /tasks - creating a new task.&quot;&quot;&quot;<br>    pass<br><br>class TaskUpdate(BaseModel):<br>    &quot;&quot;&quot;Schema for PUT /tasks/{id} - updating an existing task. All fields optional.&quot;&quot;&quot;<br>    title: Optional[str] = Field(None, min_length=1, max_length=200)<br>    description: Optional[str] = None<br>    status: Optional[TaskStatus] = None<br>    priority: Optional[TaskPriority] = None<br>    due_date: Optional[datetime] = None<br>    tags: Optional[List[str]] = None<br>    @field_validator(&quot;title&quot;)<br>    @classmethod<br>    def strip_title(cls, v: Optional[str]) -&gt; Optional[str]:<br>        return v.strip() if v else v<br><br>class TaskResponse(TaskBase):<br>    &quot;&quot;&quot;Schema for GET responses - includes DB-generated fields.&quot;&quot;&quot;<br>    id: int<br>    user_id: int<br>    created_at: datetime<br>    updated_at: datetime<br>    deleted_at: Optional[datetime] = None<br>    @computed_field<br>    @property<br>    def is_overdue(self) -&gt; bool:<br>        if self.due_date and self.status not in [TaskStatus.DONE, TaskStatus.ARCHIVED]:<br>            return datetime.utcnow() &gt; self.due_date.replace(tzinfo=None)<br>        return False<br>    model_config = {&quot;from_attributes&quot;: True}  # Pydantic v2: allows ORM model as input<br><br>class TaskListResponse(BaseModel):<br>    &quot;&quot;&quot;Paginated list response envelope.&quot;&quot;&quot;<br>    data: List[TaskResponse]<br>    meta: dict  # {total, page, per_page}<br>```<br>## Validation Checklist<br>- [ ] `model_config = {&quot;from_attributes&quot;: True}` on Response schema<br>- [ ] All enums are `str, Enum` for JSON serialization<br>- [ ] `TaskUpdate` has all Optional fields (partial update support)<br>- [ ] Validators use `@classmethod` (Pydantic v2 requirement)<br>- [ ] Field descriptions set for OpenAPI docs<br>- [ ] No SQLAlchemy imports in schema files<br></pre><h3>How Skills Are Discovered and Used</h3><p>Claude auto-discovers skills based on your request matching the description field. You can also explicitly invoke:</p><pre>&quot;Create a new endpoint for task comments. Use the fastapi-endpoint skill.&quot;</pre><p>Or let Claude decide:</p><pre>&quot;Add a DELETE endpoint for tasks&quot;<br>→ Claude reads fastapi-endpoint.md automatically based on description match</pre><p>The skill system transforms Claude from a generic code generator into a specialist who knows your exact patterns. Instead of producing vanilla FastAPI code, it produces <em>your team’s</em> FastAPI code — every time, consistently.</p><h3>Key Takeaways</h3><ol><li><strong>Skills encode your team’s expertise</strong> — not just syntax, but patterns and decisions.</li><li><strong>Three sections matter most</strong>: context (why), instructions (how), validation (done right).</li><li><strong>Description determines discoverability</strong> — write it for Claude’s understanding, not human readers.</li><li><strong>Progressive disclosure</strong> — keep skills focused; link to other files rather than embedding everything.</li><li><strong>Validation checklists</strong> make quality measurable and consistent.</li></ol><p>In Part 3, we’ll go deep on <strong>Sub-agents</strong> — how to design parallel, isolated AI workers that handle complex multi-step workflows for your full-stack application.</p><p><em>Follow for Part 3 → [Claude Code: Sub-agents — Parallel AI Workflows for Full-Stack Development]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5fd12c52832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Claude Code: The Architect’s Guide — Part 1 of 5]]></title>
            <link>https://medium.com/@meghnani.bhavya/claude-code-the-architects-guide-part-1-of-5-e15964ae702e?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/e15964ae702e</guid>
            <category><![CDATA[anthropic-claude]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Sun, 03 May 2026 16:56:07 GMT</pubDate>
            <atom:updated>2026-05-03T16:56:07.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foundations, Project Architecture &amp; CLAUDE.md Mastery</h3><blockquote>This is Part 1 of a 5-part series on engineering production-grade AI-assisted development workflows with Claude Code. We’ll build everything around a real CRUD application: a <strong>Task Management System</strong> built with React + Vite + shadcn/ui + Material UI on the frontend, FastAPI + Pydantic + SQLite on the backend.</blockquote><h3>The Mental Model Shift: Claude Code Is Not a Chatbot</h3><p>Most developers approach Claude Code the way they approach ChatGPT — they type a question, get an answer, copy-paste. That’s leaving 90% of the value on the table. Claude Code is an <strong>autonomous AI coding manager</strong>. Think of it as a senior engineer sitting inside your terminal who can:</p><ul><li>Read your entire codebase in one shot</li><li>Spawn isolated sub-processes to do parallel work</li><li>Remember your architectural decisions across sessions</li><li>Execute bash commands, run tests, commit code</li><li>Operate tools: file reads, grep, web search, MCP servers</li></ul><p>The developer’s new role is <strong>AI Manager</strong> — you set direction, define constraints, validate outputs, and ensure quality. You are not writing every line. You are architecting the system and the <strong><em>instructions</em></strong> that govern the AI’s behavior. This distinction matters because <strong>how you configure Claude Code determines the quality of everything it produces</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g98ag6h8yResFgPV" /><figcaption>Claude Code on Terminal</figcaption></figure><h3>What’s Coming in This Series</h3><ul><li><strong>Part 2</strong>: Skills — Writing Reusable AI Instructions for Your Stack</li><li><strong>Part 3</strong>: Sub-agents — Parallelism, Isolation, and Orchestration Patterns</li><li><strong>Part 4</strong>: Slash Commands — Custom Workflows and Team Automation</li><li><strong>Part 5</strong>: Production Patterns — Memory, Observability, and Advanced Architecture</li></ul><h3>Understanding the Context Window: The Scarcest Resource</h3><p>Before diving into configuration, you need to internalize one constraint: <strong>the context window</strong>. Claude has a 200k token context window. Every token matters:</p><pre>Context Budget Breakdown (approximate):<br>├── System Prompt / CLAUDE.md          →  ~6k  tokens (fixed)<br>├── Tool Schema                         →  ~8k  tokens (fixed)<br>├── Conversation History                →  ~45% of remaining<br>├── Tool Results (file reads, bash)     →  variable<br>└── Auto-compact threshold              →  ~33k reserved for summarization</pre><p>When you approach the limit, Claude auto-compacts — it summarizes the conversation and loads that summary. You can check via /content command. <strong>Why this matters architecturally</strong>: Every file you ask Claude to read consumes tokens. Every long response Claude gives consumes tokens. Your CLAUDE.md, skills, and sub-agent design should be built with token efficiency in mind. <strong>Key principle</strong>: Keep CLAUDE.md under 300 lines. Never let it be a dumping ground.</p><h3>Project Structure: The Foundation of Everything</h3><p>Every directory in .claude/ is a first-class citizen. It is not an afterthough. Here is the full structure for our Task Management System, designed for Claude Code from the ground up:</p><pre>task-manager/<br>├── .claude/<br>│   ├── commands/                    # Custom slash commands<br>│   │   ├── review.md<br>│   │   ├── commit.md<br>│   │   ├── test.md<br>│   │   ├── security-scan.md<br>│   │   └── db-migrate.md<br>│   ├── agents/                      # Sub-agent definitions<br>│   │   ├── frontend-agent.md<br>│   │   ├── backend-agent.md<br>│   │   ├── test-agent.md<br>│   │   └── security-agent.md<br>│   └── skills/                      # Reusable skill files<br>│       ├── react-component.md<br>│       ├── fastapi-endpoint.md<br>│       ├── pydantic-model.md<br>│       └── sqlite-migration.md<br>├── .claude/specs/<br>│   ├── api-design.md               # API conventions<br>│   ├── component-design.md         # Frontend conventions<br>│   └── database-schema.md          # DB conventions<br>├── frontend/<br>│   ├── src/<br>│   │   ├── components/<br>│   │   │   ├── ui/                 # shadcn components<br>│   │   │   └── tasks/              # domain components<br>│   │   ├── pages/<br>│   │   ├── hooks/<br>│   │   ├── services/               # API layer<br>│   │   └── types/<br>│   ├── vite.config.ts<br>│   └── package.json<br>├── backend/<br>│   ├── app/<br>│   │   ├── api/<br>│   │   │   └── v1/<br>│   │   │       ├── endpoints/<br>│   │   │       │   ├── tasks.py<br>│   │   │       │   ├── users.py<br>│   │   │       │   └── auth.py<br>│   │   │       └── router.py<br>│   │   ├── core/<br>│   │   │   ├── config.py<br>│   │   │   ├── database.py<br>│   │   │   └── security.py<br>│   │   ├── models/                 # SQLAlchemy models<br>│   │   │   ├── task.py<br>│   │   │   └── user.py<br>│   │   ├── schemas/                # Pydantic schemas<br>│   │   │   ├── task.py<br>│   │   │   └── user.py<br>│   │   ├── crud/                   # CRUD operations<br>│   │   │   ├── task.py<br>│   │   │   └── user.py<br>│   │   └── main.py<br>│   ├── tests/<br>│   │   ├── api/<br>│   │   └── crud/<br>│   └── requirements.txt<br>├── CLAUDE.md                        # ← THE MOST IMPORTANT FILE<br>└── .claudeignore</pre><h3>CLAUDE.md: Your Architecture Contract</h3><p>CLAUDE.md is the <strong>project-level instruction file</strong> that Claude reads at the start of every session. It is the single most important file you will write for AI-assisted development.</p><p><strong>Critical rules for CLAUDE.md</strong>:</p><ol><li>Keep it under 300 lines (ideally ~200)</li><li>Be declarative, not conversational</li><li>Define what NOT to do as clearly as what TO do</li><li>Link to spec files for deeper detail — don’t embed everything</li></ol><p>Here is the production CLAUDE.md for our Task Management System:</p><pre># Task Manager — Claude Code Instructions<br><br>## Project Overview<br>Full-stack CRUD application for task management.<br>- Frontend: React 18 + Vite + TypeScript + shadcn/ui + Material UI<br>- Backend: FastAPI + Pydantic v2 + SQLAlchemy + SQLite<br>- Auth: JWT-based, stored in httpOnly cookies<br><br>## Architecture Principles<br>- Separation of concerns: UI components never call API directly - always via service layer<br>- Pydantic models are the single source of truth for data contracts<br>- All DB operations go through CRUD layer - never raw SQL in endpoints<br>- No business logic in React components - use custom hooks<br><br>## Directory Conventions<br>- `/frontend/src/components/ui/` → shadcn primitives only, never domain logic<br>- `/frontend/src/components/tasks/` → domain components, compose from ui/<br>- `/frontend/src/services/` → Axios service classes, one per domain entity<br>- `/backend/app/schemas/` → Pydantic request/response schemas<br>- `/backend/app/models/` → SQLAlchemy ORM models<br>- `/backend/app/crud/` → database operations, return ORM objects or None<br>- `/backend/app/api/v1/endpoints/` → route handlers, thin layer only<br><br>## Naming Conventions<br>- React components: PascalCase (`TaskCard`, `TaskListPage`)<br>- Hooks: camelCase with `use` prefix (`useTaskList`, `useTaskMutation`)<br>- Services: PascalCase class (`TaskService`)<br>- API endpoints: snake_case, RESTful (`/api/v1/tasks/{task_id}`)<br>- Pydantic schemas: suffix with `Base`, `Create`, `Update`, `Response`<br>- SQLAlchemy models: singular PascalCase (`Task`, `User`)<br><br>## Code Style<br>- TypeScript: strict mode, no `any`<br>- Python: type hints on all functions, Google-style docstrings<br>- Components: functional only, no class components<br>- Prefer named exports over default exports in services/hooks<br>- shadcn takes precedence over MUI for form elements; MUI for data-heavy tables/charts<br><br>## What to Avoid<br>- Do NOT install new npm packages without explicit user approval<br>- Do NOT use `useEffect` for data fetching - use React Query (TanStack Query)<br>- Do NOT write raw SQL - always use SQLAlchemy ORM<br>- Do NOT put try/catch in React components - use error boundaries + React Query&#39;s error state<br>- Do NOT commit migrations manually - use `/db-migrate` command<br>- Do NOT expose internal SQLAlchemy models in API responses - always use Pydantic schemas<br><br>## Testing Requirements<br>- Every new endpoint must have a test in `/backend/tests/api/`<br>- React components with business logic must have a Vitest unit test<br>- Run `pytest` before marking any backend task complete<br>- Run `vitest` before marking any frontend task complete<br><br>## Workflow<br>- For multi-step features: Design → Backend API → Frontend Service → UI Component → Tests<br>- For bug fixes: Reproduce → Root cause → Fix → Test → Verify<br>- Always check `/backend/app/schemas/` before creating new Pydantic models - schemas may already exist<br><br>## Key Files to Know<br>- `backend/app/core/database.py` - DB session management, connection string<br>- `backend/app/core/config.py` - Environment configuration<br>- `frontend/src/services/api.ts` - Base Axios instance with interceptors<br>- `frontend/src/types/index.ts` - Shared TypeScript interfaces<br><br>## Specs (read when working in relevant areas)<br>- API design: `.claude/specs/api-design.md`<br>- Component patterns: `.claude/specs/component-design.md`<br>- Database schema: `.claude/specs/database-schema.md`</pre><h3>The .claudeignore File: Token Efficiency</h3><p>Just like .gitignore, .claudeignore tells Claude what <strong>not</strong> to read. This is critical for token efficiency. Without this, Claude wastes tokens reading node_modules entries and binary SQLite files.</p><pre># .claudeignore<br><br># Build artifacts<br>frontend/dist/<br>frontend/.vite/<br>__pycache__/<br>*.pyc<br>*.pyo<br><br># Dependencies (Claude should never need to read these)<br>node_modules/<br>.venv/<br>venv/<br><br># Database files (read from schema, not the binary)<br>*.db<br>*.sqlite3<br><br># Generated files<br>frontend/src/components/ui/*.js<br>coverage/<br>.pytest_cache/<br>htmlcov/<br><br># Large static assets<br>frontend/public/<br><br># Lock files (informational only, no need to read)<br>package-lock.json<br>yarn.lock<br>poetry.lock</pre><h3>The .claude/specs/ Directory: Deep Architecture Docs</h3><p>The CLAUDE.md links to spec files for deeper detail. Here’s what the API spec looks like:</p><p>markdown</p><pre># .claude/specs/api-design.md<br><br>## API Design Conventions for Task Manager<br>### Response Envelope<br>All endpoints return a consistent envelope:<br>```json<br>{<br>  &quot;data&quot;: {...} | [...],<br>  &quot;meta&quot;: { &quot;total&quot;: 100, &quot;page&quot;: 1, &quot;per_page&quot;: 20 },<br>  &quot;error&quot;: null | { &quot;code&quot;: &quot;NOT_FOUND&quot;, &quot;message&quot;: &quot;...&quot; }<br>}<br>```<br>### Pydantic Schema Pattern<br>Every entity has exactly 4 schemas:<br>- `TaskBase` - shared fields<br>- `TaskCreate` - input for POST (inherits Base)<br>- `TaskUpdate` - input for PUT/PATCH (all Optional fields)<br>- `TaskResponse` - output schema (inherits Base + adds id, timestamps)<br><br>### HTTP Status Codes<br>- 200: Successful GET, PUT<br>- 201: Successful POST (creation)<br>- 204: Successful DELETE (no body)<br>- 400: Validation error (Pydantic will handle most)<br>- 401: Unauthenticated<br>- 403: Unauthorized (authenticated but no permission)<br>- 404: Resource not found<br>- 422: Unprocessable entity (Pydantic validation failure - FastAPI default)<br><br>### Pagination<br>All list endpoints accept: `?page=1&amp;per_page=20&amp;sort_by=created_at&amp;sort_order=desc`<br><br>### Error Codes<br>Use string codes: `NOT_FOUND`, `ALREADY_EXISTS`, `INVALID_STATUS_TRANSITION`, `UNAUTHORIZED`</pre><h3>Key Takeaways</h3><ol><li><strong>CLAUDE.md is an architecture contract</strong>, not a chat message. Write it like you’d write an ADR.</li><li><strong>Token budget is your scarcest resource</strong> — every configuration decision affects it.</li><li><strong>Project structure is intentional</strong> — .claude/ directories are first-class, not optional.</li><li><strong>Specs separate concerns</strong> — CLAUDE.md stays thin by delegating to spec files.</li><li><strong>Memory is layered</strong> — global, project, and auto-memory each serve different purposes.</li></ol><p>In Part 2, we’ll go deep on <strong>Skills</strong> — how to write reusable, composable AI instructions that make Claude consistently produce production-quality code for your specific stack.</p><p><em>Follow for Part 2 → [Claude Code: Writing Skills That Make AI Produce Consistent, Production-Grade Code]</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e15964ae702e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conclusion: Putting It All Together]]></title>
            <link>https://medium.com/@meghnani.bhavya/conclusion-putting-it-all-together-773a0934a046?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/773a0934a046</guid>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 17:43:39 GMT</pubDate>
            <atom:updated>2026-03-17T17:44:07.721Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A four-part series on building AI systems that know when they’re wrong.</em></p><h3>THIS SERIES</h3><p>A complete guide from theory to hands-down code implementing Insurance AI copilot use-case.</p><blockquote><a href="https://medium.com/@meghnani.bhavya/everything-theory-why-rag-breaks-and-how-research-fixed-it-2d5c23a7a0ef?postPublishedType=repub"><strong>Part 1 </strong>— Everything Theory: why RAG breaks, what the research says, and the conceptual architecture of corrective and self-reflective systems.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/corrective-rag-fixing-bad-retrieval-before-it-reaches-the-generator-818cbe1a931d?postPublishedType=repub"><strong>Part 2 </strong>— Corrective RAG (CRAG): the paper, the architecture diagram, the code, the graph. Fixing bad retrieval before it reaches the generator.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/self-rag-when-the-generator-needs-to-check-its-own-work-8c71afd73a44"><strong>Part 3 </strong>— Self-RAG: the paper, the reflection tokens, the nine-node LangGraph implementation. Fixing bad generation after it happens.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/conclusion-putting-it-all-together-773a0934a046"><strong>Part 4 </strong>— Conclusion: side-by-side comparison, combined pipeline design, limitations, and what to build next.</a></blockquote><h3>RAG Is Not a Pipeline. It Is a Reasoning System.</h3><p>Standard RAG trusts retrieval and trusts generation. It delivers one answer and moves on. CRAG does not trust retrieval. Self-RAG does not trust generation. Together, they treat every step in the pipeline as a hypothesis to be tested — not a result to be passed through.</p><p>The implementations in this series are model-agnostic by design. The intelligence is in the graph topology, the evaluation contracts, and the routing logic — not in any specific LLM. You can run them with a capable local model, a cloud API, or a hybrid combination. You can swap the evaluator model without changing the calling code. You can tune the thresholds without rewriting the prompts.</p><p>This is what production-grade RAG architecture looks like: not a clever prompt, but a system that earns its confidence through evidence, verification, and reflection.</p><blockquote><strong><em>“The most dangerous AI system is the one that sounds confident. The most useful AI system is the one that has earned that confidence — step by step, claim by claim, source by source.”</em></strong></blockquote><h3><strong>CRAG vs. Self-RAG: A Definitive Comparison</strong></h3><h4><strong>What Problem Each Solves</strong></h4><p><strong>CRAG:</strong> The retriever returned bad documents. Prevents contaminated context from reaching the generator. Pre-generation.</p><p><strong>Self-RAG:</strong> The generator produced an unsupported or vague answer despite good (or adequate) context. Post-generation.</p><p><strong>Combined: </strong>Full failure surface coverage. Bad retrieval is caught before generation. Bad generation is caught after it.</p><h3><strong>Honest Trade-offs</strong></h3><h4><strong>CRAG Limitations</strong></h4><ul><li>Document-level evaluation misses intra-document noise. A chunk can score 0.85 but contain two relevant sentences and eight irrelevant ones. The full paper’s sentence-level decompose-then-recompose addresses this; our implementation applies document-level filtering only.</li><li>The Ambiguous path is collapsed (INCORRECT behaviour). A full implementation should combine both k_in and k_ex when confidence is genuinely uncertain.</li><li>Web search quality depends on CSE configuration. A poorly tuned Custom Search Engine returns SEO content, not authoritative insurance information. The architecture is only as good as the knowledge sources it can access.</li><li>No post-generation verification. If the generator hallucinations despite receiving CRAG’s refined context, CRAG has no mechanism to catch it. This is the gap Self-RAG fills.</li></ul><h4><strong>Self-RAG Limitations</strong></h4><ul><li>Non-deterministic latency. Clean-path: ~5 LLM calls. Worst case: 12+. For user-facing applications, implement streaming to surface intermediate stage labels so latency feels like progress rather than delay.</li><li>Evaluator quality is bounded by base model capability. The hallucination checker, relevance grader, and utility grader all run on the same model. A model with systematic generation biases will exhibit the same biases when evaluating. Separate evaluation and generation models when possible.</li><li>Context window pressure at check_hallucination. This node must hold the full answer and full source context simultaneously. Design chunk sizes (600 chars) and retrieval k (4) with this constraint in mind.</li><li>No external escalation path. Self-RAG exhausts its rewrite budget and falls back gracefully — it cannot escalate to web search when the local corpus is insufficient. The combined CRAG + Self-RAG pipeline solves this.</li></ul><h4><strong>Shared Limitations</strong></h4><ul><li>Structured output reliability. Both systems rely on Pydantic schemas enforced via structured output. Smaller or less capable models fail more often on complex schemas (List[str] fields, nested Literal types). If you see frequent parsing failures, simplify schemas or upgrade the model. The Pydantic contract makes model swaps safe — calling code is unchanged.</li><li>Single-model evaluation bias. Using the same model for generation and evaluation creates correlated failure modes. A model that tends to omit exclusions in generation may also fail to flag their absence in evaluation. Mitigate with a fine-tuned classifier for evaluation nodes.</li><li>Logging and observability. Both implementations include per-run Markdown log files with stage-by-stage execution traces. In production, this should feed into a structured observability system (Langsmith, Arize Phoenix, or similar) for aggregate quality monitoring.</li></ul><h3><strong>Extending the Architecture</strong></h3><p>The implementations in this series are production-ready for small-to-medium enterprise use cases. Here are the most impactful next steps, ordered by value delivered per engineering effort:</p><h4><strong>1. Streaming Intermediate States</strong></h4><p>Both pipelines make 5–12 LLM calls. Without streaming, users see a loading spinner for the full duration. With streaming, you can surface intermediate labels: “Checking document relevance (2/4)…”, “Verifying facts against source…”, “Refining answer (attempt 1/2)…”. The implementation is a LangGraph stream_mode=’values’ call with a simple stage-label SSE stream to the frontend.</p><h4><strong>2. Sentence-Level CRAG Refinement</strong></h4><p>The current CRAG implementation applies document-level filtering. For documents longer than ~500 words, implementing the full decompose-then-recompose algorithm at the sentence level will materially improve context quality. Each sentence is individually scored against the query, with only the top-scoring sentences passed to the generator. This is the implementation closest to the original paper.</p><h4><strong>3. Separate Evaluation and Generation Models</strong></h4><p>The most impactful quality improvement available within the current architecture: use a stronger reasoning model for check_hallucination, grade_documents, eval_each_doc, and grade_utility — and a faster model for synthesize_answer and generate. The Pydantic schemas and structured output contracts are model-agnostic. A one-line model name change in the evaluation nodes is the only code change required.</p><h4><strong>4. Evidence Citations in the UI</strong></h4><p>Self-RAG’s check_hallucination node returns an evidence list: specific facts it verified, with implicit source attribution. Surfacing this in the agent UI — “This answer is grounded in [policy document, page 12]” — provides both transparency and regulatory compliance support. In insurance, being able to trace an answer to a specific policy document is not just good practice; it may be a regulatory requirement.</p><h4><strong>5. CRAG Ambiguous Path</strong></h4><p>Implement the genuine three-way verdict by keeping documents with scores between LOWER_TH (0.3) and UPPER_TH (0.7) as ambiguous_docs, running web search in parallel for these cases, and combining both good_docs + web_docs as context for the Ambiguous path. This is the most faithful implementation of the paper and handles the genuinely uncertain cases that the current binary CORRECT/INCORRECT misclassifies.</p><p>If you would like to dive deeper, the <strong>complete implementation of Corrective RAG and Self-RAG using LangGraph and LangChain is available on GitHub</strong>:<br> <a href="https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG">https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMyIjR_4DzJYtwUPx8F0nQ.png" /><figcaption>Github Snapshot</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=773a0934a046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-RAG: When the Generator Needs to Check Its Own Work]]></title>
            <link>https://medium.com/@meghnani.bhavya/self-rag-when-the-generator-needs-to-check-its-own-work-8c71afd73a44?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c71afd73a44</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 17:40:12 GMT</pubDate>
            <atom:updated>2026-03-17T17:44:43.214Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A four-part series on building AI systems that know when they’re wrong.</em></p><blockquote><strong>Prerequisites: </strong>Read Part 2 (CRAG) before this. Self-RAG picks up exactly where CRAG leaves off — at the moment the generator receives its context.</blockquote><h3>THIS SERIES</h3><p>A complete guide from theory to hands-down code implementing Insurance AI copilot use-case.</p><blockquote><a href="https://medium.com/@meghnani.bhavya/everything-theory-why-rag-breaks-and-how-research-fixed-it-2d5c23a7a0ef"><strong>Part 1 </strong>— Everything Theory: why RAG breaks, what the research says, and the conceptual architecture of corrective and self-reflective systems.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/corrective-rag-fixing-bad-retrieval-before-it-reaches-the-generator-818cbe1a931d"><strong>Part 2 </strong>— Corrective RAG (CRAG): the paper, the architecture diagram, the code, the graph. Fixing bad retrieval before it reaches the generator.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/self-rag-when-the-generator-needs-to-check-its-own-work-8c71afd73a44"><strong>Part 3 </strong>— Self-RAG: the paper, the reflection tokens, the nine-node LangGraph implementation. Fixing bad generation after it happens.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/conclusion-putting-it-all-together-773a0934a046"><strong>Part 4 </strong>— Conclusion: side-by-side comparison, combined pipeline design, limitations, and what to build next.</a></blockquote><h3><strong>Self-RAG: What the Paper Actually Says</strong></h3><p>Self-RAG was published by Akari Asai, Zeqiu Wu, Yizhong Wang, Avirup Sil, and Hannaneh Hajishirzi in October 2023, from the University of Washington, IBM AI Research, and the Allen Institute for AI. It was accepted at ICLR 2024 as an Oral presentation (top 1% of submissions) — a rare distinction that reflects the paper’s influence. <strong>Link: </strong><a href="https://arxiv.org/abs/2310.11511"><strong>https://arxiv.org/abs/2310.11511</strong></a></p><p>The paper’s full title is “Self-RAG: Learning to Retrieve, Generate, and Critique through Self-Reflection” (arXiv:2310.11511). The core claim: rather than applying a separate evaluator model on top of a standard LM, Self-RAG trains a single model that interleaves generation with special reflection tokens — making self-critique an intrinsic part of the generation process, not a post-hoc addition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*x-DMKs4B7XBxJxBYdrHl4A.png" /><figcaption>SELF-RAG learns to retrieve, critique, and generate text passages to enhance overall generation quality, factuality, and verifiability</figcaption></figure><h3><strong>Reflection Tokens: The Original Mechanism</strong></h3><p>In the original paper, Self-RAG trains a language model to generate four types of special tokens interspersed with its regular output:</p><ul><li><strong>[Retrieve] —</strong> should the model retrieve passages for this segment? (yes/no)</li><li><strong>[IsREL] —</strong> are the retrieved passages relevant to the query? (relevant/irrelevant)</li><li><strong>[IsSUP] — </strong>does the generated output segment follow from the retrieved passages? (fully supported / partially supported / no support)</li><li><strong>[IsUSE] — </strong>is the overall response useful for the query? (score 1–5)</li></ul><p>These tokens are not generated by a separate critic model at inference time — they are part of the model’s vocabulary, produced as part of the same forward pass that generates the answer. The model is fine-tuned on a dataset of 150,000 instances where GPT-4 was used to generate the reflection token labels, which were then distilled into a smaller (7B or 13B parameter) open-source model.</p><p><strong>This is the key architectural difference between the paper and our LangGraph implementation. </strong>In the paper, reflection is an intrinsic model capability. In our implementation, reflection is an extrinsic graph capability — separate evaluation nodes that call the LLM with structured output schemas. The behaviour is equivalent; the mechanism differs.</p><blockquote>“Self-RAG’s contribution is not a clever prompt — it is a new training paradigm that makes self-reflection a first-class capability of the model itself, not a wrapper around it.” — Asai et al., 2023</blockquote><h4><strong>Why the LangGraph Approach Is Still Valuable</strong></h4><p>Training a Self-RAG model from scratch requires the original paper’s fine-tuning pipeline, 150K training instances, and a suitable base LM. For most production teams, this is impractical. The LangGraph approach replicates the behaviour — adaptive retrieval, relevance grading, hallucination checking, utility evaluation — using any instruction-following LLM as a black box, with structured output schemas enforcing the same decision contracts.</p><p><strong>The trade-off:</strong> the LangGraph approach is slower (separate LLM calls for each evaluation) and requires a capable base model for reliable structured output. The paper’s approach is faster at inference but requires a fine-tuning pipeline upfront. For teams that cannot fine-tune, the LangGraph approach is the practical path to Self-RAG-level behaviour.</p><h3><strong>ARCHITECTURE: The Nine-Node Graph</strong></h3><p>Our Self-RAG implementation uses nine specialised nodes organised into a directed cyclic graph with two nested feedback loops. The graph visualisation below was generated directly from the compiled LangGraph application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*Lx4GZQ3Y9N8jd9LLvuwOeg.png" /><figcaption><strong><em>The compiled Self-RAG LangGraph graph, generated directly from app.get_graph().draw_mermaid_png(). Solid arrows are unconditional edges; dotted arrows are conditional. The two feedback cycles are clearly visible.</em></strong></figcaption></figure><p>If you would like to dive deeper, the <strong>complete implementation of Corrective RAG and Self-RAG using LangGraph and LangChain is available on GitHub</strong>:<br> <a href="https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG">https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG</a></p><h3><strong>The Two Feedback Loops</strong></h3><p><strong>The inner loop (hallucination correction) </strong>runs until the answer is fully supported by source context or MAX_RETRIES (2) is exhausted. It corrects micro-hallucinations — subtle paraphrasing, approximate numbers, missing conditions — that pass the relevance filter but introduce inaccuracy.</p><p><strong>The outer loop (retrieval correction) </strong>activates when an answer that passed hallucination checking is still judged not useful — indicating the problem was at retrieval, not at generation. It rewrites the original query with a different strategy and re-enters the full pipeline from fetch_documents. MAX_REWRITE_TRIES is 3.</p><blockquote>The loops are bounded. The system will not run forever. If both loops exhaust their budgets, handle_fallback terminates gracefully with a best-effort answer and a clear signal that the corpus may not contain the information needed.</blockquote><h3><strong>The Shared State: What Every Node Knows</strong></h3><p>The separation between question and retrieval_query is architecturally critical. question is immutable — it records the user’s original intent. retrieval_query starts as question but diverges on each rewrite cycle.</p><p>All evaluation nodes (grade_documents, check_hallucination, grade_utility) evaluate against question, not retrieval_query. Without this separation, a rewritten query could distort every downstream judgment.</p><pre>class State(TypedDict):<br>    question: str           # original user question — NEVER modified<br>    retrieval_query: str    # current search query (rewritten by transform_query)<br>    rewrite_tries: int      # outer loop counter — max 3<br><br>    need_retrieval: bool    # decision from route_query<br>    docs: List[Document]    # raw retrieved chunks<br>    relevant_docs: List[Document]  # chunks passing grade_documents<br>    context: str            # joined relevant_docs, passed to hallucination check<br>    answer: str             # current answer (may be revised multiple times)<br><br>    issup: Literal[         # grounding verdict from check_hallucination<br>        &#39;fully_supported&#39;,<br>        &#39;partially_supported&#39;,<br>        &#39;no_support&#39;]<br>    evidence: List[str]     # specific facts verified (audit trail)<br>    retries: int            # inner loop counter — max 2<br><br>    isuse: Literal[&#39;useful&#39;, &#39;not_useful&#39;]<br>    use_reason: str         # utility grader&#39;s explanation (for logging)</pre><h4><strong>Route_query — Adaptive Retrieval</strong></h4><p>The first question Self-RAG asks: does this query even need retrieval? General concepts, greetings, and widely-known information do not. Only queries requiring document-specific knowledge — client cases, policy terms, product details — should trigger retrieval.</p><pre>class RetrieveDecision(BaseModel):<br>    should_retrieve: bool<br><br># System prompt logic:<br># ALWAYS retrieve for: specific products, policies, client case files,<br>#   premium calculations, claim procedures, regulatory compliance.<br># NO retrieval for: greetings, general concepts, how-to-use-copilot.<br># Bias instruction: &#39;When in doubt, choose True.&#39;<br><br>def route_query(state: State):<br>    decision = route_llm.invoke(<br>        route_prompt.format_messages(question=state[&#39;question&#39;])<br>    )<br>    return {&#39;need_retrieval&#39;: decision.should_retrieve}</pre><blockquote>The “when in doubt, choose True” bias is a deliberate asymmetry that encodes domain risk. In insurance, the cost of an incorrect answer (wrong policy number, wrong coverage amount) greatly exceeds the cost of an unnecessary retrieval call (added latency). Biasing toward retrieval is the right default when stakes are high.</blockquote><h4><strong>Grade_documents — Coarse Relevance Filtering</strong></h4><p>Binary relevance judgment for each retrieved chunk. Unlike CRAG’s continuous scorer, Self-RAG uses a simple yes/no because the hallucination checker downstream provides a second, finer quality gate. The grader’s job is coarse filtering, not precision scoring.</p><pre>class RelevanceDecision(BaseModel):<br>    is_relevant: bool<br><br># Generous with relevance — &#39;when unsure, return True&#39;.<br># Rationale: hallucination checker catches false positives.<br># Being too strict here risks discarding genuine context.<br><br>def grade_documents(state: State):<br>    relevant_docs = []<br>    for doc in state.get(&#39;docs&#39;, []):<br>        decision = relevance_llm.invoke(<br>            relevance_prompt.format_messages(<br>                question=state[&#39;question&#39;],<br>                document=doc.page_content,<br>            )<br>        )<br>        if decision.is_relevant:<br>            relevant_docs.append(doc)<br>    return {&#39;relevant_docs&#39;: relevant_docs}</pre><h4><strong>Synthesize_answer — First Generation</strong></h4><p>Generates the initial answer from filtered context. The prompt is tightly constrained: answer only from context, include specific numbers, do not mention the knowledge base, do not add information beyond what the context contains.</p><pre>def synthesize_answer(state: State):<br>    context = &#39;\n\n---\n\n&#39;.join(<br>        [d.page_content for d in state.get(&#39;relevant_docs&#39;, [])]<br>    )<br>    out = llm.invoke(<br>        rag_prompt.format_messages(<br>            question=state[&#39;question&#39;],<br>            context=context<br>        )<br>    )<br>    return {&#39;answer&#39;: out.content, &#39;context&#39;: context}</pre><blockquote>The ‘ — -’ separator between chunks is a small but meaningful detail. It provides the model with a visual cue that a new source document is beginning, reducing the risk of context bleeding — where the model accidentally merges information from two separate documents into a single claim.</blockquote><p>We save context to state alongside the answer because the hallucination checker needs both simultaneously. This is why context window management matters: check_hallucination must see the full answer and the full source context in the same prompt.</p><h4><strong>Check_hallucination — The Core Innovation</strong></h4><p>This is the node that operationalises Self-RAG’s core contribution. After every generation, we ask: is what was generated actually supported by the source documents?</p><pre>class IsSUPDecision(BaseModel):<br>    issup: Literal[<br>        &#39;fully_supported&#39;,<br>        &#39;partially_supported&#39;,<br>        &#39;no_support&#39;<br>    ]<br>    evidence: List[str] = Field(default_factory=list)<br><br># Evaluation instructions in the system prompt:<br># STRICT: exact numbers, dates, client specifics, policy terms.<br>#   &#39;90 days&#39; ≠ &#39;approximately 90 days&#39;. No rounding, no approximation.<br># TOLERANT: paraphrasing explanations, reordering information,<br>#   professional rephrasing that preserves factual content.<br><br>MAX_RETRIES = 2<br><br>def route_after_check_hallucination(state):<br>    if state.get(&#39;issup&#39;) == &#39;fully_supported&#39;:<br>        return &#39;grade_utility&#39;<br>    if state.get(&#39;retries&#39;, 0) &gt;= MAX_RETRIES:<br>        return &#39;grade_utility&#39;  # best-effort: proceed with caveats<br>    return &#39;refine_response&#39;    # inner loop: try again</pre><p><strong>The three-level verdict maps to different actions:</strong> fully_supported proceeds to utility grading, partially_supported triggers refinement (the inner loop), no_support also triggers refinement. After MAX_RETRIES, even a partially_supported answer proceeds to grade_utility — the system acknowledges that sometimes the documents simply do not contain enough information for a fully grounded answer.</p><p><strong>Strict vs. tolerant:</strong> the distinction matters enormously in practice. In insurance, exact numbers are legally material. ’90 days’ and ‘approximately 90 days’ are not equivalent when one is a contractual term. We instruct the checker to be strict about numerics and dates while tolerating legitimate professional rephrasing.</p><h4><strong>Refine_response — The Inner Loop</strong></h4><p>When the hallucination check fails, we do not regenerate from scratch. We use the existing answer as input and ask the model to remove or correct only the unsupported elements, keeping the structure and professional language intact.</p><pre>def refine_response(state: State):<br>    retry_count = state.get(&#39;retries&#39;, 0) + 1<br><br>    # System prompt instructions:<br>    # 1. Verify ALL numerical values against context (exact, not approximate)<br>    # 2. Remove any statement not directly in context<br>    # 3. Keep policy terms and conditions verbatim<br>    # 4. Maintain professional insurance terminology<br>    # CRITICAL: &#39;Output ONLY the revised response, nothing else.&#39;<br><br>    out = llm.invoke(<br>        refinement_prompt.format_messages(<br>            answer=state.get(&#39;answer&#39;, &#39;&#39;),<br>            context=state.get(&#39;context&#39;, &#39;&#39;),<br>        )<br>    )<br>    return {&#39;answer&#39;: out.content, &#39;retries&#39;: retry_count}<br><br># Graph edge: refine_response → check_hallucination (inner loop)</pre><blockquote>“Output ONLY the revised response” prevents meta-commentary. Without this constraint, the model typically prepends something like “I have revised the response to remove the unsupported claim about the premium amount…” — which would be displayed to the agent as if it were an answer about claim procedures. The constraint is load-bearing, not stylistic.</blockquote><h4><strong>Grade_utility — Is the Answer Actually Useful?</strong></h4><p>Grounding is necessary but not sufficient. An answer can be fully supported by its source documents and still fail the user if it is too generic, missing critical details, or structured in a way the agent cannot relay to a client.</p><pre>class IsUSEDecision(BaseModel):<br>    isuse: Literal[&#39;useful&#39;, &#39;not_useful&#39;]<br>    reason: str<br><br># Useful if: directly answers the query with specific actionable info,<br>#   includes relevant numerics (amounts, percentages, timelines),<br>#   complete information (claims → documents + timeline + criteria),<br>#   professional language the agent can relay to clients.<br><br># NOT useful if: too generic (&#39;varies by case&#39; without specifics),<br>#   missing critical details (premium without coverage),<br>#   vague timelines, contains &#39;consult the policy&#39; without actual info.<br><br>MAX_REWRITE_TRIES = 3<br><br>def route_after_grade_utility(state):<br>    if state.get(&#39;isuse&#39;) == &#39;useful&#39;:<br>        return &#39;END&#39;<br>    if state.get(&#39;rewrite_tries&#39;, 0) &gt;= MAX_REWRITE_TRIES:<br>        return &#39;handle_fallback&#39;<br>    return &#39;transform_query&#39;   # outer loop</pre><h4><strong>Transform_query — The Outer Loop</strong></h4><p>When an answer passes hallucination checking but fails utility grading, the problem is upstream: retrieval did not surface the right documents. The query transformer rewrites the original question with a different retrieval strategy.</p><pre>class RewriteDecision(BaseModel):<br>    retrieval_query: str<br><br># The transformer sees both:<br># - state[&#39;question&#39;]          original user intent, immutable<br># - state[&#39;retrieval_query&#39;]   previous search that failed<br># Seeing the failed query prevents generating the same one again.<br><br># Domain-aware rewriting strategies:<br># 1. Expand abbreviations: CI → Critical Illness, NCB → No Claim Bonus<br># 2. Add insurance context: &#39;loan&#39; → &#39;policy loan facility life insurance&#39;<br># 3. Include related terminology: synonyms, document types<br># 4. Specify document type: products | policies | client cases<br><br># Examples:<br># &#39;NCB for client X&#39; → &#39;No claim bonus accumulated client policy X motor&#39;<br># &#39;Loan on policy&#39;   → &#39;Life insurance policy loan facility eligibility amount&#39;<br><br>def transform_query(state: State):<br>    rewrite_count = state.get(&#39;rewrite_tries&#39;, 0) + 1<br>    decision = rewrite_llm.invoke(<br>        rewrite_prompt.format_messages(<br>            question=state[&#39;question&#39;],<br>            retrieval_query=state.get(&#39;retrieval_query&#39;, &#39;&#39;),<br>        )<br>    )<br>    return {<br>        &#39;retrieval_query&#39;: decision.retrieval_query,<br>        &#39;rewrite_tries&#39;:   rewrite_count,<br>        &#39;docs&#39;: [], &#39;relevant_docs&#39;: [], &#39;context&#39;: &#39;&#39;,  # reset for new cycle<br>    }<br><br># Graph edge: transform_query → fetch_documents (outer loop)</pre><h3><strong>Self-RAG in Action: The Same Query</strong></h3><blockquote><strong>Test query: “What is the claim settlement process for SecureLife’s critical illness insurance?”</strong></blockquote><p><strong>[route_query] </strong>Retrieval required — specific product and procedure query. Routes to fetch_documents.</p><p><strong>[fetch_documents → grade_documents] </strong>4 chunks retrieved; 3 pass the binary relevance check (the motor insurance chunk is filtered). relevant_docs contains 3 items.</p><p><strong>[synthesize_answer]</strong> Initial answer generated. Covers required documents and approval criteria. States the settlement window as ‘approximately 90 days’ — a subtle paraphrase of the source text.</p><p><strong>[check_hallucination]</strong> Returns partially_supported. Evidence list flags: ‘Source says within 90 days; response says approximately 90 days. Approximation introduces uncertainty not present in the document.’ Routes to refine_response.</p><p><strong>[refine_response]</strong> Corrects ‘approximately 90 days’ to ‘within 90 days’. Retries = 1.</p><p><strong>[check_hallucination again]</strong> Returns fully_supported. All numerical values verified. Routes to grade_utility.</p><p><strong>[grade_utility] </strong>Returns useful. Answer includes all required documents (diagnosis certificate, attending physician statement, original policy), the 90-day timeline, and the two-stage approval process. Routes to END.</p><blockquote>What Self-RAG caught that CRAG missed: the ‘approximately 90 days’ paraphrase. CRAG’s architecture stops at the generator input — it has no mechanism to detect what the generator does with the context. Self-RAG’s hallucination checker operates on the generated output and enforces an exact-match standard for contractual numerical terms.</blockquote><p><strong><em>Read next: Part 4 closes the series with a full comparison, the combined CRAG + Self-RAG pipeline, honest limitations, and what to build next.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c71afd73a44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Corrective RAG: Fixing Bad Retrieval Before It Reaches the Generator]]></title>
            <link>https://medium.com/@meghnani.bhavya/corrective-rag-fixing-bad-retrieval-before-it-reaches-the-generator-818cbe1a931d?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/818cbe1a931d</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 17:35:40 GMT</pubDate>
            <atom:updated>2026-03-17T17:45:40.501Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A four-part series on building AI systems that know when they’re wrong.</em></p><blockquote><strong>Prerequisites: </strong>Read Part 1 of this series for the theoretical background on why vanilla RAG fails and how the research community approached the problem.</blockquote><h3>THIS SERIES</h3><p>A complete guide from theory to hands-down code implementing Insurance AI copilot use-case.</p><blockquote><a href="https://medium.com/@meghnani.bhavya/everything-theory-why-rag-breaks-and-how-research-fixed-it-2d5c23a7a0ef"><strong>Part 1 </strong>— Everything Theory: why RAG breaks, what the research says, and the conceptual architecture of corrective and self-reflective systems.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/corrective-rag-fixing-bad-retrieval-before-it-reaches-the-generator-818cbe1a931d"><strong>Part 2 </strong>— Corrective RAG (CRAG): the paper, the architecture diagram, the code, the graph. Fixing bad retrieval before it reaches the generator.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/self-rag-when-the-generator-needs-to-check-its-own-work-8c71afd73a44"><strong>Part 3 </strong>— Self-RAG: the paper, the reflection tokens, the nine-node LangGraph implementation. Fixing bad generation after it happens.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/conclusion-putting-it-all-together-773a0934a046"><strong>Part 4 </strong>— Conclusion: side-by-side comparison, combined pipeline design, limitations, and what to build next.</a></blockquote><h3><strong>Corrective RAG (CRAG): What the Paper Actually Says</strong></h3><p>CRAG was published by Shi-Qi Yan, Jia-Chen Gu, Yun Zhu, and Zhen-Hua Ling in January 2024, from USTC and UCLA. It was accepted and presented at ICLR 2024. The paper’s central thesis is deceptively simple: most RAG systems treat retrieval as infallible. They retrieve, then generate — regardless of whether the retrieved documents are actually relevant. Link: <strong>Link: </strong><a href="https://arxiv.org/abs/2401.15884"><strong>https://arxiv.org/abs/2401.15884</strong></a><strong>?</strong></p><p><strong>“CRAG asks the question that standard RAG never does: what if the retriever got it wrong?”</strong></p><blockquote><strong>“Indiscriminately incorporating retrieved documents, regardless of relevance, can actively mislead the generator — making RAG worse than no retrieval at all.” — Yan et al., 2024</strong></blockquote><h4><strong>The Three-Way Verdict</strong></h4><p>CRAG introduces a lightweight retrieval evaluator that assigns one of three confidence levels to the set of retrieved documents for a given query:</p><ul><li><strong>Correct (score ≥ UPPER_TH):</strong> At least one retrieved document is sufficiently relevant. Proceed with Knowledge Refinement — decompose documents into sentence-level strips, filter irrelevant strips, recompose the survivors as clean knowledge (k_in).</li><li><strong>Incorrect (score ≤ LOWER_TH):</strong> No retrieved document is relevant. Discard all local documents. Rewrite the query for web search and use the web results as external knowledge (k_ex).</li><li><strong>Ambiguous (LOWER_TH &lt; score &lt; UPPER_TH): </strong>Uncertain quality. Combine both k_in (refined local) and k_ex (web-searched) as the generator’s context — hedging between the two sources.</li></ul><p>The Ambiguous path is the most nuanced part of the paper and the most commonly omitted in implementations. When the evaluator is uncertain, the safest strategy is to use both knowledge sources. This is not the same as always using both — it is only triggered when confidence is genuinely low.</p><h4><strong>The Decompose-Then-Recompose Algorithm</strong></h4><p>Even when a document is classified as Correct, it likely contains irrelevant content. A policy document may contain relevant claim procedures on one page but administrative boilerplate and definitions of other products across many others. CRAG addresses this with a sentence-level refinement algorithm:</p><ol><li><strong>Decompose: </strong>Split each retrieved document into individual sentences (strips).</li><li><strong>Filter: </strong>Score each strip for relevance to the specific query. Discard strips below a relevance threshold.</li><li><strong>Recompose:</strong> Join the surviving strips into a coherent context string, preserving order.</li></ol><p>The result is a context that is both smaller and more signal-dense than the original retrieved chunks. The generator is never distracted by irrelevant sentences — even within otherwise relevant documents.</p><blockquote><strong>In the original paper, a fine-tuned T5 model performs the strip-level scoring. In our code implementation, we apply the same LLM that handles all other evaluations — trading marginal scoring accuracy for operational simplicity and fewer models to maintain.</strong></blockquote><h4><strong>ARCHITECTURE DIAGRAM</strong></h4><p><strong>Reading the CRAG Architecture Diagram</strong></p><p>The figure below is taken directly from the CRAG paper (Figure 2, Yan et al. 2024). Reading it carefully is the fastest way to understand the full system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*-aWlyZOhETGf-ihK-WES_A.png" /><figcaption><strong><em>Figure 2 from Yan et al. (2024) — The CRAG framework at inference time. Retrieved documents d₁ and d₂ are evaluated; the resulting confidence degree triggers one of three knowledge retrieval actions before the Generator sees any context.</em></strong></figcaption></figure><h4><strong>Walking Through the Diagram</strong></h4><ul><li><strong>Top row (Retrieval):</strong> A question x is posed; the retriever returns documents d₁ and d₂. These are raw, unfiltered retrieval results.</li><li><strong>Middle left (Retrieval Evaluator): </strong>The evaluator asks “If retrieved documents are correct to x?” — scoring confidence and branching into Correct (green), Ambiguous (orange), or Incorrect (red).</li><li><strong>Middle right — Knowledge Refinement (green box):</strong> For the Correct path, d₁ and d₂ are decomposed into strip₁, strip₂…strip<em>ₙ</em>. A filter removes irrelevant strips (shown with the ✗ filter symbol). Surviving strips are recomposed into k_in (internal knowledge).</li><li><strong>Middle right — Knowledge Searching (red box):</strong> For the Incorrect path, x is rewritten into a search query q (e.g., ‘Death of a Batman; screenwriter; Wikipedia’). A web search returns k₁…k<em>ₙ</em>, which are selected to produce k_ex (external knowledge).</li><li><strong>Bottom row (Generation): </strong>The Generator receives x plus the appropriate knowledge: Correct → x + k_in; Ambiguous → x + k_in + k_ex; Incorrect → x + k_ex. The Generator never receives raw, unfiltered d₁/d₂.</li></ul><blockquote><strong>The key insight the diagram conveys: The Generator </strong>is downstream of a quality gate. It only ever receives knowledge that has been evaluated, filtered, or verified by an external source. Context contamination is architecturally impossible in a correctly implemented CRAG system.</blockquote><h3><strong>IMPLEMENTATION</strong></h3><p>If you would like to dive deeper, the <strong>complete implementation of Corrective RAG and Self-RAG using LangGraph and LangChain is available on GitHub</strong>:<br> <a href="https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG">https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG</a></p><h4><strong>Building CRAG: Node by Node</strong></h4><p>Our implementation follows the paper’s architecture faithfully. Seven nodes, one conditional branch, no cycles. Here is each node in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*5582N-itSmaidhPQm8FK9g.png" /><figcaption><strong><em>The compiled CRAG LangGraph graph — generated directly from app.get_graph().draw_mermaid_png(). The Document Relevance Check node is the single conditional branch point. Both paths converge at Context Synthesis before Answer Generation.</em></strong></figcaption></figure><h4><strong>The State Schema</strong></h4><p>LangGraph requires a TypedDict that serves as the shared memory across all nodes. Every node reads from it and returns a partial update.</p><pre>class State(TypedDict):<br>    question: str            # original user question, never modified<br>    docs: List[Document]     # raw top-k retrieved chunks<br>    good_docs: List[Document]# chunks that passed the evaluator<br>    verdict: str             # CORRECT | INCORRECT<br>    reason: str              # evaluator&#39;s reasoning (for logging)<br>    strips: List[str]        # sentence-level decomposed strips<br>    kept_strips: List[str]   # strips surviving relevance filter<br>    refined_context: str     # final assembled context for generator<br>    web_query: str           # rewritten query for Google search<br>    web_docs: List[Document] # results from Google Custom Search<br>    answer: str              # final generated answer</pre><h4><strong>Node: Knowledge Retrieval</strong></h4><p>Takes the user question, queries the FAISS vector store, returns the top-4 chunks.</p><pre># Ingestion (runs once at startup)<br>chunks = RecursiveCharacterTextSplitter(<br>    chunk_size=900, chunk_overlap=150<br>).split_documents(docs)<br>retriever = FAISS.from_documents(chunks, embeddings)<br>             .as_retriever(search_kwargs={&#39;k&#39;: 4})<br><br>def retrieve_node(state: State):<br>    docs = retriever.invoke(state[&#39;question&#39;])<br>    return {&#39;docs&#39;: docs}</pre><h4><strong>Node: Document Relevance Check</strong></h4><p>The architectural heart of CRAG. Each retrieved document receives a continuous confidence score (0.0–1.0). Documents scoring above UPPER_TH (0.7) are kept as good_docs. If any good_docs exist, verdict = CORRECT. Otherwise verdict = INCORRECT and the system escalates to web search.</p><pre>UPPER_TH = 0.7   # paper&#39;s recommended threshold for Correct<br>LOWER_TH = 0.3   # below this = Incorrect (middle = Ambiguous)<br><br>class DocEvalScore(BaseModel):<br>    score: float    # 0.0–1.0 confidence<br>    reason: str     # brief explanation (logged for debugging)<br><br># Scoring rubric in the system prompt:<br># 1.0   → directly answers query with specific details<br># 0.7-0.9 → moderately relevant, useful related information<br># 0.4-0.6 → tangentially relevant<br># 0.0-0.3 → not relevant, no connection to query<br><br>def eval_each_doc_node(state: State):<br>    good_docs = []<br>    for i, doc in enumerate(state[&#39;docs&#39;], start=1):<br>        decision = doc_eval_llm.invoke(<br>            doc_eval_prompt.format_messages(<br>                question=state[&#39;question&#39;], doc=doc.page_content<br>            )<br>        )<br>        if decision.score &gt;= UPPER_TH:<br>            good_docs.append(doc)<br>    verdict = &#39;CORRECT&#39; if good_docs else &#39;INCORRECT&#39;<br>    return {&#39;good_docs&#39;: good_docs, &#39;verdict&#39;: verdict}</pre><blockquote><strong>Why a continuous score rather than direct classification? </strong>The threshold becomes a configuration parameter, not a prompt change. In a high-precision domain like insurance you can raise UPPER_TH to 0.85 without modifying the LLM prompt — just change a constant. This is good systems design: separate policy from mechanism.</blockquote><h4><strong>Node: Query Optimization</strong></h4><p>Activates only on the INCORRECT path. Rewrites the user’s conversational question into a keyword-rich web search query. The strategy is explicitly domain-aware: expand abbreviations, add insurance terminology, remove conversational language.</p><pre>class WebQuery(BaseModel):<br>    query: str<br><br># Rewriting examples baked into the prompt:<br># &#39;How does CI claims work?&#39;<br>#   → &#39;critical illness insurance claim settlement process requirements&#39;<br># &#39;What are the benefits of life insurance?&#39;<br>#   → &#39;life insurance policy benefits coverage sum assured&#39;<br><br>def rewrite_query_node(state: State):<br>    decision = rewrite_llm.invoke(<br>        rewrite_prompt.format_messages(question=state[&#39;question&#39;])<br>    )<br>    return {&#39;web_query&#39;: decision.query}</pre><h4><strong>Node: External Knowledge Search</strong></h4><p>Calls the Google Custom Search API and wraps each snippet as a LangChain Document. The uniform Document interface means the downstream Context Synthesis node handles both local and web-sourced content identically.</p><pre>def web_search_node(state: State):<br>    params = {<br>        &#39;key&#39;: os.getenv(&#39;GOOGLE_API_KEY&#39;),<br>        &#39;cx&#39;:  os.getenv(&#39;GOOGLE_CSE_ID&#39;),<br>        &#39;q&#39;:   state[&#39;web_query&#39;]<br>    }<br>    r = requests.get(&#39;https://www.googleapis.com/customsearch/v1&#39;,<br>                     params=params)<br>    web_docs = [<br>        Document(page_content=item[&#39;snippet&#39;])<br>        for item in r.json().get(&#39;items&#39;, [])<br>    ]<br>    return {&#39;web_docs&#39;: web_docs}</pre><h4><strong>Node: Context Synthesis</strong></h4><p>Assembles the final context for the generator. Simple logic, significant consequence.</p><pre>def refine(state: State):<br>    # CORRECT path: use locally evaluated good_docs<br>    # INCORRECT path: use web_docs (good_docs will be empty)<br>    # Full CRAG: Ambiguous path would use both<br>    docs = state[&#39;good_docs&#39;] or state[&#39;web_docs&#39;]<br>    context = &#39;\n\n&#39;.join([d.page_content for d in docs])<br>    return {&#39;refined_context&#39;: context}</pre><h3><strong>CRAG in Action: A Real Query</strong></h3><blockquote><strong>Test query: “What is the claim settlement process for SecureLife’s critical illness insurance?”</strong></blockquote><p><strong>[Input Query → Knowledge Retrieval]</strong> 4 chunks retrieved from the insurance corpus via FAISS.</p><p><strong>[Document Relevance Check]</strong></p><ul><li>Doc 1 → 0.92 (critical illness claim procedures — directly relevant).</li><li>Doc 2 → 0.78 (claim documentation requirements — relevant).</li><li>Doc 3 → 0.41 (general health insurance overview — tangential).</li><li>Doc 4 → 0.18 (motor insurance exclusions — not relevant).</li></ul><p><strong><em>Verdict: CORRECT. 2 of 4 docs pass. Routes direct to Context Synthesis.</em></strong></p><p><strong>[Context Synthesis] </strong>Context assembled from docs 1 and 2 only. Motor insurance and generic health context discarded. Generator receives 2 focused, relevant chunks.</p><p><strong>[Answer Generation → Final Response]</strong> Answer generated from clean context: lists required documents (medical reports, diagnosis certificate, attending physician statement), settlement timeline (within 90 days of complete documentation), and the two-stage approval process.</p><blockquote><strong>What CRAG prevented:</strong> without the document filter, the generator would have received the motor insurance exclusion chunk (Doc 4, score 0.18) as context. A well-behaved model might ignore it; a model under pressure to generate might attempt to synthesise from it, producing a confused answer that mixes CI and motor insurance procedures.</blockquote><p><strong><em>Read next: Part 3 covers Self-RAG — what happens when the generator still produces a partially-supported answer even after CRAG’s pre-filtering.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=818cbe1a931d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything Theory: Why RAG Breaks and How Research Fixed It]]></title>
            <link>https://medium.com/@meghnani.bhavya/everything-theory-why-rag-breaks-and-how-research-fixed-it-2d5c23a7a0ef?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d5c23a7a0ef</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[machine-learning-ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 17:28:59 GMT</pubDate>
            <atom:updated>2026-03-17T17:45:54.409Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A four-part series on building AI systems that know when they’re wrong</em></p><h3><strong>THIS SERIES</strong></h3><p>A complete guide from theory to hands-down code implementing Insurance AI copilot use-case.</p><blockquote><a href="https://medium.com/@meghnani.bhavya/everything-theory-why-rag-breaks-and-how-research-fixed-it-2d5c23a7a0ef"><strong>Part 1 </strong>— Everything Theory: why RAG breaks, what the research says, and the conceptual architecture of corrective and self-reflective systems.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/corrective-rag-fixing-bad-retrieval-before-it-reaches-the-generator-818cbe1a931d"><strong>Part 2 </strong>— Corrective RAG (CRAG): the paper, the architecture diagram, the code, the graph. Fixing bad retrieval before it reaches the generator.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/self-rag-when-the-generator-needs-to-check-its-own-work-8c71afd73a44"><strong>Part 3 </strong>— Self-RAG: the paper, the reflection tokens, the nine-node LangGraph implementation. Fixing bad generation after it happens.</a></blockquote><blockquote><a href="https://medium.com/@meghnani.bhavya/conclusion-putting-it-all-together-773a0934a046"><strong>Part 4 </strong>— Conclusion: side-by-side comparison, combined pipeline design, limitations, and what to build next.</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*52asxopIGGQqWzHK" /><figcaption>RAG is a framework designed to bridge the gap between parametric knowledge (what an LLM learns during pre-training) and non-parametric knowledge (external, dynamic data).</figcaption></figure><h3><strong>The Question Every RAG Developer Eventually Asks</strong></h3><p>You build your RAG pipeline. You embed your documents, wire up a retriever, prompt your LLM. It works — until it doesn’t. Your system confidently cites the wrong policy number. Or it retrieves something plausibly adjacent to the question but contextually useless and synthesises nonsense from it. Or the answer is technically grounded but so generic it fails the user completely.</p><p>These are not edge cases. They are the default failure modes of every production RAG system. They are silent, hard to catch in testing, and expensive in high-stakes domains — insurance, legal, medical, finance — where a wrong answer has real-world consequences.</p><p><strong>Two research papers, </strong>published months apart in 2023 and 2024, tackle this from opposite ends of the pipeline. Together they represent a fundamentally different philosophy: instead of trusting the pipeline, they audit it.</p><p><strong>Corrective RAG (CRAG)</strong> intercepts bad retrieval before it reaches the generator. <strong>Link: </strong><a href="https://arxiv.org/abs/2401.15884"><strong>https://arxiv.org/abs/2401.15884</strong></a><strong>?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*F6QEVTr-ev0_MYOTy3ge0g.png" /><figcaption>An overview of the proposed CRAG at inference. A retrieval evaluator is constructed to evaluate the relevance of the retrieved documents to the input, and estimate a confidence degree based on which different knowledge retrieval actions of {Correct, Incorrect, Ambiguous} can be triggered.</figcaption></figure><p><strong>Self-RAG</strong> intercepts bad generation before it reaches the user. <strong>Link: </strong><a href="https://arxiv.org/abs/2310.11511"><strong>https://arxiv.org/abs/2310.11511</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*x-DMKs4B7XBxJxBYdrHl4A.png" /><figcaption>Overview of SELF-RAG. SELF-RAG learns to retrieve, critique, and generate text passages to enhance overall generation quality, factuality, and verifiability</figcaption></figure><blockquote><strong>“Standard RAG is a one-shot gamble. The advanced systems in this series don’t gamble — they verify.”</strong></blockquote><h3><strong>THE STANDARD RAG PIPELINE</strong></h3><h4><strong>How Vanilla RAG Works — and Where It Fails</strong></h4><p>Before we can understand what CRAG and Self-RAG fix, we need to be precise about what vanilla RAG does and where each step can go wrong. The pipeline has four stages:</p><ol><li><strong>Embed the question</strong> into a vector using a dense embedding model (e.g. nomic-embed-text, text-embedding-3-small).</li><li><strong>Retrieve the top-k</strong> nearest chunks from a vector store (FAISS, Pinecone, Chroma) using approximate nearest-neighbour search.</li><li><strong>Assemble a prompt</strong> by concatenating the retrieved chunks as context with the original question.</li><li><strong>Generate an answer</strong> using a large language model conditioned on that prompt.</li></ol><p>Each stage introduces a distinct failure mode. Understanding which stage failed is essential for choosing the right corrective strategy.</p><h4><strong>Failure Mode 1: The Semantic Gap</strong></h4><p>Cosine similarity between embedding vectors is a proxy for semantic relatedness — not for relevance to a specific question. A query about “policy loan eligibility” may retrieve chunks about “loan documentation requirements” because both live in the insurance-loan semantic neighbourhood. The retriever has no concept of what the user actually needs; it only knows what words appear near what other words in the embedding space.</p><blockquote>This is the fundamental limitation that CRAG addresses. By introducing an evaluator between retrieval and generation, CRAG replaces the implicit trust in cosine similarity with an explicit relevance judgment.</blockquote><h4><strong>Failure Mode 2: Context Contamination</strong></h4><p>Even when some retrieved chunks are relevant, the others are not. Vanilla RAG passes all top-k chunks to the generator regardless. The generator, trained to be helpful and to use the provided context, will attempt to synthesise an answer from all of it — including the irrelevant parts. This produces answers that are diluted, confused, or confidently wrong about details from the wrong chunk.</p><blockquote>CRAG’s document-level filtering and decompose-then-recompose algorithm both target this failure mode.</blockquote><h4><strong>Failure Mode 3: Hallucination Under Pressure</strong></h4><p>Even with perfectly relevant context, a language model can hallucinate. This is not always obvious — the hallucination is often a small modification of something that is in the context, not an outright fabrication. A waiting period of “within 90 days” becomes “approximately 90 days”. A coverage limit of “up to 90% of surrender value” becomes “around 85%”. These micro-hallucinations are the most dangerous kind because they pass a surface-level reading.</p><blockquote>This is precisely what Self-RAG’s hallucination checker is designed to catch — not gross fabrications, but subtle paraphrasing that introduces inaccuracy.</blockquote><h4><strong>Failure Mode 4: The Query-Retrieval Mismatch</strong></h4><p>User questions are written in natural language optimised for communication, not retrieval. “Can Priya take a loan on her policy?” is a perfectly clear question. But the relevant document chunk is indexed under “life insurance policy loan facility eligibility” — a phrase that appears nowhere in the user’s question. The embedding of the user’s question and the embedding of the relevant chunk will be further apart in vector space than the embedding of a superficially related but actually useless chunk.</p><blockquote>Both CRAG and Self-RAG include query rewriting mechanisms, each calibrated to their respective contexts.</blockquote><h4><strong>Failure Mode 5: No Quality Signal</strong></h4><p>Standard RAG is a one-shot, open-loop system. It has no mechanism to evaluate what it produced. It cannot distinguish between an answer that is precise and actionable versus one that is vague enough to be technically grounded but practically useless. It does not know to try again.</p><blockquote>“Self-RAG’s utility grader exists specifically to close this loop.”</blockquote><h3><strong>THE RESEARCH LANDSCAPE: How the Research Community Responded</strong></h3><p>The limitations of vanilla RAG were well-known before 2023. Several research directions emerged to address them:</p><h4><strong>Adaptive Retrieval</strong></h4><p>Early work recognised that not every query needs retrieval. For general knowledge, common concepts, and conversational exchanges, retrieval adds latency and can introduce noise. The first question a self-aware RAG system should ask is whether to retrieve at all. Self-RAG formalises this as the [Retrieve] token in the paper’s training framework — though in our implementation it becomes the route_query node.</p><h4><strong>Retrieval Evaluation</strong></h4><p>If you are going to retrieve, you should evaluate what you retrieved. CRAG (Yan et al., 2024) formalised this as the retrieval evaluator — a lightweight model that scores retrieved documents and triggers different downstream paths based on a three-way confidence verdict. Concurrent work by Yoran et al. (2023) used NLI models for similar filtering. CRAG’s contribution was the three-way verdict (Correct/Ambiguous/Incorrect) and the web search escalation path.</p><h4><strong>Generation Verification</strong></h4><p>Even after evaluating retrieved documents, the generator can still hallucinate. Self-RAG (Asai et al., 2023) introduced the idea of using the model itself as a critic — generating special reflection tokens that encode whether retrieval was needed, whether retrieved documents were relevant, and whether the generated output was supported by them. In the original paper, these are actual tokens in the model’s vocabulary, produced by a fine-tuned LM. In our agentic LangGraph implementation, we replicate this behaviour through explicit evaluation nodes with structured outputs.</p><blockquote>“Both CRAG and Self-RAG are built on the same philosophical premise: a system that can evaluate the quality of its own intermediate outputs is more robust than one that cannot. Quality gates, not quality assumptions.”</blockquote><h3><strong>ARCHITECTURE OVERVIEW</strong></h3><h4><strong>The Two Architectures at a Glance</strong></h4><p>Before diving into the implementations in Parts 2 and 3, it helps to understand the structural difference between the two approaches. This shapes everything from code organisation to latency profiles to deployment decisions.</p><h4><strong>CRAG: A Pre-Generation Quality Gate</strong></h4><p>CRAG inserts evaluation between retrieval and generation. Its graph is a directed acyclic graph — a single forward pass with one conditional branch. The question is: are the retrieved documents good enough to generate from? If yes, refine them and generate. If no, escalate to web search, then generate. Either way, the generator receives clean, pre-filtered context.</p><blockquote>CRAG’s graph looks like this: Retrieve → Evaluate → (Refine | Rewrite + Web Search) → Synthesise Context → Generate. No cycles. No iteration. One pass.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*5582N-itSmaidhPQm8FK9g.png" /><figcaption><strong><em>The compiled CRAG LangGraph graph — generated directly from app.get_graph().draw_mermaid_png(). The Document Relevance Check node is the single conditional branch point. Both paths converge at Context Synthesis before Answer Generation.</em></strong></figcaption></figure><h4><strong>Self-RAG: A Post-Generation Quality Gate</strong></h4><p>Self-RAG inserts evaluation after generation. Its graph is a directed cyclic graph — it has two feedback loops. The inner loop corrects hallucinations: generate → check → refine → check again. The outer loop corrects retrieval failures: evaluate utility → rewrite query → re-retrieve → regenerate. The generator may run multiple times, with each run checked against its source context.</p><blockquote>Self-RAG’s graph looks like this: Route → (Skip | Retrieve → Grade) → Synthesise → Check Hallucination → (Pass | Refine)* → Grade Utility → (Pass | Rewrite → Retrieve)*. The asterisks mark the loops.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*Lx4GZQ3Y9N8jd9LLvuwOeg.png" /><figcaption><strong><em>The compiled Self-RAG LangGraph graph, generated directly from app.get_graph().draw_mermaid_png(). Solid arrows are unconditional edges; dotted arrows are conditional. The two feedback cycles are clearly visible.</em></strong></figcaption></figure><p>If you would like to dive deeper, the <strong>complete implementation of Corrective RAG and Self-RAG using LangGraph and LangChain is available on GitHub</strong>: <a href="https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG">https://github.com/bhavyameghnani/Corrective-RAG-Self-Reflective-RAG</a></p><p><strong><em>Read next: Part 2 of this series goes deep into CRAG — the paper, the full architecture diagram, and every node of the LangGraph implementation with annotated code.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d5c23a7a0ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Compelling ESG Stories with LangGraph and Gemini]]></title>
            <link>https://medium.com/@meghnani.bhavya/crafting-compelling-esg-stories-with-langgraph-and-gemini-1bd56cf95f2f?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bd56cf95f2f</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[langgraph-use-cases]]></category>
            <category><![CDATA[esg]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 17:25:53 GMT</pubDate>
            <atom:updated>2025-09-13T17:42:54.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbmT9vSPCD4JanQbY91QEw.png" /><figcaption>The power of story telling to change the world !!</figcaption></figure><p>ESG (Environmental, Social, and Governance) isn’t just a corporate buzzword. It’s a critical lens for understanding a company’s impact and values. Yet, these complex topics can often feel dry or abstract. What if we could automate the process of turning dense ESG data into engaging, human-centric stories?</p><p>This article will show you how to build a dynamic storytelling agent using <strong>LangGraph</strong> and <strong>Google’s Gemini model</strong>, creating a system that can research, draft, and even refine compelling narratives on any sustainability topic.</p><h3>The Challenge: From Data to Narrative</h3><p>Transforming research into a story is a multi-step process. A human writer would first research a topic, extract key insights, create an outline, draft the story, and then edit it. Each of these steps requires different skills — from analytical research to creative writing and critical editing.</p><p>This is where LangGraph excels. It allows us to define a <strong>state machine</strong> where each node represents a specific task, and the output of one task becomes the input for the next. The entire process is orchestrated as a single, cohesive workflow, moving the story from its initial topic to a final, polished draft.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxtoDTGfeFDhyLF8MWHLWA.png" /><figcaption>And the story begins — LangGraph and it’s Multi-Agents :)</figcaption></figure><h3>The Architecture: A Multi-Agent Workflow</h3><p>Our system is built on a series of specialized AI agents, each handling a distinct part of the storytelling process. Let’s break down the core components of the provided code: <a href="https://github.com/bhavyameghnani/LangGraph-AI-Agents-Code-Snippets-Use-cases/blob/main/Use-cases/StoryGenerator/gemini-esg-story-agent-v1.py">Full Code</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uMeAP40882iXOim6EQFTiw.png" /><figcaption>LangGraph Workflow</figcaption></figure><h4>1. State Definition (StoryState)</h4><p>We begin by defining the StoryState, a TypedDict that acts as the shared memory for our entire graph. This dictionary holds all the information needed at each stage, from the initial topic to the final_story.</p><pre>class StoryState(TypedDict):<br>    topic: str<br>    queries: list<br>    search_results: str<br>    insights: str<br>    story_draft: str<br>    story_final: str<br>    qa_result: Literal[&quot;approved&quot;, &quot;needs_fix&quot;]<br>    feedback: str<br>    iteration: int<br>    max_iterations: int</pre><p>This state object is the single source of truth that is passed from node to node, ensuring continuity and coherence throughout the workflow.</p><p>In our LangGraph workflow, qa_result: Literal[&quot;approved&quot;, &quot;needs_fix&quot;] is a crucial part of the shared <strong>state</strong> that governs the flow of the entire process.</p><ul><li>qa_result: This is a key in our StoryState dictionary, a variable that holds the result of the quality assurance check.</li><li>Literal[&quot;approved&quot;, &quot;needs_fix&quot;]: This is a Python type hint. It tells us that the value of qa_result can only be one of two specific strings: &quot;approved&quot; or &quot;needs_fix&quot;. This enforces a strict, predictable outcome from the QA step, which is essential for the graph&#39;s routing logic.</li></ul><p>When the qa_story function runs, it evaluates the drafted story. Based on its assessment, it updates the state by setting the qa_result to either &quot;approved&quot; (if the story meets the criteria) or &quot;needs_fix&quot; (if it doesn&#39;t).</p><p>This simple binary output is what the route_qa function uses to decide whether the workflow should end or if the story needs to be sent back for refinement. It&#39;s the lynchpin that allows the graph to create a powerful, self-correcting loop.</p><h4>2. Agent Nodes: The Specialized AIs</h4><p>Each function in the code represents a <strong>node</strong> in our LangGraph workflow. These nodes are the “agents” that perform specific tasks.</p><ul><li>form_queries: This node takes the topic and generates a list of focused search queries. For example, for the topic &quot;Plastic Waste in Oceans,&quot; it creates queries like &quot;Plastic Waste in Oceans ESG challenges and failures.&quot;</li><li>run_research: This agent uses the GoogleSearchAPIWrapper and a news API to fetch a comprehensive set of results for each query. It combines these results into a single string for the next step.</li><li>extract_insights: Using the powerful <strong>Gemini 1.5 Flash</strong> model, this node analyzes the raw research and distills it into key themes: problems, mindset barriers, best practices, and recent examples.</li><li>draft_story: With the extracted insights in hand, this creative agent crafts a full narrative based on a predefined structure (hook, problem, solution, ending). This is where the magic of Gemini&#39;s storytelling capabilities shines.</li></ul><pre>Example of node (agent):<br><br>def draft_story(state: StoryState):<br>    messages = [<br>        SystemMessage(content=&quot;You are a creative storyteller specializing in ESG and sustainability.&quot;),<br>        HumanMessage(content=f&quot;&quot;&quot;<br>Using these insights:<br>{state[&#39;insights&#39;]}<br><br>Write an engaging short story (~600-800 words, ~5 minutes read). <br>Story structure:<br>- Hook (why it matters now)<br>- Problem (real-world failures / challenges)<br>- Mindset barrier (what prevents change)<br>- Solutions (best practices + recent examples)<br>- Ending (hopeful, inspiring, call to action)<br><br>Keep it human, narrative-driven, and impactful.<br>&quot;&quot;&quot;)<br>    ]<br>    draft = llm.invoke(messages).content<br>    return {&quot;story_draft&quot;: draft}</pre><ul><li>qa_story: This is our QA editor agent. It reviews the draft against a set of requirements, such as word count and narrative flow. It returns a verdict: &quot;approved&quot; or &quot;needs_fix&quot;.</li><li>refine_story: If the story needs a fix, this agent takes the QA feedback and the previous draft to generate a refined version.</li></ul><h4>3. Tool: The Agent’s Hands and Eyes</h4><p>In the provided code, a <strong>Tool</strong> is an abstraction that gives our LangGraph agent the ability to interact with the external world. While the Large Language Model (LLM) is great at reasoning and generating text, it’s limited to the data it was trained on. A <strong>Tool</strong> extends the agent’s capabilities beyond this. Think of it as a function the agent can call to perform a specific, real-world task.</p><pre># Search tool abstraction for LangChain<br>search_tool = Tool(<br>    name=&quot;google_search&quot;,<br>    func=search_wrapper.run,<br>    description=&quot;Use this tool to search Google&quot;<br>)<br><br>def run_research(state: StoryState):<br>    all_results = []<br>    for q in state[&quot;queries&quot;]:<br>        google_res = search_tool.run(q)<br>        news_res = requests.get(<br>            f&quot;https://newsapi.org/v2/everything?q={q}&amp;language=en&amp;sortBy=publishedAt&amp;pageSize=3&amp;apiKey={NEWS_API_KEY}&quot;<br>        ).json()<br>        snippets = [a[&quot;title&quot;] + &quot; - &quot; + a[&quot;url&quot;] for a in news_res.get(&quot;articles&quot;, [])]<br>        all_results.append(f&quot;Query: {q}\nGoogle: {google_res}\nNews: {snippets}&quot;)<br>    return {&quot;search_results&quot;: &quot;\n\n&quot;.join(all_results)}</pre><h3>How the search_tool Works</h3><p>The search_tool in the code is a prime example of this concept. It&#39;s a special kind of callable object designed to be used by an agent.</p><ol><li><strong>Name and Description</strong>: The name (&quot;google_search&quot;) and description are crucial. The LLM, when given a choice of tools, uses these descriptions to understand what each tool does and when to use it. In this case, the description, &quot;Use this tool to search Google,&quot; is explicit and directs the LLM to use it for information retrieval.</li><li><strong>Functionality</strong>: The func parameter is where the real power lies. Here, it&#39;s set to search_wrapper.run, which is a function that executes a Google search using the Google Search API.</li><li><strong>Integration</strong>: Inside the run_research function, the agent explicitly calls search_tool.run(q). This isn&#39;t the LLM making a decision to use a tool; it&#39;s a pre-programmed, human-defined step in the workflow. This highlights a key distinction in LangGraph—we are orchestrating the process and telling the agent <em>when</em> to use its tools, rather than letting it decide autonomously. This deterministic approach provides control and predictability.</li></ol><h3>The Workflow Graph: Orchestrating the Process</h3><p>The real power lies in how we connect these nodes. The StateGraph object defines the flow, including crucial decision points.</p><pre>graph = StateGraph(StoryState)<br># Add all the nodes<br># ...<br>graph.add_edge(START, &quot;form_queries&quot;)<br>graph.add_edge(&quot;form_queries&quot;, &quot;research&quot;)<br>graph.add_edge(&quot;research&quot;, &quot;insights&quot;)<br>graph.add_edge(&quot;insights&quot;, &quot;draft&quot;)<br>graph.add_edge(&quot;draft&quot;, &quot;qa&quot;)<br><br># The critical conditional edge:<br>graph.add_conditional_edges(&quot;qa&quot;, route_qa, {&quot;done&quot;: END, &quot;fix&quot;: &quot;refine&quot;})<br>graph.add_edge(&quot;refine&quot;, &quot;qa&quot;)</pre><p>This graph creates a <strong>loop</strong>: after a story is drafted and reviewed by the qa node, a conditional edge, route_qa, decides the next step. If the story is approved (&quot;done&quot;), the workflow ends. If it needs a fix (&quot;fix&quot;), it routes the story back to the refine node, starting the cycle again. This allows our agent to automatically iterate and improve the story until it meets the quality standards. Example of the final 5mins short story curated by our Multi-Agent project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HX3RW_3XhWFp5zazKRZY6g.png" /><figcaption>Final Output</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sJR-GZaf3kNiJB8c4CSwBA.png" /><figcaption>The Happy Ending !!</figcaption></figure><h3>The Power of Iteration and Loops</h3><p>Traditional LLM chains are linear: a prompt goes in, an answer comes out, and the process is finished. Our LangGraph workflow, however, introduces a crucial element: a <strong>feedback loop</strong>. This is the qa -&gt; route_qa -&gt; refine -&gt; qa cycle. This pattern is a cornerstone of building robust, autonomous AI systems.</p><p><strong>Why are iterative loops so powerful?</strong></p><ol><li><strong>Self-Correction and Improvement:</strong> The agent doesn’t just produce a single draft and hope for the best. It actively evaluates its own work. The qa_story node acts as a critical editor, identifying weaknesses like a lack of real-world examples or poor narrative flow.</li><li><strong>Increased Reliability:</strong> By adding a max_iterations parameter, we ensure the agent doesn&#39;t get stuck in an infinite loop while also giving it a chance to fix its mistakes. This &quot;try again&quot; mechanism dramatically increases the chances of a high-quality final output.</li><li><strong>Mimicking Human Processes:</strong> This iterative refinement mirrors how a human writer works. A writer drafts a piece, reads it over, gets feedback from an editor, and then revises. LangGraph allows us to model this complex, non-linear process programmatically, making the AI’s behavior more human-like and effective.</li></ol><p>The add_conditional_edges function is the key to this loop. It evaluates the output of a node (in this case, the qa_result from qa_story) and dynamically decides which path to take. This is a massive leap from simple, sequential chains, as it allows for intelligent, state-dependent decision-making within the graph.</p><h3>Putting It All Together</h3><p>The final workflow is a Compiled graph ready for use. When we invoke it with an initial state (like the topic &quot;Plastic Waste in Oceans&quot;), the graph handles the entire process autonomously, from forming queries to printing the final, polished story. This demonstrates how a complex, multi-step creative task can be broken down into manageable, automatable steps using the right tools.</p><p>This approach isn’t just for writing; it’s a powerful pattern for any complex task that requires multiple, sequential steps with conditional logic, from data analysis to content generation and beyond. The combination of LangGraph for orchestration and powerful models like Gemini for reasoning and creativity opens up new possibilities for building sophisticated, intelligent systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGNFQAK6_OlJuefPSWPOXA.png" /><figcaption>What’s stops you to create a Multi-Agent Tool?</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bd56cf95f2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gemini API and Vertex AI SDK for Python Developers]]></title>
            <link>https://medium.com/@meghnani.bhavya/gemini-api-and-vertex-ai-sdk-for-python-developers-385301e6918c?source=rss-f6ea646131b8------2</link>
            <guid isPermaLink="false">https://medium.com/p/385301e6918c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[vertex-ai]]></category>
            <dc:creator><![CDATA[Bhavya Meghnani]]></dc:creator>
            <pubDate>Sun, 17 Aug 2025 08:02:39 GMT</pubDate>
            <atom:updated>2025-08-17T08:04:57.314Z</atom:updated>
            <content:encoded><![CDATA[<p>The Gemini family of generative AI models, developed by Google DeepMind, is a versatile tool designed for a variety of multimodal use cases.</p><p>This article will walk you through how to use the Gemini API in Vertex AI with the Vertex AI SDK for Python. You’ll learn how to generate text from text prompts and work with multimodal inputs like images and videos.</p><p><strong>GithHub Repo for developers:</strong> <a href="https://github.com/bhavyameghnani/Google-Cloud---GenAI-Academy-Gemini-and-Vertex-AI-">https://github.com/bhavyameghnani/Google-Cloud---GenAI-Academy-Gemini-and-Vertex-AI-</a></p><h3>Prerequisites and Setup</h3><p>Before you start, you’ll need a Google Cloud project with the Vertex AI API enabled. First, install the Vertex AI SDK for Python by running the following command in your environment:</p><pre>%pip install --upgrade --user google-cloud-aiplatform</pre><p>Next, you need to initialize the Vertex AI SDK with your Google Cloud project ID and location.</p><pre>import os<br>import vertexai<br><br>PROJECT_ID = &quot;your-project-id&quot;  # Replace with your project ID<br>LOCATION = os.environ.get(&quot;GOOGLE_CLOUD_REGION&quot;, &quot;us-central1&quot;)<br><br>vertexai.init(project=PROJECT_ID, location=LOCATION)</pre><h3>Interacting with the Gemini Model</h3><p>The Gemini API in Vertex AI offers a unified interface for interacting with Gemini models. This article focuses on the gemini-2.0-flash model.</p><p>First, load the model. You can send a text prompt to the model using the generate_content method to get a text response.</p><pre>from vertexai.generative_models import GenerativeModel<br>model = GenerativeModel(&quot;gemini-2.0-flash&quot;)<br><br>response = model.generate_content(&quot;Why is the sky blue?&quot;)<br>print(response.text)</pre><p>By default, the model returns a complete response at once. For longer responses, you can use streaming to get chunks of the response as they are generated.</p><pre>responses = model.generate_content(&quot;Why is the sky blue?&quot;, stream=True)<br>for response in responses:<br>    print(response.text, end=&quot;&quot;)</pre><h3>Model parameters</h3><p>Every prompt you send to the model includes parameter values that control how the model generates a response. The model can generate different results for different parameter values. You can experiment with different model parameters to see how the results change.</p><pre>generation_config = GenerationConfig(<br>    temperature=0.9,<br>    top_p=1.0,<br>    top_k=32,<br>    candidate_count=1,<br>    max_output_tokens=8192,<br>)<br><br>response = model.generate_content(<br>    &quot;Why is the sky blue?&quot;,<br>    generation_config=generation_config,<br>)<br><br>print(response.text)</pre><h3>Safety Filters</h3><p>The Gemini API provides safety filters that you can adjust across multiple filter categories to restrict or allow certain types of content. You can use these filters to adjust what’s appropriate for your use case. See the Configure safety filters page for details.</p><p>When you make a request to Gemini, the content is analyzed and assigned a safety rating. You can inspect the safety ratings of the generated content by printing out the model responses, as in this example:</p><pre>response = model.generate_content(&quot;Why is the sky blue?&quot;)<br>print(f&quot;Safety ratings:\n{response.candidates[0].safety_ratings}&quot;)</pre><p>Gemini 2.0 Flash, by default, employs safety filters with relatively low block thresholds, effectively allowing more content through. Developers can use the safety_settings parameter to customize the block thresholds for various content categories, such as setting BLOCK_ONLY_HIGH for dangerous content, to enforce stricter safety measures on a per-request basis.</p><pre>from vertexai.generative_models import HarmCategory, HarmBlockThreshold, SafetySetting<br><br>safety_settings = [<br>    SafetySetting(<br>        category=HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,<br>        threshold=HarmBlockThreshold.BLOCK_ONLY_HIGH,<br>    ),<br>]<br>prompt = &quot;&quot;&quot;    Write a list of 2 disrespectful things that I might say to the universe after stubbing my toe in the dark.&quot;&quot;&quot;<br>response = model.generate_content(<br>    prompt,<br>    safety_settings=safety_settings,<br>)<br>print(response)</pre><h3>Multi-turn Conversations</h3><p>The Gemini API also supports natural, multi-turn conversations, making it great for building chatbots or other conversational applications.</p><p>Here’s an example of a simple chat interaction: The model remembers the context of the conversation. You can send a follow-up prompt, and it will respond based on the previous turns.</p><pre>chat = model.start_chat()<br><br>prompt_1 = &quot;My name is Ned. You are my personal assistant. My favorite movies are Lord of the Rings and Hobbit. Suggest another movie I might like.&quot;<br>response_1 = chat.send_message(prompt_1)<br>print(response_1.text)<br><br>prompt_2 = &quot;Are my favorite movies based on a book series?&quot;<br>response_2 = chat.send_message(prompt_2)<br>print(response_2.text)<br><br>#You can also inspect the full chat history to see the conversation flow.<br>print(chat.history)</pre><h3>Multimodal Capabilities: Images and Videos</h3><p>Gemini excels at understanding and generating content based on multimodal inputs. You can use it to analyze and respond to prompts that include images and videos.</p><h4>Working with Images</h4><p>To work with images, you need to import the Image class from the Vertex AI SDK and specify the image path. The model can then analyze the image and respond to a text prompt.</p><pre>from vertexai.generative_models import GenerativeModel, Part, Image<br>model = GenerativeModel(&quot;gemini-1.5-pro-preview-0409&quot;)<br><br># Load image from a file<br>image_path = &quot;path/to/your/image.jpg&quot;<br>image_file = Part.from_image(Image.load_from_file(image_path))<br><br># Load image from a URI<br>image_url = &quot;https://example.com/your/image.jpg&quot;<br>image_file = Part.from_uri(image_url, mime_type=&quot;image/jpeg&quot;)<br><br># Generate content from the image<br>response = model.generate_content([image_file, &quot;Describe this image in detail.&quot;])<br>print(response.text)</pre><h4>Working with Videos</h4><p>Similarly, you can analyze video content. This example shows how to send a video file and a text prompt to the model to generate a structured response, such as a summary of key moments.</p><pre>from vertexai.generative_models import GenerativeModel, Part, GenerationConfig<br>model = GenerativeModel(&quot;gemini-1.5-flash-preview-0514&quot;)<br><br># Load a video file from a Google Cloud Storage URI<br>video_file = Part.from_uri(<br>    &quot;gs://cloud-samples-data/generative-ai/video/rio_de_janeiro_beyond_the_map_rio.mp4&quot;,<br>    &quot;video/mp4&quot;,<br>)<br><br># Define the prompt and the desired output schema<br>prompt = &quot;&quot;&quot;<br>Analyze the video and provide a summary of each chapter.<br>Please only capture key events and highlights. If you are not sure about any info, please do not make it up.<br>&quot;&quot;&quot;<br><br>response_schema = {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>        &quot;chapters&quot;: {<br>            &quot;type&quot;: &quot;array&quot;,<br>            &quot;items&quot;: {<br>                &quot;type&quot;: &quot;object&quot;,<br>                &quot;properties&quot;: {<br>                    &quot;start_time&quot;: {&quot;type&quot;: &quot;number&quot;},<br>                    &quot;end_time&quot;: {&quot;type&quot;: &quot;number&quot;},<br>                    &quot;summary&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                },<br>            },<br>        }<br>    },<br>}<br><br># Generate content from the video and prompt with the specified schema<br>response = model.generate_content(<br>    contents=[video_file, prompt],<br>    generation_config=GenerationConfig(<br>        response_mime_type=&quot;application/json&quot;,<br>        response_schema=response_schema,<br>    ),<br>)<br>print(response.text)</pre><h3>Eample: Image Analysis</h3><p>The Gemini API can also analyze and respond to image inputs. This is useful for tasks like object recognition, content summarization, or answering questions about an image’s content.</p><pre>import base64<br>import vertexai<br>from vertexai.generative_models import GenerativeModel, Part, FinishReason<br>import vertexai.preview.generative_models as generative_models<br><br>def generate():<br>  vertexai.init(project=&quot;your-project-id&quot;, location=&quot;europe-west4&quot;)<br>  model = GenerativeModel(&quot;gemini-2.0-flash-001&quot;)<br>  <br>  # A placeholder for the image data<br>  image1 = Part.from_data(<br>      mime_type=&quot;image/png&quot;,<br>      data=base64.b64decode(&quot;&quot;&quot;[... long base64 string ...]&quot;&quot;&quot;)<br>  )<br>  <br>  responses = model.generate_content(<br>      [image1, &quot;&quot;&quot;Change the wording of the prompt in the code cell to make the output less than 10 words.&quot;&quot;&quot;],<br>      generation_config=generation_config,<br>      safety_settings=safety_settings,<br>      stream=True,<br>  )<br><br>  for response in responses:<br>    print(response.text, end=&quot;&quot;)</pre><h3>Additional Examples: Taglines</h3><p>The Gemini API can also be fine-tuned for specific tasks, such as generating creative content like marketing taglines. By providing examples of desired input and output, you can guide the model to produce relevant and high-quality results.</p><p>Here is an example demonstrating a few-shot prompting approach to generate taglines for a durable backpack, emphasizing preparedness and nature:</p><pre>from vertexai.preview.generative_models import GenerativeModel<br><br>model = GenerativeModel(&quot;gemini-2.0-flash-001&quot;)<br>prompt = &quot;&quot;&quot;Cymbal Direct is partnering with an outdoor gear retailer. They&#39;re launching a new line of products designed to encourage young people to explore the outdoors. Help them create catchy taglines for this product line.<br><br>input: Write a tagline for a durable backpack designed for hikers that makes them feel prepared. Consider styles like minimalist.<br>output: Built for the Journey: Your Adventure Essentials.<br><br>input: specifically request that the tagline includes the keyword nature<br>output:&quot;&quot;&quot;<br><br>responses = model.generate_content(<br>    prompt,<br>    generation_config={<br>        &quot;temperature&quot;: 0.5,<br>        &quot;max_output_tokens&quot;: 2048,<br>        &quot;top_p&quot;: 1.0,<br>        &quot;top_k&quot;: 40,<br>    },<br>    stream=True<br>)<br><br>for response in responses:<br>    print(response.text)</pre><h3>Conclusion</h3><p>By blending the power of Gemini with the scalable capabilities of Vertex AI and harnessing the simplicity of the Python SDK, developers can now build generative AI applications that are not only expressive but production-ready. This synergy — whether it’s generating contextual text, handling multimodal inputs like images and videos, or managing function calls — demonstrates how accessible and efficient building intelligent systems has become.</p><p>Also, I am excited to wrap up the <strong>Gen AI Exchange Program — </strong>a step forward in applying Generative AI to real-world projects and solutions. Big thanks to Google Cloud for such a powerful <strong>Gen AI Academy Program. </strong>Gained hands-on skills with Gemini, Vertex AI, Imagen, Streamlit, and Multimodal RAG. Super thrilled to apply these tools in my upcoming projects!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byvdiKIhrfX0GAJHMnNeUA.jpeg" /><figcaption><a href="https://www.credly.com/badges/ea712f54-d8a8-48ef-b203-f07d649bea57/public_url">https://www.credly.com/badges/ea712f54-d8a8-48ef-b203-f07d649bea57/public_url</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=385301e6918c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>