<?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 sajosam on Medium]]></title>
        <description><![CDATA[Stories by sajosam on Medium]]></description>
        <link>https://medium.com/@sajo02?source=rss-f0205b223fca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QcUSRRV9muW6gEVDYcWSbg.jpeg</url>
            <title>Stories by sajosam on Medium</title>
            <link>https://medium.com/@sajo02?source=rss-f0205b223fca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 17:36:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sajo02/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[I Built an AI System That Writes Its Own Agents (Open Source)]]></title>
            <link>https://medium.com/@sajo02/i-built-an-ai-system-that-writes-its-own-agents-open-source-8619fb332b40?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8619fb332b40</guid>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 03:01:00 GMT</pubDate>
            <atom:updated>2026-03-25T03:01:00.875Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What if you never had to define a single agent again?</em></p><p>Every time I tried LangChain, CrewAI, or AutoGen, I hit the same wall. Before the task even arrives, I’m already writing roles. Defining prompts. Wiring tools. Building the team manually before I even know what the task needs.</p><p>That felt backwards to me.</p><p>So I built <strong>SpawnVerse.</strong></p><p>SpawnVerse is an Agent Operating System — where agents are generated, executed, evaluated, and evolved automatically.</p><p>Zero pre-built agents. One sentence in. A complete workforce out.</p><p>👉 <strong>GitHub</strong>: <a href="https://github.com/sajosam/spawnverse">https://github.com/sajosam/spawnverse</a></p><p>👉 <strong>Website</strong>: <a href="https://spawnverse.wasmer.app/">https://spawnverse.wasmer.app</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EUhBNNPrkHRLyP9Uffwtg.png" /></figure><h3>The Core Idea is Stupid Simple</h3><p>Traditional frameworks:</p><pre>You → define agents → task arrives → agents run</pre><p>SpawnVerse:</p><pre>Task arrives → agents invented → agents run → agents die → leave memory</pre><p>That’s the whole thing. The task is the architect of the workforce, not you.</p><p>You write one thing:</p><p>python</p><pre>from spawnverse import Orchestrator<br><br>Orchestrator().run({<br>    &quot;description&quot;: &quot;Research top 5 EVs in India under 25 lakhs for 2025&quot;,<br>    &quot;context&quot;: {&quot;buyer_type&quot;: &quot;first-time EV buyer&quot;, &quot;location&quot;: &quot;Bangalore&quot;}<br>})</pre><p>SpawnVerse reads that sentence, asks the LLM what agents this task needs, writes their Python code at runtime, runs them in parallel as real subprocesses, scores their outputs, and deposits a fossil record when each one dies.</p><pre>Output:<br><br>- ev_research_agent → top EVs under ₹25L in India<br>- specs_comparison_agent → battery, range, charging time<br>- pricing_agent → on-road Bangalore cost<br>- recommendation_agent → ranked best EV for first-time buyer<br><br>You didn’t define ANY of these agents.</pre><p>You didn’t design the system. The system designed itself for the task.</p><h3>The Architecture (this is where it gets interesting)</h3><p>Here’s the system architecture that makes it all work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*f8VRohqOVImraKcbFhDkkg.png" /></figure><p><strong>This isn’t a workflow engine.<br>It’s a system that writes and runs its own workflows.</strong></p><p>Think of it like:</p><ul><li>Orchestrator = brain</li><li>Agents = workers</li><li>Memory = shared nervous system</li><li>Fossils = long-term learning</li></ul><p>The flow is simple but powerful:</p><ul><li>The Orchestrator reads the task and decomposes it into required agents</li><li>The LLM generates Python code for each agent at runtime</li><li>Agents run as sandboxed subprocesses in parallel</li><li>All agents communicate through distributed memory (SQLite WAL)</li><li>Results are validated, scored, and stored</li><li>Every agent leaves a fossil that future agents can learn from</li></ul><p>The whole thing is built in one file: engine.py.</p><p>No abstractions for the sake of abstractions.<br> Just a clean machine that reads a sentence and builds a team.</p><h3>The Part Nobody Else Does — The Fossil Record</h3><p>Every agent that runs leaves a fossil when it dies.</p><p>Not logs. Not traces. A proper fossil — the Python code that defined that agent, its quality score, intent drift score, tokens used, runtime, and depth. All saved to SQLite permanently.</p><p>When you run SpawnVerse 100 times on similar tasks, the system has 800+ fossils indexed in ChromaDB. Future agents search those fossils semantically before doing their work. They find the best-performing past constitutions and build on them.</p><pre>Run 1:   flight_agent · quality=0.71 · drift=0.83<br>Run 10:  flight_agent · quality=0.81 · drift=0.89 ↑ improved<br>Run 100: flight_agent · quality=0.92 · drift=0.95 ★ canonical</pre><p>No other agent framework does this. LangChain forgets everything. CrewAI forgets everything. AutoGen forgets everything. SpawnVerse accumulates intelligence across runs.</p><p>This turns every run into training data — without retraining a model.</p><h3>Four Guardrail Layers That Actually Mean Something</h3><p>The LLM writes Python code at runtime. That’s scary if you do nothing about it. SpawnVerse runs four independent safety checks on every agent:</p><p><strong>Layer 1 — Code scanner</strong> runs before the file is ever written to disk. Blocks os.system, subprocess, eval, exec, socket, requests.post, open(&quot;/etc/...&quot;). If any dangerous pattern is found — the file never runs.</p><p><strong>Layer 2 — Budget enforcer</strong> lives inside every agent’s stdlib. Each agent gets 8,000 tokens. When exhausted, think() returns empty. One runaway agent cannot consume the entire run budget.</p><p><strong>Layer 3 — Output validator</strong> runs before the result enters shared memory. Not None. Not empty. Not too large. Not an empty dict.</p><p><strong>Layer 4 — Semantic judge</strong> is an LLM reviewing every output independently. Personal data, harmful instructions, misinformation, prompt injection — any of these and the output is blocked from shared memory.</p><p>All four layers are independent. Disabling one doesn’t disable the others.</p><h3>The Memory Model Is The Most Underrated Part</h3><p>Every agent can read any other agent’s memory. But every agent can only write to its own namespace.</p><p>This is enforced twice — once at code generation time (the write() function has no namespace parameter, _ID is hardcoded into the file at birth), and once at the database layer (a second check against caller_id).</p><p>Without this, parallel agents corrupt each other’s outputs. Race conditions everywhere. Data from the wrong agent overwriting the right one.</p><p>With this, you get full visibility + zero interference. Exactly what multi-agent systems need.</p><h3>What’s Coming Next</h3><p>The roadmap has things I’m genuinely excited about:</p><p><strong>Soul system</strong> — persistent agent identities across runs. The same “flight_researcher” accumulates reputation over hundreds of runs. High-quality agents get promoted to canonical status.</p><p><strong>Fossil curator agent</strong> — a meta-agent that reviews all fossils, promotes the best constitutions, and retires the weak ones. The system evolves.</p><p><strong>Docker sandbox</strong> — stronger isolation per agent subprocess.</p><p><strong>REST API + web UI</strong> — run SpawnVerse as a server, inspect runs through a browser.</p><p>This is not about building better agents.</p><p>It’s about not building them at all.</p><p>Define the task.<br>Let the system figure out who it needs to be.</p><p>If you believe agents should be discovered, not predefined — <br>try it, break it, and tell me where it fails.</p><p>⭐ Star the repo — it helps more people discover this</p><p>⭐ <strong>GitHub</strong>: <a href="https://github.com/sajosam/spawnverse">https://github.com/sajosam/spawnverse</a></p><p><em>Built by sajosam. MIT license. Written in one Python file.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8619fb332b40" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Opening AWS Tickets: Build a Self-Service Platform with Backstage + Crossplane]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@sajo02/stop-opening-aws-tickets-build-a-self-service-platform-with-backstage-crossplane-dc2790a0dd60?source=rss-f0205b223fca------2"><img src="https://cdn-images-1.medium.com/max/1536/1*IwTvN7p1W9j6F6GuhMHCUw.png" width="1536"></a></p><p class="medium-feed-snippet">Provision real AWS S3 buckets from your Backstage Developer Portal using Crossplane and Kubernetes &#x2014; no tickets, no Terraform, no console&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@sajo02/stop-opening-aws-tickets-build-a-self-service-platform-with-backstage-crossplane-dc2790a0dd60?source=rss-f0205b223fca------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sajo02/stop-opening-aws-tickets-build-a-self-service-platform-with-backstage-crossplane-dc2790a0dd60?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc2790a0dd60</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[backstage]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Tue, 24 Feb 2026 13:05:28 GMT</pubDate>
            <atom:updated>2026-05-14T10:33:20.205Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building Production-Ready AI Pipelines with LangChain Runnables: A Complete LCEL Guide]]></title>
            <link>https://medium.com/@sajo02/building-production-ready-ai-pipelines-with-langchain-runnables-a-complete-lcel-guide-2f9b27f6d557?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f9b27f6d557</guid>
            <category><![CDATA[lcel]]></category>
            <category><![CDATA[llm-orchestration]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[healthcare-ai]]></category>
            <category><![CDATA[ai-engineering]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Mon, 16 Feb 2026 13:50:11 GMT</pubDate>
            <atom:updated>2026-02-16T13:50:11.163Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s the uncomfortable truth: a single LLM prompt won’t cut it in production healthcare environments.</p><p>Real-world systems need structured pipelines that can extract clinical facts, apply deterministic rules, maintain memory, and generate safe, controlled responses. This level of reliability isn’t possible with one prompt alone.</p><p>What you need instead is a <strong>Runnable-based architecture</strong> — composable, testable components that combine deterministic logic with LLM reasoning. LangChain’s core Runnable primitives like <strong>RunnableLambda, RunnableParallel, and RunnableBranch</strong> allow you to build predictable, production-ready AI pipelines.</p><p>In this tutorial, we’ll build a real-world healthcare AI pipeline step by step using LangChain Runnables.</p><p>All complete code for this tutorial is available on GitHub:<br> <a href="https://github.com/sajosam/langchain/tree/main/langchain-runnable"><strong>[</strong>sajosam/langchain<strong>]</strong></a></p><figure><img alt="LangChain pipeline, LCEL tutorial, healthcare AI pipeline, deterministic AI workflow, LangChain runnable lambda, runnable parallel example, runnable branch tutorial, production AI architecture, clinical AI workflow, LangChain healthcare project" src="https://cdn-images-1.medium.com/max/1024/1*pDe-QU5GXRBwNgyK9glEqQ.png" /><figcaption>RunnableLambda, RunnableParallel, RunnableBranch, Memory, and Supervisor Review</figcaption></figure><h3>Understanding Runnables: The Core Interface for Production AI</h3><p>Every component in LangChain LCEL implements the <strong>Runnable interface</strong>, which provides:</p><pre>class Runnable:<br>    def invoke(self, input: Any) -&gt; Any:      # Execute with single input<br>    def batch(self, inputs: List[Any]) -&gt; List[Any]:  # Process multiple inputs<br>    def stream(self, input: Any) -&gt; Iterator[Any]:    # Stream results<br>    def ainvoke(self, input: Any) -&gt; Awaitable[Any]:  # Async execution</pre><p>This unified interface means you can compose <strong>any Runnable with any other Runnable</strong> using the pipe operator (|).</p><h4>The Five Essential Runnable Types</h4><ol><li><strong>RunnableLambda</strong>: Wraps any Python function as a composable Runnable</li><li><strong>RunnableParallel</strong>: Executes multiple Runnables concurrently</li><li><strong>RunnableBranch</strong>: Routes to different Runnables based on conditions</li><li><strong>Chain Runnables</strong>: Prompt | LLM | Parser compositions</li><li><strong>RunnablePassthrough</strong>: Passes input unchanged (useful in parallel branches)</li></ol><h4>Our Runnable-Based Healthcare Pipeline Architecture</h4><pre>Patient Input<br>    ↓<br>RunnableLambda(clean_input)              # Sanitize input<br>    ↓<br>RunnableParallel({                        # Concurrent extraction<br>    &quot;symptoms&quot;: symptom_chain,<br>    &quot;labs&quot;: lab_chain<br>})<br>    ↓<br>RunnableLambda(memory_persistence)       # Store patient history<br>    ↓<br>RunnableLambda(clinical_risk_tool)       # Apply clinical rules<br>    ↓<br>RunnableBranch([                          # Conditional routing<br>    (high_risk, high_risk_runnable),<br>    (default, low_risk_runnable)<br>])<br>    ↓<br>supervisor_chain                          # Safety validation<br>    ↓<br>Final Safe Response</pre><p>Notice how <strong>everything is a Runnable</strong>. This enables composability, testability, observability, and extensibility.</p><h3>Implementation: Building the Runnable Pipeline Step-by-Step</h3><h4>Setup and RunnableLambda for Input Cleaning</h4><pre>import re<br>from datetime import datetime<br>from typing import Dict, List<br><br>from dotenv import load_dotenv<br>from langchain_groq import ChatGroq<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br>from langchain_core.runnables import (<br>    RunnableLambda,<br>    RunnableParallel,<br>    RunnableBranch<br>)<br><br>load_dotenv()<br><br># ChatGroq is itself a Runnable!<br>llm = ChatGroq(model_name=&quot;llama-3.3-70b-versatile&quot;, temperature=0)<br>parser = StrOutputParser()<br><br># Memory storage (in production, use FHIR-compliant database)<br>patient_memory: Dict[str, Dict] = {}<br><br>def get_memory(user_id: str):<br>    return patient_memory.setdefault(user_id, {<br>        &quot;symptoms&quot;: [],<br>        &quot;labs&quot;: {},<br>        &quot;risk_history&quot;: []<br>    })<br><br># RunnableLambda #1: Clean input<br>clean_input = RunnableLambda(<br>    lambda x: {&quot;user_id&quot;: x[&quot;user_id&quot;], &quot;text&quot;: x[&quot;text&quot;].strip()}<br>)</pre><h4>RunnableParallel: Concurrent Clinical Entity Extraction</h4><pre># Create extraction chain Runnables<br>symptom_prompt = PromptTemplate.from_template(&quot;Extract symptoms from: {text}&quot;)<br>lab_prompt = PromptTemplate.from_template(&quot;Extract lab values from: {text}&quot;)<br><br>symptom_chain = symptom_prompt | llm | parser<br>lab_chain = lab_prompt | llm | parser<br><br># RunnableParallel: Execute both chains concurrently<br>parallel_extract = RunnableParallel({<br>    &quot;symptoms&quot;: symptom_chain,      # Runs in parallel<br>    &quot;labs&quot;: lab_chain,               # Runs in parallel<br>    &quot;text&quot;: RunnableLambda(lambda x: x[&quot;text&quot;]),<br>    &quot;user_id&quot;: RunnableLambda(lambda x: x[&quot;user_id&quot;])<br>})</pre><p><strong>Performance impact</strong>: Traditional sequential processing takes Time(symptom) + Time(lab). With RunnableParallel, it’s max(Time(symptom), Time(lab)) — often 40–50% faster.</p><h4>RunnableLambda: Memory Persistence and Clinical Risk Assessment</h4><pre># RunnableLambda #2: Store patient history<br>def memory_step(data):<br>    mem = get_memory(data[&quot;user_id&quot;])<br>    mem[&quot;symptoms&quot;].append(data[&quot;symptoms&quot;])<br>    mem[&quot;labs&quot;][&quot;latest&quot;] = data[&quot;labs&quot;]<br>    data[&quot;memory&quot;] = mem<br>    return data<br><br>memory_runnable = RunnableLambda(memory_step)<br><br># RunnableLambda #3: Apply clinical risk rules (deterministic)<br>def risk_tool(data):<br>    &quot;&quot;&quot;American Diabetes Association guidelines:<br>    HbA1c ≥8.0: HIGH | 6.5-7.9: MODERATE | &lt;6.5: LOW&quot;&quot;&quot;<br>    labs = data.get(&quot;labs&quot;, &quot;&quot;)<br>    match = re.search(r&quot;(\d+\.?\d*)&quot;, labs)<br>    <br>    if not match:<br>        risk = &quot;UNKNOWN&quot;<br>    else:<br>        hba1c = float(match.group(1))<br>        risk = &quot;HIGH&quot; if hba1c &gt;= 8 else &quot;MODERATE&quot; if hba1c &gt;= 6.5 else &quot;LOW&quot;<br>    <br>    data[&quot;risk&quot;] = risk<br>    return data<br><br>risk_runnable = RunnableLambda(risk_tool)</pre><p><strong>Why RunnableLambda matters</strong>: This wraps deterministic clinical logic as a composable Runnable. Unlike LLM-based risk assessment, this gives identical outputs for identical inputs — essential for regulatory compliance.</p><h3>RunnableBranch and Supervisor Chain: Conditional Routing with Safety Validation</h3><h4>RunnableBranch: Deterministic Clinical Decision Paths</h4><pre># Define risk-specific response templates<br>low_prompt = PromptTemplate.from_template(<br>    &quot;Patient symptoms: {symptoms}\nRisk level: LOW\nProvide general safe advice.&quot;<br>)<br><br>high_prompt = PromptTemplate.from_template(<br>    &quot;Patient symptoms: {symptoms}\nRisk level: HIGH\nProvide urgent but non-diagnostic advice.&quot;<br>)<br><br>low_chain = low_prompt | llm | parser<br>high_chain = high_prompt | llm | parser<br><br># RunnableBranch: Explicit conditional routing<br>branch = RunnableBranch(<br>    (lambda x: x[&quot;risk&quot;] == &quot;HIGH&quot;,<br>     RunnableLambda(lambda x: {&quot;symptoms&quot;: x[&quot;symptoms&quot;]}) | high_chain),<br>    <br>    RunnableLambda(lambda x: {&quot;symptoms&quot;: x[&quot;symptoms&quot;]}) | low_chain  # Default<br>)</pre><p><strong>How RunnableBranch works</strong>:</p><ul><li>Checks conditions sequentially (like if-elif-else)</li><li>Executes the first matching Runnable</li><li>Provides explicit, auditable routing logic</li></ul><p><strong>Why not agents?</strong> Agents introduce non-determinism. RunnableBranch provides reproducible decision paths that can be traced, logged, and reviewed — essential for regulatory compliance.</p><h4>Supervisor Runnable Chain: AI-in-the-Loop Safety</h4><pre>supervisor_prompt = PromptTemplate.from_template(<br>    &quot;&quot;&quot;You are a clinical supervisor.<br>    Ensure response is safe and non-diagnostic.<br>    Response: {response}<br>    Rewrite safely if needed.&quot;&quot;&quot;<br>)<br><br>supervisor_chain = supervisor_prompt | llm | parser<br><br>supervisor_runnable = (<br>    RunnableLambda(lambda x: {&quot;response&quot;: x}) <br>    | supervisor_chain<br>)</pre><p>The supervisor catches:</p><ul><li>Diagnostic language (“you have diabetes” → “discuss with provider”)</li><li>Specific medical advice (“increase insulin” → “review treatment plan”)</li><li>Missing disclaimers → Adds appropriate hedging</li></ul><h3>The Complete Runnable Pipeline: Bringing It All Together</h3><pre>pipeline = (<br>    clean_input           # RunnableLambda: Sanitize input<br>    | parallel_extract    # RunnableParallel: Concurrent extraction<br>    | memory_runnable     # RunnableLambda: Store patient history<br>    | risk_runnable       # RunnableLambda: Apply clinical rules<br>    | branch              # RunnableBranch: Conditional routing<br>    | supervisor_runnable # Runnable Chain: Safety validation<br>)<br><br># Run the pipeline<br>if __name__ == &quot;__main__&quot;:<br>    print(&quot;\n🏥 Clinical Intake Risk Assessment Pipeline\n&quot;)<br>    user_id = input(&quot;Enter patient ID: &quot;)<br>    <br>    while True:<br>        text = input(&quot;\nPatient message (or exit): &quot;)<br>        if text.lower() == &quot;exit&quot;:<br>            break<br>        <br>        result = pipeline.invoke({<br>            &quot;user_id&quot;: user_id,<br>            &quot;text&quot;: text<br>        })<br>        <br>        print(&quot;\n--- Final Supervisor Approved Response ---\n&quot;)<br>        print(result)</pre><h4>Data Flow Through the Runnable Pipeline</h4><pre># Input<br>{&quot;user_id&quot;: &quot;patient_123&quot;, &quot;text&quot;: &quot;fatigue, dizzy, HbA1c 8.2&quot;}<br><br># After clean_input<br>{&quot;user_id&quot;: &quot;patient_123&quot;, &quot;text&quot;: &quot;fatigue, dizzy, HbA1c 8.2&quot;}<br><br># After parallel_extract<br>{&quot;user_id&quot;: &quot;patient_123&quot;, &quot;symptoms&quot;: &quot;fatigue, dizziness&quot;, &quot;labs&quot;: &quot;HbA1c 8.2&quot;, ...}<br><br># After memory_runnable<br>{..., &quot;memory&quot;: {&quot;symptoms&quot;: [&quot;fatigue, dizziness&quot;], &quot;labs&quot;: {...}}}<br><br># After risk_runnable<br>{..., &quot;risk&quot;: &quot;HIGH&quot;}  # ← Clinical rule applied<br><br># After branch<br>&quot;Your HbA1c indicates suboptimal control...&quot; # ← high_chain output<br><br># After supervisor_runnable<br>&quot;Your HbA1c level of 8.2 is above target. Please discuss with your provider...&quot; # ← Safe!</pre><h4>Alternative Runnable Invocation Methods</h4><pre># Batch processing multiple patients<br>results = pipeline.batch([<br>    {&quot;user_id&quot;: &quot;p1&quot;, &quot;text&quot;: &quot;...&quot;},<br>    {&quot;user_id&quot;: &quot;p2&quot;, &quot;text&quot;: &quot;...&quot;}<br>])<br><br># Streaming for real-time UI<br>for chunk in pipeline.stream({&quot;user_id&quot;: &quot;p123&quot;, &quot;text&quot;: &quot;...&quot;}):<br>    print(chunk)<br><br># Async for high-concurrency<br>result = await pipeline.ainvoke({&quot;user_id&quot;: &quot;p123&quot;, &quot;text&quot;: &quot;...&quot;})</pre><h3>Conclusion: Build Certifiable Healthcare AI with Runnables</h3><p>The healthcare AI revolution is about <strong>augmenting clinical workflows</strong> with intelligent automation that’s safe, auditable, and effective.</p><p><strong>LangChain’s Runnable architecture</strong> gives you:</p><p>✅ <strong>RunnableLambda</strong> — Deterministic clinical logic as composable units<br> ✅ <strong>RunnableParallel</strong> — Concurrent extraction for performance<br> ✅ <strong>RunnableBranch</strong> — Explicit routing based on evidence-based protocols<br> ✅ <strong>Supervisor Runnables</strong> — Multi-layer safety validation</p><p>This is the architecture pattern for <strong>trustworthy, certifiable healthcare AI</strong>.</p><h3>Get the Complete Code</h3><p>👉 <strong>GitHub Repository: </strong><a href="https://github.com/sajosam/langchain"><strong>[sajosam-langchain]</strong> </a>👈</p><p>Includes:</p><ul><li>Full Runnable pipeline implementation</li><li>Individual component examples</li><li>Unit tests for each Runnable</li><li>LangSmith tracing integration</li><li>Production deployment guide</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f9b27f6d557" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning to Build Deterministic AI Pipelines with LangChain: A Practical Approach]]></title>
            <link>https://medium.com/@sajo02/learning-to-build-deterministic-ai-pipelines-with-langchain-a-practical-approach-aec6422c84ef?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/aec6422c84ef</guid>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 13:16:32 GMT</pubDate>
            <atom:updated>2026-02-10T13:16:32.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding the Challenge with Single-Prompt AI</h3><p>You’ve built an impressive AI demo. It works perfectly in development. Then you try to scale it — and challenges emerge.</p><p>Most AI applications start with this simple pattern:</p><pre>User Input → LLM → Answer</pre><p>This works great for demos and experimentation. However, as you scale or work in domains like healthcare, finance, or legal services, you might encounter some challenges:</p><ul><li>Limited visibility into the reasoning process</li><li>Difficulty creating audit trails</li><li>Potential hallucination risks without validation steps</li><li>Variability that can make testing harder</li></ul><p>One approach to consider? <strong>Deterministic AI pipelines</strong> that can give you more control while maintaining LLM capabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YLY5VZAKDl71xsyjj_QguA.png" /><figcaption>Building Production-Ready AI Pipelines with LangChain: The Definitive Guide to Deterministic Workflows for Healthcare and Enterprise Systems</figcaption></figure><h3>A Learning Example: Healthcare AI Use Case</h3><p>Let’s explore this with a practical example. Imagine you’re building a healthcare AI system that receives messages like:</p><blockquote><em>“I feel tired for the last two weeks and my HbA1c is 8.2”</em></blockquote><p>What would an ideal system handle?</p><p>✅ Understanding messy, informal language<br> ✅ Extracting precise medical facts (symptoms + lab values)<br> ✅ Applying clinical rules consistently<br> ✅ Generating safe, non-diagnostic responses<br> ✅ Storing structured data for continuity<br> ✅ Creating audit trails for compliance</p><p><strong>For this use case, you might want to consider a more controlled approach</strong> rather than fully autonomous agents. Let’s explore how deterministic pipelines could work.</p><h3>Exploring a 7-Stage Pipeline Approach</h3><p>Here’s one approach you could consider for building structured AI workflows:</p><pre>User Input<br>    ↓<br>1. Normalize Text (LLM)<br>    ↓<br>2. Extract Facts (LLM)<br>    ↓<br>3. Store Memory (Deterministic)<br>    ↓<br>4. Apply Rules (Tool/Function)<br>    ↓<br>5. Generate Summary (LLM)<br>    ↓<br>6. Supervisor Review (LLM)<br>    ↓<br>Final Output</pre><p><strong>The core idea:</strong> LLMs handle language tasks, while Python handles business logic. This separation can help with debugging and testing.</p><h4>Stage 1: Normalize Input (LLM)</h4><p>One way to start is by converting messy user text into a clean, standardized format.</p><pre>normalize_prompt = PromptTemplate.from_template(<br>    &quot;&quot;&quot;<br>    Normalize the following patient message into clear medical English.<br>    <br>    Patient message:<br>    {text}<br>    &quot;&quot;&quot;<br>)<br>normalize_chain = normalize_prompt | llm | parser</pre><p><strong>Input:</strong> “been feelin real tired lately, hba1c came back 8.2 😞”<br><strong>Output:</strong> “I have been feeling very tired recently. My HbA1c test result was 8.2.”</p><h4>Stage 2: Extract Facts (LLM)</h4><p>You could then pull structured data from the normalized text.</p><pre>extract_prompt = PromptTemplate.from_template(<br>    &quot;&quot;&quot;<br>    Extract medical facts from the text.<br>    <br>    Return in this format (plain text):<br>    Symptoms: &lt;comma-separated symptoms&gt;<br>    Labs: &lt;lab-name value&gt;<br>    <br>    Text:<br>    {text}<br>    &quot;&quot;&quot;<br>)<br>extract_chain = extract_prompt | llm | parser</pre><p><strong>Output:</strong></p><pre>Symptoms: fatigue, tiredness<br>Labs: HbA1c 8.2</pre><h4>Stage 3: Store Structured Memory (Deterministic)</h4><p>Consider storing validated facts rather than raw conversation history.</p><pre>patient_memory = {<br>    &quot;symptoms&quot;: [&quot;fatigue&quot;, &quot;tiredness&quot;],<br>    &quot;labs&quot;: {&quot;HbA1c&quot;: 8.2},<br>    &quot;risk_history&quot;: [&quot;HIGH&quot;],<br>    &quot;last_updated&quot;: &quot;2024-02-10T12:00:00Z&quot;<br>}</pre><h4>Stage 4: Apply Business Rules (Tool)</h4><p>For critical thresholds, you might want to use pure Python functions rather than relying on LLM interpretation.</p><pre>def interpret_hba1c(value: float) -&gt; str:<br>    &quot;&quot;&quot;Deterministic medical rule based on clinical guidelines.&quot;&quot;&quot;<br>    if value &gt;= 8.0:<br>        return &quot;HIGH&quot;<br>    elif value &gt;= 6.5:<br>        return &quot;MODERATE&quot;<br>    else:<br>        return &quot;LOW&quot;</pre><p>This approach can offer <strong>testability, auditability, and predictability</strong> — reducing hallucination risks.</p><h4>Stage 5: Generate Summary (LLM)</h4><p>You can create human-friendly responses from your structured data.</p><pre>summary_prompt = PromptTemplate.from_template(<br>    &quot;&quot;&quot;<br>    Using the information below, write a short, non-diagnostic clinical summary.<br>    Use cautious language and general guidance only.<br>    <br>    Extracted Facts: {facts}<br>    Risk Level: {risk}<br>    <br>    Write 3–4 sentences.<br>    &quot;&quot;&quot;<br>)<br>summary_chain = summary_prompt | llm | parser</pre><h4>Stage 6: Supervisor Safety Review (LLM)</h4><p>Adding a final safety check before outputs reach users can be helpful for regulated domains.</p><pre>supervisor_prompt = PromptTemplate.from_template(<br>    &quot;&quot;&quot;<br>    You are a clinical safety supervisor.<br>    <br>    Review the response below and check for:<br>    - Diagnosis or definitive medical claims<br>    - Overconfident or absolute language<br>    - Missing safety disclaimers<br>    <br>    If SAFE, return: APPROVED: &lt;original response&gt;<br>    If NOT SAFE, rewrite the response to be cautious and safe.<br>    <br>    Response: {response}<br>    &quot;&quot;&quot;<br>)<br>supervisor_chain = supervisor_prompt | llm | parser</pre><p>This concept mirrors real-world review systems: <strong>Junior doctor → Senior doctor → Patient</strong></p><h3>How to Orchestrate the Pipeline</h3><p>Here’s one way to bring all these stages together:</p><pre>def run_healthcare_pipeline(user_id: str, user_input: str) -&gt; Dict:<br>    &quot;&quot;&quot;Deterministic healthcare pipeline with memory + supervisor.&quot;&quot;&quot;<br>    <br>    # Stage 1: Normalize<br>    normalized = normalize_chain.invoke({&quot;text&quot;: user_input})<br>    <br>    # Stage 2: Extract facts<br>    extracted = extract_chain.invoke({&quot;text&quot;: normalized})<br>    <br>    # Parse extracted data (deterministic)<br>    symptoms = parse_symptoms(extracted)<br>    hba1c_value = parse_hba1c(extracted)<br>    <br>    # Stage 4: Apply business logic tool<br>    risk = interpret_hba1c(hba1c_value) if hba1c_value else &quot;UNKNOWN&quot;<br>    <br>    # Stage 3: Update memory (facts only)<br>    patient = get_patient_memory(user_id)<br>    patient[&quot;symptoms&quot;].extend(symptoms)<br>    patient[&quot;labs&quot;][&quot;HbA1c&quot;] = hba1c_value<br>    patient[&quot;risk_history&quot;].append(risk)<br>    <br>    # Stage 5: Generate summary<br>    summary = summary_chain.invoke({<br>        &quot;facts&quot;: extracted,<br>        &quot;risk&quot;: risk<br>    })<br>    <br>    # Stage 6: Supervisor review<br>    reviewed_response = supervisor_chain.invoke({<br>        &quot;response&quot;: summary<br>    })<br>    <br>    return {<br>        &quot;risk_level&quot;: risk,<br>        &quot;final_response&quot;: reviewed_response,<br>        &quot;patient_memory&quot;: patient<br>    }</pre><p><strong>What makes this approach deterministic:</strong> <br> ✓ No loops or retry logic<br> ✓ No dynamic tool selection<br> ✓ No LLM-controlled flow<br> ✓ No hidden state</p><p>Every step is <strong>explicit and predictable</strong>. That’s the core idea of deterministic pipelines.</p><h3>Benefits of This Approach for Your Use Case</h3><h4>Potential Advantages:</h4><p>✓ <strong>Predictability</strong> — Same input → same steps → more consistent behavior<br> ✓ <strong>Safety</strong> — Multiple validation layers can catch issues early<br> ✓ <strong>Debuggability</strong> — Easier to identify which stage needs adjustment<br> ✓ <strong>Audit Trails</strong> — Each stage can log inputs/outputs for compliance<br> ✓ <strong>Testability</strong> — You can unit test each stage independently</p><h4>Where You Might Consider This Pattern:</h4><p>🏥 <strong>Healthcare AI</strong> — Patient triage, clinical summaries<br> 💰 <strong>Financial Systems</strong> — Risk assessment, compliance checking<br> ⚖️ <strong>Legal Services</strong> — Contract analysis, compliance review<br> 🏢 <strong>Enterprise Platforms</strong> — Document processing, customer support</p><p>Of course, every use case is different, so you’ll want to evaluate what works best for your specific requirements.</p><h3>Learning Summary</h3><p>Here are some key concepts to remember when building deterministic AI pipelines:</p><ol><li><strong>Separation of Concerns</strong>: Consider using LLMs for language tasks, while keeping business logic in Python functions</li><li><strong>Start Simple</strong>: Begin with a deterministic approach, add complexity only when needed</li><li><strong>Safety Layers</strong>: For critical applications, a supervisor review stage might be valuable</li><li><strong>Logging Early</strong>: Implement comprehensive logging from the start to help with debugging</li><li><strong>Test Thoroughly</strong>: Edge cases and unexpected inputs can help you refine your pipeline</li></ol><h3>Explore the Complete Implementation</h3><p>Want to see the full code and explore how this works in practice? Check out the GitHub repository with:</p><p><a href="https://github.com/sajosam/langchain/tree/main/langchain-pipeline"><strong>View Complete Code Repository</strong></a><strong> →</strong></p><p>You’ll find:</p><ul><li>✅ Complete Python implementation with all stages</li><li>✅ LangChain LCEL chain examples</li><li>✅ Memory management patterns</li><li>✅ Supervisor safety layer implementation</li><li>✅ Unit tests and usage examples</li><li>✅ Setup and configuration guide</li><li>✅ Docker configuration</li><li>✅ Monitoring examples</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aec6422c84ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The 7 Types of LangChain Chains Every Developer Must Know in 2026]]></title>
            <link>https://medium.com/@sajo02/the-7-types-of-langchain-chains-every-developer-must-know-in-2026-a3982619948b?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3982619948b</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Tue, 27 Jan 2026 13:34:43 GMT</pubDate>
            <atom:updated>2026-01-27T13:34:43.497Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Imagine this scenario:</strong> A patient walks into an ER at 3 AM with chest pain.</p><p>Within seconds, the AI system needs to:</p><ul><li>✅ Normalize “my chest hurts real bad” into clinical terminology</li><li>✅ Extract vital signs, symptoms, and history</li><li>✅ Assess risk level (LOW/MODERATE/HIGH/CRITICAL)</li><li>✅ Route to the appropriate protocol</li><li>✅ Generate clinical notes, billing codes, and discharge instructions</li><li>✅ Personalize the response based on patient history</li><li>✅ Pull evidence-based guidelines from medical knowledge base</li></ul><p><strong>One single LLM call can’t do all this reliably.</strong></p><p>But <strong>7 different types of chains working together?</strong> That’s a production-ready system.</p><p>I spent weeks exploring every type of LangChain chain, building a real healthcare triage system. This article is your complete guide to understanding <strong>when, why, and how</strong> to use each chain type.</p><p>By the end, you’ll know exactly which chain to reach for in any situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_FR0zIgsZFiW7gGmGCEwXQ.png" /><figcaption>LangChain chains | sequential chain | parallel chain | RAG chain | conditional chains | tool chains | memory chains</figcaption></figure><h3>Why Chain Types Matter</h3><h4>The Single Chain Trap</h4><p>Most tutorials show you this:</p><pre>prompt = &quot;Analyze this patient message&quot;<br>response = llm.invoke(prompt)</pre><p><strong>This works for demos.</strong> It fails in production.</p><h3>The Multi-Chain Reality</h3><p>Different problems need different chain architectures:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AfvMMTdbaIHnb8tP9zndA.png" /><figcaption>LangChain patterns, AI architecture</figcaption></figure><p><strong>Each chain type solves a specific class of problems.</strong></p><p>Let me show you all 7, with real healthcare examples.</p><h3>Chain Type 1: Simple Chain</h3><h4>What It Is</h4><p><strong>One input → One transformation → One output</strong></p><p>The simplest form: prompt | llm | parser</p><h4>When to Use</h4><p>✅ Quick text transformations<br> ✅ Single-step processing<br> ✅ Format standardization<br> ✅ No dependencies between steps</p><h4>Real-World Use Case: Complaint Normalization</h4><p><strong>Problem:</strong> Patients say “my tummy hurts real bad” but EMR systems need “abdominal pain, moderate severity”</p><p><strong>Solution:</strong></p><pre>from langchain_groq import ChatGroq<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br>llm = ChatGroq(model_name=&quot;llama-3.3-70b-versatile&quot;, temperature=0)<br>parser = StrOutputParser()<br><br># Define the chain<br>normalize_prompt = PromptTemplate.from_template(<br>    &quot;Convert this to medical terminology (1 sentence):\n{text}&quot;<br>)<br><br>normalize_chain = normalize_prompt | llm | parser<br><br># Use it<br>patient_input = &quot;my tummy hurts real bad and i feel like throwing up&quot;<br>result = normalize_chain.invoke({&quot;text&quot;: patient_input})<br><br>print(result)<br># Output: &quot;Patient reports severe abdominal pain with associated nausea.&quot;</pre><h4>Who Uses This</h4><ul><li>🏥 <strong>Front desk staff</strong> — Standardize intake forms</li><li>👨‍⚕️ <strong>Nurses</strong> — Normalize patient complaints</li><li>📋 <strong>Medical assistants</strong> — Format vitals documentation</li></ul><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*k-qOzBKbYdLOist7o5L0lA.png" /></figure><h3>Chain Type 2: Sequential Chain</h3><h4>What It Is</h4><p><strong>Multiple steps where each step feeds the next</strong></p><pre>Input → Step 1 → Step 2 → Step 3 → Output</pre><p>Each step depends on the previous one.</p><h4>When to Use</h4><p>✅ Multi-step reasoning required<br> ✅ Each step builds on previous<br> ✅ Need intermediate outputs<br> ✅ Diagnostic or analytical workflows</p><h4>Real-World Use Case: Clinical Reasoning</h4><p><strong>Problem:</strong> Diagnose requires: Extract symptoms → Assess risk → Recommend actions</p><p><strong>Solution:</strong></p><pre>def sequential_chain_analyze(text: str):<br>    &quot;&quot;&quot;3-step clinical reasoning pipeline&quot;&quot;&quot;<br>    <br>    # STEP 1: Extract findings<br>    extract_prompt = PromptTemplate.from_template(<br>        &quot;Extract symptoms, vitals, labs from:\n{text}\nList concisely:&quot;<br>    )<br>    extract_chain = extract_prompt | llm | parser<br>    findings = extract_chain.invoke({&quot;text&quot;: text})<br>    <br>    print(f&quot;✓ Step 1 - Findings: {findings[:100]}...&quot;)<br>    <br>    # STEP 2: Assess risk<br>    risk_prompt = PromptTemplate.from_template(<br>        &quot;Classify risk as LOW/MODERATE/HIGH/CRITICAL:\n{signals}\nBrief reason:&quot;<br>    )<br>    risk_chain = risk_prompt | llm | parser<br>    risk = risk_chain.invoke({&quot;signals&quot;: findings})<br>    <br>    print(f&quot;✓ Step 2 - Risk: {risk[:80]}...&quot;)<br>    <br>    # STEP 3: Recommend actions<br>    action_prompt = PromptTemplate.from_template(<br>        &quot;For {risk} risk, recommend: timeframe, tests, provider (brief):&quot;<br>    )<br>    action_chain = action_prompt | llm | parser<br>    actions = action_chain.invoke({&quot;risk&quot;: risk})<br>    <br>    print(f&quot;✓ Step 3 - Actions: {actions[:80]}...&quot;)<br>    <br>    return {<br>        &quot;findings&quot;: findings,<br>        &quot;risk&quot;: risk,<br>        &quot;actions&quot;: actions<br>    }<br><br># Test it<br>complaint = &quot;Severe chest pain for 2 hours, sweating, BP 180/100, history of CAD&quot;<br>result = sequential_chain_analyze(complaint)<br><br># Output:<br># ✓ Step 1 - Findings: Severe chest pain (2h duration), diaphoresis, hypertension (180/100), known coronary...<br># ✓ Step 2 - Risk: CRITICAL - Concerning for acute coronary syndrome given chest pain + diaphoresis + HTN...<br># ✓ Step 3 - Actions: Immediate: ECG, troponin, aspirin. Call cardiology STAT. Transfer to cath lab if...</pre><h4>Who Uses This</h4><ul><li>👨‍⚕️ <strong>Physicians</strong> — Diagnostic reasoning</li><li>🔬 <strong>Specialists</strong> — Complex case analysis</li><li>🚑 <strong>Paramedics</strong> — Field triage protocols</li></ul><h4>Visual Flow</h4><pre>┌─────────────────────┐<br>│   Patient Message   │<br>└──────────┬──────────┘<br>           │<br>           ▼<br>┌─────────────────────┐<br>│ STEP 1: Extract     │<br>│ Symptoms: chest pain│<br>│ Vitals: BP 180/100  │<br>└──────────┬──────────┘<br>           │<br>           ▼<br>┌─────────────────────┐<br>│ STEP 2: Assess Risk │<br>│ CRITICAL - ACS risk │<br>└──────────┬──────────┘<br>           │<br>           ▼<br>┌─────────────────────┐<br>│ STEP 3: Actions     │<br>│ ECG, troponin, cath │<br>└─────────────────────┘</pre><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*GQ4BNacrEmtErMG8TNqvOw.png" /></figure><h3>Chain Type 3: Tool Chain</h3><h4>What It Is</h4><p><strong>Chains that execute functions/tools with business logic</strong></p><p>Instead of asking the LLM to calculate, you run actual code.</p><h4>When to Use</h4><p>✅ Apply domain-specific rules<br> ✅ Need exact calculations<br> ✅ Medical/legal guidelines<br> ✅ Compliance requirements</p><h4>Real-World Use Case: Lab Value Interpretation</h4><p><strong>Problem:</strong> HbA1c 8.2% needs precise interpretation per ADA guidelines, not LLM guesswork</p><p><strong>Solution:</strong></p><pre>from langchain_core.runnables import RunnableLambda<br>import re<br><br>def interpret_hba1c_tool(input_data):<br>    &quot;&quot;&quot;Apply American Diabetes Association clinical guidelines&quot;&quot;&quot;<br>    <br>    text = input_data[&quot;text&quot;]<br>    <br>    # Extract HbA1c value<br>    match = re.search(r&#39;HbA1c.*?(\d+\.\d+)&#39;, text, re.IGNORECASE)<br>    <br>    if not match:<br>        return &quot;No HbA1c value detected&quot;<br>    <br>    value = float(match.group(1))<br>    <br>    # Apply ADA guidelines (exact medical rules)<br>    if value &gt;= 9.0:<br>        return f&quot;🚨 CRITICAL: HbA1c {value}% - Severe hyperglycemia. Immediate endocrine consult required.&quot;<br>    elif value &gt;= 8.0:<br>        return f&quot;⚠️  HIGH RISK: HbA1c {value}% - Poor control. Adjust medications within 1 week.&quot;<br>    elif value &gt;= 6.5:<br>        return f&quot;📊 MODERATE: HbA1c {value}% - Diabetes range. Optimize treatment plan.&quot;<br>    elif value &gt;= 5.7:<br>        return f&quot;📈 BORDERLINE: HbA1c {value}% - Prediabetes. Lifestyle modifications needed.&quot;<br>    else:<br>        return f&quot;✅ NORMAL: HbA1c {value}% - Good glycemic control. Continue current plan.&quot;<br><br># Create tool chain<br>lab_tool_chain = RunnableLambda(interpret_hba1c_tool)<br><br># Test it<br>test_input = &quot;Patient reports fatigue. Recent labs show HbA1c of 8.2%&quot;<br>result = lab_tool_chain.invoke({&quot;text&quot;: test_input})<br><br>print(result)<br># Output: &quot;⚠️  HIGH RISK: HbA1c 8.2% - Poor control. Adjust medications within 1 week.&quot;</pre><h4>Why This Matters</h4><p><strong>LLM alone:</strong></p><ul><li>❌ Might say “slightly elevated” (vague)</li><li>❌ Might recommend wrong action</li><li>❌ Not compliant with guidelines</li></ul><p><strong>Tool Chain:</strong></p><ul><li>✅ Exact ADA guideline application</li><li>✅ Precise risk classification</li><li>✅ Compliant with medical standards</li><li>✅ Reproducible results</li></ul><h4>Who Uses This</h4><ul><li>🔬 <strong>Lab technicians</strong> — Result interpretation</li><li>💊 <strong>Pharmacists</strong> — Drug dosing calculations</li><li>📊 <strong>Clinical specialists</strong> — Guideline application</li></ul><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*wc4lNH76EfEfDt4-fQgMjg.png" /></figure><h3>Chain Type 4: Conditional Branch</h3><h4>What It Is</h4><p><strong>Different paths based on conditions</strong></p><pre>Input → Evaluate condition<br>        ├─ If A → Chain A<br>        ├─ If B → Chain B<br>        └─ Else → Chain C</pre><h4>When to Use</h4><p>✅ Different workflows for different cases<br> ✅ Risk-based routing<br> ✅ Emergency vs routine protocols<br> ✅ Personalized pathways</p><h4>Real-World Use Case: Triage Routing</h4><p><strong>Problem:</strong> CRITICAL needs ER protocol, LOW needs wellness protocol — different workflows entirely</p><p><strong>Solution:</strong></p><pre>from langchain_core.runnables import RunnableBranch<br><br>def conditional_triage_router(risk_level: str):<br>    &quot;&quot;&quot;Route to appropriate protocol based on risk&quot;&quot;&quot;<br>    <br>    # Define different protocol chains<br>    critical_protocol = PromptTemplate.from_template(<br>        &quot;CRITICAL PROTOCOL - Immediate actions (3 bullets):&quot;<br>    ) | llm | parser<br>    <br>    high_protocol = PromptTemplate.from_template(<br>        &quot;HIGH PRIORITY - Urgent actions within 30 min (3 bullets):&quot;<br>    ) | llm | parser<br>    <br>    moderate_protocol = PromptTemplate.from_template(<br>        &quot;STANDARD PROTOCOL - Routine actions within 2-4 hours (3 bullets):&quot;<br>    ) | llm | parser<br>    <br>    low_protocol = PromptTemplate.from_template(<br>        &quot;WELLNESS PROTOCOL - Preventive care recommendations (3 bullets):&quot;<br>    ) | llm | parser<br>    <br>    # Create conditional branch<br>    triage_branch = RunnableBranch(<br>        (lambda x: &quot;CRITICAL&quot; in x[&quot;risk&quot;].upper(), critical_protocol),<br>        (lambda x: &quot;HIGH&quot; in x[&quot;risk&quot;].upper(), high_protocol),<br>        (lambda x: &quot;MODERATE&quot; in x[&quot;risk&quot;].upper(), moderate_protocol),<br>        low_protocol  # Default<br>    )<br>    <br>    result = triage_branch.invoke({&quot;risk&quot;: risk_level})<br>    return result<br><br># Test different risk levels<br>print(&quot;--- CRITICAL CASE ---&quot;)<br>print(conditional_triage_router(&quot;CRITICAL: Chest pain, possible MI&quot;))<br><br># Output:<br># • Activate Code Blue/STEMI protocol immediately<br># • Obtain 12-lead ECG within 10 minutes<br># • Administer aspirin 324mg, start IV access, continuous monitoring<br><br>print(&quot;\n--- LOW RISK CASE ---&quot;)<br>print(conditional_triage_router(&quot;LOW: Routine checkup, no concerns&quot;))<br><br># Output:<br># • Schedule annual physical exam<br># • Review preventive health screenings (colonoscopy, mammogram)<br># • Discuss healthy lifestyle: diet, exercise, stress management</pre><h4>Visual Flow</h4><pre>Risk Assessment<br>      │<br>      ├─── CRITICAL? ───→ Emergency Protocol<br>      │                   (Code Blue, ECG, Cath Lab)<br>      │<br>      ├─── HIGH? ───────→ Urgent Protocol<br>      │                   (30-min response, labs, imaging)<br>      │<br>      ├─── MODERATE? ───→ Standard Protocol<br>      │                   (2-4 hour response, routine workup)<br>      │<br>      └─── LOW ─────────→ Wellness Protocol<br>                          (Preventive care, education)</pre><h4>Who Uses This</h4><ul><li>🚑 <strong>ER staff</strong> — Emergency triage</li><li>👨‍⚕️ <strong>Paramedics</strong> — Field assessment</li><li>📞 <strong>Telehealth nurses</strong> — Remote triage</li></ul><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*AXcTu93mWMKn6p9D_enTKw.png" /></figure><h3>Chain Type 5: Parallel Chain</h3><h4>What It Is</h4><p><strong>Multiple chains run simultaneously</strong></p><pre>Input ──┬─→ Chain A ──→ Output A<br>        ├─→ Chain B ──→ Output B<br>        └─→ Chain C ──→ Output C</pre><p>All at the same time, not sequential.</p><h4>When to Use</h4><p>✅ Need multiple independent outputs<br> ✅ Speed matters (parallel &gt; sequential)<br> ✅ Different document types<br> ✅ Multi-department needs</p><h4>Real-World Use Case: Medical Documentation</h4><p><strong>Problem:</strong> After patient visit, need 3 documents: Clinical note (for doctor), ICD-10 codes (for billing), Patient instructions (for patient)</p><p><strong>Solution:</strong></p><pre>from langchain_core.runnables import RunnableParallel<br><br>def parallel_documentation(encounter_text: str):<br>    &quot;&quot;&quot;Generate 3 documents simultaneously&quot;&quot;&quot;<br>    <br>    # Define 3 independent chains<br>    clinical_note_chain = PromptTemplate.from_template(<br>        &quot;Clinical summary (SOAP format, 2-3 sentences):\n{text}&quot;<br>    ) | llm | parser<br>    <br>    icd10_chain = PromptTemplate.from_template(<br>        &quot;Top 3 ICD-10 codes with descriptions for:\n{text}&quot;<br>    ) | llm | parser<br>    <br>    patient_instructions_chain = PromptTemplate.from_template(<br>        &quot;Patient discharge instructions (3 bullet points, simple language):\n{text}&quot;<br>    ) | llm | parser<br>    <br>    # Run in parallel<br>    parallel_chain = RunnableParallel({<br>        &quot;clinical_note&quot;: clinical_note_chain,<br>        &quot;icd10_codes&quot;: icd10_chain,<br>        &quot;patient_instructions&quot;: patient_instructions_chain<br>    })<br>    <br>    result = parallel_chain.invoke({&quot;text&quot;: encounter_text})<br>    return result<br><br># Test it<br>encounter = &quot;&quot;&quot;<br>Patient: 45yo female with type 2 diabetes<br>Chief complaint: Fatigue, polyuria, polydipsia for 2 weeks<br>Vitals: BP 145/90, HR 88, BMI 32<br>Labs: HbA1c 8.2%, fasting glucose 180<br>Assessment: Uncontrolled diabetes, adjust metformin<br>Plan: Increase metformin to 1000mg BID, recheck labs in 6 weeks<br>&quot;&quot;&quot;<br><br>docs = parallel_documentation(encounter)<br><br>print(&quot;📄 CLINICAL NOTE:&quot;)<br>print(docs[&quot;clinical_note&quot;])<br>print(&quot;\n💰 ICD-10 CODES:&quot;)<br>print(docs[&quot;icd10_codes&quot;])<br>print(&quot;\n📋 PATIENT INSTRUCTIONS:&quot;)<br>print(docs[&quot;patient_instructions&quot;])<br><br># Output (all generated simultaneously):<br># 📄 CLINICAL NOTE:<br># 45F with T2DM presents with 2-week history of fatigue and hyperglycemic symptoms.<br># HbA1c 8.2% indicates poor control. Metformin increased to 1000mg BID.<br><br># 💰 ICD-10 CODES:<br># 1. E11.65 - Type 2 diabetes with hyperglycemia<br># 2. R53.83 - Fatigue<br># 3. E66.9 - Obesity, unspecified<br><br># 📋 PATIENT INSTRUCTIONS:<br># • Take your diabetes medication twice daily with meals<br># • Check blood sugar levels before breakfast and dinner<br># • Return in 6 weeks for follow-up blood work</pre><h4>Why Parallel Beats Sequential</h4><p><strong>Sequential (one after another):</strong></p><ul><li>Chain A: 2 seconds</li><li>Chain B: 2 seconds</li><li>Chain C: 2 seconds</li><li><strong>Total: 6 seconds</strong></li></ul><h4><strong>Parallel (all at once):</strong></h4><ul><li>All 3 chains: 2 seconds</li><li><strong>Total: 2 seconds</strong> ✅</li></ul><h4>Who Uses This</h4><ul><li>📋 <strong>Medical records</strong> — Documentation</li><li>💰 <strong>Billing department</strong> — Coding</li><li>✅ <strong>Quality assurance</strong> — Compliance checks</li></ul><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*yuEN0FRliPly-pBmuBwtxw.png" /></figure><h3>Chain Type 6: Memory Chain</h3><h4>What It Is</h4><p><strong>Chains that use persistent context/history</strong></p><pre>Patient History + Current Input → Personalized Response</pre><h4>When to Use</h4><p>✅ Need patient/user history<br> ✅ Continuity of care<br> ✅ Personalization required<br> ✅ Context-aware responses</p><h4>Real-World Use Case: Personalized Care</h4><p><strong>Problem:</strong> Generic “How are you?” vs “How’s your diabetes and blood pressure doing, John?”</p><p><strong>Solution:</strong></p><pre># Patient database (in production, this is your EMR/database)<br>PATIENT_DATABASE = {<br>    &quot;P001&quot;: {<br>        &quot;name&quot;: &quot;John Smith&quot;,<br>        &quot;age&quot;: 58,<br>        &quot;gender&quot;: &quot;Male&quot;,<br>        &quot;conditions&quot;: [&quot;Type 2 Diabetes&quot;, &quot;Hypertension&quot;, &quot;Hyperlipidemia&quot;],<br>        &quot;medications&quot;: [&quot;Metformin 1000mg BID&quot;, &quot;Lisinopril 20mg QD&quot;, &quot;Atorvastatin 40mg QHS&quot;],<br>        &quot;allergies&quot;: [&quot;Penicillin&quot;, &quot;Sulfa drugs&quot;],<br>        &quot;last_visit&quot;: &quot;2025-01-15&quot;,<br>        &quot;recent_labs&quot;: {&quot;HbA1c&quot;: 7.8, &quot;LDL&quot;: 120, &quot;BP&quot;: &quot;138/88&quot;}<br>    }<br>}<br><br>def memory_chain_personalized_greeting(patient_id: str):<br>    &quot;&quot;&quot;Generate personalized greeting using patient history&quot;&quot;&quot;<br>    <br>    # Retrieve patient context (THE MEMORY)<br>    patient = PATIENT_DATABASE.get(patient_id, {})<br>    <br>    print(f&quot;📂 Loading patient context for {patient.get(&#39;name&#39;, &#39;Unknown&#39;)}...&quot;)<br>    print(f&quot;   Conditions: {&#39;, &#39;.join(patient.get(&#39;conditions&#39;, []))}&quot;)<br>    print(f&quot;   Recent HbA1c: {patient.get(&#39;recent_labs&#39;, {}).get(&#39;HbA1c&#39;, &#39;N/A&#39;)}&quot;)<br>    <br>    # Create context-aware prompt<br>    prompt = PromptTemplate.from_template(<br>&quot;&quot;&quot;You are {name}&#39;s primary care physician.<br><br>Patient Profile:<br>- Name: {name}, {age}yo {gender}<br>- Conditions: {conditions}<br>- Current Medications: {medications}<br>- Known Allergies: {allergies}<br>- Last Visit: {last_visit}<br>- Recent Labs: HbA1c {hba1c}, LDL {ldl}, BP {bp}<br><br>Write a warm, personalized greeting (2-3 sentences) that:<br>1. Shows you remember them<br>2. References their specific conditions<br>3. Asks about relevant symptoms/concerns<br>&quot;&quot;&quot;<br>    )<br>    <br>    chain = prompt | llm | parser<br>    <br>    # Invoke with patient context<br>    result = chain.invoke({<br>        &quot;name&quot;: patient[&quot;name&quot;],<br>        &quot;age&quot;: patient[&quot;age&quot;],<br>        &quot;gender&quot;: patient[&quot;gender&quot;],<br>        &quot;conditions&quot;: &quot;, &quot;.join(patient[&quot;conditions&quot;]),<br>        &quot;medications&quot;: &quot;, &quot;.join(patient[&quot;medications&quot;]),<br>        &quot;allergies&quot;: &quot;, &quot;.join(patient[&quot;allergies&quot;]),<br>        &quot;last_visit&quot;: patient[&quot;last_visit&quot;],<br>        &quot;hba1c&quot;: patient[&quot;recent_labs&quot;][&quot;HbA1c&quot;],<br>        &quot;ldl&quot;: patient[&quot;recent_labs&quot;][&quot;LDL&quot;],<br>        &quot;bp&quot;: patient[&quot;recent_labs&quot;][&quot;BP&quot;]<br>    })<br>    <br>    return result<br><br># Test it<br>greeting = memory_chain_personalized_greeting(&quot;P001&quot;)<br>print(f&quot;\n👨‍⚕️ Personalized Greeting:\n{greeting}&quot;)<br><br># Output:<br># 📂 Loading patient context for John Smith...<br>#    Conditions: Type 2 Diabetes, Hypertension, Hyperlipidemia<br>#    Recent HbA1c: 7.8<br>#<br># 👨‍⚕️ Personalized Greeting:<br># Hello John, it&#39;s good to see you again. I see it&#39;s been about two weeks<br># since your last visit when we reviewed your diabetes and blood pressure<br># management. How have you been feeling since we adjusted your metformin,<br># and have you noticed any improvements in your energy levels?</pre><h4>Compare: Generic vs Personalized</h4><p><strong>Without Memory (Generic):</strong></p><blockquote><em>“Hello! How can I help you today?”</em></blockquote><p><strong>With Memory (Personalized):</strong></p><blockquote><em>“Hello John, it’s good to see you again. I see it’s been two weeks since we adjusted your diabetes medications. How have you been feeling, and have you noticed any improvements in your energy levels?”</em></blockquote><p><strong>The difference is night and day.</strong></p><h4>Who Uses This</h4><ul><li>👨‍⚕️ <strong>Primary care physicians</strong> — Longitudinal care</li><li>💼 <strong>Care managers</strong> — Chronic disease management</li><li>📞 <strong>Patient navigators</strong> — Continuity across visits</li></ul><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*6Ty8uoXmZiFJkVOg9R--Ow.png" /></figure><h3>Chain Type 7: RAG Chain</h3><h4>What It Is</h4><p><strong>Retrieval Augmented Generation</strong></p><pre>Question → Search Knowledge Base → Retrieved Docs → Generate Answer</pre><h3>When to Use</h3><p>✅ Need evidence-based answers<br> ✅ Large knowledge base<br> ✅ Medical guidelines/protocols<br> ✅ Reduce hallucinations</p><h4>Real-World Use Case: Clinical Guidelines Query</h4><p><strong>Problem:</strong> “What are the current HbA1c management guidelines?” needs ADA/WHO guidelines, not LLM guesswork</p><p><strong>Solution:</strong></p><pre>from langchain_core.runnables import RunnableLambda<br><br># Simulated knowledge base (in production, use vector DB)<br>CLINICAL_KNOWLEDGE_BASE = {<br>    &quot;diabetes_hba1c&quot;: &quot;&quot;&quot;<br>    American Diabetes Association Guidelines 2025:<br>    - HbA1c target: &lt;7% for most adults<br>    - HbA1c target: &lt;8% for elderly or comorbidities<br>    - Check HbA1c every 3 months if not at goal<br>    - Check HbA1c every 6 months if stable at goal<br>    - HbA1c &gt;9%: Immediate medication adjustment required<br>    &quot;&quot;&quot;,<br>    &quot;chest_pain_protocol&quot;: &quot;&quot;&quot;<br>    ACC/AHA Chest Pain Guidelines:<br>    - Immediate ECG within 10 minutes<br>    - Serial troponin at 0h, 3h<br>    - Risk stratify: HEART score or TIMI score<br>    - STEMI: Door-to-balloon &lt;90 minutes<br>    - NSTEMI: Cardiology consult within 24 hours<br>    &quot;&quot;&quot;<br>}<br><br>def rag_chain_guidelines(question: str):<br>    &quot;&quot;&quot;Retrieve relevant guidelines and generate answer&quot;&quot;&quot;<br>    <br>    def retriever(input_data):<br>        &quot;&quot;&quot;Search knowledge base&quot;&quot;&quot;<br>        q = input_data[&quot;question&quot;].lower()<br>        <br>        print(f&quot;🔍 Searching knowledge base for: &#39;{question}&#39;&quot;)<br>        <br>        # Semantic search simulation (in production, use vector similarity)<br>        context = &quot;&quot;<br>        sources = []<br>        <br>        if any(term in q for term in [&quot;hba1c&quot;, &quot;diabetes&quot;, &quot;a1c&quot;, &quot;glycemic&quot;]):<br>            context += CLINICAL_KNOWLEDGE_BASE[&quot;diabetes_hba1c&quot;]<br>            sources.append(&quot;ADA Guidelines 2024&quot;)<br>            print(&quot;   ✓ Found: Diabetes/HbA1c guidelines&quot;)<br>        <br>        if any(term in q for term in [&quot;chest pain&quot;, &quot;cardiac&quot;, &quot;mi&quot;, &quot;acs&quot;]):<br>            context += &quot;\n\n&quot; + CLINICAL_KNOWLEDGE_BASE[&quot;chest_pain_protocol&quot;]<br>            sources.append(&quot;ACC/AHA Chest Pain Protocol&quot;)<br>            print(&quot;   ✓ Found: Cardiac protocols&quot;)<br>        <br>        if not context:<br>            context = &quot;No specific guidelines found in knowledge base.&quot;<br>            print(&quot;   ⚠️  No matching guidelines&quot;)<br>        <br>        return {<br>            &quot;context&quot;: context,<br>            &quot;question&quot;: input_data[&quot;question&quot;],<br>            &quot;sources&quot;: sources<br>        }<br>    <br>    # Augment prompt with retrieved context<br>    rag_prompt = PromptTemplate.from_template(<br>&quot;&quot;&quot;Based on these clinical guidelines:<br><br>{context}<br><br>Question: {question}<br><br>Provide an evidence-based answer citing the guidelines:&quot;&quot;&quot;<br>    )<br>    <br>    # Build RAG chain<br>    rag_chain = RunnableLambda(retriever) | rag_prompt | llm | parser<br>    <br>    result = rag_chain.invoke({&quot;question&quot;: question})<br>    return result<br><br># Test it<br>question = &quot;What are the HbA1c management guidelines?&quot;<br>answer = rag_chain_guidelines(question)<br><br>print(f&quot;\n💡 Answer:\n{answer}&quot;)<br><br># Output:<br># 🔍 Searching knowledge base for: &#39;What are the HbA1c management guidelines?&#39;<br>#    ✓ Found: Diabetes/HbA1c guidelines<br>#<br># 💡 Answer:<br># According to the American Diabetes Association Guidelines 2025, HbA1c<br># management follows these evidence-based recommendations:<br># <br># Target Levels:<br># - Most adults should aim for HbA1c &lt;7%<br># - Elderly patients or those with comorbidities should target &lt;8%<br># <br># Monitoring Frequency:<br># - Check every 3 months if not at goal<br># - Check every 6 months if stable and at target<br># <br># Action Thresholds:<br># - HbA1c &gt;9% requires immediate medication adjustment<br>#<br># These guidelines emphasize individualized targets based on patient<br># characteristics while maintaining evidence-based standards of care.</pre><h4>Why RAG Beats Pure LLM</h4><p><strong>Pure LLM (No RAG):</strong></p><ul><li>❌ Might cite outdated guidelines</li><li>❌ Might hallucinate recommendations</li><li>❌ Can’t cite specific sources</li><li>❌ Limited to training data cutoff</li></ul><p><strong>RAG Chain:</strong></p><ul><li>✅ Uses current, verified guidelines</li><li>✅ Cites specific sources</li><li>✅ Grounds response in facts</li><li>✅ Reduces hallucinations</li></ul><h4>Who Uses This</h4><ul><li>🎓 <strong>Medical residents</strong> — Learning evidence-based medicine</li><li>🔬 <strong>Researchers</strong> — Protocol queries</li><li>👨‍⚕️ <strong>Specialists</strong> — Rare condition guidelines</li></ul><h4>Key Characteristics</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*OB0mZ_98-jxriCEjbCyxWA.png" /></figure><h3>Choosing the Right Chain: Decision Matrix</h3><h4>Quick Reference Guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*MnmOnI-uIqizcGEvawWyxA.png" /></figure><h4>Decision Tree</h4><pre>Do you need multiple outputs?<br>├─ YES → Use Parallel Chain<br>└─ NO<br>    │<br>    Do you need patient history?<br>    ├─ YES → Use Memory Chain<br>    └─ NO<br>        │<br>        Do you need guidelines/docs?<br>        ├─ YES → Use RAG Chain<br>        └─ NO<br>            │<br>            Do you need routing?<br>            ├─ YES → Use Conditional Branch<br>            └─ NO<br>                │<br>                Do you need exact calculations?<br>                ├─ YES → Use Tool Chain<br>                └─ NO<br>                    │<br>                    Multiple reasoning steps?<br>                    ├─ YES → Use Sequential Chain<br>                    └─ NO → Use Simple Chain</pre><h3>Real-World Integration: Building a Complete System</h3><h4>The Patient Journey (Using All 7 Chains)</h4><p>Let me show you how all these chains work together in a real ER visit:</p><p><strong>Patient arrives:</strong> “I’ve been having really bad chest pain for 2 hours”</p><p><strong>System workflow:</strong></p><pre>1️⃣ SIMPLE CHAIN: Normalize complaint<br>   Input: &quot;really bad chest pain for 2 hours&quot;<br>   Output: &quot;Severe chest pain, 2-hour duration&quot;<br><br>2️⃣ MEMORY CHAIN: Load patient history<br>   Retrieved: &quot;John Smith, 58M, known CAD, on aspirin + statin&quot;<br><br>3️⃣ SEQUENTIAL CHAIN: Clinical reasoning<br>   Step A - Extract: &quot;Chest pain, duration 2h, history CAD&quot;<br>   Step B - Risk: &quot;CRITICAL - Acute coronary syndrome suspected&quot;<br>   Step C - Actions: &quot;ECG, troponin, aspirin, cardiology STAT&quot;<br><br>4️⃣ TOOL CHAIN: Apply cardiac protocol<br>   Input: &quot;Chest pain, 2h, CAD history&quot;<br>   Output: &quot;STEMI protocol activated - Door-to-balloon &lt;90min&quot;<br><br>5️⃣ CONDITIONAL BRANCH: Route by risk<br>   Risk: CRITICAL<br>   Routed to: Emergency cardiac protocol<br><br>6️⃣ PARALLEL CHAIN: Generate documentation<br>   Output A: Clinical note for physician<br>   Output B: ICD-10 codes for billing (I21.0 - STEMI)<br>   Output C: Alert to cardiology team<br><br>7️⃣ RAG CHAIN: Pull guidelines<br>   Question: &quot;What&#39;s the STEMI door-to-balloon target?&quot;<br>   Retrieved: &quot;ACC/AHA: &lt;90 minutes&quot;<br>   Answer: &quot;Target achieved: 67 minutes&quot;</pre><p><strong>Total processing time:</strong> ~8 seconds for complete triage</p><h4>Code: Orchestrating Multiple Chains</h4><pre>def complete_er_workflow(patient_id: str, complaint: str):<br>    &quot;&quot;&quot;<br>    Complete ER workflow using all 7 chain types<br>    &quot;&quot;&quot;<br>    <br>    print(&quot;🏥 ER WORKFLOW INITIATED&quot;)<br>    print(&quot;=&quot;*80)<br>    <br>    # 1. Simple Chain - Normalize<br>    normalized = simple_chain_normalize(complaint, verbose=False)<br>    print(f&quot;1️⃣ Normalized: {normalized}&quot;)<br>    <br>    # 2. Memory Chain - Patient history<br>    history = memory_chain_personalized_care(patient_id, verbose=False)<br>    print(f&quot;2️⃣ Patient Context Loaded: {history[:100]}...&quot;)<br>    <br>    # 3. Sequential Chain - Reasoning<br>    analysis = sequential_chain_analyze(complaint, verbose=False)<br>    print(f&quot;3️⃣ Risk Assessment: {analysis[&#39;risk&#39;][:80]}...&quot;)<br>    <br>    # 4. Tool Chain - Lab interpretation (if labs mentioned)<br>    if &quot;hba1c&quot; in complaint.lower() or &quot;glucose&quot; in complaint.lower():<br>        lab_result = tool_chain_lab_interpreter(complaint, verbose=False)<br>        print(f&quot;4️⃣ Lab Interpretation: {lab_result}&quot;)<br>    <br>    # 5. Conditional Branch - Protocol routing<br>    protocol = conditional_chain_triage(analysis[&#39;risk&#39;], verbose=False)<br>    print(f&quot;5️⃣ Protocol Assigned: {protocol[:100]}...&quot;)<br>    <br>    # 6. Parallel Chain - Documentation<br>    docs = parallel_chain_documentation(complaint, verbose=False)<br>    print(f&quot;6️⃣ Documentation: Generated clinical note + ICD-10 + instructions&quot;)<br>    <br>    # 7. RAG Chain - Evidence-based guidance<br>    guidelines = rag_chain_clinical_guidelines(<br>        &quot;What are the management guidelines for this case?&quot;,<br>        verbose=False<br>    )<br>    print(f&quot;7️⃣ Guidelines: {guidelines[:100]}...&quot;)<br>    <br>    print(&quot;=&quot;*80)<br>    print(&quot;✅ COMPLETE WORKFLOW EXECUTED IN ~8 SECONDS&quot;)<br>    <br>    return {<br>        &quot;normalized&quot;: normalized,<br>        &quot;analysis&quot;: analysis,<br>        &quot;protocol&quot;: protocol,<br>        &quot;documentation&quot;: docs,<br>        &quot;guidelines&quot;: guidelines<br>    }<br><br># Execute<br>result = complete_er_workflow(&quot;P001&quot;, &quot;Severe chest pain for 2 hours&quot;)</pre><h3>Conclusion</h3><p>You started this article wondering which chain to use.</p><p>Now you know:</p><ol><li><strong>Simple Chain</strong> — Quick text transformations</li><li><strong>Sequential Chain</strong> — Multi-step reasoning</li><li><strong>Tool Chain</strong> — Exact rules and calculations</li><li><strong>Conditional Branch</strong> — Smart routing</li><li><strong>Parallel Chain</strong> — Simultaneous outputs</li><li><strong>Memory Chain</strong> — Personalized with history</li><li><strong>RAG Chain</strong> — Evidence-based answers</li></ol><p><strong>The secret?</strong> Production systems use <strong>all of them together</strong>.</p><p>Each chain type solves a specific problem. The art is knowing which tool to reach for when.</p><h3>Resources</h3><p><strong>Code Repository:</strong></p><ul><li><a href="https://github.com/sajosam/langchain/tree/main/langchain-types-of-chains">Full examples on GitHub</a></li><li>Includes all 7 chain types with tests</li></ul><p><strong>Documentation:</strong></p><ul><li><a href="https://python.langchain.com/docs/expression_language/">LangChain LCEL Guide</a></li><li><a href="https://console.groq.com/">Groq API Docs</a></li><li><a href="https://python.langchain.com/docs/expression_language/primitives/">LangChain Runnable Docs</a></li></ul><p><strong>Related Articles:</strong></p><ul><li>Building Multi-Step Clinical Reasoning with LCEL</li><li>Production LangChain Architecture Patterns</li><li>Healthcare AI Safety &amp; Compliance</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3982619948b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Multi-Step AI Reasoning Pipelines with LangChain LCEL + Groq]]></title>
            <link>https://medium.com/@sajo02/building-multi-step-ai-reasoning-pipelines-with-langchain-lcel-groq-580c5b686465?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/580c5b686465</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Fri, 23 Jan 2026 03:20:35 GMT</pubDate>
            <atom:updated>2026-01-23T03:20:35.964Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From Single Prompts to Structured Intelligence: A Healthcare AI Journey</em></p><p><strong>Imagine asking an AI assistant:</strong> “I’ve been tired for 2 weeks and my HbA1c is 8.2”</p><p><strong>Most chatbots respond with:</strong> Generic advice disconnected from clinical reality.</p><p><strong>What if the AI could:</strong></p><ul><li>Extract the symptom (fatigue)</li><li>Interpret the lab value (HbA1c 8.2 = poor diabetes control)</li><li>Assess combined risk (moderate/high)</li><li>Provide time-bound, actionable guidance</li></ul><p><strong>That’s what multi-step chains enable.</strong></p><p>In this article, I’ll show you how I built a healthcare reasoning system using <strong>LangChain LCEL</strong> (LangChain Expression Language) and <strong>Groq’s Llama 3.3</strong> that thinks in steps, not just responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKRoWKUkXZa7q6yGsirIUg.png" /><figcaption>How to Design Multi-Step AI Workflows Using LangChain LCEL and Groq</figcaption></figure><h3>Why Chains Instead of Single Prompts?</h3><h4>The Single-Prompt Problem</h4><p>Most AI applications look like this:</p><pre>prompt = &quot;Analyze this patient message and provide advice&quot;<br>response = llm.invoke(prompt)</pre><p><strong>Problems:</strong></p><ul><li>Tries to do everything at once</li><li>No intermediate reasoning</li><li>Hard to debug when wrong</li><li>Can’t validate steps</li><li>Black box decision-making</li></ul><h4>The Chain Solution</h4><p>Chains split reasoning into <strong>cognitive steps</strong>:</p><pre>User Message<br>      ↓<br>Step 1: Extract symptoms &amp; findings<br>      ↓<br>Step 2: Assess clinical risk<br>      ↓<br>Step 3: Recommend actions<br>      ↓<br>Final Response</pre><p><strong>Benefits:</strong></p><ul><li>✅ Each step does one thing well</li><li>✅ Can inspect intermediate outputs</li><li>✅ Easy to debug and improve</li><li>✅ Explainable reasoning</li><li>✅ Clinical safety controls</li></ul><h3>Architecture: The Three-Chain System</h3><pre>┌─────────────────────────┐<br>│    User Input           │<br>│ &quot;Tired for 2 weeks,     │<br>│  HbA1c is 8.2&quot;          │<br>└──────────┬──────────────┘<br>           │<br>           ▼<br>┌──────────────────────────┐<br>│ Chain 1: EXTRACTION      │<br>│ symptom_prompt | llm     │<br>│ Output: &quot;fatigue,        │<br>│          HbA1c: 8.2&quot;     │<br>└──────────┬───────────────┘<br>           │<br>           ▼<br>┌──────────────────────────┐<br>│ Chain 2: RISK ASSESSMENT │<br>│ risk_prompt | llm        │<br>│ Output: &quot;HIGH&quot;           │<br>└──────────┬───────────────┘<br>           │<br>           ▼<br>┌──────────────────────────┐<br>│ Chain 3: ACTION PLAN     │<br>│ action_prompt | llm      │<br>│ Output: &quot;Schedule MD     │<br>│  within 1 week...&quot;       │<br>└──────────────────────────┘</pre><p>Each chain is independent, testable, and composable.</p><h3>LCEL: The Modern LangChain Standard</h3><h4>What is LCEL?</h4><p><strong>LangChain Expression Language</strong> is the official way to build chains in 2024+.</p><p>Core concept: <strong>The pipe operator</strong> (|)</p><pre>chain = prompt | llm | parser</pre><p>Reads like English: <em>“prompt, then LLM, then parser”</em></p><h4>Basic Example</h4><pre>from langchain_groq import ChatGroq<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br># Initialize<br>llm = ChatGroq(<br>    model_name=&quot;llama-3.3-70b-versatile&quot;,<br>    temperature=0<br>)<br>parser = StrOutputParser()<br><br># Define prompt<br>prompt = PromptTemplate(<br>    input_variables=[&quot;question&quot;],<br>    template=&quot;Answer this question concisely: {question}&quot;<br>)<br><br># Build chain<br>chain = prompt | llm | parser<br><br># Use it<br>answer = chain.invoke({&quot;question&quot;: &quot;What is diabetes?&quot;})<br>print(answer)</pre><p><strong>That’s it.</strong> Three lines to create a working chain.</p><h3>Building the Healthcare Reasoning System</h3><h4>Step 1: Symptom &amp; Finding Extraction</h4><p><strong>Goal:</strong> Pull out medical information from free text.</p><pre>symptom_prompt = PromptTemplate(<br>    input_variables=[&quot;user_input&quot;, &quot;medical_context&quot;],<br>    template=&quot;&quot;&quot;<br>Extract symptoms and medical findings from patient message.<br><br>Patient message: {user_input}<br><br>Medical context: {medical_context}<br><br>Instructions:<br>- List symptoms (headache, fatigue, etc.)<br>- Extract lab values (HbA1c: 8.2, glucose: 180)<br>- Return comma-separated or &quot;none&quot;<br><br>Examples:<br>- &quot;I feel tired&quot; → &quot;fatigue&quot;<br>- &quot;My A1C is 8.2&quot; → &quot;HbA1c: 8.2&quot;<br>- &quot;Hello&quot; → &quot;none&quot;<br>&quot;&quot;&quot;<br>)<br><br>symptom_chain = symptom_prompt | llm | parser</pre><p><strong>Test it:</strong></p><pre>result = symptom_chain.invoke({<br>    &quot;user_input&quot;: &quot;I&#39;ve been dizzy and my blood sugar was 180&quot;,<br>    &quot;medical_context&quot;: &quot;Patient has diabetes type 2&quot;<br>})<br><br>print(result)<br># Output: &quot;dizziness, blood glucose: 180&quot;</pre><p><strong>Why this works:</strong></p><ul><li>Clear instructions</li><li>Examples for formatting</li><li>Context-aware (sees patient history)</li><li>Fallback behavior (“none”)</li></ul><h4>Step 2: Clinical Risk Assessment</h4><p><strong>Goal:</strong> Classify overall health risk level.</p><pre>risk_prompt = PromptTemplate(<br>    input_variables=[&quot;symptoms&quot;, &quot;medical_context&quot;, &quot;lab_interpretation&quot;],<br>    template=&quot;&quot;&quot;<br>Assess clinical risk level based on ALL available information.<br><br>Current findings: {symptoms}<br><br>Medical history: {medical_context}<br><br>Lab interpretation: {lab_interpretation}<br><br>Risk Classification Rules:<br>- HIGH: Emergency symptoms, critically abnormal labs, urgent care needed<br>- MODERATE: Concerning symptoms &gt;1 week, abnormal labs, chronic disease issues<br>- LOW: Mild symptoms, routine concerns, normal values<br><br>Return ONLY one word: LOW, MODERATE, or HIGH<br>&quot;&quot;&quot;<br>)<br><br>risk_chain = risk_prompt | llm | parser</pre><p><strong>Test it:</strong></p><pre>result = risk_chain.invoke({<br>    &quot;symptoms&quot;: &quot;dizziness, blood glucose: 180&quot;,<br>    &quot;medical_context&quot;: &quot;Diabetes type 2, takes metformin&quot;,<br>    &quot;lab_interpretation&quot;: &quot;Glucose 180 mg/dL: Elevated - needs management&quot;<br>})<br><br>print(result)<br># Output: &quot;MODERATE&quot;</pre><p><strong>Key features:</strong></p><ul><li>Uses clinical rules</li><li>Considers context</li><li>Multi-factor assessment</li><li>Constrained output (3 options only)</li></ul><h4>Step 3: Action Recommendation</h4><p><strong>Goal:</strong> Provide clear, safe, actionable guidance.</p><pre>action_prompt = PromptTemplate(<br>    input_variables=[&quot;risk_level&quot;, &quot;symptoms&quot;, &quot;medical_context&quot;],<br>    template=&quot;&quot;&quot;<br>Provide clear next steps for patient care.<br><br>Risk Level: {risk_level}<br>Symptoms/Findings: {symptoms}<br>Medical Context: {medical_context}<br><br>Guidelines:<br>- Be specific and actionable<br>- Include timeframes (within 24 hours, 3-5 days, etc.)<br>- Use simple language<br>- Max 3-4 sentences<br>- Safety first<br><br>Respond:<br>&quot;&quot;&quot;<br>)<br><br>action_chain = action_prompt | llm | parser</pre><p><strong>Test it:</strong></p><pre>result = action_chain.invoke({<br>    &quot;risk_level&quot;: &quot;MODERATE&quot;,<br>    &quot;symptoms&quot;: &quot;dizziness, blood glucose: 180&quot;,<br>    &quot;medical_context&quot;: &quot;Diabetes type 2, takes metformin&quot;<br>})<br><br>print(result)<br># Output: &quot;Your elevated blood sugar combined with dizziness <br>#          needs attention. Check your blood sugar levels twice <br>#          daily and schedule a doctor&#39;s appointment within 3-5 <br>#          days to review your diabetes management plan.&quot;</pre><h3>The Orchestrator: Putting It All Together</h3><h4>Manual Pipeline (Full Control)</h4><pre>def run_health_pipeline(user_input, user_id):<br>    &quot;&quot;&quot;<br>    Process patient input through 3-step clinical reasoning<br>    &quot;&quot;&quot;<br>    <br>    # Get patient&#39;s medical context (from memory/database)<br>    medical_context = get_medical_context(user_id)<br>    <br>    context_str = f&quot;&quot;&quot;<br>    Conditions: {&#39;, &#39;.join(medical_context[&#39;conditions&#39;])}<br>    Medications: {&#39;, &#39;.join(medical_context[&#39;medications&#39;])}<br>    Recent Labs: {medical_context[&#39;labs&#39;]}<br>    &quot;&quot;&quot;<br>    <br>    # STEP 1: Extract symptoms &amp; findings<br>    symptoms = symptom_chain.invoke({<br>        &quot;user_input&quot;: user_input,<br>        &quot;medical_context&quot;: context_str<br>    }).strip()<br>    <br>    # STEP 2: Interpret labs (if present)<br>    lab_interpretation = interpret_labs(user_input)<br>    <br>    # STEP 3: Assess risk<br>    risk_level = risk_chain.invoke({<br>        &quot;symptoms&quot;: symptoms,<br>        &quot;medical_context&quot;: context_str,<br>        &quot;lab_interpretation&quot;: lab_interpretation<br>    }).strip()<br>    <br>    # STEP 4: Generate recommendations<br>    recommendation = action_chain.invoke({<br>        &quot;risk_level&quot;: risk_level,<br>        &quot;symptoms&quot;: symptoms,<br>        &quot;medical_context&quot;: context_str<br>    }).strip()<br>    <br>    return {<br>        &quot;symptoms&quot;: symptoms,<br>        &quot;risk_level&quot;: risk_level,<br>        &quot;lab_interpretation&quot;: lab_interpretation,<br>        &quot;recommendation&quot;: recommendation<br>    }</pre><p><strong>Why manual control?</strong></p><ul><li>Can validate between steps</li><li>Easy error handling</li><li>Can log intermediate outputs</li><li>Flexible data flow</li></ul><h4>Domain Intelligence: Lab Interpretation</h4><p>Medical AI needs domain rules. Here’s how to ground the model:</p><pre>LAB_RANGES = {<br>    &quot;HbA1c&quot;: {<br>        &quot;normal&quot;: (0, 5.7, &quot;Normal - no diabetes&quot;),<br>        &quot;prediabetes&quot;: (5.7, 6.5, &quot;Prediabetes - monitor&quot;),<br>        &quot;controlled&quot;: (6.5, 7.0, &quot;Diabetes - target range&quot;),<br>        &quot;poor&quot;: (7.0, 8.0, &quot;Fair control&quot;),<br>        &quot;very_poor&quot;: (8.0, 100, &quot;Poor control - needs adjustment&quot;)<br>    },<br>    &quot;glucose&quot;: {<br>        &quot;low&quot;: (0, 70, &quot;Low - hypoglycemia risk&quot;),<br>        &quot;normal&quot;: (70, 100, &quot;Normal fasting glucose&quot;),<br>        &quot;elevated&quot;: (100, 126, &quot;Prediabetes range&quot;),<br>        &quot;high&quot;: (126, 300, &quot;Diabetes range&quot;)<br>    }<br>}<br><br>def interpret_lab_value(test_name, value):<br>    &quot;&quot;&quot;Interpret lab results with medical rules&quot;&quot;&quot;<br>    if test_name not in LAB_RANGES:<br>        return {&quot;interpretation&quot;: &quot;Unknown test&quot;, &quot;risk&quot;: &quot;MODERATE&quot;}<br>    <br>    ranges = LAB_RANGES[test_name]<br>    for status, (low, high, interpretation) in ranges.items():<br>        if low &lt;= value &lt; high:<br>            # Determine risk<br>            if &quot;poor&quot; in status or &quot;high&quot; in status:<br>                risk = &quot;HIGH&quot;<br>            elif &quot;elevated&quot; in status or &quot;prediabetes&quot; in status:<br>                risk = &quot;MODERATE&quot;<br>            else:<br>                risk = &quot;LOW&quot;<br>            <br>            return {<br>                &quot;test&quot;: test_name,<br>                &quot;value&quot;: value,<br>                &quot;interpretation&quot;: interpretation,<br>                &quot;risk&quot;: risk<br>            }<br>    <br>    return {&quot;interpretation&quot;: &quot;Out of range&quot;, &quot;risk&quot;: &quot;HIGH&quot;}</pre><p><strong>Usage:</strong></p><pre>result = interpret_lab_value(&quot;HbA1c&quot;, 8.2)<br>print(result)<br># {<br>#     &quot;test&quot;: &quot;HbA1c&quot;,<br>#     &quot;value&quot;: 8.2,<br>#     &quot;interpretation&quot;: &quot;Poor control - needs adjustment&quot;,<br>#     &quot;risk&quot;: &quot;HIGH&quot;<br># }</pre><p><strong>This grounds the LLM with medical facts.</strong></p><h3>Complete Working Example</h3><pre>from langchain_groq import ChatGroq<br>from langchain_core.prompts import PromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br># Initialize<br>llm = ChatGroq(model_name=&quot;llama-3.3-70b-versatile&quot;, temperature=0)<br>parser = StrOutputParser()<br><br># Build chains<br>symptom_prompt = PromptTemplate(<br>    input_variables=[&quot;user_input&quot;],<br>    template=&quot;Extract symptoms from: {user_input}\nReturn comma-separated or &#39;none&#39;&quot;<br>)<br>symptom_chain = symptom_prompt | llm | parser<br><br>risk_prompt = PromptTemplate(<br>    input_variables=[&quot;symptoms&quot;],<br>    template=&quot;Risk level for: {symptoms}\nReturn: LOW, MODERATE, or HIGH&quot;<br>)<br>risk_chain = risk_prompt | llm | parser<br><br>action_prompt = PromptTemplate(<br>    input_variables=[&quot;risk_level&quot;, &quot;symptoms&quot;],<br>    template=&quot;Next steps for {risk_level} risk with {symptoms}?\nMax 3 sentences.&quot;<br>)<br>action_chain = action_prompt | llm | parser<br><br># Pipeline<br>def analyze_patient(message):<br>    symptoms = symptom_chain.invoke({&quot;user_input&quot;: message}).strip()<br>    risk = risk_chain.invoke({&quot;symptoms&quot;: symptoms}).strip()<br>    action = action_chain.invoke({<br>        &quot;risk_level&quot;: risk,<br>        &quot;symptoms&quot;: symptoms<br>    }).strip()<br>    <br>    return {<br>        &quot;symptoms&quot;: symptoms,<br>        &quot;risk&quot;: risk,<br>        &quot;action&quot;: action<br>    }<br><br># Test<br>result = analyze_patient(<br>    &quot;I&#39;ve had severe chest pain for 2 hours and feel short of breath&quot;<br>)<br><br>print(result)<br># {<br>#     &quot;symptoms&quot;: &quot;severe chest pain, shortness of breath&quot;,<br>#     &quot;risk&quot;: &quot;HIGH&quot;,<br>#     &quot;action&quot;: &quot;Seek immediate emergency care. Call 911 now. <br>#                This could be a cardiac emergency requiring <br>#                urgent evaluation.&quot;<br># }</pre><h3>Real-World Test: Complete Conversation</h3><h4>Turn 1: Symptoms</h4><p><strong>Input:</strong> “I’ve been tired for 2 weeks and feel dizzy”</p><p><strong>Processing:</strong></p><pre>[Step 1] Symptoms: fatigue, dizziness<br>[Step 2] Risk: MODERATE (2+ weeks duration)<br>[Step 3] Action: Schedule doctor within 3-5 days, <br>                 stay hydrated, monitor symptoms</pre><p><strong>Response:</strong></p><blockquote><em>“You’ve been experiencing fatigue and dizziness for 2 weeks. This warrants medical evaluation. Schedule an appointment with your doctor within 3–5 days. In the meantime, stay well hydrated and keep track of when symptoms are worst.”</em></blockquote><h4>Turn 2: Lab Results</h4><p><strong>Input:</strong> “Got my HbA1c — it’s 8.2”</p><p><strong>Processing:</strong></p><pre>[Step 1] Symptoms: HbA1c: 8.2<br>[Lab Interpretation] HbA1c 8.2: Poor control - needs adjustment (Risk: HIGH)<br>[Step 2] Risk: HIGH (poor diabetes control + previous fatigue)<br>[Step 3] Action: Schedule appointment within 1 week, <br>                 monitor glucose, review medications</pre><p><strong>Response:</strong></p><blockquote><em>“Your HbA1c of 8.2 indicates your diabetes needs better control. Combined with your recent fatigue and dizziness, this requires prompt attention. Schedule a doctor’s appointment within the next week to discuss adjusting your diabetes management plan.”</em></blockquote><p><strong>The chain connected current labs with previous symptoms — that’s intelligent reasoning.</strong></p><h3>Why This Architecture Works</h3><h4>Explainable AI</h4><p>Every decision has intermediate steps:</p><pre>Symptoms → Risk → Action</pre><p>You can see exactly where reasoning might be wrong.</p><h4>Safety First</h4><ul><li>Medical rules ground the model</li><li>Risk classification prevents underestimation</li><li>Actions always include timeframes</li><li>No diagnostic claims (triage only)</li></ul><h4>Modular &amp; Testable</h4><pre># Test each chain independently<br>assert symptom_chain.invoke(test_input) == expected_symptoms<br>assert risk_chain.invoke(test_data) in [&quot;LOW&quot;, &quot;MODERATE&quot;, &quot;HIGH&quot;]</pre><h4>Context Aware</h4><p>Medical context flows through every step:</p><ul><li>Previous conditions</li><li>Current medications</li><li>Past lab results</li><li>Recent symptoms</li></ul><h3>Full Source Code</h3><p>The complete working implementation — including:</p><ul><li>LCEL multi-step chains</li><li>Lab interpretation logic</li><li>Memory buffer</li><li>LangGraph InMemoryStore</li><li>Context-aware orchestration</li></ul><p>is available on GitHub:</p><p>👉 <strong>GitHub Repository:<br></strong><a href="https://github.com/sajosam/langchain.git"><strong>https://github.com/sajosam/langchain.git</strong></a></p><h3>Final Thought</h3><p><strong>Single prompts ask LLMs to do everything.</strong></p><p><strong>Chains let LLMs think step by step.</strong></p><p>In healthcare — and any high-stakes domain — structured reasoning isn’t optional. It’s how we move from impressive demos to trustworthy systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=580c5b686465" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Intelligent AI Memory Systems: Combining Conversation Buffers with Structured Storage in…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@sajo02/building-intelligent-ai-memory-systems-combining-conversation-buffers-with-structured-storage-in-065c083b061c?source=rss-f0205b223fca------2"><img src="https://cdn-images-1.medium.com/max/1536/1*WidAvMxErbHMwJggjt7oig.png" width="1536"></a></p><p class="medium-feed-snippet">How I Built a Hybrid AI Memory System with LangChain and LangGraph. Conversation Memory vs InMemoryStore: A Practical Guide with Groq</p><p class="medium-feed-link"><a href="https://medium.com/@sajo02/building-intelligent-ai-memory-systems-combining-conversation-buffers-with-structured-storage-in-065c083b061c?source=rss-f0205b223fca------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sajo02/building-intelligent-ai-memory-systems-combining-conversation-buffers-with-structured-storage-in-065c083b061c?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/065c083b061c</guid>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 18:58:42 GMT</pubDate>
            <atom:updated>2026-01-19T18:58:42.316Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Stop Writing If-Else Chains! This Trick Changed My Code Forever]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://python.plainenglish.io/stop-writing-if-else-chains-this-trick-changed-my-code-forever-8ced01702aea?source=rss-f0205b223fca------2"><img src="https://cdn-images-1.medium.com/max/1536/1*71t89ka43LaaNwH3Do3hQA.png" width="1536"></a></p><p class="medium-feed-snippet">A tale of three approaches, two languages, and some surprising results</p><p class="medium-feed-link"><a href="https://python.plainenglish.io/stop-writing-if-else-chains-this-trick-changed-my-code-forever-8ced01702aea?source=rss-f0205b223fca------2">Continue reading on Python in Plain English »</a></p></div>]]></description>
            <link>https://python.plainenglish.io/stop-writing-if-else-chains-this-trick-changed-my-code-forever-8ced01702aea?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ced01702aea</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 08:51:58 GMT</pubDate>
            <atom:updated>2025-08-24T05:26:02.224Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Getting Started with gRPC in Go: Golang Tutorial for Fast and Reliable APIs]]></title>
            <link>https://medium.com/@sajo02/getting-started-with-grpc-in-go-golang-tutorial-for-fast-and-reliable-apis-e357290e5872?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e357290e5872</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[protobuf]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[grpc]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 10:52:23 GMT</pubDate>
            <atom:updated>2025-07-23T10:52:23.625Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine a fintech company that handles high-frequency trading where ultra-fast, real-time data exchange between microservices is critical. The traditional REST API approach is introducing delays, affecting both performance and reliability. To meet real-time demands, the team explores switching to gRPC for better efficiency and scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmsF8sx2Q7NUgWA1Q5Xc1g.png" /><figcaption>gRPC vs REST API: The Power of gRPC Over REST APIs</figcaption></figure><h3>What is gRPC?</h3><p><strong>gRPC</strong> (gRPC Remote Procedure Call) is a high-performance, open-source universal RPC framework developed by Google.</p><ul><li>Uses <strong>HTTP/2</strong> for transport</li><li>Communicates using <strong>Protocol Buffers (Protobuf)</strong> (compact binary format)</li><li>Offers features like:</li><li>Bi-directional streaming</li><li>Deadlines/timeouts</li><li>Strong typing</li><li>Code generation across languages (Go, Python, Java, etc.)</li></ul><h3>Why Choose gRPC in Go?</h3><p>Go is a <strong>compiled, strongly typed language</strong> built for performance — making it a perfect match for gRPC. Benefits include:</p><ul><li>Fast request-response cycle using compiled Protobuf</li><li>Native support for concurrency via goroutines</li><li>Minimal memory footprint</li><li>Cross-platform, cross-language support</li><li>Auto-generated Go client and server code</li></ul><p>Before writing gRPC services in Go, you need the following tools installed:</p><h3>Prerequisites</h3><h4>1. Install protoc (Protocol Buffer Compiler)</h4><ul><li>Download the latest release from the <a href="https://github.com/protocolbuffers/protobuf/releases">Protobuf GitHub Releases</a>.</li><li>Extract and add the bin folder (which contains protoc) to your system PATH.</li></ul><h4>2. Install Go Plugins for gRPC</h4><p>Run the following commands:</p><pre>go install google.golang.org/protobuf/cmd/protoc-gen-go@latest<br>go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest</pre><p>Make sure $GOPATH/bin is in your system PATH so protoc can find the plugins.</p><h4>Verify Installation</h4><pre>protoc --version<br>protoc-gen-go --version<br>protoc-gen-go-grpc --version</pre><h3>Hands-On: Build a gRPC Simple User Management System in Go</h3><p>Let’s build a simple <strong>gRPC-based User Management system</strong> in Go with 3 main operations:</p><ul><li>Create a user</li><li>Get user by ID</li><li>List all users</li></ul><p>We’ll define the API with Protocol Buffers, implement the gRPC server in Go, and interact with it using a client.</p><h4>Project Structure</h4><pre>grpc-demo/<br>├── go.mod<br>├── proto/<br>│   └── user.proto<br>├── server/<br>│   └── server.go<br>├── client/<br>│   └── client.go</pre><h4>Step 1: Define the Protobuf API</h4><p><strong>File:</strong> proto/user.proto</p><pre>syntax = &quot;proto3&quot;;<br><br>package user;<br><br>option go_package = &quot;proto/;user&quot;;<br><br>service UserService {<br>  rpc CreateUser (CreateUserRequest) returns (UserResponse);<br>  rpc GetUser (GetUserRequest) returns (UserResponse);<br>  rpc ListUsers (Empty) returns (UserList);<br>}<br><br>message User {<br>  string id = 1;<br>  string name = 2;<br>  string email = 3;<br>}<br><br>message CreateUserRequest {<br>  string name = 1;<br>  string email = 2;<br>}<br><br>message GetUserRequest {<br>  string id = 1;<br>}<br><br>message UserResponse {<br>  User user = 1;<br>}<br><br>message UserList {<br>  repeated User users = 1;<br>}<br><br>message Empty {}</pre><p>Run the following command from the <strong>project root</strong> (grpc-demo/):</p><pre>protoc --go_out=. --go-grpc_out=. proto/user.proto</pre><p>This generates:</p><ul><li>proto/user.pb.go</li><li>proto/user_grpc.pb.go</li></ul><h4>Step 3: gRPC Server Implementation</h4><p><strong>File:</strong> server/server.go</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;net&quot;<br><br> pb &quot;github.com/localgrpc/proto&quot; // Import the generated protobuf package<br><br> &quot;github.com/google/uuid&quot;         // Used to generate unique user IDs<br> &quot;google.golang.org/grpc&quot;         // gRPC library<br>)<br><br>// server struct implements the gRPC UserServiceServer interface<br>type server struct {<br> pb.UnimplementedUserServiceServer // Required to implement gRPC server<br> users map[string]*pb.User         // In-memory user storage<br>}<br><br>// CreateUser creates a new user with a generated UUID<br>func (s *server) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.UserResponse, error) {<br> id := uuid.New().String() // Generate unique ID<br><br> user := &amp;pb.User{<br>  Id:    id,<br>  Name:  req.GetName(),<br>  Email: req.GetEmail(),<br> }<br><br> s.users[id] = user // Save to in-memory map<br><br> return &amp;pb.UserResponse{User: user}, nil<br>}<br><br>// GetUser fetches a user by ID<br>func (s *server) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.UserResponse, error) {<br> user, exists := s.users[req.GetId()]<br> if !exists {<br>  return nil, fmt.Errorf(&quot;user not found&quot;)<br> }<br> return &amp;pb.UserResponse{User: user}, nil<br>}<br><br>// ListUsers returns all users in the map<br>func (s *server) ListUsers(ctx context.Context, _ *pb.Empty) (*pb.UserList, error) {<br> var all []*pb.User<br> for _, u := range s.users {<br>  all = append(all, u)<br> }<br> return &amp;pb.UserList{Users: all}, nil<br>}<br><br>func main() {<br> // Listen on TCP port 50051<br> lis, err := net.Listen(&quot;tcp&quot;, &quot;:50051&quot;)<br> if err != nil {<br>  log.Fatal(&quot;Failed to listen:&quot;, err)<br> }<br><br> // Create new gRPC server instance<br> s := grpc.NewServer()<br><br> // Register our service implementation with the server<br> pb.RegisterUserServiceServer(s, &amp;server{users: make(map[string]*pb.User)})<br><br> log.Println(&quot;Server running at :50051&quot;)<br><br> // Start serving<br> if err := s.Serve(lis); err != nil {<br>  log.Fatal(err)<br> }<br>}</pre><h4>Step 4: gRPC Client Implementation</h4><p><strong>File:</strong> client/client.go</p><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br><br> pb &quot;github.com/localgrpc/proto&quot;     // Import the generated protobuf package<br> &quot;google.golang.org/grpc&quot;           // gRPC client library<br>)<br><br>func main() {<br> // Connect to the gRPC server on localhost:50051<br> conn, err := grpc.Dial(&quot;:50051&quot;, grpc.WithInsecure())<br> if err != nil {<br>  log.Fatal(&quot;Failed to connect:&quot;, err)<br> }<br> defer conn.Close()<br><br> // Create a new UserService client<br> c := pb.NewUserServiceClient(conn)<br><br> // Set a timeout context for requests<br> ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)<br> defer cancel()<br><br> // Create a new user<br> createResp, err := c.CreateUser(ctx, &amp;pb.CreateUserRequest{<br>  Name:  &quot;Alice&quot;,<br>  Email: &quot;alice@example.com&quot;,<br> })<br> if err != nil {<br>  log.Fatal(&quot;CreateUser failed:&quot;, err)<br> }<br> log.Println(&quot;✅ User created:&quot;, createResp.User)<br><br> // Get the user by ID<br> getResp, err := c.GetUser(ctx, &amp;pb.GetUserRequest{<br>  Id: createResp.User.Id,<br> })<br> if err != nil {<br>  log.Fatal(&quot;GetUser failed:&quot;, err)<br> }<br> log.Println(&quot;📥 User fetched:&quot;, getResp.User)<br><br> // List all users<br> listResp, err := c.ListUsers(ctx, &amp;pb.Empty{})<br> if err != nil {<br>  log.Fatal(&quot;ListUsers failed:&quot;, err)<br> }<br> log.Println(&quot;📄 Listing users:&quot;)<br> for _, u := range listResp.Users {<br>  log.Println(&quot;🧑 User:&quot;, u)<br> }<br>}</pre><h3>Is gRPC Right for Your Go Project?</h3><p>gRPC is a good choice for your Go project if you want fast and efficient communication between different parts of your system. It works well when:</p><ul><li>Your app needs to send or receive data quickly.</li><li>You want to save bandwidth by sending smaller, faster messages.</li><li>You need strong type checking and auto-generated code for fewer mistakes.</li><li>You use microservices or need different programming languages to work together.</li></ul><p>But if your needs are basic — just simple read and write operations — or if you want something easy to use in all browsers, REST might still be better.</p><p><strong>In short:<br></strong>Pick gRPC for modern, high-speed Go projects. Stick with REST for simple apps or when you need maximum compatibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e357290e5872" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitHub Actions to AWS ECS: Build, Push, and Deploy Docker Images Easily]]></title>
            <link>https://medium.com/@sajo02/github-actions-to-aws-ecs-build-push-and-deploy-docker-images-easily-7d4e8ab3efb6?source=rss-f0205b223fca------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d4e8ab3efb6</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[sajosam]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 10:17:50 GMT</pubDate>
            <atom:updated>2025-06-27T10:17:50.689Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re building a microservice that needs to:</p><ul><li>Build and containerize using Docker</li><li>Push images to Amazon ECR</li><li>Deploy automatically to AWS ECS</li><li>Use CalVer for image tagging</li><li>Trigger deployment on main or dev pushes</li><li>Avoid any manual deployment steps</li></ul><p>This blog will walk you through <strong>exactly how to do that</strong>, using <strong>GitHub Actions</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0XS7HN102BSPDDS5Khk0A.png" /></figure><p>Deploying to AWS ECS can be complex without automation.<br> With GitHub Actions, you can:</p><ul><li>Auto-build and push Docker images</li><li>Update ECS task definitions and services</li><li>Enable fully automated, versioned deployments with zero manual work</li></ul><p>Let’s break this down step-by-step.</p><h3>Project Structure Overview</h3><p>You’ll need the following:</p><ul><li>A Dockerized app</li><li>AWS ECS setup with:<br>- A Cluster (e-Kart)<br>- A Service (e-Kart-svc)<br>- A Task Definition Family (e-Kart)</li><li>GitHub Repository with:</li><li><strong>Secrets</strong>: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY</li><li><strong>Variables</strong>: AWS_REGISTRY_URL, REPOSITORY_NAME</li></ul><h3>GitHub Actions Workflow Explained</h3><p>Here’s the workflow you’ll add in .github/workflows/release.yml:</p><pre>name: Release Docker Image to ECR<br><br>on:<br>  push:<br>    branches:<br>      - main<br>      - dev</pre><p>This listens for any push on the main or dev branches.</p><h3>Environment Setup</h3><pre>env:<br>  AWS_REGION: ap-southeast-2<br>  ECS_CLUSTER: e-Kart<br>  ECS_SERVICE: e-Kart-svc<br>  CONTAINER_NAME: backend<br>  TASK_DEFINITION_FAMILY: e-Kart<br>  AWS_REGISTRY_URL: &quot;${{ vars.AWS_REGISTRY_URL }}&quot;<br>  REPOSITORY_NAME: &quot;${{ vars.REPOSITORY_NAME }}&quot;</pre><h3>Complete CI/CD Workflow Steps</h3><h4>✅ Step 1: Checkout Code</h4><pre>- name: Checkout code<br>  uses: actions/checkout@v3</pre><p>Pulls your latest code into the runner.</p><h4>🔐 Step 2: Configure AWS Credentials</h4><pre># Step 2: Configure AWS credentials<br>- name: Configure AWS credentials<br>  uses: aws-actions/configure-aws-credentials@v2<br>  with:<br>    aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}<br>    aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>    aws-region: ${{ env.AWS_REGION }}</pre><h4>🏷️ Step 3: Set CalVer Tag</h4><pre># Step 3: Set CalVer tag<br>- name: Set CalVer tag<br>  id: set-tag<br>  run: echo &quot;TAG=$(date +&#39;%Y.%m.%d-%H%M%S&#39;)&quot; &gt;&gt; $GITHUB_ENV</pre><p>This generates a version tag like 2025.06.27-130541.</p><h4>📦 Step 4: Docker Build and Push to ECR</h4><pre># Step 4.1: Login to Amazon ECR<br>- name: Login to Amazon ECR<br>  run: |<br>    aws ecr get-login-password --region $AWS_REGION \<br>    | docker login --username AWS --password-stdin ${{ env.AWS_REGISTRY_URL }}<br><br># Step 4.2: Build Docker image and tag it<br>- name: Build Docker image and tag it<br>  run: |<br>    echo &quot;Building Docker image with tag: $TAG&quot;<br>    docker build -t &quot;${{ env.REPOSITORY_NAME }}&quot; .<br>    docker tag &quot;${{ env.REPOSITORY_NAME }}&quot; &quot;${{ env.AWS_REGISTRY_URL }}/${{ env.REPOSITORY_NAME }}:$TAG&quot;<br><br># Step 4.3: Push Docker image to Amazon ECR<br>- name: Push Docker image to Amazon ECR<br>  run: |<br>    docker push &quot;${{ env.AWS_REGISTRY_URL }}/${{ env.REPOSITORY_NAME }}:$TAG&quot;</pre><p>These steps:</p><ul><li>Authenticate to ECR</li><li>Build Docker image</li><li>Tag and push to ECR with CalVer version</li></ul><h4>📄 Step 5: Update Task Definition</h4><pre># Step 5.1: Download current ECS task definition<br>- name: Download current task definition<br>  run: |<br>    aws ecs describe-task-definition \<br>      --task-definition ${{ env.TASK_DEFINITION_FAMILY }} \<br>      --query taskDefinition &gt; task-definition.json<br><br># Step 5.2: Clean the task definition by removing metadata<br>- name: Clean task definition<br>  run: |<br>    jq &#39;del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .deregisteredAt, .registeredBy, .enableFaultInjection)&#39; task-definition.json &gt; cleaned-task-definition.json<br>    mv cleaned-task-definition.json task-definition.json</pre><p>Removes metadata so it can be reused for the new deployment.</p><h4>🧩 Step 6: Render New Task Definition</h4><pre># Step 6: Render updated ECS task definition with new Docker image<br>- name: Render updated task definition<br>  id: render-task-def<br>  uses: aws-actions/amazon-ecs-render-task-definition@v1<br>  with:<br>    task-definition: task-definition.json<br>    container-name: ${{ env.CONTAINER_NAME }}<br>    image: ${{ env.AWS_REGISTRY_URL }}/${{ env.REPOSITORY_NAME }}:${{ env.TAG }}<br>    environment-variables: |<br>      AWS_ACCESS_KEY_ID=${{ secrets.AWS_ACCESS_KEY_ID }}<br>      AWS_SECRET_ACCESS_KEY=${{ secrets.AWS_SECRET_ACCESS_KEY }}<br>      AWS_REGION=${{ env.AWS_REGION }}</pre><p>This plugs the new image into the existing task definition, ready for ECS.</p><h4>🚀 Step 7: Deploy to ECS</h4><pre># Step 7: Deploy the new task definition to the ECS service<br>- name: Deploy to ECS service<br>  uses: aws-actions/amazon-ecs-deploy-task-definition@v2<br>  with:<br>    task-definition: ${{ steps.render-task-def.outputs.task-definition }}<br>    service: ${{ env.ECS_SERVICE }}<br>    cluster: ${{ env.ECS_CLUSTER }}<br>    wait-for-service-stability: true</pre><p>Finally, ECS:</p><ul><li>Registers a new revision</li><li>Updates the service</li><li>Ensures it’s stable</li></ul><h3>Managing Environment Variables and Secrets</h3><p>Proper environment and secret management is essential for secure and scalable container deployments.</p><h4>Environment Variables</h4><p>Use the environment-variables input in the ECS task definition update step to inject non-sensitive config values. This enables dynamic behavior based on environments (e.g., dev, staging, prod) without modifying code.</p><h4>Secrets Management</h4><p>Sensitive data like AWS credentials, DB passwords, or API keys should be:</p><ul><li>Stored securely in <strong>GitHub Secrets</strong></li><li>Or injected at runtime via <strong>AWS Secrets Manager</strong> / <strong>Parameter Store</strong> with ECS integration</li></ul><h4>Best Practices</h4><ul><li>Avoid hardcoding secrets in code or workflows</li><li>Use <strong>IAM roles</strong> with least privilege access</li><li>Rotate secrets regularly</li><li>Keep task definitions version-controlled</li></ul><h3>Key Takeaways</h3><p>By combining <strong>GitHub Actions</strong> with <strong>AWS ECS</strong>, you achieve a robust, fully automated container deployment pipeline. It triggers on every code push, streamlines the release cycle, and ensures production stability.</p><p>Here’s a quick recap:</p><ul><li>Prepare AWS resources: <strong>ECR, ECS cluster, service, IAM credentials</strong></li><li>Secure secrets via <strong>GitHub Secrets</strong> or <strong>AWS Secrets Manager</strong></li><li>Automate build, tag, and push of Docker images using <strong>GitHub Actions</strong></li><li>Inject env vars dynamically to configure containers at runtime</li><li>Use ECS’s update and rollback features to monitor deployment health</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d4e8ab3efb6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>