<?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 Argha Dey Sarkar on Medium]]></title>
        <description><![CDATA[Stories by Argha Dey Sarkar on Medium]]></description>
        <link>https://medium.com/@email2argha?source=rss-11eea86a4877------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Jc2VDa8VQzkRImkImYvhkA.jpeg</url>
            <title>Stories by Argha Dey Sarkar on Medium</title>
            <link>https://medium.com/@email2argha?source=rss-11eea86a4877------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:13:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@email2argha/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[ AasthaSathi: Building a Production-Grade Multilingual AI Banking Assistant with LangGraph…]]></title>
            <link>https://medium.com/@email2argha/aasthasathi-building-a-production-grade-multilingual-ai-banking-assistant-with-langgraph-489b05c2443e?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/489b05c2443e</guid>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[finance-ai-tools]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 09:26:47 GMT</pubDate>
            <atom:updated>2025-11-10T09:26:47.326Z</atom:updated>
            <content:encoded><![CDATA[<h3>🏦 AasthaSathi: Building a Production-Grade Multilingual AI Banking Assistant with LangGraph, LangChain &amp; Streamlit</h3><p><strong>GitHub Repository:</strong> <a href="https://github.com/arghads9177/AasthaSathi">AasthaSathi — AI Banking Assistant</a><br> <strong>Duration:</strong> ~156 Man-Hours | <em>End-to-End Development: 3 Weeks</em><br> <strong>Stack:</strong> LangGraph · LangChain · Streamlit · ChromaDB · OpenAI · Google · Groq</p><h3>🚀 Introduction — Bridging Cooperative Banking and AI</h3><p>The journey of <strong>AasthaSathi</strong> began with a simple vision — <em>to bring AI intelligence into the daily operations of a cooperative banking ecosystem</em>.<br> As part of <strong>Aastha Co-operative Credit Society</strong>, the goal was to assist employees, agents, and customers in accessing real-time policy, account, and operational information seamlessly — in their <strong>preferred language</strong>.</p><p>Cooperative banking institutions often rely heavily on manual processes, human intervention, and scattered documentation.<br> AasthaSathi was developed to solve this — a <strong>production-ready AI assistant</strong> that combines <strong>Retrieval-Augmented Generation (RAG)</strong>, <strong>LangGraph-based Agentic Orchestration</strong>, and <strong>Multilingual Intelligence</strong>, all accessible through a clean Streamlit interface.</p><h3>🧱 The Problem Statement</h3><p>Employees and advisors of cooperative societies need to handle:</p><ul><li>Member queries about deposits, loans, or maturity schemes</li><li>Policy clarifications from long PDFs or manuals</li><li>Language barriers between branches and users</li></ul><p>Existing systems lacked a unified, intelligent support layer.<br> Thus, <strong>AasthaSathi</strong> was envisioned as an <em>AI-powered knowledge and operations assistant</em> to:</p><ul><li>Answer queries in <strong>English, Hindi, or Bengali</strong></li><li>Pull verified information from manuals and policies (RAG)</li><li>Retrieve live operational data via APIs</li><li>Offer a transparent, secure, and easy-to-deploy AI experience</li></ul><h3>🧠 System Overview</h3><p><strong>AasthaSathi</strong> is not a chatbot — it’s a <strong>banking AI companion</strong>.<br> It intelligently routes user queries through a hybrid architecture that integrates:</p><ol><li><strong>RAG Knowledge Engine</strong> (for document-based answers)</li><li><strong>Agentic Layer (LangGraph)</strong> for tool orchestration and API interaction</li><li><strong>LLM Fallback System</strong> for robust answer generation</li><li><strong>Multilingual Layer</strong> for contextual response generation in the user’s preferred language</li><li><strong>Streamlit Frontend</strong> for user authentication, role management, and transparent answer display</li></ol><h3>🕰️ Project Timeline &amp; Man-Hours</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*295K17FDi7qo4g2QDkLIOg.png" /></figure><p>The timeline reflects an engineering-focused approach — not just experimentation, but a <em>deployable solution</em> built for real users.</p><h3>⚙️ Architecture Overview</h3><p>The assistant follows a <strong>modular LangGraph-based agentic architecture</strong>, allowing dynamic control of query routing, fallback handling, and language selection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*uBJFlKIaUBY3Msi0YM2uRw.png" /></figure><h3>🧩 Core Components Explained</h3><h3>1️⃣ RAG Knowledge Engine (ChromaDB + LangChain)</h3><ul><li>The <strong>data ingestion pipeline</strong> extracts and embeds organizational content — from product manuals, policy PDFs, and website pages — using <strong>OpenAI embeddings</strong>.</li><li>The data is stored in <strong>ChromaDB</strong>, chosen for its speed, local scalability, and cost efficiency.</li><li>When a user queries, the relevant chunks are retrieved, verified, and passed to the LLM for context-aware response generation.</li></ul><blockquote><em>🧠 </em>This forms the foundation of policy awareness and factual accuracy in the system.</blockquote><h3>2️⃣ Agentic Orchestration with LangGraph</h3><p>Unlike static pipelines, AasthaSathi uses <strong>LangGraph</strong> to orchestrate multiple tools and decision nodes dynamically.</p><ul><li>The <strong>controller node</strong> decides whether the query is policy-based (RAG) or data-based (API).</li><li>Each node (RAG retriever, API handler, language detector, or LLM responder) communicates via graph edges, enabling modular scaling.</li><li>If one model or node fails, LangGraph ensures graceful recovery.</li></ul><blockquote><em>🧩 </em>This modular graph design mimics enterprise workflow automation — but entirely within AI reasoning.</blockquote><h3>3️⃣ Smart LLM Fallback System</h3><p>Reliability in production AI systems is critical.<br> To prevent downtime or model dependency failures, AasthaSathi implements a <strong>three-tier LLM fallback mechanism</strong>:</p><ol><li><strong>Primary:</strong> OpenAI (high-quality response generation)</li><li><strong>Secondary:</strong> Google API (used if OpenAI API timeout/error occurs)</li><li><strong>Tertiary:</strong> Groq API (ultra-fast inference backup)</li></ol><p>This ensures continuous operation even if one service is unavailable.</p><blockquote><em>⚙️ </em>Result: 99.9% uptime and consistent response flow across providers.</blockquote><h3>4️⃣ Multilingual Intelligence Layer</h3><p>India’s cooperative banking workforce communicates in multiple languages.<br> AasthaSathi handles <strong>English, Hindi, and Bengali</strong> seamlessly by:</p><ul><li>Detecting query language automatically</li><li>Routing it through a language-aware LLM prompt template</li><li>Returning the response in the same detected language</li><li>Displaying confidence levels and language metadata in the UI</li></ul><h4>Example:</h4><p><strong>Query (Bengali):</strong> “আসানসোলে কোথায় শাখা রয়েছে?”<br> <strong>Response:</strong> Lists all Asansol branch addresses and codes in Bengali, preserving structure and readability.</p><p><strong>Query (Hindi):</strong> “ट्रस्ट का मिशन क्या है?”<br> <strong>Response:</strong> The system retrieves and explains the cooperative’s mission statement from the policy database, citing the original source.</p><h3>5️⃣ Streamlit Frontend — Simple Yet Powerful</h3><p>The Streamlit-based interface gives a professional, production-like feel with features such as:</p><ul><li>🔐 <strong>User Login &amp; Roles:</strong> Admin, Employee, Advisor</li><li>🗣️ <strong>Multilingual Chat Window:</strong> Auto-detection and translation</li><li>📚 <strong>Source Transparency:</strong> Shows citation links, metadata, and confidence</li><li>📈 <strong>Response Metadata Visualization:</strong> Displays model response times and confidence levels</li><li>🌍 <strong>Language Selector:</strong> Optional manual override</li></ul><h4>UI Showcase</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyptVqLury0RoYqrzvthUw.png" /><figcaption>Home Page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CenQc6mh0DkzRYNz_8PonQ.png" /><figcaption>Chat Home</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lh9EClmotTebIZ8OCSoEJA.png" /><figcaption>Chat in English</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpizW3IvQ2VA4VdbhD6ybQ.png" /><figcaption>Chat in Hindi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4DV61nj1ABM7woczrA3ksg.png" /><figcaption>Chat in Bengali</figcaption></figure><p>Each chat displays:</p><ul><li>Retrieved source links</li><li>Response metadata</li><li>Confidence score</li><li>Like/Dislike feedback options for continuous improvement</li></ul><h3>🧪 Testing &amp; Evaluation</h3><p>AasthaSathi underwent a structured testing process across all layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*m9DQ-N5xMWbixrKMh6AAwA.png" /></figure><blockquote><em>🧾 The final model achieved 98% accuracy in policy-related retrievals and consistent language fidelity across all supported languages.</em></blockquote><h3>📊 Deployment &amp; Production Readiness</h3><ul><li><strong>Deployed:</strong> As part of the MyAastha ecosystem</li><li><strong>Mode:</strong> Streamlit Web App embedded into the existing website</li><li><strong>Scalability:</strong> New knowledge sources or APIs can be added as independent LangGraph nodes</li><li><strong>Security:</strong> Role-based authentication + API tokenization</li><li><strong>Maintenance:</strong> Simple vector store refresh scripts handle periodic data updates</li></ul><h3>🧩 Engineering Insights &amp; Learnings</h3><ol><li><strong>LangGraph &gt; Sequential Pipelines:</strong><br> Graph-based orchestration enables better tool control and modular expansion.</li><li><strong>Fallback Logic is Non-Negotiable:</strong><br> Production systems must plan for API failures; the OpenAI → Google → Groq cascade kept the assistant live at all times.</li><li><strong>ChromaDB Simplifies Vector Management:</strong><br> Local-first, fast, and easy to integrate — ideal for enterprise-scale RAG systems.</li><li><strong>Multilingual Systems Need Context, Not Just Translation:</strong><br> Direct translation can distort semantics — instead, designing prompt templates per language ensures clarity and respect for regional tone.</li><li><strong>Streamlit Makes AI UX Production-Ready:</strong><br> With proper state management and role control, Streamlit can go far beyond prototypes.</li></ol><h3>🧭 Conclusion — Beyond a Prototype</h3><p><strong>AasthaSathi</strong> is a demonstration of how modern AI frameworks like <strong>LangGraph</strong> and <strong>LangChain</strong> can be engineered to create <strong>real, usable AI assistants</strong> — not just demos.</p><p>It integrates structured reasoning, reliable retrieval, multilingual adaptability, and a clean user experience into one cohesive solution.<br> Built in just <strong>156 hours</strong>, it stands as a <strong>production-grade AI Banking Assistant</strong> ready for deployment in cooperative financial institutions.</p><p>🔗 Explore the full implementation here:<br> 👉 <a href="https://github.com/arghads9177/AasthaSathi">GitHub Repository — AasthaSathi</a></p><h3>💬 Closing Thought</h3><blockquote>AI adoption in traditional finance doesn’t always require complex infrastructure — it needs thoughtful architecture, modular design, and reliable engineering. AasthaSathi is a testament to that philosophy.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=489b05c2443e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Supervisor in the Loop: How I Built a Smarter Multi-Agent Travel Planner with LangGraph & GPT-4]]></title>
            <link>https://medium.com/@email2argha/supervisor-in-the-loop-how-i-built-a-smarter-multi-agent-travel-planner-with-langgraph-gpt-4-0b65a9483107?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b65a9483107</guid>
            <category><![CDATA[generative-ai-use-cases]]></category>
            <category><![CDATA[langgraph-use-cases]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[supervisor-multi-agent]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 10:00:11 GMT</pubDate>
            <atom:updated>2025-10-05T10:00:11.312Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An end-to-end walkthrough of a Supervisor-style multi-agent architecture that plans your next trip intelligently — with LLMs that don’t just talk, but collaborate.</em></p><h3>✈️ TL;DR</h3><p>Planning a trip usually means juggling flights, hotels, itineraries, and budgets — a perfect storm for automation.<br> This post shows how I built an <strong>AI Travel Planner Assistant</strong> powered by a <strong>Supervisor multi-agent architecture</strong> using <strong>LangGraph</strong>, <strong>LangChain</strong>, <strong>GPT-4</strong>, <strong>FastAPI</strong>, and <strong>Gradio</strong>.</p><p>You’ll learn:</p><ul><li>What a <em>Supervisor multi-agent system</em> is and why it matters.</li><li>How each agent — transport, hotel, itinerary — works under a supervisor’s guidance.</li><li>How the workflow ensures correctness, constraint validation, and iterative refinement.</li><li>How to implement this architecture yourself.</li></ul><h3>🌍 1. Introduction: Why Supervisors Matter in Multi-Agent Systems</h3><p>Modern LLMs can plan, reason, and summarize — but not <em>govern</em> themselves.<br> When multiple LLMs collaborate, things can go wrong: overlapping roles, redundant reasoning, and missing constraints.</p><p>That’s where the <strong>Supervisor architecture</strong> comes in.<br> Inspired by <strong>hierarchical multi-agent systems</strong> and <strong>supervisory control theory</strong>, this pattern introduces a <em>manager agent</em> (the Supervisor) that delegates tasks to specialized agents, collects results, validates them, and integrates feedback into a single coherent output.</p><blockquote><em>💡 </em><strong><em>In short:</em></strong><em> The Supervisor doesn’t do the work — it makes sure every agent does the </em>right<em> work, correctly.</em></blockquote><h3>🧳 2. Problem Statement: Building the AI Travel Planner</h3><p><strong>Challenge:</strong><br> Planning a trip is a high-dimensional optimization problem involving user goals, dates, locations, budgets, and preferences.</p><p><strong>Goal:</strong><br> Design a conversational AI that takes a plain-English goal like</p><blockquote><em>“Plan a 4-day cultural trip to Jaipur next month within ₹40,000”</em></blockquote><p>and automatically outputs a complete, feasible markdown travel plan.</p><p><strong>Features implemented:</strong></p><ul><li>🗣️ <strong>Natural-language goal input</strong></li><li>🧠 <strong>Intent classification</strong> — full trip / hotel-only / transport-only</li><li>🧩 <strong>Constraint extraction</strong> — origin, destination, budget, interests, dates</li><li>👥 <strong>Multi-agent workflow</strong> — supervisor + specialized agents</li><li>🔁 <strong>Supervisor review loop</strong> — iterative validation and improvement</li><li>🧾 <strong>Final plan summarization</strong> — markdown format</li><li>⚙️ <strong>FastAPI + Gradio integration</strong></li><li>✅ <strong>Pytest automation for reliability</strong></li></ul><h3>🧠 3. Supervisor Architecture Explained</h3><p>At the core of this system lies a <strong>LangGraph-powered multi-agent workflow</strong>.</p><h3>🔺 Hierarchical View</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*ft0IF2KAUXOvYyKRGR8kwA.jpeg" /><figcaption>Supervisor Agent Architecture</figcaption></figure><h3>💬 Key Roles</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*TwQZHpZwEoSOOTh_NxfIUg.png" /></figure><h3>⚙️ Core Technologies</h3><ul><li><strong>LangGraph</strong> — orchestrates nodes (agents) and manages the review loop.</li><li><strong>GPT-4 (ChatOpenAI)</strong> — powers reasoning, extraction, and summarization.</li><li><strong>TavilySearch</strong> — fetches live travel/hotel data.</li><li><strong>FastAPI</strong> — backend for /plan endpoint.</li><li><strong>Gradio</strong> — frontend for user input and output.</li><li><strong>Pydantic</strong> — validation of structured outputs</li><li><strong>Pytest</strong> — automated endpoint testing.</li></ul><h3>🧩 4. Implementation Walkthrough</h3><h3>4.1 Data &amp; Schema Design</h3><p>The project defines all agent outputs as <strong>Pydantic models</strong> in models.py:</p><pre>class Constraints(BaseModel):<br>    origin: str<br>    destination: str<br>    start_date: str<br>    end_date: str<br>    budget: str<br>    interests: List[str]</pre><p>Similar models exist for:</p><ul><li>TransportOption (mode, price, provider)</li><li>HotelOption (name, rating, cost, amenities)</li><li>ItineraryItem (day, description, activity)</li><li>ReviewFeedback (approved, feedback)</li><li>Intention (travel_plan, hotel_only, transport_only, unrelated)</li></ul><p>This ensures the LLMs always produce <strong>typed, parseable JSON</strong>.</p><h3>4.2 Supervisor Workflow (from agents.py)</h3><p>The LangGraph <strong>StateGraph</strong> defines nodes for every agent:</p><pre>graph = StateGraph(PlannerState)</pre><pre>graph.add_node(&quot;supervisor&quot;, supervisor_node)<br>graph.add_node(&quot;planner&quot;, planner_node)<br>graph.add_node(&quot;transport&quot;, transport_node)<br>graph.add_node(&quot;hotel&quot;, hotel_node)<br>graph.add_node(&quot;itinerary&quot;, itinerary_node)<br>graph.add_node(&quot;final_summarizer&quot;, summarizer_node)<br>graph.add_node(&quot;end_unrelated&quot;, end_unrelated_node)</pre><p>The <strong>supervisor_gate</strong> decides next steps based on intent and review count:</p><pre>if intent == &quot;unrelated&quot;:<br>    return &quot;end_unrelated&quot;<br>if state[&quot;supervisor_approved&quot;]:<br>    return END<br>if state[&quot;review_count&quot;] &gt; 2:<br>    return END<br>return &quot;planner&quot;</pre><p>This logic creates an <strong>iterative feedback loop</strong> — the Supervisor reviews the generated plan, provides feedback, and asks the Planner to adjust constraints or regenerate sections until satisfied.</p><h3>4.3 Agent Responsibilities</h3><p>Each agent has a single, focused role.</p><h4>🚌 Transport Agent</h4><pre>query = f&quot;transport options from {origin} to {destination}&quot;<br>results = tavily_tool.invoke({&quot;query&quot;: query})<br>transport_chain.invoke({&quot;context&quot;: results, &quot;constraints&quot;: constraints})</pre><h4>🏨 Hotel Agent</h4><pre>query = f&quot;best hotels in {destination} within {budget}&quot;<br>results = tavily_tool.invoke({&quot;query&quot;: query})<br>hotel_chain.invoke({&quot;context&quot;: results, &quot;constraints&quot;: constraints})</pre><h4>📅 Itinerary Agent</h4><pre>query = f&quot;top attractions in {destination} for {interests}&quot;<br>results = tavily_tool.invoke({&quot;query&quot;: query})<br>itinerary_chain.invoke({&quot;context&quot;: results, &quot;constraints&quot;: constraints})</pre><p>Each chain instructs GPT-4 to return <strong>only valid JSON</strong> according to its schema. If parsing fails, the agent returns an empty list, keeping the system resilient.</p><h3>4.4 Supervisor Review Loop</h3><p>After the final_summarizer Composes the markdown plan, the <strong>Supervisor</strong> reviews it:</p><pre>review_feedback = review_chain.invoke({<br>    &quot;plan&quot;: state[&quot;final_plan&quot;],<br>    &quot;constraints&quot;: state[&quot;constraints&quot;]<br>})<br>if not review_feedback.approved:<br>    state[&quot;supervisor_feedback&quot;] = review_feedback.feedback<br>    state[&quot;review_count&quot;] += 1</pre><p>This is the critical <em>supervisory control loop</em> — quality assurance before final output.</p><h3>4.5 Backend + UI Integration</h3><h4>⚙️ FastAPI Backend (main.py)</h4><pre>@app.post(&quot;/plan&quot;)<br>async def plan_endpoint(request: dict):<br>    state = generate_travel_plan(request)<br>    return {&quot;final_plan&quot;: state[&quot;final_plan&quot;]}</pre><h4>💻 Gradio UI (app.py)</h4><pre>import gradio as gr<br>iface = gr.Interface(fn=call_api, inputs=&quot;text&quot;, outputs=&quot;markdown&quot;)<br>iface.launch()</pre><p>This keeps the architecture modular — API for integration, Gradio for demos.</p><h3>💎 5. Benefits, Challenges &amp; Mitigations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*WyipMP___XnVcntkvTqqdA.png" /></figure><h3>⚠️ Challenges</h3><ul><li><strong>Latency:</strong> multiple LLM calls per iteration. → <em>Mitigation:</em> run agents in parallel.</li><li><strong>Single Point of Failure:</strong> supervisor crash halts flow. → <em>Mitigation:</em> hierarchical supervisors or retry logic.</li><li><strong>Cost:</strong> multiple GPT-4 calls. → <em>Mitigation:</em> use smaller models for extraction &amp; review.</li></ul><h3>📊 6. Observability &amp; Metrics</h3><p>What we track:</p><ul><li>success_rate = completed itineraries / total requests</li><li>avg_review_loops per request</li><li>avg_agent_latency</li><li>supervisor_rework_ratio</li></ul><p>Metrics exported via FastAPI middleware → Prometheus/Grafana.</p><p>Example queries:</p><pre>rate(supervisor_reviews_total[5m])<br>histogram_quantile(0.95, sum(rate(agent_latency_seconds_bucket[5m])) by (le, agent))</pre><h3>🏭 7. When (and When Not) to Use This Architecture</h3><p>✅ Use it when:</p><ul><li>The task requires <em>validation</em> or <em>cross-agent consistency</em>.</li><li>You want modularity &amp; interpretability.</li><li>You expect complex, multi-constraint reasoning.</li></ul><p>🚫 Avoid it when:</p><ul><li>Tasks are trivial or time-critical (latency-sensitive).</li><li>Peer consensus or decentralization is required (use networked MAS instead).</li></ul><h3>✨ 8. Results</h3><p>When a user says:</p><blockquote><em>“Plan a 3-day budget trip to Goa next month focused on beaches.”</em></blockquote><p>The system produces a markdown itinerary:</p><pre>## ✈️ Your 3-Day Goa Beach Trip<br>**Dates:** 12–14 Nov  <br>**Budget:** ₹25,000  <br>**Transport:** Indigo Flight (₹6,500 return)  <br>**Stay:** OceanView Resort (₹4,200/night)  <br>**Itinerary:**<br>- Day 1: Arrival + Baga Beach sunset<br>- Day 2: Island Cruise + Water Sports<br>- Day 3: Café hopping + return flight</pre><p>And yes — all under Supervisor control, ensuring every section aligns with constraints.</p><h3>🧩 9. Code Organization Recap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*cECq7adpIqdmBkoIOKqeiw.png" /></figure><h3>🚀 10. Conclusion</h3><p>The <strong>Supervisor multi-agent architecture</strong> bridges the gap between LLM creativity and real-world reliability.<br> By combining <em>structured data</em>, <em>specialized agents</em>, and a <em>supervisory review loop</em>, we can build AI systems that plan, reason, and validate like domain experts.</p><blockquote><em>“Agents work fast — but Supervisors make them </em>right<em>.”</em></blockquote><p>The Travel Planner Assistant isn’t just a prototype; it’s a blueprint for <strong>multi-agent orchestration with real-world impact</strong> — extendable to financial advisory, document workflows, and decision-support systems.</p><h3>🖼️ Visual Assets for the Post</h3><ul><li>Diagram: “Supervisor → Agents → Feedback Loop”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubuU-DLSnK1wUehA8n1nRA.png" /><figcaption>Use Case Architecture</figcaption></figure><ul><li>Screenshot: Gradio interface with a generated plan</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQAATnlAhU663bhTOPLXrA.png" /><figcaption>Travel Planner</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WIPGnyqn_QijUrS5RVXb9g.png" /><figcaption>Generated Full Travel Plan</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cU1cOvHNHOCLEgS99U-5A.png" /><figcaption>Generated Tranport Only Plan</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7HsG2anITV3JRJLCmw7dQw.png" /><figcaption>Generated Hotel Only Plan</figcaption></figure><p><strong>CTA:</strong><br> 💡 <em>Want to explore the full repo, LangGraph YAML, and test scripts?</em><br> Drop a comment or DM me — I’ll share the public GitHub link soon.</p><p><strong>#AI #LangChain #LangGraph #MultiAgentSystems #GPT4 #GenerativeAI #FastAPI #TravelTech</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b65a9483107" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚙️Delegate, Parallelize, Synthesize — Building Orchestrator–Worker Workflows with LangGraph]]></title>
            <link>https://medium.com/@email2argha/%EF%B8%8Fdelegate-parallelize-synthesize-building-orchestrator-worker-workflows-with-langgraph-d01b767655c4?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/d01b767655c4</guid>
            <category><![CDATA[generative-ai]]></category>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[orchestrator]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 14:31:41 GMT</pubDate>
            <atom:updated>2025-09-12T14:31:41.349Z</atom:updated>
            <content:encoded><![CDATA[<h3>⚙️<strong>Delegate, Parallelize, Synthesize — Building Orchestrator–Worker Workflows with LangGraph</strong></h3><h3>Introduction</h3><p>When working with Large Language Models (LLMs), some tasks are straightforward (summarize a document, classify a text), but many are <strong>complex and dynamic</strong>. For example, creating a detailed technical report may require different sections depending on the topic.</p><p>Running a static, predefined workflow won’t cut it here. Instead, you need an <strong>orchestrator</strong> that can:</p><ol><li><strong>Plan</strong> the subtasks at runtime,</li><li><strong>Dispatch</strong> them to multiple workers (in parallel), and</li><li><strong>Synthesize</strong> the worker outputs into a polished final result.</li></ol><p>This is the essence of the <strong>Orchestrator–Worker pattern in LangGraph</strong>.</p><p>In this blog, we’ll explore this pattern step by step through a <strong>practical use case</strong>: generating a multi-section technical report dynamically with an orchestrator planner, worker nodes, and a synthesizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDjzHwi2H-Ld990oZkjH3A.png" /></figure><h3>What Is Orchestrator–Worker in LangGraph?</h3><p>The <strong>Orchestrator–Worker</strong> pattern is an agentic workflow architecture where a central <strong>orchestrator</strong> (planner) inspects an input, <strong>dynamically</strong> breaks the job into subtasks, dispatches those subtasks to multiple <strong>worker</strong> nodes (often in parallel), and then <strong>synthesizes</strong> the worker outputs into a single coherent result.</p><p>Unlike a static fan-out (where parallel branches are known at design time), the orchestrator–worker pattern <em>decides at runtime</em>:</p><ul><li>How many workers are needed?</li><li>which subtasks to create,</li><li>and what payload each worker should process.</li></ul><p>This makes it ideal for complex or variable tasks — e.g., generating variable-length documents, decomposing engineering change requests, or splitting a large document into per-page extraction jobs.</p><h3>When — and Why — to Use This Pattern</h3><p><strong>When to use:</strong></p><ul><li>The task has a dynamic structure determined by the content (e.g., the number and type of sections depend on the topic).</li><li>Subtasks can be executed independently.</li><li>You want <strong>horizontal scalability</strong>: run many workers in parallel to reduce latency.</li><li>You want a <strong>clear separation</strong> of planning, execution, and synthesis.</li></ul><p><strong>Why use it (benefits):</strong></p><ul><li><strong>Adaptability:</strong> Orchestrator can adapt the plan to each request.</li><li><strong>Speed:</strong> Workers run concurrently — lower wall-clock time than sequential execution.</li><li><strong>Modularity:</strong> Workers have single responsibilities; easier to test and maintain.</li><li><strong>Resilience:</strong> Orchestrator can implement retries, fallbacks, and partial results synthesis.</li></ul><h3>The Send API &amp; Worker Orchestration (LangGraph)</h3><p>LangGraph exposes primitives to dynamically spawn worker tasks from an orchestrator node (commonly referred to as the <strong>Send</strong> API in LangGraph documentation). Typical flow:</p><ol><li><strong>Orchestrator / Planner</strong>: Creates a structured plan (list of subtasks).</li><li><strong>Dispatch</strong>: For each subtask, the orchestrator issues a Send(&quot;worker&quot;, payload) to run worker with payload.</li><li><strong>Workers</strong>: Execute independently (often LLM calls) and return structured outputs (e.g., {&quot;completed&quot;: {...}}).</li><li><strong>Synthesizer</strong>: Aggregates worker outputs into final product (report/document/summary).</li></ol><p>The code walkthrough below follows this pattern (and mirrors the orchestrator notebook you provided).</p><h3>The Send API &amp; Worker Orchestration</h3><p>LangGraph provides the <strong>Send API</strong> to dynamically dispatch worker nodes from an orchestrator.</p><ul><li>The <strong>Planner Node</strong> creates subtasks.</li><li>The <strong>Assign Workers function</strong> returns multiple Send(&quot;worker&quot;, payload) instructions.</li><li>Each <strong>Worker Node</strong> processes its payload.</li><li>The <strong>Synthesizer</strong> merges results deterministically.</li></ul><p>This makes the orchestrator–worker pattern <strong>flexible and production-ready</strong>.</p><h3>Step 1: Defining the State</h3><pre>from typing_extensions import TypedDict<br><br>class State(TypedDict, total=False):<br>    topic: str<br>    plan: list<br>    completed_sections: list<br>    final_report: str</pre><p>📌 <strong>Explanation:</strong><br> The State is the shared memory of our workflow.</p><ul><li>topic: The subject for the report.</li><li>plan: Subtasks created by the planner.</li><li>completed_sections: Results returned by workers.</li><li>final_report: The synthesized document.</li></ul><h3>Step 2: Planner Node (Orchestrator)</h3><pre>def planner_node(state: State) -&gt; State:<br>    prompt = f&quot;&quot;&quot;<br>    For the topic &quot;{state[&#39;topic&#39;]}&quot;, create a JSON plan with 3–7 sections.<br>    Each section should include:<br>      - name<br>      - description<br>      - order index<br>    &quot;&quot;&quot;<br>    plan = llm_planner.invoke([prompt])<br>    subtasks = [s.dict() for s in plan.subtasks]<br>    return {&quot;plan&quot;: subtasks}</pre><p>📌 <strong>Explanation:</strong><br> The planner uses the LLM to generate a <strong>structured plan</strong> of sections.</p><ul><li>Example: For <em>“Edge AI in Healthcare”</em>, it may output:</li><li>Introduction</li><li>Key Technologies</li><li>Applications</li><li>Challenges</li><li>Future Outlook</li></ul><p>This is the <strong>orchestrator brain</strong>: it decides how to break the task.</p><h3>Step 3: Assigning Workers with Send API</h3><pre>from langgraph.graph import Send<br><br>def assign_workers(state: State):<br>    sends = []<br>    for sub in state.get(&quot;plan&quot;, []):<br>        payload = {&quot;subtask&quot;: sub}<br>        sends.append(Send(&quot;worker&quot;, payload))<br>    return sends</pre><p>📌 <strong>Explanation:</strong><br> For each subtask in the plan, the orchestrator issues a Send(&quot;worker&quot;, payload).</p><ul><li>If there are 5 sections, 5 workers are dispatched.</li><li>If there are 3 sections, only 3 workers are sent.</li></ul><p>This makes the workflow <strong>dynamic and adaptive</strong>.</p><h3>Step 4: Worker Node</h3><pre>def worker_node(state: State) -&gt; State:<br>    sub = state.get(&quot;subtask&quot;)<br>    name, desc = sub[&quot;name&quot;], sub[&quot;description&quot;]<br><br>    prompt = (<br>        f&quot;Write a clear section titled &#39;{name}&#39;.\n&quot;<br>        f&quot;Description: {desc}\n&quot;<br>        f&quot;Keep it 80–200 words, technical, and concise.&quot;<br>    )<br>    response = llm.invoke(prompt)<br>    text = response.content.strip()<br><br>    return {&quot;completed_sections&quot;: [<br>        {&quot;name&quot;: name, &quot;order&quot;: sub[&quot;order&quot;], &quot;text&quot;: text}<br>    ]}</pre><p>📌 <strong>Explanation:</strong><br> Each worker takes their assigned subtask (e.g., “Applications”), calls the LLM, and produces the section text.</p><p>Workers return results in a standard format so the synthesizer can merge them easily.</p><h3>Step 5: Synthesizer Node</h3><pre>def synthesizer_node(state: State) -&gt; State:<br>    completed = state.get(&quot;completed_sections&quot;, [])<br>    ordered = sorted(completed, key=lambda x: x[&quot;order&quot;])<br><br>    lines = [f&quot;# {state.get(&#39;topic&#39;, &#39;Report&#39;)}\n\n&quot;, &quot;## Table of Contents\n&quot;]<br>    for sec in ordered:<br>        lines.append(f&quot;- [{sec[&#39;name&#39;]}](#{sec[&#39;name&#39;].lower().replace(&#39; &#39;, &#39;-&#39;)})\n&quot;)<br>    lines.append(&quot;\n&quot;)<br><br>    for sec in ordered:<br>        lines.append(f&quot;## {sec[&#39;name&#39;]}\n\n{sec[&#39;text&#39;]}\n\n&quot;)<br><br>    return {&quot;final_report&quot;: &quot;&quot;.join(lines)}</pre><p>📌 <strong>Explanation:</strong></p><ul><li>Sorts worker results by order.</li><li>Creates a <strong>Table of Contents</strong> with anchors.</li><li>Builds a polished markdown report.</li></ul><p>This is the <strong>fan-in</strong> step, where everything comes together.</p><h3>Step 6: Building the Graph</h3><pre>from langgraph.graph import StateGraph, START, END<br><br>workflow = StateGraph(State)<br><br>workflow.add_node(&quot;planner&quot;, planner_node)<br>workflow.add_node(&quot;worker&quot;, worker_node)<br>workflow.add_node(&quot;synthesizer&quot;, synthesizer_node)<br><br># Flow: START → Planner → Workers → Synthesizer → END<br>workflow.add_edge(START, &quot;planner&quot;)<br>workflow.add_conditional_edges(&quot;planner&quot;, assign_workers)<br>workflow.add_edge(&quot;synthesizer&quot;, END)<br><br>graph = workflow.compile()</pre><p>📌 <strong>Explanation:</strong></p><ul><li>START goes to planner.</li><li>Planner spawns workers dynamically via Send.</li><li>Workers feed into synthesizer.</li><li>synthesizer produces the final report and sends to END.</li></ul><h3>Step 7: Invoking the Workflow</h3><pre>result = graph.invoke({&quot;topic&quot;: &quot;Edge AI for Drones&quot;})<br>print(result[&quot;final_report&quot;])</pre><p>✅ <strong>Output:</strong> A multi-section, well-structured report with TOC and headings.</p><h3>Workflow Diagram (Mermaid)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*4kpGPLANBVAmZZxTkV3sOA.png" /></figure><p>📌 <strong>Explanation:</strong><br> The planner dynamically decides how many workers are needed. Each worker executes independently, and their outputs converge in the synthesizer.</p><h3>Real-Life Use Cases</h3><ol><li><strong>Research Papers &amp; Technical Report</strong></li></ol><ul><li>Orchestrator designs sections, workers draft them, and the synthesizer merges them into a full paper.</li></ul><p><strong>2. Document Processing (OCR)</strong></p><ul><li>Orchestrator splits PDF into pages, workers OCR in parallel, synthesizer merges text.</li></ul><p><strong>3. Software Documentation</strong></p><ul><li>Orchestrator creates file-level tasks, workers write each file’s docs, and synthesizer builds a manual.</li></ul><p><strong>4. Data Pipeline</strong></p><ul><li>Orchestrator batches records, workers enrich data in parallel, and synthesizer aggregates</li></ul><h3>Best Practices</h3><ul><li><strong>Use structured outputs</strong> for planner → avoids parsing errors.</li><li><strong>Design deterministic reducers</strong> to merge worker outputs.</li><li><strong>Keep workers stateless</strong> and focused.</li><li><strong>Set limits</strong> on fan-out (avoid 1000s of workers at once).</li><li><strong>Add retries &amp; fallbacks</strong> for workers (timeouts, defaults).</li><li><strong>Monitor routing &amp; synthesis</strong> with tools like LangSmith.</li><li><strong>Cache subtasks</strong> when reusing results across requests.</li></ul><h3>Conclusion</h3><p>The <strong>Orchestrator–Worker pattern in LangGraph</strong> gives you a way to handle <strong>dynamic, complex workflows</strong> with elegance.</p><ul><li>Planner (orchestrator) → breaks tasks down.</li><li>Workers → execute independently and in parallel.</li><li>Synthesizer → merges results into a polished product.</li></ul><p>This pattern powers adaptive content generation, document processing, and large-scale AI data workflows.</p><p>With LangGraph’s <strong>Send API</strong>, building these workflows becomes both <strong>powerful</strong> and <strong>maintainable</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d01b767655c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Smarter AI Workflows with Routing in LangGraph: The Content Router Use Case]]></title>
            <link>https://medium.com/@email2argha/smarter-ai-workflows-with-routing-in-langgraph-the-content-router-use-case-2c2c48adb71e?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c2c48adb71e</guid>
            <category><![CDATA[workflow]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[generative-ai]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 14:31:43 GMT</pubDate>
            <atom:updated>2025-09-09T14:31:43.425Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When building AI applications with Large Language Models (LLMs), not all requests are the same. Some users want a <strong>detailed blog post</strong>, others prefer a <strong>short witty tweet</strong>, and some need a <strong>professional LinkedIn update</strong>. Handling all these intents with a <strong>single, monolithic prompt</strong> often results in messy, inconsistent outputs.</p><p>The solution? <strong>Routing.</strong></p><p>Routing allows a workflow to <strong>decide dynamically which node (or agent) should handle a request</strong>, based on the content of the input. Instead of forcing one prompt to do everything, you create specialized nodes and let the workflow route requests intelligently.</p><p>In this blog, we’ll explore routing in LangGraph through a practical use case: <strong>a Content Router that automatically directs queries to the right content generator (blog, tweet, or LinkedIn post).</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*808eMshbcouDXLMX-MxM3g.png" /></figure><h3>What is Routing in LangGraph?</h3><p><strong>Routing</strong> is the process of directing workflow execution to the correct node based on conditions or decisions. In LangGraph, routing can be:</p><ul><li><strong>Deterministic (gates):</strong> Based on rules, validations, or state (e.g., if summary too short → retry).</li><li><strong>LLM-driven (router node):</strong> A lightweight model interprets the user’s request and decides where it should go.</li></ul><h3>🔑 Benefits of Routing</h3><ul><li><strong>Specialization:</strong> Each node handles one format well (blog, tweet, LinkedIn).</li><li><strong>Flexibility:</strong> Easily add or remove content types without breaking the system.</li><li><strong>Maintainability:</strong> Cleaner, modular design instead of one overstuffed prompt.</li><li><strong>Reliability:</strong> Routes are explicit, making it easier to debug and improve.</li></ul><h3>Use Case: Content Router Workflow</h3><p>Our goal: <strong>Build a workflow that routes user queries to the right content type generator.</strong></p><ul><li><strong>Input:</strong> A user query (e.g., <em>“Make a short witty post about coffee.”</em>)</li><li><strong>Router Decision:</strong> Classify as blog/tweet / LinkedIn post.</li><li><strong>Output:</strong> Content generated in the right style.</li></ul><h3>Step 1: Setup &amp; Router Schema</h3><pre>from dotenv import load_dotenv<br>load_dotenv()<br><br>from langchain_groq import ChatGroq<br>from pydantic import BaseModel, Field<br>from typing import Literal<br>from typing_extensions import TypedDict<br><br># Initialize LLM<br>llm = ChatGroq(model=&quot;llama-3.3-70b-versatile&quot;)<br><br># Define structured output schema for router<br>class Route(BaseModel):<br>    next_step: Literal[&quot;blog&quot;, &quot;tweet&quot;, &quot;linkedin&quot;] = Field(<br>        None, description=&quot;Next step in query processing&quot;<br>    )<br><br># Router LLM with structured output<br>llm_router = llm.with_structured_output(Route)</pre><p>📌 <strong>Explanation:</strong><br> We use ChatGroq with a Pydantic schema Route to ensure the router produces a valid next_step (one of: blog, tweet, linkedin). This eliminates parsing ambiguity and makes routing deterministic.</p><h3>Step 2: Defining the State</h3><pre>class State(TypedDict):<br>    query: str<br>    decision: str<br>    output: str</pre><p>📌 <strong>Explanation:</strong><br> The State tracks the user’s query, the router’s decision, and the generated output.</p><h3>Step 3: Router Node</h3><pre>from langchain_core.messages import SystemMessage, HumanMessage<br><br>def router_node(state: State):<br>    &quot;&quot;&quot;Route the input to blog, tweet, or linkedin.&quot;&quot;&quot;<br>    decision = llm_router.invoke(<br>        [<br>            SystemMessage(<br>                content=(<br>                    &quot;Classify the user query into one of: blog, tweet, linkedin &quot;<br>                    &quot;based on what type of content the user is asking for. &quot;<br>                    &quot;If user says &#39;write a detailed article/post&#39; → blog. &quot;<br>                    &quot;If user says &#39;make it short, witty&#39; → tweet. &quot;<br>                    &quot;If user says &#39;write something professional&#39; → LinkedIn.&quot;<br>                )<br>            ),<br>            HumanMessage(content=state[&quot;query&quot;]),<br>        ]<br>    )<br>    return {&quot;decision&quot;: decision.next_step}</pre><p>📌 <strong>Explanation:</strong><br> This node uses the router LLM to decide where to send the query. The output is stored in state[&quot;decision&quot;].</p><h3>Step 4: Handler Nodes</h3><pre># Blog Node: ~150-word article<br>def blog_node(state: State):<br>    response = llm.invoke(<br>        f&quot;Write a detailed blog post (~150 words) based on the request: {state[&#39;query&#39;]}.&quot;<br>        &quot; Make it engaging, structured with an intro, body, and conclusion.&quot;<br>    )<br>    return {&quot;output&quot;: response.content.strip()}<br><br># Tweet Node: &lt;280-character witty post<br>def tweet_node(state: State):<br>    response = llm.invoke(<br>        f&quot;Write a catchy and witty tweet under 280 characters based on the request: {state[&#39;query&#39;]}.&quot;<br>    )<br>    return {&quot;output&quot;: response.content.strip()}<br><br># LinkedIn Node: Professional update<br>def linkedin_node(state: State):<br>    response = llm.invoke(<br>        f&quot;Write a professional LinkedIn post based on the request: {state[&#39;query&#39;]}.&quot;<br>        &quot; Make it formal, concise, and include relevant hashtags.&quot;<br>    )<br>    return {&quot;output&quot;: response.content.strip()}</pre><p>📌 <strong>Explanation:</strong><br> Each handler node specializes in one type of content. Instead of one giant prompt, each node is simple and focused.</p><h3>Step 5: Conditional Routing</h3><pre>from typing import Literal<br><br># Decide which node to route to<br>def route_decision(state: State) -&gt; Literal[&quot;blog_node&quot;, &quot;tweet_node&quot;, &quot;linkedin_node&quot;]:<br>    if state[&quot;decision&quot;] == &quot;blog&quot;:<br>        return &quot;blog_node&quot;<br>    elif state[&quot;decision&quot;] == &quot;tweet&quot;:<br>        return &quot;tweet_node&quot;<br>    elif state[&quot;decision&quot;] == &quot;linkedin&quot;:<br>        return &quot;linkedin_node&quot;</pre><p>📌 <strong>Explanation:</strong><br> The router’s decision is mapped to the actual node names in the graph.</p><h3>Step 6: Building the Graph</h3><pre>from langgraph.graph import StateGraph, START, END<br><br>workflow = StateGraph(State)<br><br># Add nodes<br>workflow.add_node(&quot;router_node&quot;, router_node)<br>workflow.add_node(&quot;blog_node&quot;, blog_node)<br>workflow.add_node(&quot;tweet_node&quot;, tweet_node)<br>workflow.add_node(&quot;linkedin_node&quot;, linkedin_node)<br><br># Start → Router<br>workflow.add_edge(START, &quot;router_node&quot;)<br><br># Router → Conditional edges<br>workflow.add_conditional_edges(<br>    &quot;router_node&quot;,<br>    route_decision,<br>    {<br>        &quot;blog_node&quot;: &quot;blog_node&quot;,<br>        &quot;tweet_node&quot;: &quot;tweet_node&quot;,<br>        &quot;linkedin_node&quot;: &quot;linkedin_node&quot;,<br>    },<br>)<br><br># Handlers → End<br>workflow.add_edge(&quot;blog_node&quot;, END)<br>workflow.add_edge(&quot;tweet_node&quot;, END)<br>workflow.add_edge(&quot;linkedin_node&quot;, END)<br><br># Compile<br>content_creation_flow = workflow.compile()</pre><p>📌 <strong>Explanation:</strong></p><ul><li>router_node decides the path.</li><li>add_conditional_edges directs execution to the correct handler.</li><li>Each handler flows to END.</li></ul><h3>Step 7: Testing the Workflow</h3><pre># Example 1: Blog<br>q = &quot;Write me a detailed post about AI in education.&quot;<br>result = content_creation_flow.invoke({&quot;query&quot;: q})<br>print(&quot;Decision:&quot;, result[&quot;decision&quot;])<br>print(&quot;Output:&quot;, result[&quot;output&quot;])<br><br># Example 2: Tweet<br>q = &quot;Make a short witty post about coffee.&quot;<br>result = content_creation_flow.invoke({&quot;query&quot;: q})<br>print(&quot;Decision:&quot;, result[&quot;decision&quot;])<br>print(&quot;Output:&quot;, result[&quot;output&quot;])<br><br># Example 3: LinkedIn<br>q = &quot;Draft a professional update about our new product launch.&quot;<br>result = content_creation_flow.invoke({&quot;query&quot;: q})<br>print(&quot;Decision:&quot;, result[&quot;decision&quot;])<br>print(&quot;Output:&quot;, result[&quot;output&quot;])</pre><p>✅ Outputs:</p><ul><li>Blog → A 150-word blog with intro/body/conclusion.</li><li>Tweet → A short witty post under 280 characters.</li><li>LinkedIn → A professional post with hashtags.</li></ul><h3>Workflow Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*Q1If61SMmZd9ZB1YoCEyWA.png" /></figure><p>📌 <strong>Explanation:</strong><br> The router node is the decision point. Depending on the classification, execution flows to one of three handlers.</p><h3>Real-Life Use Cases of Routing</h3><ol><li><strong>Customer Support Triage</strong></li></ol><ul><li>Route tickets to Billing / Tech / Sales teams automatically.</li></ul><p><strong>2. Multi-Channel Marketing</strong></p><ul><li>Route content to blog, tweet, LinkedIn, or newsletter generators.</li></ul><p><strong>3. Conversational Assistants</strong></p><ul><li>Route questions to domain-specific agents (legal, HR, engineering).</li></ul><p><strong>4. Document Processing</strong></p><ul><li>Route documents to specialized extractors (invoices vs contracts vs resumes).</li></ul><h3>Best Practices</h3><ul><li><strong>Use structured outputs</strong> (like Route Pydantic model) to avoid parsing errors.</li><li><strong>Keep nodes specialized</strong> → each handler does one job well.</li><li><strong>Fallbacks matter</strong> → if the router is uncertain, route to a safe default.</li><li><strong>Monitor routing decisions</strong> → log queries and chosen routes to improve accuracy.</li><li><strong>Balance cost &amp; performance</strong> → use a lightweight model for routing if possible.</li></ul><h3>Conclusion</h3><p>Routing in LangGraph enables you to design <strong>modular, scalable, and intelligent workflows</strong> where each request goes to the right specialist.</p><p>In this blog, we built a <strong>Content Router</strong> that:</p><ul><li>Uses a structured LLM to classify requests.</li><li>Routes to specialized handlers (blog, tweet, LinkedIn).</li><li>Returns polished outputs tailored to the format.</li></ul><p>This pattern is widely applicable, from content pipelines to customer support systems. By combining <strong>router nodes</strong> with <strong>conditional edges</strong>, LangGraph makes it easy to build workflows that are <strong>adaptable, maintainable, and production-ready</strong>.</p><p>🔥 <strong>Your Turn:</strong> Try extending this workflow — add new channels (e.g., Instagram captions or YouTube video scripts) and let routing handle the complexity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c2c48adb71e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚡ Supercharging LLM Workflows with Parallelization in LangGraph: The One-Page Tech Brief Use Case]]></title>
            <link>https://medium.com/@email2argha/supercharging-llm-workflows-with-parallelization-in-langgraph-the-one-page-tech-brief-use-case-43f1813514f0?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/43f1813514f0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[parallelization]]></category>
            <category><![CDATA[genegative-ai]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 05:36:56 GMT</pubDate>
            <atom:updated>2025-09-07T05:36:56.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When working with Large Language Models (LLMs), efficiency and reliability are just as important as creativity. Many tasks — like content generation, report writing, or document summarization — require <strong>multiple independent sections</strong> to be written before producing a final result. Running these steps <strong>sequentially</strong> can lead to slow execution and bottlenecks.</p><p>That’s where <strong>parallelization in LangGraph</strong> shines. By running multiple nodes simultaneously and merging their outputs, LangGraph enables <strong>fast, scalable, and reliable workflows</strong>.</p><p>In this blog, we’ll explore parallelization in LangGraph through a practical use case: <strong>automatically generating a one-page technical brief</strong>. You’ll see how five independent sections are written in parallel, validated, merged, and styled into a polished final document.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j5ZA-53RqB0ep4fOrDXPrA.png" /></figure><h3>What is Parallelization in LangGraph?</h3><p>Parallelization means allowing multiple tasks (nodes) to execute <strong>simultaneously</strong> instead of one after the other. In LangGraph, this is achieved by:</p><ul><li><strong>Fan-Out:</strong> Splitting execution into multiple parallel branches.</li><li><strong>Fan-In:</strong> Merging results deterministically after parallel nodes finish.</li></ul><h3>🔑 Benefits of Parallelization</h3><ul><li><strong>Reduced Latency</strong>: Tasks run concurrently → faster results.</li><li><strong>Scalability</strong>: Add or remove independent subtasks easily.</li><li><strong>Reliability</strong>: Each branch is validated independently before merging.</li><li><strong>Cleaner Design</strong>: Break complex workflows into modular, independent nodes.</li></ul><p>Think of it as a team of writers working on different sections of a report at the same time, instead of one person writing everything from start to finish.</p><h3>Use Case: One-Page Tech Brief Generator</h3><p><strong>Assignment Goal</strong>: Given a topic, generate a <strong>structured, multi-section tech brief</strong> by running independent section writers in parallel and merging their results into a final document.</p><h3>Inputs &amp; Outputs</h3><ul><li><strong>Input</strong>: topic (e.g., <em>Artificial Intelligence in Healthcare</em>).</li><li><strong>Outputs</strong>: A structured brief with:</li><li>Overview (120–150 words)</li><li>History (≥3 timeline bullets)</li><li>Pros &amp; Cons (3 each)</li><li>Use Cases (3 concise bullets)</li><li>Pitfalls (3 bullets)</li><li>Final styled brief (600–800 words, neutral &amp; actionable tone)</li></ul><h3>Step 1: Defining the State</h3><pre>from typing import Dict<br>from typing_extensions import TypedDict, Literal<br><br>class State(TypedDict, total=False):<br>    topic: str<br>    overview: str<br>    history: str<br>    pros_cons: str<br>    use_cases: str<br>    pitfalls: str<br>    overview_retries: int<br>    history_retries: int<br>    use_case_retries: int<br>    pros_cons_retries: int<br>    pitfalls_retries: int<br>    final_brief: str<br><br>MAX_RETRIES = 3</pre><p>📌 <strong>Explanation</strong>:<br> The State acts as <strong>shared memory</strong> for the workflow. Each node updates a section, while retry counters prevent infinite loops when a section fails validation.</p><h3>Step 2: Writing Independent Section Nodes</h3><p>Each section is generated by a separate node.</p><pre># Write overview node<br>def write_overview(state: State) -&gt; State:<br>    prompt = f&#39;Write a detailed overview of &quot;{state[&quot;topic&quot;]}&quot; in plain language, 120–150 words.&#39;<br>    overview = llm.invoke(prompt).content.strip()<br>    return {&quot;overview&quot;: overview}<br><br># Write history node<br>def write_history(state: State) -&gt; State:<br>    prompt = (<br>        f&#39;Give ≥3 timeline milestones for the history of &quot;{state[&quot;topic&quot;]}&quot;.\n&#39;<br>        &#39;Return ONLY bullet lines, each starting with &quot;- &quot;.&#39;<br>    )<br>    text = llm.invoke(prompt).content.strip()<br>    return {&quot;history&quot;: text}<br><br># Write  pros and cons node. bullet lists; 3 pros, 3 cons<br>def write_pros_cons(state: State) -&gt; State:<br>    prompt = (<br>        f&#39;List pros and cons of &quot;{state[&quot;topic&quot;]}&quot;.\n&#39;<br>        &quot;Return exactly TWO blocks:\n&quot;<br>        &quot;Pros:\n- &lt;item&gt;\n- &lt;item&gt;\n- &lt;item&gt;\n&quot;<br>        &quot;Cons:\n- &lt;item&gt;\n- &lt;item&gt;\n- &lt;item&gt;\n&quot;<br>        &quot;No extra text.&quot;<br>    )<br>    text = llm.invoke(prompt).content.strip()<br>    return {&quot;pros_cons&quot;: text}<br><br># Write use case node. 3 concise use cases with who benefits.<br>def write_use_cases(state: State) -&gt; State:<br>    prompt = (<br>        f&#39;List 3 concise use cases for &quot;{state[&quot;topic&quot;]}&quot;.\n&#39;<br>        &#39;Return ONLY 3 bullets, each starting with &quot;- &quot;.&#39;<br>    )<br>    text = llm.invoke(prompt).content.strip()<br>    return {&quot;use_cases&quot;: text}<br><br># Write pitfalls node. 3 common mistakes and how to avoid.<br>def write_pitfalls(state: State) -&gt; State:<br>    prompt = (<br>        f&#39;List 3 common pitfalls for &quot;{state[&quot;topic&quot;]}&quot; and how to avoid them.\n&#39;<br>        &#39;Return ONLY 3 bullets, each starting with &quot;- &quot;.&#39;<br>    )<br>    text = llm.invoke(prompt).content.strip()<br>    return {&quot;pitfalls&quot;: text}</pre><p>📌 <strong>Explanation</strong>:</p><ul><li>write_overview creates a concise intro.</li><li>write_history ensures a timeline with ≥3 milestones</li><li>Similar nodes exist for <strong>pros/cons, use cases, and pitfalls</strong>.</li></ul><p>These nodes are <strong>independent</strong>, making them ideal for parallelization.</p><h3>Step 3: Validation Gates</h3><p>Outputs are validated before merging.</p><pre># ------------ helpers: normalization + checks ------------<br>def ensure_bullets_dash_space(text: str) -&gt; str:<br>    # Convert lines that look like bullets into &quot;- ...&quot; form<br>    lines = [ln.strip() for ln in text.splitlines() if ln.strip()]<br>    fixed = []<br>    for ln in lines:<br>        if not ln.startswith(&quot;- &quot;):<br>            # strip leading bullet chars and add &quot;- &quot;<br>            ln = ln.lstrip(&quot;*•-&quot;).strip()<br>            ln = f&quot;- {ln}&quot;<br>        fixed.append(ln)<br>    return &quot;\n&quot;.join(fixed)<br><br>def word_count(s: str) -&gt; int:<br>    return len(s.split())<br><br>def gate_overview(state:State) -&gt; Literal[&quot;all_good&quot;, &quot;redo_overview&quot;]:<br>    # --- Overview: enforce bounds programmatically to converge ---<br>    ov = state.get(&quot;overview&quot;, &quot;&quot;).strip()<br>    ov_retries = state.get(&quot;overview_retries&quot;, 0)<br>    if ov_retries &lt; MAX_RETRIES:<br>        if ov:<br>            wc = word_count(ov)<br>            if wc &gt; 150:<br>                # Trim to ~150 by words<br>                ov = &quot; &quot;.join(ov.split()[:150])<br>                state[&quot;overview&quot;] = ov<br>            elif wc &lt; 120:<br>                return &quot;redo_overview&quot;<br>        else:<br>            return &quot;redo_overview&quot;<br>    return &quot;all_good&quot;<br><br>def gate_history(state:State) -&gt; Literal[&quot;all_good&quot;, &quot;redo_history&quot;]:<br>    # --- History ---<br>    hist = state.get(&quot;history&quot;, &quot;&quot;).strip()<br>    hist_retries = state.get(&quot;history_retries&quot;, 0)<br>    if hist_retries &lt; MAX_RETRIES:<br>        if hist:<br>            hist = ensure_bullets_dash_space(hist)<br>            state[&quot;history&quot;] = hist<br>            if hist.count(&quot;- &quot;) &lt; 3:<br>                return &quot;redo_history&quot;<br>        else:<br>            return &quot;redo_history&quot;<br>    return &quot;all_good&quot;<br><br>def gate_pros_cons(state:State) -&gt; Literal[&quot;all_good&quot;, &quot;redo_pros_cons&quot;]:<br>    # --- Pros/Cons ---<br>    pc = state.get(&quot;pros_cons&quot;, &quot;&quot;).strip()<br>    pc_retires = state.get(&quot;pros_cons_retries&quot;, 0)<br>    if pc_retires &lt; MAX_RETRIES:<br>        if pc:<br>            # Normalize bullets inside both blocks<br>            blocks = []<br>            for ln in pc.splitlines():<br>                blocks.append(ln.strip())<br>            pc_fixed = []<br>            in_block = None<br>            for ln in blocks:<br>                if ln.lower().startswith(&quot;pros&quot;):<br>                    in_block = &quot;pros&quot;<br>                    pc_fixed.append(&quot;Pros:&quot;)<br>                elif ln.lower().startswith(&quot;cons&quot;):<br>                    in_block = &quot;cons&quot;<br>                    pc_fixed.append(&quot;Cons:&quot;)<br>                else:<br>                    if ln:<br>                        if not ln.startswith(&quot;- &quot;):<br>                            ln = ln.lstrip(&quot;*•-&quot;).strip()<br>                            ln = f&quot;- {ln}&quot;<br>                        pc_fixed.append(ln)<br>            pc = &quot;\n&quot;.join(pc_fixed)<br>            state[&quot;pros_cons&quot;] = pc<br>            if pc.count(&quot;- &quot;) &lt; 6:<br>                return &quot;redo_pros_cons&quot;<br>        else:<br>            return &quot;redo_pros_cons&quot;<br>    return &quot;all_good&quot;<br><br>def gate_use_cases(state:State) -&gt; Literal[&quot;all_good&quot;, &quot;redo_use_cases&quot;]:<br>    # --- Use cases ---<br>    uc = state.get(&quot;use_cases&quot;, &quot;&quot;).strip()<br>    uc_retries = state.get(&quot;use_case_retries&quot;, 0)<br>    if uc_retries &lt; MAX_RETRIES:<br>        if uc:<br>            uc = ensure_bullets_dash_space(uc)<br>            state[&quot;use_cases&quot;] = uc<br>            if uc.count(&quot;- &quot;) &lt; 3:<br>                return &quot;redo_use_cases&quot;<br>        else:<br>            return &quot;redo_use_cases&quot;<br>    return &quot;all_good&quot;<br><br>def gate_pitfalls(state:State) -&gt; Literal[&quot;all_good&quot;, &quot;redo_pitfalls&quot;]:<br>    # --- Pitfalls ---<br>    pf = state.get(&quot;pitfalls&quot;, &quot;&quot;).strip()<br>    pf_retries = state.get(&quot;pitfalls_retries&quot;, 0)<br>    if pf_retries &lt; MAX_RETRIES:<br>        if pf:<br>            pf = ensure_bullets_dash_space(pf)<br>            state[&quot;pitfalls&quot;] = pf<br>            if pf.count(&quot;- &quot;) &lt; 3:<br>                return &quot;redo_pitfalls&quot;<br>        else:<br>            return &quot;redo_pitfalls&quot;<br>    return &quot;all_good&quot;</pre><p>📌 <strong>Explanation</strong>:</p><ul><li>Each gate checks rules (word count, bullet format).</li><li>If invalid → rerun node (up to 3 retries)</li><li>This ensures <strong>that only valid sections are merged</strong>.</li></ul><h3>Step 4: Merging Sections</h3><p>After all sections pass validation, they are merged.</p><pre>def merge_sections(state: State) -&gt; State:<br>    final = f&quot;# {state[&#39;topic&#39;]}\n\n&quot; \<br>            &quot;## Overview\n&quot; + state.get(&quot;overview&quot;,&quot;&quot;) + &quot;\n\n&quot; \<br>            &quot;## History\n&quot; + state.get(&quot;history&quot;,&quot;&quot;) + &quot;\n\n&quot; \<br>            &quot;## Pros &amp; Cons\n&quot; + state.get(&quot;pros_cons&quot;,&quot;&quot;) + &quot;\n\n&quot; \<br>            &quot;## Use Cases\n&quot; + state.get(&quot;use_cases&quot;,&quot;&quot;) + &quot;\n\n&quot; \<br>            &quot;## Pitfalls\n&quot; + state.get(&quot;pitfalls&quot;,&quot;&quot;)<br>    return {&quot;final_brief&quot;: final}</pre><p>📌 <strong>Explanation</strong>:<br> The merge_sections node acts as a <strong>fan-in point,</strong> deterministically combining all sections into a single structured Markdown report.</p><h3>Step 5: Style Pass</h3><p>Finally, a style pass ensures professionalism.</p><pre>def style_pass(state: State) -&gt; State:<br>    styled = llm.invoke(<br>        &quot;Rewrite the following brief to be neutral, concise, actionable (600–800 words), &quot;<br>        &quot;keeping headings intact:\n\n&quot; + state[&quot;final_brief&quot;]<br>    ).content.strip()<br>    return {&quot;final_brief&quot;: styled}</pre><p>📌 <strong>Explanation</strong>:<br> This rewrites the merged brief to enforce word limits, tone, and style consistency.</p><h3>Step 6: Building the Graph</h3><pre># ------------ build graph ------------<br>workflow = StateGraph(State)<br><br># writer nodes (fan-out)<br>workflow.add_node(&quot;write_overview&quot;, write_overview)<br>workflow.add_node(&quot;write_history&quot;, write_history)<br>workflow.add_node(&quot;write_pros_cons&quot;, write_pros_cons)<br>workflow.add_node(&quot;write_use_cases&quot;, write_use_cases)<br>workflow.add_node(&quot;write_pitfalls&quot;, write_pitfalls)<br><br># gate + utility nodes<br>workflow.add_node(&quot;merge_sections&quot;, merge_sections)<br>workflow.add_node(&quot;style_pass&quot;, style_pass)<br><br># fan-out from START<br>for n in [&quot;write_overview&quot;,&quot;write_history&quot;,&quot;write_pros_cons&quot;,&quot;write_use_cases&quot;,&quot;write_pitfalls&quot;]:<br>    workflow.add_edge(START, n)<br>    if n == &quot;write_overview&quot;:<br>        workflow.add_conditional_edges(n, gate_overview, {&quot;all_good&quot;: &quot;merge_sections&quot;, &quot;redo_overview&quot;: &quot;write_overview&quot;})<br>    elif n == &quot;write_history&quot;:<br>        workflow.add_conditional_edges(n, gate_history, {&quot;all_good&quot;: &quot;merge_sections&quot;, &quot;redo_overview&quot;: &quot;write_history&quot;})<br>    elif n == &quot;write_use_cases&quot;:<br>        workflow.add_conditional_edges(n, gate_use_cases, {&quot;all_good&quot;: &quot;merge_sections&quot;, &quot;redo_overview&quot;: &quot;write_use_cases&quot;})<br>    elif n == &quot;write_pros_cons&quot;:<br>        workflow.add_conditional_edges(n, gate_pros_cons, {&quot;all_good&quot;: &quot;merge_sections&quot;, &quot;redo_overview&quot;: &quot;write_pros_cons&quot;})<br>    elif n == &quot;write_pitfalls&quot;:<br>        workflow.add_conditional_edges(n, gate_pitfalls, {&quot;all_good&quot;: &quot;merge_sections&quot;, &quot;redo_overview&quot;: &quot;write_pitfalls&quot;})<br># finalize<br>workflow.add_edge(&quot;merge_sections&quot;, &quot;style_pass&quot;)<br>workflow.add_edge(&quot;style_pass&quot;, END)<br><br>graph = workflow.compile()</pre><p>📌 <strong>Explanation</strong>:</p><ul><li><strong>Fan-out</strong>: All writer nodes run concurrently.</li><li><strong>Validation gates</strong>: Retry until sections meet requirements.</li><li><strong>Fan-in</strong>: Merge → Style → End.</li></ul><h3>Workflow Diagram (Fan-Out / Fan-In)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVAFn6ETCXAcw1LFVbrc1A.png" /><figcaption>Memaid Diagram</figcaption></figure><p>📌 <strong>Explanation</strong>:<br> This diagram shows how <strong>parallel branches converge</strong> into a single merged output before styling.</p><h3>Execution Example</h3><pre>response = graph.invoke({&quot;topic&quot;: &quot;Artificial Intelligence in Healthcare&quot;})<br>print(response[&quot;final_brief&quot;])</pre><p>✅ Output: A structured, 600–800 word brief with <strong>overview, history, pros/cons, use cases, and pitfalls</strong>.</p><h3>Real-Life Use Cases of Parallelization in LangGraph</h3><ol><li><strong>Research Reports</strong></li></ol><ul><li>Generate multiple sections (introduction, methodology, results) in parallel.</li></ul><p><strong>2. Customer Support</strong></p><ul><li>Run sentiment analysis, topic classification, and FAQ search simultaneously.</li></ul><p><strong>3. Content Generation</strong></p><ul><li>Create SEO keywords, meta descriptions, and blog sections concurrently.</li></ul><p><strong>4. Data Processing</strong></p><ul><li>Parallel extraction of entities, summaries, and translations from documents.</li></ul><h3>Best Practices</h3><ul><li><strong>Use validation gates</strong> to enforce quality before merging.</li><li><strong>Keep nodes independent</strong> so they can run truly in parallel.</li><li><strong>Limit retries</strong> to avoid infinite loops.</li><li><strong>Deterministic merging</strong> ensures consistency despite non-deterministic LLM outputs.</li><li><strong>Scale gradually</strong> — start with small fan-outs, then expand.</li></ul><h3>Conclusion</h3><p>Parallelization in LangGraph transforms LLM workflows from slow, sequential pipelines into <strong>fast, modular, and scalable systems</strong>.</p><p>In our use case, we built a <strong>One-Page Tech Brief Generator</strong> where five independent sections are generated in parallel, validated, merged, and styled into a polished document.</p><p>This pattern — <strong>fan-out + validation + fan-in</strong> — is a powerful tool for anyone building production-grade AI workflows.</p><p>🔥 <strong>Your Turn:</strong> Try parallelizing your next LLM workflow. Whether it’s a research report, customer support pipeline, or multi-section article generator, LangGraph gives you the tools to make it scalable and reliable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43f1813514f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[✨ Mastering Prompt Chaining in LangGraph: A Blog Post Generator Use Case]]></title>
            <link>https://medium.com/@email2argha/mastering-prompt-chaining-in-langgraph-a-blog-post-generator-use-case-9180b52eb690?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/9180b52eb690</guid>
            <category><![CDATA[workflow-automation]]></category>
            <category><![CDATA[prompt-chaining]]></category>
            <category><![CDATA[langgraph]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Sun, 31 Aug 2025 08:36:26 GMT</pubDate>
            <atom:updated>2025-08-31T08:36:26.396Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>When working with Large Language Models (LLMs), one of the biggest challenges is <strong>structure and reliability</strong>. A single prompt can generate impressive results, but it often lacks <strong>consistency, control, and modularity</strong>. What if we want a process that can generate not just text, but a <strong>coherent workflow</strong> — a blog post with a catchy title, a structured body, and a crisp summary?</p><p>This is where <strong>Prompt Chaining</strong> comes in. Instead of relying on a single prompt, we break tasks into smaller, connected steps. By chaining these prompts together, we can design workflows that are <strong>repeatable, testable, and robust</strong>.</p><p>In this blog, we’ll explore <strong>Prompt Chaining using LangGraph</strong> with a practical use case: <strong>automatically generating a blog post with a title and summary</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9C4zUzeFcHWNwyCcY9JVQ.gif" /></figure><h3>What is Prompt Chaining?</h3><p><strong>Prompt Chaining</strong> is the technique of linking multiple prompts in sequence, where the output of one step becomes the input for the next.</p><p>For example:</p><ol><li>Generate content.</li><li>Validate it.</li><li>Create a title.</li><li>Summarize it</li></ol><p>This modular approach has several advantages:</p><ul><li><strong>Reliability</strong>: Built-in validation and retries.</li><li><strong>Clarity</strong>: Each step handles a focused task.</li><li><strong>Scalability</strong>: Easy to extend with new nodes.</li></ul><p>LangGraph provides a <strong>graph-based framework</strong> to build such workflows with nodes, edges, and gates.</p><h3>Use Case: Blog Post Generator</h3><p>Our task is simple but practical:</p><p>👉 <strong>Generate a blog post on a given topic, ensure it’s well-structured, and then produce a catchy title and summary.</strong></p><p>The workflow has four major steps:</p><ol><li>Generate the blog post.</li><li>Validate that it has at least three paragraphs.</li><li>Create a short, catchy title.</li><li>Generate a concise summary</li></ol><h3>Step 1: Defining the State</h3><pre>from typing_extensions import TypedDict</pre><pre># Define State<br>class State(TypedDict):<br>    topic: str<br>    blog_post: str<br>    title: str<br>    summary: str<br>    count: int</pre><p>📌 <strong>Explanation</strong>:<br> The State holds all data that flows through the workflow:</p><ul><li>topic → input given by the user.</li><li>blog_post → generated draft.</li><li>title → catchy blog title.</li><li>summary → final condensed summary.</li><li>count → retry counter</li></ul><h3>Step 2: Generating the Blog Post</h3><p>We start by creating the blog content.</p><pre>def generate_blog_post(state: State) -&gt; State:<br>    prompt = f&quot;&quot;&quot;<br>    Write a detailed blog post about the topic: {state[&#39;topic&#39;]}.<br>    The blog post should be short (within 150-200 words) in multiple paragraphs<br>    and cover various aspects of the topic.<br>    &quot;&quot;&quot;<br>    response = llm.invoke(prompt)<br><br>    return {&quot;blog_post&quot;: response.content.strip()}</pre><p>📌 <strong>Explanation</strong>:<br> This node asks the LLM to write a <strong>150–200 words blog</strong> with <strong>multiple paragraphs</strong>. The result is saved in the state as blog_post.</p><h3>Step 3: Validating the Blog Post</h3><p>Next, we check whether the blog has at least three paragraphs.</p><pre>📌 Explanation:<br>This node asks the LLM to write a 150–200 word blog with multiple paragraphs. The result is saved in the state as blog_post.<br><br>Step 3: Validating the Blog Post<br><br>Next, we check whether the blog has at least three paragraphs.</pre><p>📌 <strong>Explanation</strong>:</p><ul><li>If the blog has <strong>≥ 3 paragraphs</strong> → Pass.</li><li>If not, retry <strong>up to 2 times</strong>.</li><li>After retries fail, the workflow ends.</li></ul><p>This ensures we don’t accept poorly formatted results.</p><h3>Step 4: Generating a Title</h3><p>Once we have a valid blog post, we generate a catchy title.</p><pre>def generate_title(state: State) -&gt; State:<br>    prompt = f&quot;&quot;&quot;<br>    Generate a catchy title for the following blog post:<br>    {state[&#39;blog_post&#39;]}<br>    Choose only one title and keep it under 10 words.<br>    Return only the title without any additional text.<br>    &quot;&quot;&quot;<br>    response = llm.invoke(prompt)<br><br>    return {&quot;title&quot;: response.content.strip()}</pre><p>📌 <strong>Explanation</strong>:<br> This node ensures we get a <strong>short and engaging title</strong> (under 10 words), with no extra text.</p><h3>Step 5: Summarizing the Blog</h3><p>Finally, we create a concise summary.</p><pre>def generate_summary(state: State) -&gt; State:<br>    prompt = f&quot;&quot;&quot;<br>    Summarize the following blog post in 2-3 sentences:<br>    {state[&#39;blog_post&#39;]}<br>    The summary should capture the main points of the blog post.<br>    Return only the summary without any additional text.<br>    &quot;&quot;&quot;<br>    response = llm.invoke(prompt)<br><br>    return {&quot;summary&quot;: response.content.strip()}</pre><p>📌 <strong>Explanation</strong>:<br> The summary captures the <strong>essence of the blog</strong> in just a few sentences — perfect for quick consumption.</p><h3>Step 6: Building the Workflow Graph</h3><p>Now we connect everything with LangGraph.</p><pre>from langgraph.graph import StateGraph, START, END<br><br>workflow = StateGraph(State)<br><br># Add nodes<br>workflow.add_node(&quot;generate_blog_post&quot;, generate_blog_post)<br>workflow.add_node(&quot;generate_title&quot;, generate_title)<br>workflow.add_node(&quot;generate_summary&quot;, generate_summary)<br><br># Add edges<br>workflow.add_edge(START, &quot;generate_blog_post&quot;)<br>workflow.add_conditional_edges(<br>    &quot;generate_blog_post&quot;, check_blog_post,<br>    {&quot;Pass&quot;: &quot;generate_title&quot;, &quot;Retry&quot;: &quot;generate_blog_post&quot;, &quot;Fail&quot;: END}<br>)<br>workflow.add_edge(&quot;generate_title&quot;, &quot;generate_summary&quot;)<br>workflow.add_edge(&quot;generate_summary&quot;, END)<br><br>chain = workflow.compile()</pre><p>📌 <strong>Explanation</strong>:</p><ul><li><strong>Start</strong> → Generate blog post.</li><li>Gate ensures valid formatting.</li><li>If Pass → Title → Summary → End.</li><li>If Retry → Loop back to blog generation</li><li>If Fail → Stop execution.</li></ul><p>This makes the workflow both <strong>structured and resilient</strong>.</p><h3>Workflow Diagram</h3><p>Here’s a <strong>Mermaid diagram</strong> of the workflow for better visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*g1KBro7l_VuLbwg-Wil5cQ.png" /></figure><p>📌 <strong>Explanation</strong>:</p><ul><li>Blog post generation → validated with a gate.</li><li>If it <em>passes</em> → generate title → generate summary.</li><li>If it <em>fails</em> → workflow stops.</li><li>If it <em>retries</em> → loop back to generation.</li></ul><h3>Step 7: Running the Workflow</h3><p>Let’s test it with a topic:</p><pre>state = chain.invoke({&quot;topic&quot;: &quot;Retrieval Augmented Generation&quot;})<br>print(&quot;Blog Post:\n&quot;, state[&quot;blog_post&quot;])<br>print(&quot;\n--- --- ---\n&quot;)<br>print(&quot;Title:&quot;, state[&quot;title&quot;])<br>print(&quot;\nSummary:\n&quot;, state[&quot;summary&quot;])</pre><p>✅ Example Output:</p><ul><li>A <strong>multi-paragraph blog</strong> about Retrieval Augmented Generation.</li><li>A <strong>catchy title</strong>, e.g., <em>“RAG: Smarter AI with Knowledge Recall”</em>.</li><li>A <strong>2–3 sentence summary</strong>.</li></ul><h3>Why This Matters</h3><p>This small workflow demonstrates why <strong>Prompt Chaining with LangGraph</strong> is so powerful</p><ul><li><strong>Reliability</strong> → Blog must meet formatting rules.</li><li><strong>Structure</strong> → Each node has a clear, focused purpose.</li><li><strong>Scalability</strong> → Easy to add nodes like “generate keywords” or “SEO optimization.”</li></ul><p>Instead of one oversized prompt, we get a <strong>modular pipeline</strong> — much easier to test, debug, and reuse.</p><h3>Extending the Workflow</h3><p>This system can be extended to build a <strong>full blogging assistant</strong>:</p><ul><li>Add an <strong>SEO keyword generator</strong> node.</li><li>Include a <strong>tone adjustment</strong> step (e.g., formal, casual).</li><li>Generate <strong>social media snippets</strong>.</li></ul><h3>Conclusion</h3><p>Prompt Chaining transforms raw prompting into <strong>structured workflows</strong>. With LangGraph, we can orchestrate these workflows visually and programmatically, adding validation and retries for reliability.</p><p>In this blog, we built a <strong>Blog Post Generator</strong> that:</p><ul><li>Creates a post,</li><li>Validates structure,</li><li>Generates a catchy title,</li><li>Produces a clear summary.</li></ul><p>This is just the beginning — LangGraph opens the door to building complex, multi-step AI applications that are <strong>robust, scalable, and production-ready.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9180b52eb690" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Text: Building a Multimodal RAG Assistant]]></title>
            <link>https://medium.com/@email2argha/beyond-text-building-a-multimodal-rag-assistant-with-langchain-179ebcacfb2a?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/179ebcacfb2a</guid>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[ai-assistant]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 10:36:45 GMT</pubDate>
            <atom:updated>2025-08-24T15:09:57.899Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In my previous blogs, I explored how domain-specific AI assistants and Retrieval-Augmented Generation (RAG) pipelines empower knowledge-intensive applications. While these approaches work wonderfully for text-based knowledge, the reality is that most enterprise and research data is <em>not just text</em>. It often contains tables, diagrams, flowcharts, and images. Relying on text-only pipelines means losing a large portion of that valuable information.</p><p>This is where <strong>Multimodal RAG</strong> comes in. By combining text and vision models, we can build AI assistants that understand and reason across <em>all modalities</em> of data. In this blog, I’ll walk you through the concept of multimodal RAG, highlight its benefits, showcase real-world use cases, and then share a hands-on project I built: <strong>Ask PDF</strong> — a multimodal assistant that can read, interpret, and answer questions from PDFs containing text, tables, and images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*hPOmnKtELz4YpPROMSAYaw.png" /><figcaption>Figure: A general Multimodal RAG architecture — extracting text and images, embedding into a unified vector space, and using semantic retrieval for LLM-based generation.</figcaption></figure><h3>What is Multimodal RAG?</h3><p>Multimodal Retrieval-Augmented Generation (RAG) extends the classical RAG framework by incorporating multiple data modalities — text, images, tables, and even audio or video.</p><p>In a <strong>typical text-only RAG </strong>pipeline, the process looks like this:</p><ol><li>Split and embed text into vector representations.</li><li>Store embeddings in a vector database.</li><li>Retrieve relevant chunks using similarity search.</li><li>Pass them as context to a <strong>Large Language Model (LLM) </strong>for answer generation.</li></ol><p>In <strong>multimodal RAG</strong>, we add an extra layer:</p><ul><li>Extract features not only from text but also from images, diagrams, and other non-textual content.</li><li>Use vision or multimodal models to convert those into structured or textual representations.</li><li>Combine them with textual embeddings in a single retriever.</li><li>Allow the LLM to reason across all modalities seamlessly.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9_3en6yIcxoh1g1GWK3RA.png" /><figcaption>Figure B: Comparison between traditional text-only RAG (left) and multimodal RAG pipelines (right), showing how different content types are embedded and retrieved in a unified system.</figcaption></figure><h3>Benefits of Multimodal RAG</h3><ol><li><strong>Holistic Understanding</strong> — Captures insights from diagrams, charts, and tables that would otherwise be ignored.</li><li><strong>Domain Applicability</strong> — Particularly useful in scientific research, engineering, medicine, and law, where visuals carry critical information.</li><li><strong>Improved Accuracy</strong> — Answers are more grounded since the model leverages both textual and visual evidence.</li><li><strong>Future-Proofing</strong> — Prepares your pipeline for richer modalities like video transcripts, sensor data, or geospatial maps.</li></ol><h3>Use Cases of Multimodal RAG</h3><ul><li><strong>Research Papers</strong> — Summarizing and answering queries across both textual findings and diagrams.</li><li><strong>Medical Reports</strong> — Combining X-ray scans with doctors’ notes.</li><li><strong>Engineering Drawings</strong> — Understanding manuals that include schematics, tables, and technical descriptions.</li><li><strong>Legal Contracts</strong> — Parsing clauses, along with embedded tables and exhibits.</li><li><strong>Education</strong> — Creating study assistants that can process textbooks with mixed text, images, and exercises.</li></ul><h3>My Use Case: Ask PDF</h3><p>One of the most common needs I’ve seen is querying complex PDF documents — research papers, reports, manuals, etc. These documents are multimodal by nature. So, I set out to build an assistant called <strong>Ask PDF</strong> using LangChain and modern multimodal models.</p><p>Here’s how it works step by step:</p><h3>1. User Input</h3><ul><li>The user selects a list of PDFs (with text, images, diagrams, and tables) to process.</li></ul><h3>2. Extracting Text</h3><ul><li>Each PDF is processed page by page using the <strong>Unstructured library</strong>.</li><li>Text is extracted and chunked using LangChain’s TextSplitter.</li><li>Each chunk is stored as part of a document list.</li></ul><h3>3. Extracting Images</h3><ul><li>The same library is used to extract images from each page.</li><li>Images are stored in a temporary folder for processing.</li></ul><h3>4. Image Processing with Vision Model</h3><ul><li>Images are passed through <strong>Google Gemini</strong> (a multimodal vision model).</li><li>Summaries of each image are generated.</li><li>These summaries are appended to the document list alongside text chunks.</li></ul><h3>5. Embedding</h3><ul><li>All text chunks and image summaries are embedded using a HuggingFace embedding model.</li><li>Embeddings are stored in a local <strong>ChromaDB</strong> vector database.</li></ul><h3>6. Retrieval</h3><ul><li>A retriever is created on top of the vector store.</li></ul><h3>7. RAG Pipeline</h3><ul><li>A carefully designed prompt template guides the pipeline.</li><li>The retriever fetches relevant text and image summaries.</li><li>An LLM (GPT/Gemini) generates the final grounded answer.</li></ul><h3>8. Q&amp;A</h3><ul><li>The user asks any questions about the PDFs.</li></ul><p>The system retrieves the most relevant text/image-based context and produces an answer.</p><h3>Architecture Diagram</h3><p>Here’s a high-level view of the <em>Ask PDF</em> pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*N5HGw_Zcc7wNpUjdH3WBWQ.png" /><figcaption>Figure C: This diagram reflects the core design of our <em>Ask PDF</em> pipeline — though we summarize images and text separately and use a local ChromaDB vector store, the underlying flow is identical.</figcaption></figure><h3>Why Multimodal RAG Was Essential Here</h3><p>If I had only used a <strong>text-based RAG</strong>, my assistant would miss:</p><ul><li>Diagrams that explain processes better than words.</li><li>Tables that summarize numerical data.</li><li>Flowcharts that show sequences and dependencies.</li></ul><p>By integrating Gemini Vision for image understanding, I ensured that no information was left behind. The assistant could answer questions like:</p><ul><li><em>“What does the diagram on page 5 illustrate?”</em></li><li><em>“Summarize the data table on page 12.”</em></li><li><em>“Explain the relationship between the figure and the text in section 3.”</em></li></ul><h3>Limitations and Future Directions</h3><p>While <em>Ask PDF</em> works effectively, there are still challenges:</p><ul><li><strong>Processing Cost</strong> — Vision models can be computationally expensive.</li><li><strong>Accuracy of Image Summarization</strong> — Sometimes, fine-grained details are lost.</li><li><strong>Scalability</strong> — Handling hundreds of PDFs at once requires optimization in storage and retrieval.</li></ul><p>Future improvements I’m exploring:</p><ul><li>Hybrid retrieval (combining dense and sparse retrieval).</li><li>Fine-tuned domain-specific embeddings.</li><li>Enhanced visualization in responses (e.g., regenerating tables in markdown).</li><li>Collaborative querying (multiple users working on the same document set).</li></ul><h3>Conclusion and Call to Action</h3><p>Multimodal RAG opens up exciting new possibilities for AI assistants that truly understand all aspects of human knowledge — not just text. My <em>Ask PDF</em> project is one example of how we can combine LangChain, Gemini, and ChromaDB to build assistants that read and reason across PDFs containing text, images, and tables.</p><p>If you’ve been working on text-only RAG pipelines, now is the time to level up and experiment with multimodal approaches. The results are not just more accurate — they’re transformative.</p><p>Stay tuned, and let me know in the comments: <em>What’s the first multimodal use case you’d like to build?</em> 🚀</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.loom.com%2Fembed%2Fe37bf47faf6a4ccdaa3d02f678c8aff2&amp;display_name=Loom&amp;url=https%3A%2F%2Fwww.loom.com%2Fshare%2Fe37bf47faf6a4ccdaa3d02f678c8aff2%3Fsid%3D873c18dc-1a86-4fd9-ab99-f445ecf59323&amp;image=https%3A%2F%2Fcdn.loom.com%2Fsessions%2Fthumbnails%2Fe37bf47faf6a4ccdaa3d02f678c8aff2-4cda868dd4fd71d8.gif&amp;type=text%2Fhtml&amp;schema=loom" width="1920" height="1440" frameborder="0" scrolling="no"><a href="https://medium.com/media/2695ae2aa0223fde77478fbde4266f36/href">https://medium.com/media/2695ae2aa0223fde77478fbde4266f36/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=179ebcacfb2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Level Up Your Expertise: Building Domain-Specific AI Assistants with Retrieval Augmented Generation]]></title>
            <link>https://medium.com/@email2argha/level-up-your-expertise-building-domain-specific-ai-assistants-with-retrieval-augmented-generation-0f8f10bfc36d?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f8f10bfc36d</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[domain-specific]]></category>
            <category><![CDATA[ai-assistant]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 12:13:05 GMT</pubDate>
            <atom:updated>2025-08-12T12:13:05.416Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>In today’s rapidly evolving AI landscape, the demand for specialized AI assistants tailored to specific domains is skyrocketing. These aren’t your run-of-the-mill chatbots; they’re sophisticated tools capable of providing expert-level insights and support within a defined subject area. Retrieval Augmented Generation (RAG) has emerged as a powerful technique for building these high-performing, domain-specific AI assistants. Let’s dive into how RAG works and how you can leverage it to create your expert AI.</p><p><strong>What is RAG?</strong></p><p>Retrieval Augmented Generation (RAG) is an AI framework that enhances the capabilities of Large Language Models (LLMs) by providing them with access to external knowledge sources. Instead of relying solely on the information they were trained on, RAG-based systems can retrieve relevant information from a knowledge base and incorporate it into their responses. This process involves two key stages:</p><ol><li><strong>Retrieval:</strong> When a user asks a question, the RAG system retrieves relevant documents or passages from a pre-indexed knowledge base (e.g., a collection of documents, articles, or a database).</li><li><strong>Generation:</strong> The LLM uses both the user’s query and the retrieved information to generate a coherent and informative response.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*fnS-2GnI2alpLQbx1NcvvA.png" /></figure><p><strong>How RAG Powers Domain-Specific AI Assistants</strong></p><p>Traditional LLMs are trained on massive datasets, giving them a broad understanding of language and general knowledge. However, they often lack the deep, specialized knowledge required to answer complex questions within a specific domain accurately. This is where RAG shines.</p><p>By connecting an LLM to a domain-specific knowledge base, RAG enables the AI assistant to access and utilize the most up-to-date and relevant information. For example, if you’re building an AI assistant for the legal domain, you can provide it with a knowledge base consisting of legal documents, case law, and statutes. When a user asks a legal question, the RAG system retrieves the relevant legal information and uses it to generate an informed response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14cVBdSk229u9oajbeLZ5g.png" /><figcaption>Working of RAG Based AI Assistant</figcaption></figure><p><strong>Advantages of RAG for Domain-Specific AI Assistants</strong></p><ul><li><strong>Improved Accuracy and Reliability:</strong> RAG significantly reduces the risk of LLM hallucinations and inaccuracies by grounding responses in factual information from the knowledge base.</li><li><strong>Up-to-Date Knowledge:</strong> The AI assistant can stay current with the latest developments in the domain by simply updating the knowledge base. This eliminates the need to retrain the entire LLM, which is a time-consuming and expensive process.</li><li><strong>Explainability and Transparency:</strong> RAG provides a clear audit trail of the information used to generate each response, making it easier to understand and trust the AI assistant’s output.</li><li><strong>Customization and Control:</strong> You have complete control over the knowledge base used by the AI assistant, allowing you to tailor it precisely to the needs of your domain.</li><li><strong>Cost-Effectiveness:</strong> RAG reduces the need for extensive LLM retraining, making it a more cost-effective solution for building domain-specific AI assistants.</li></ul><p><strong>Steps to Implement a RAG-Based AI Assistant</strong></p><ol><li><strong>Define the Domain:</strong> Clearly define the scope of your AI assistant’s expertise. What specific questions should it be able to answer?</li><li><strong>Build the Knowledge Base:</strong> Gather and organize relevant information from reliable sources. This could include documents, articles, databases, and APIs.</li><li><strong>Choose an Embedding Model:</strong> Select an appropriate embedding model (e.g., Sentence Transformers) to convert the text in your knowledge base into vector embeddings. These embeddings capture the semantic meaning of the text and allow for efficient retrieval of relevant information.</li><li><strong>Index the Knowledge Base:</strong> Use a vector database (e.g., FAISS, Pinecone, Weaviate) to store the vector embeddings of your knowledge base. This allows for fast and efficient similarity search.</li><li><strong>Select an LLM:</strong> Choose a powerful LLM (e.g., GPT-3.5, GPT-4, GPT-5, PaLM 2) to generate the responses.</li><li><strong>Implement the RAG Pipeline:</strong> Connect the LLM to the vector database and implement the RAG pipeline. This involves retrieving relevant information from the knowledge base based on the user’s query and feeding it to the LLM to generate a response.</li><li><strong>Evaluate and Refine:</strong> Thoroughly evaluate the performance of the AI assistant and refine the knowledge base, embedding model, and LLM as needed.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mgh_e-lFj4pAB_kQHzY6pQ.png" /><figcaption>RAG Workflow</figcaption></figure><p><strong>Conclusion:</strong></p><p>Retrieval Augmented Generation offers a powerful and practical approach to building domain-specific AI assistants. By combining the strengths of LLMs with the ability to access and utilize external knowledge sources, RAG enables you to create AI assistants that are accurate, reliable, and up-to-date. Whether you’re building an AI assistant for healthcare, finance, education, or any other specialized field, RAG can help you level up your expertise and deliver exceptional results.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f8f10bfc36d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crafting Domain-Specific AI Assistants for Peak Performance]]></title>
            <link>https://medium.com/@email2argha/crafting-domain-specific-ai-assistants-for-peak-performance-595f43291d19?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/595f43291d19</guid>
            <category><![CDATA[ai-assistant]]></category>
            <category><![CDATA[domain-specific-llm]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Sun, 03 Aug 2025 14:08:14 GMT</pubDate>
            <atom:updated>2025-08-03T14:08:14.195Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Introduction</strong></h3><p>The rise of AI assistants has been nothing short of revolutionary. From answering simple questions to automating complex tasks, these digital helpers are rapidly transforming how we interact with technology. But generic AI assistants often fall short when it comes to specialized knowledge domains. This is where domain-specific AI assistants come into play, offering tailored expertise and enhanced efficiency for specific industries and tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*OC5oaXNIO-3gRSWo" /><figcaption>Your AI Assistant</figcaption></figure><h3><strong>What is an AI Assistant?</strong></h3><p>At its core, an AI assistant is a software application that uses artificial intelligence to assist users. These assistants can understand natural language, respond to commands, and perform tasks ranging from scheduling appointments to providing information. They typically leverage machine learning models to continuously improve their performance and adapt to user preferences.</p><h3><strong>Developing Domain-Specific AI Assistants: Key Approaches</strong></h3><p>Creating an AI assistant that truly excels in a specific domain requires more than just general-purpose AI. Here are several effective strategies:</p><ol><li><strong>Retrieval Augmented Generation (RAG):</strong></li></ol><p><strong>RAG</strong> combines the power of pre-trained <strong>Large Language Models (LLMs)</strong> with a retrieval mechanism that accesses a domain-specific knowledge base. When a user asks a question, the RAG system first retrieves relevant information from the knowledge base and then uses the LLM to generate a comprehensive and contextually appropriate answer.</p><p><strong>How it works:</strong> First, create a domain-specific knowledge base using the data related to the domain. A user query triggers a search within a domain-specific knowledge base (e.g., a collection of medical research papers). The retrieved documents are then fed into an LLM, which formulates an answer grounded in the provided evidence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*imyRF2kSLuPC2DMN" /></figure><p><strong>2. Fine-tuning Large Language Models:</strong></p><p>Fine-tuning involves taking a pre-trained LLM and training it further on a dataset specific to the target domain. This process adapts the model’s parameters to better understand and generate text relevant to the domain.</p><p><strong>How it works:</strong> An LLM pre-trained on a massive corpus of text is then trained on a dataset of legal documents, medical records, or financial reports. This fine-tuning process makes the model more adept at handling domain-specific language and tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/0*m75DNK_UZfWzCxas" /><figcaption>LLM Fine-tuning Pipeline</figcaption></figure><p><strong>3. Knowledge Graphs:</strong></p><p>Knowledge graphs represent information as a network of entities, concepts, and relationships. They provide a structured way to represent domain knowledge and enable AI assistants to reason and infer new information.</p><p><strong>How it works:</strong> A knowledge graph for the financial domain might include entities like “companies,” “stocks,” and “economic indicators,” with relationships like “is traded on” and “affects.” An AI assistant can then use this graph to answer complex questions about financial markets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/0*FCcOIwI_xcsyICfj" /><figcaption>Knowledge Graph Architechture</figcaption></figure><h3><strong>Comparison of Approaches</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*LN5rIbD2W33qkmbAbTLYHw.png" /></figure><h3><strong>Conclusion</strong></h3><p>Developing an efficient, domain-specific AI assistant requires careful consideration of the available approaches and their respective strengths and weaknesses. RAG, fine-tuning, and knowledge graphs each offer unique advantages and are best suited for different use cases. By strategically combining these techniques, it’s possible to create AI assistants that deliver exceptional performance and unlock new possibilities across various industries. The key is to align the chosen approach with the specific requirements of the domain and the desired capabilities of the AI assistant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595f43291d19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Data Insights: Mastering Grouping and Summarization in Pandas for Advanced Analysis]]></title>
            <link>https://medium.com/@email2argha/unlocking-data-insights-mastering-grouping-and-summarization-in-pandas-for-advanced-analysis-9c300cfdd973?source=rss-11eea86a4877------2</link>
            <guid isPermaLink="false">https://medium.com/p/9c300cfdd973</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Argha Dey Sarkar]]></dc:creator>
            <pubDate>Sat, 31 May 2025 09:51:05 GMT</pubDate>
            <atom:updated>2025-05-31T09:51:05.413Z</atom:updated>
            <content:encoded><![CDATA[<p>Data analysis isn’t just about reading numbers — it’s about turning raw data into actionable insights. One of the most powerful ways to extract meaningful patterns from large datasets in Python is through <strong>grouping</strong> and <strong>summarizing</strong> data using the <strong>Pandas</strong> library. In this blog, we’ll explore advanced techniques with <strong>GroupBy</strong>, <strong>Crosstab</strong>, <strong>Pivot Tables</strong>, and <strong>Sorting</strong> that can elevate your data analysis game.</p><h3>🔍 What is Grouping and Summarizing Data?</h3><p><strong>Grouping</strong> refers to the process of splitting data into groups based on some criteria (such as gender, class, region, etc.).</p><p><strong>Summarization</strong> (or aggregation) involves applying a function to each group independently to condense or describe the data — such as computing totals, averages, counts, etc.</p><p>Together, these operations let you break down complex data and uncover trends and distributions that might be hidden in raw formats.</p><h3>🔍 Why Do We Need Grouping and Summarization for Data Analysis?</h3><ul><li>Helps <strong>simplify</strong> and <strong>structure</strong> large datasets</li><li>Enables <strong>segment-wise</strong> analysis</li><li>Uncovers <strong>patterns</strong> and <strong>anomalies</strong> in subsets of data</li><li>Supports <strong>reporting</strong>, <strong>dashboards</strong>, and <strong>business intelligence</strong></li></ul><p>In short, it helps transform messy data into meaningful stories.</p><h3>🔢 Pandas crosstab()</h3><p>Pandas <strong>crosstab()</strong> is a function used to compute a <strong>cross-tabulation (contingency table)</strong> of two or more factors (categorical variables). It shows the frequency distribution of variables and is extremely useful in <strong>Exploratory Data Analysis (EDA)</strong>.</p><p><strong>Parameters:</strong></p><ul><li><strong>index</strong>: array-like, Series, or list of Series — rows of the table.</li><li><strong>columns</strong>: array-like, Series, or list of Series — columns of the table.</li><li><strong>values</strong>: array-like, optional — array of values to aggregate.</li><li><strong>aggfunc</strong>: function, optional — aggregation function (e.g., np.sum, np.mean).</li><li><strong>margins</strong>: bool, optional — adds row/column totals if True.</li><li><strong>normalize</strong>: bool or {‘all’, ‘index’, ‘columns’}, optional — normalize table values.</li></ul><h3>Example 1: Survival count by gender</h3><pre>pd.crosstab(df[&#39;Sex&#39;], df[&#39;Survived&#39;])</pre><p><strong>Output:</strong></p><pre>Survived    0    1<br>Sex                <br>female      81  233<br>male       468  109</pre><h3>Example 2: Gender distribution across passenger classes</h3><pre>pd.crosstab(df[&#39;Sex&#39;], df[&#39;Pclass&#39;])</pre><p><strong>Output:</strong></p><pre>Pclass     1   2   3<br>Sex                  <br>female   94  76  144<br>male    122 108  347</pre><h3>Example 3: Survival count by class with totals</h3><pre>pd.crosstab(df[&#39;Pclass&#39;], df[&#39;Survived&#39;], margins=True)</pre><p><strong>Output:</strong></p><pre>Survived    0    1  All<br>Pclass                  <br>1           80  136  216<br>2           97   87  184<br>3          372  119  491<br>All        549  342  891</pre><h3>Example 4: Normalized (percentage) survival by class</h3><pre>pd.crosstab(df[&#39;Pclass&#39;], df[&#39;Survived&#39;], normalize=True, margins=True)</pre><p><strong>Output:</strong></p><pre>Survived         0         1       All<br>Pclass                                 <br>1         0.089775  0.152663  0.242438<br>2         0.108888  0.097641  0.206529<br>3         0.417511  0.133522  0.551033<br>All       0.616174  0.383826  1.000000</pre><h3>Example 5: Mean age by gender and class</h3><pre>pd.crosstab(df[&#39;Sex&#39;], df[&#39;Pclass&#39;], values=df[&#39;Age&#39;], aggfunc=&#39;mean&#39;)</pre><p><strong>Output:</strong></p><pre>Pclass           1          2          3<br>Sex                                     <br>female  34.611765  28.722973  21.750000<br>male    41.281386  30.740707  26.507589</pre><h3>🔢 Pandas groupby()</h3><p>The Pandas <strong>groupby()</strong> function involves three steps: <strong>Splitting</strong>, <strong>Applying</strong>, and <strong>Combining</strong>.</p><ul><li><strong>Splitting</strong>: This step involves dividing the DataFrame into groups based on some criteria. The groups are defined by unique values in one or more columns.</li><li><strong>Applying</strong>: In this step, a function is applied to each group independently. You can apply various functions to each group, such as: <strong>Aggregation, Transformation &amp; Filtering.</strong></li><li><strong>Combining</strong>: Finally, the results of the applied function are combined into a new DataFrame or Series.</li></ul><p><strong>Parameters :</strong></p><ul><li><strong>by</strong>: Required parameter to specify the column(s) to group by.</li><li><strong>axis</strong>: Optional, specifies the axis to group by (default is 0 for rows).</li><li><strong>level</strong>: Optional, used for grouping by a certain level in a MultiIndex.</li><li><strong>as_index</strong>: Optional, whether to use the group labels as the index (default is True).</li><li><strong>sort</strong>: Optional, whether to sort the group keys (default is True).</li><li><strong>group_keys</strong>: Optional, whether to add the group keys to the index (default is True).</li><li><strong>dropna</strong>: Optional, whether to include rows/columns with NULL values (default is True).</li></ul><h3>Example 1: Count of males and females</h3><pre>df.groupby(&#39;Sex&#39;).size()</pre><p><strong>Output:</strong></p><pre>Sex<br>female    314<br>male      577<br>dtype: int64</pre><h3>Example 2: Average age by gender</h3><pre>df.groupby(&#39;Sex&#39;)[&#39;Age&#39;].mean()</pre><p><strong>Output:</strong></p><pre>Sex<br>female    27.915709<br>male      30.726645<br>Name: Age, dtype: float64</pre><h3>Example 3: Average age by gender and class</h3><pre>df.groupby([&#39;Sex&#39;, &#39;Pclass&#39;])[&#39;Age&#39;].mean()</pre><p><strong>Output:</strong></p><pre>Sex     Pclass<br>female  1         34.611765<br>        2         28.722973<br>        3         21.750000<br>male    1         41.281386<br>        2         30.740707<br>        3         26.507589<br>Name: Age, dtype: float64</pre><h3>Example 4: Mean, min, and max fare by class</h3><pre>df.groupby(&#39;Pclass&#39;)[&#39;Fare&#39;].agg([&#39;mean&#39;, &#39;min&#39;, &#39;max&#39;])</pre><p><strong>Output:</strong></p><pre>mean   min      max<br>Pclass                            <br>1       84.154687  0.00  512.3292<br>2       20.662183  0.00   73.5000<br>3       13.675550  0.00   69.5500</pre><h3>Example 5: Summary of age and fare by class</h3><pre>df.groupby(&#39;Pclass&#39;)[[&#39;Age&#39;, &#39;Fare&#39;]].agg([&#39;mean&#39;, &#39;min&#39;, &#39;max&#39;])</pre><p><strong>Output:</strong></p><pre>Age                        Fare                     <br>             mean   min   max       mean   min      max<br>Pclass                                                   <br>1        38.233441  0.92  80.0  84.154687  0.00  512.3292<br>2        29.877630  0.67  70.0  20.662183  0.00   73.5000<br>3        25.140620  0.42  74.0  13.675550  0.00   69.5500</pre><h3>Example 6: Custom aggregation by embarkation port</h3><pre>df.groupby(&#39;Embarked&#39;).agg({<br>    &#39;Age&#39;: &#39;mean&#39;,<br>    &#39;Survived&#39;: &#39;sum&#39;,<br>    &#39;Fare&#39;: &#39;max&#39;<br>})</pre><p><strong>Output:</strong></p><pre>Age  Survived     Fare<br>Embarked                              <br>C         32.932885       93  512.3292<br>Q         28.089286       30   90.0000<br>S         29.445397      217  263.0000</pre><h3>📊 Pivot Tables in Pandas</h3><p>Pivot tables allow you to <strong>restructure</strong> and <strong>summarize</strong> your data across multiple dimensions.</p><p>Pandas pivot tables are used to summarize and aggregate data within a DataFrame. They allow for reshaping and reorganizing data, making it easier to analyze and extract insights. The <strong>pivot_table()</strong> function is the primary tool for creating pivot tables in Pandas.</p><p>To create a pivot table, you need to specify the following:</p><ul><li><strong>data</strong>: The DataFrame to be used.</li><li><strong>index</strong>: The column(s) to group by and use as the index of the resulting pivot table.</li><li><strong>columns</strong>: The column(s) to use for creating new columns in the pivot table.</li><li><strong>values</strong>: The column(s) to populate the values in the pivot table.</li><li><strong>aggfunc (optional)</strong>: The aggregation function to apply if there are multiple values for the same index-column combination. If not specified, it defaults to mean.</li></ul><h3>Example 1: Average age by survival</h3><pre>pd.pivot_table(df, index=&#39;Survived&#39;, values=&#39;Age&#39;)</pre><p><strong>Output:</strong></p><pre>Age<br>Survived           <br>0         30.626179<br>1         28.343690</pre><h3>Example 2: Total fare by class</h3><pre>pd.pivot_table(df, index=&#39;Pclass&#39;, values=&#39;Fare&#39;, aggfunc=&#39;sum&#39;)</pre><p><strong>Output:</strong></p><pre>Fare<br>Pclass           <br>1       18177.4123<br>2        3801.8418<br>3        8187.8299</pre><h3>Example 3: Mean, min, max fare by class</h3><pre>pd.pivot_table(df, index=&#39;Pclass&#39;, values=&#39;Fare&#39;, aggfunc=[&#39;mean&#39;, &#39;min&#39;, &#39;max&#39;])</pre><p><strong>Output:</strong></p><pre>mean   min      max<br>Pclass                            <br>1       84.154687  0.00  512.3292<br>2       20.662183  0.00   73.5000<br>3       13.675550  0.00   69.5500</pre><h3>Example 4: Average age by gender and class</h3><pre>pd.pivot_table(df, index=&#39;Sex&#39;, columns=&#39;Pclass&#39;, values=&#39;Age&#39;, aggfunc=&#39;mean&#39;)</pre><p><strong>Output:</strong></p><pre>Pclass           1          2          3<br>Sex                                     <br>female  34.611765  28.722973  21.750000<br>male    41.281386  30.740707  26.507589</pre><h3>Example 5: Fare by gender, embarkation port, and class</h3><pre>pd.pivot_table(df, index=[&#39;Sex&#39;, &#39;Embarked&#39;], columns=&#39;Pclass&#39;, values=&#39;Fare&#39;)</pre><p><strong>Output (sample):</strong></p><pre>Pclass                     1          2         3<br>Sex    Embarked                                  <br>female C        106.125798  21.750000  17.875000<br>       Q         90.000000        NaN  11.241667<br>       S         78.173340  20.236290  14.644083<br>male   C         68.624237  18.875000  18.682917<br>       Q         13.007143  11.000000   9.081667<br>       S         52.278250  18.296505  12.448867</pre><h3>Example 6: Multiple aggregations by gender</h3><pre>pd.pivot_table(df, index=&#39;Sex&#39;, values=[&#39;Age&#39;, &#39;Fare&#39;], aggfunc={&#39;Age&#39;: &#39;mean&#39;, &#39;Fare&#39;: &#39;sum&#39;})</pre><p><strong>Output:</strong></p><pre>Age         Fare<br>Sex                            <br>female  27.915709  13966.6628<br>male    30.726645  15800.4212</pre><h3>🌟 Conclusion</h3><p>Grouping and summarization techniques in Pandas are not just nice-to-have skills — they’re essential for real-world data analysis. Whether you’re cleaning data, exploring datasets, or preparing reports, knowing how to use groupby(), crosstab(), pivot_table(), and sorting functions empowers you to distill clarity from complexity.</p><p>Level up your analysis by mastering these tools, and let your data do the talking!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9c300cfdd973" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>