<?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 daudi mungah on Medium]]></title>
        <description><![CDATA[Stories by daudi mungah on Medium]]></description>
        <link>https://medium.com/@mungahdaudi?source=rss-746b30b51180------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0rg6ZswG4mjtAzGO.jpg</url>
            <title>Stories by daudi mungah on Medium</title>
            <link>https://medium.com/@mungahdaudi?source=rss-746b30b51180------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:00:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mungahdaudi/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[Beyond the Router: A Decentralized Architecture for Multi-Agent Activation]]></title>
            <link>https://medium.com/@mungahdaudi/beyond-the-router-a-decentralized-architecture-for-multi-agent-activation-a691a78d46d0?source=rss-746b30b51180------2</link>
            <guid isPermaLink="false">https://medium.com/p/a691a78d46d0</guid>
            <dc:creator><![CDATA[daudi mungah]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 07:41:21 GMT</pubDate>
            <atom:updated>2026-08-14T07:41:21.011Z</atom:updated>
            <content:encoded><![CDATA[<h4>How capability-scoped competition, layered context, and a little chaos theory replace a central orchestrator</h4><p>Most multi-agent systems are built around a router. A fact or event arrives, and something upstream reads it, understands what it means, and decides which agents should care. It’s an intuitive design, and it’s also a trap. The router has to understand every agent’s job well enough to route correctly, which means it becomes the ceiling on the system’s intelligence rather than a neutral pipe. Every new agent added to the system is a new rule the router has to learn. And because it sits in the middle of every decision, it’s a single point of both failure and semantic authority in a system that’s supposed to be distributed.</p><p>The alternative starts from a simple reversal: instead of something else deciding whether an agent should care about a fact, the agent decides for itself.</p><h3>Local relevance instead of central routing</h3><p>Give each agent its own context, its own relevance function, and its own activation threshold. When a fact appears, it doesn’t get routed — it gets broadcast to whichever agents are reachable, and each one independently asks a single question: <em>is this sufficiently relevant to me to justify waking up?</em> An agent that scores a fact below its threshold goes back to sleep having done almost no work. One that scores above it activates, does its job, and — often — produces a new fact of its own that flows downstream to the next layer of agents.</p><p>Agent → Router → Agents becomes Fact → [independent local scoring] → Activation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*RsItIcAK6lf93PEhiTfc6g.png" /></figure><p>This is a genuine architectural shift, not a cosmetic one. The system no longer has a single component that needs to understand everything; it has many components that each need to understand only themselves. But it immediately runs into the problem the router was quietly solving all along.</p><h3>The problem is not multiple agents — it’s redundant ones</h3><p>Remove the router and the obvious failure mode shows up fast: several agents independently decide a fact is relevant, and they all activate. The first instinct is to fix this the way a router would — give each fact a global activation budget, let agents submit competing relevance scores, and let only the highest scorer fire. Everyone else stays asleep.</p><p>That works, right up until it doesn’t. Consider an API change reaching both a security agent and a testing agent. Both score it highly, and both <em>should</em> activate — they’re doing fundamentally different work with the same input. A global budget that only lets the winner through throws away exactly the parallelism that made decentralization worth doing in the first place.</p><p>The real problem was never “too many agents activate.” It’s “too many agents doing the same kind of work activate for the same thing.” That’s a narrower, more useful claim, and it changes where the arbitration boundary needs to sit. Competition shouldn’t be scoped to the fact — it should be scoped to a capability class. Agents doing the same category of work (two agents that both do risk triage, say) compete, and only one wins. Agents in different capability classes never compete at all, no matter how many of them fire on the same fact.</p><h3>Context is the quiet dependency</h3><p>Every agent’s relevance score is only as good as the context it’s scoring against, and in a decentralized system nothing keeps that context automatically fresh. The fix is to stop treating context as one thing. It’s really at least three things with different lifespans: working context (the last few facts an agent has seen — stays fully local, updates constantly), episodic context (an agent’s own history of past activations, letting it recalibrate from experience without central retraining), and a slower semantic layer (stable world assumptions plus awareness of its own capability class) — which is exactly the layer that goes stale.</p><p>That staleness matters more than it sounds like it should, because a missed activation caused by stale context is invisible — nobody notices a fact that should have woken an agent up but didn’t. So when an agent’s confidence in its own context is low, that should lower its bar to engage, not raise it.</p><p>There’s also a nearly free channel for keeping the slow layer in sync: when an agent activates and emits a new fact downstream, it can carry a compressed context update along with it, propagating exactly along the edges that already mattered.</p><h3>Borrowing stability results from chaos theory</h3><p>A network of local agents with thresholds that fire and propagate to neighbors is structurally the same object studied as a sandpile model in self-organized criticality: cells absorb input, and when one exceeds its threshold it topples, distributing to neighbors, who may topple in turn. Such systems evolve toward a critical state on their own, where cascade sizes naturally follow a power law — most stay tiny, occasionally one sweeps through. A cascade isn’t a defect to engineer away; it’s the expected signature of the architecture working. The useful move is to watch the <em>distribution</em> of cascade sizes for an anomalous bump, not to treat any cascade as a bug.</p><p>That gives a tunable number: the branching factor of a fact (average downstream activations per activation), held near 1 — the edge of chaos, the narrow band between a frozen network (thresholds too high, nothing propagates) and a chaotic one (thresholds too low, indistinguishable from noise).</p><p>Two more results shape the mechanics. Scores hovering right at a threshold are a knife’s edge where noise decides everything, fixed the way a Schmitt trigger fixes it in circuit design — two thresholds instead of one (hysteresis). And because agents can influence each other’s firing, the lateral inhibition enforcing capability-scoped competition is formally negative coupling between oscillators — tuned too weak, same-class agents synchronize into pile-ons; too strong, and independent agents wrongly suppress each other.</p><h3>What’s still open</h3><p>None of this has been built yet. How topology and reachability get defined, how capability classes get declared, whether thresholds should be hand-tuned or learned online, and how you’d actually instrument a running system to watch its branching factor and cascade-size distribution are all unresolved on paper. What the reframing buys, even before any of that exists, is a cleaner picture of where the hard problems actually live — not in one central component that has to understand everything, but in a handful of local, tunable parameters that turn out to already have been studied, under different names, in fields that had nothing to do with software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a691a78d46d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Secure Multi-Tenant RAG: Implementing Role-Based Access Control (RBAC) with Elasticsearch…]]></title>
            <link>https://medium.com/@mungahdaudi/building-secure-multi-tenant-rag-implementing-role-based-access-control-rbac-with-elasticsearch-364e03c6ce9e?source=rss-746b30b51180------2</link>
            <guid isPermaLink="false">https://medium.com/p/364e03c6ce9e</guid>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[offline-chatbot]]></category>
            <dc:creator><![CDATA[daudi mungah]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 13:45:21 GMT</pubDate>
            <atom:updated>2026-01-10T13:45:21.838Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Secure Multi-Tenant RAG: Implementing Role-Based Access Control (RBAC) with Elasticsearch and Ollama</strong></h3><p>Retrieval-Augmented Generation (RAG) is transforming how we build chatbots, allowing LLMs to answer questions using private data. But as soon as you move from a solo dev project to a production system, you hit a massive wall: <strong>Security</strong>.</p><p>In an enterprise environment, not every employee should see every document. You cannot simply dump all your PDFs into a vector store and let the LLM retrieve whatever looks similar. You need <strong>Multi-Tenant Isolation</strong> and <strong>Role-Based Access Control (RBAC)</strong>.</p><p>In this article, I’ll walk you through how I implemented a secure, local RAG pipeline using <strong>Elasticsearch</strong>, <strong>Ollama (Gemma 3)</strong>, and <strong>Python</strong></p><p><strong>The Problem: The “Chatty” LLM</strong></p><p>Imagine a scenario where a user asks: <em>”What are the financial results?”</em></p><p>In a naive RAG system:</p><p>1. The system embeds the question.</p><p>2. It performs a vector search across the <em>entire “</em>database”.</p><p>3. It retrieves the “Q3 Confidential Financial Report” because it has high semantic similarity but has our secret information .</p><p>4. It feeds this report to the LLM.</p><p>5. The LLM summarizes the confidential secrets to an intern . 😱</p><p>We need a way to ensure the LLM “<em>never sees”</em> data the user isn’t allowed to access.</p><p><strong>The Solution: Pre-Retrieval Filtering</strong></p><p>The most robust way to secure RAG is <strong>Pre-Retrieval Filtering</strong>. We enforce security at the fetching level i.e before the data ever reaches the application logic or the LLM.</p><p><strong>The Tech Stack</strong></p><p><strong>Elasticsearch (v8.x)</strong>: For vector storage and filtering.</p><p><strong>Ollama</strong>: Running nomic-embed-text for embeddings and gemma3 for inference.</p><p><strong>Python</strong>: To glue it all together.</p><p><strong>Step 1: Data Modeling with Security Metadata</strong></p><p>The key to RBAC is tagging your data. When we index a document, we don’t just store the text and the vector; we store the <strong>access rules</strong>.</p><p>Here is how our Elasticsearch mapping looks conceptually:</p><pre>{<br>&quot;text&quot;: &quot;Confidential Project Alpha Results…&quot;,<br>&quot;tenant_id&quot;: &quot;tenant-A&quot;,<br>&quot;allowed_roles&quot;: [&quot;finance&quot;, &quot;admin&quot;],<br>&quot;embedding&quot;: [0.12, -0.45, …]<br>}</pre><p>In our Python script (`demo.py`), we enforce this structure when indexing:</p><pre>documents = [<br>{<br>&quot;id&quot;: &quot;doc1&quot;,<br>&quot;text&quot;: &quot;The project &#39;Alpha&#39; confidential financial results… (Finance Only)&quot;,<br>&quot;tenant_id&quot;: &quot;tenant-A&quot;,<br>&quot;allowed_roles&quot;: [&quot;finance&quot;, &quot;admin&quot;]<br>},<br>{<br>&quot;id&quot;: &quot;doc3&quot;,<br>&quot;text&quot;: &quot;Tenant B&#39;s secret strategy… (Tenant B Only)&quot;,<br>&quot;tenant_id&quot;: &quot;tenant-B&quot;,<br>&quot;allowed_roles&quot;: [&quot;admin&quot;]<br>}<br>]</pre><p><strong>Step 2: The Secure Retrieval Function</strong></p><p>This is where the magic happens. When a user asks a question, we pass their <strong>User Context </strong>(their ID, Tenant ID, and Roles) along with the query.</p><p>We construct an Elasticsearch query that uses a `filter` clause inside the `knn` search. This tells Elasticsearch: <em>”Find the most similar vectors, BUT only look at documents that match this tenant and these roles.”</em></p><p>Here is the core logical function from `secure_search.py`:</p><pre>def secure_retrieve(query_text: str, user_context: Dict[str, Any]) -&gt; str:<br><br># Generate Query Embedding via Ollama<br>query_vector = get_ollama_embedding(query_text)<br><br># Extract User Context<br>tenant_id = user_context.get(&quot;tenantId&quot;)<br>user_roles = user_context.get(&quot;roles&quot;, [])<br><br># Construct Secure Query<br>es_query = {<br>&quot;knn&quot;: {<br>&quot;field&quot;: &quot;embedding&quot;,<br>&quot;query_vector&quot;: query_vector,<br>&quot;k&quot;: 5,<br>&quot;filter&quot;: [<br><br># Security Boundary 1: Tenant Isolation<br>{ &quot;term&quot;: { &quot;tenant_id&quot;: tenant_id } },<br># Security Boundary 2: RBAC<br># Document must have at least one of the user&#39;s roles<br>{ &quot;terms&quot;: { &quot;allowed_roles&quot;: user_roles } }<br>]<br>},<br>&quot;_source&quot;: [&quot;text&quot;]<br>}<br> # Execute Search<br>response = es_client.search(index=&quot;pdf-rag&quot;, body=es_query)<br><br>return format_results(response)</pre><p>By using the filter clause inside knn, we ensure that <strong><em>k</em></strong> results are returned from the pool of accessible documents</p><p><strong>Step 3: Proving it Works (The Scenarios)</strong></p><p>I wrote a `demo.py` script to test this implementation against real-world scenarios.</p><p><strong>query</strong>: What are the financial results?</p><p><strong>Scenario A: </strong>The <strong>Authorized</strong> Finance Manager</p><p><strong>User</strong>: tenant-A</p><p><strong>Role</strong>: finance</p><p><strong>Result</strong>: <strong>Access Granted</strong>.</p><p>The system matches the tenant and the role. The vector search finds the “Project Alpha” document. The LLM gets the context and answers the question.</p><p><strong>Scenario B: </strong>The Employee (<strong>Unauthorized</strong> Role)</p><p><strong>User</strong>: tenant-A</p><p><strong>Role</strong>: employee</p><p><strong>Result</strong>: None or only the relevant documents attached to the role.</p><p>Even though the user is in the correct tenant, they lack the <strong>finance role </strong>and the vector search is blocked by the terms filter.</p><p><strong>Scenario C: The Competitor (Wrong Tenant)</strong></p><p><strong>User</strong>: tenant-B</p><p>Role: admin</p><p><strong>Result</strong>: <strong>Total Isolation</strong>.</p><p>This user is an Admin, which is a powerful role! But they belong to Tenant B. The term: {“tenant_id”: “tenant-B”} filter ensures they never even see the existence of Tenant A’s data.</p><p><strong>Why This Matters</strong></p><p>1. <strong>Zero Hallucinations of Secrets</strong>: The LLM isn’t taught to keep secrets. It simply never knows they exist.</p><p>2. <strong>Performance</strong>: Elasticsearch filters are heavily optimized. Filtering down the document set before performing the expensive vector distance calculation actually makes the search faster.</p><p>3. <strong>Auditability</strong>: The security logic is defined in code and database queries, not in a vague prompt instruction like <em>”</em><strong><em>Please don’t show confidential data to user Bob.</em></strong><em>”</em></p><p><strong>Conclusion</strong></p><p>Building local, secure AI is entirely possible with open-source tools. By combining <strong>Ollama</strong> for local inference and <strong>Elasticsearch</strong> for secure vector storage, we’ve built a RAG system that is enterprise-ready and privacy-preserving.</p><p><em>Code availability: The full implementation is available in the elastic_Store directory of the </em><a href="https://github.com/davidmungai/local_chatbot/blob/elk-stack/elastic_Store/demo.py"><em>project repository.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=364e03c6ce9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>