<?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 Prem S Gangadharan on Medium]]></title>
        <description><![CDATA[Stories by Prem S Gangadharan on Medium]]></description>
        <link>https://medium.com/@prem_sg?source=rss-370fcfbc36a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MBU1qklHY3cSwd7S.jpg</url>
            <title>Stories by Prem S Gangadharan on Medium</title>
            <link>https://medium.com/@prem_sg?source=rss-370fcfbc36a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 16:56:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prem_sg/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[How I Built an AI Agent in PHP]]></title>
            <link>https://medium.com/@prem_sg/how-i-built-a-langgraph-style-ai-agent-in-php-27e265851b30?source=rss-370fcfbc36a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/27e265851b30</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[symfony]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[agentic-workflow]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Prem S Gangadharan]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 09:57:31 GMT</pubDate>
            <atom:updated>2026-10-01T10:19:32.520Z</atom:updated>
            <content:encoded><![CDATA[<p>Just Symfony, Redis and MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*77bMyOARQ7Y0bJHNqPBvFA.png" /></figure><p>I kept seeing AI agent projects built in Python with LangGraph. Every tutorial, every article, every repo. All Python. I have been working with PHP for years. So I wanted to know one thing. Can we do the same in PHP?</p><blockquote>I tried it. It works. This is what I learned.</blockquote><h4>What I built</h4><p>A small NL2SQL agent. You ask a question in normal English. It writes the SQL, runs it on MySQL, and gives you the answer back in English.</p><p>But it is not just a prompt that writes SQL. It behaves like an agent:</p><ul><li>It first decides whether the question can be answered at all.</li><li>If the question is unclear, it stops and asks you for more detail.</li><li>If the data does not exist in the database, it refuses instead of guessing.</li><li>When it writes a wrong query, it reads the MySQL error and fixes the query itself.</li></ul><blockquote>Repo is here if you want to look at the code:<br> <a href="https://github.com/premsgdev/agentic-nl2sql-with-php"><strong>https://github.com/premsgdev/agentic-nl2sql-with-php</strong></a></blockquote><h3>First, what is LangGraph actually doing?</h3><p>When I started I thought LangGraph is something complicated. It is not.</p><p>If you remove the branding, it is three things:</p><ol><li><strong>A state object.</strong> One bag of data that moves through the whole run.</li><li><strong>Nodes and edges.</strong> A node is a function. It takes the state, changes something, and returns it. An edge decides which node runs next.</li><li><strong>A checkpoint.</strong> After each node, the state is saved somewhere so the run can stop and continue later.</li></ol><p>This might be an <strong>oversimplification </strong>but at its core,<strong> the mental model is a stateful graph:</strong> shared state moves through nodes, edges determine what runs next, and check-pointing allows the execution to be persisted and resumed.</p><h3>The problem</h3><p>In the traditional PHP-FPM model, the application state is not tied to a long-lived application process. Each HTTP request is handled independently, so anything held only in request memory cannot be relied upon for the next request.</p><p>So when my agent asks a clarification question, the process ends there. The user thinks for some time and replies. That reply comes to a <strong>completely new PHP process</strong>. It has no idea what happened before.</p><p>I use FrankenPHP, so I thought worker mode will solve this. It does not. Worker mode only keeps the app warm. There are many workers, they restart after some number of requests, and if you run two containers it breaks anyway. You cannot keep a conversation in memory.</p><blockquote>So the only way is to save the state properly and load it back using an id.</blockquote><p>At first I felt this is a PHP limitation. Later I understood it is actually better. A Python agent also loses in-memory state when its process or pod disappears unless that state has been persisted externally. But in Python you can ignore this for a long time. In PHP you cannot ignore it even on day one.</p><h3>The graph engine</h3><p>This is the main part. It is around 50 lines.</p><pre>final class Graph<br>{<br>    public const END = &#39;__end__&#39;;<br><br>    private array $nodes = [];<br>    private array $routes = [];<br><br>    public function __construct(private readonly int $maxSteps = 15) {}<br><br>    public function node(string $name, NodeInterface $node): self<br>    {<br>        $this-&gt;nodes[$name] = $node;<br>        return $this;<br>    }<br><br>    public function edge(string $from, string $to): self<br>    {<br>        $this-&gt;routes[$from] = static fn (State $state): string =&gt; $to;<br>        return $this;<br>    }<br><br>    public function conditionalEdge(string $from, callable $router): self<br>    {<br>        $this-&gt;routes[$from] = $router;<br>        return $this;<br>    }<br><br>    public function run(State $state, string $entry): State<br>    {<br>        $current = $state-&gt;resumeAt ?? $entry;<br>        $state-&gt;resumeAt = null;<br><br>        while (self::END !== $current) {<br>            if (++$state-&gt;steps &gt; $this-&gt;maxSteps) {<br>                throw new StepLimitException($state-&gt;steps, $state-&gt;trace);<br>            }<br><br>            $state-&gt;trace[] = $current;<br>            $state = ($this-&gt;nodes[$current])($state);<br>            $current = ($this-&gt;routes[$current])($state);<br>        }<br><br>        return $state;<br>    }<br>}</pre><p>A node is any class with this one method:</p><pre>interface NodeInterface<br>{<br>    public function __invoke(State $state): State;<br>}</pre><p>Two small things in that loop that are important.</p><p><strong>The step limit.</strong> Without it, one wrong condition gives you an infinite loop. And with LLM calls inside the nodes, that means burning your API quota while you wait. Four lines prevent it.</p><p><strong>Loops are allowed.</strong> A node can go back to a previous node. That is what makes it a graph and not a pipeline. My normal clarification run looks like this:</p><pre>classify → clarify → classify → generate</pre><p>It came back to classify with the updated question and took the other path this time.</p><h3>How the agent stops and continues</h3><p>When a node wants to ask the user something, it throws an exception:</p><pre>final class Interrupt extends \RuntimeException<br>{<br>    public function __construct(<br>        public readonly string $question,<br>        public readonly string $resumeAt,<br>    ) {<br>        parent::__construct($question);<br>    }<br>}</pre><p>I used an exception because it comes out of the while loop automatically. The node only says “stop here”. The caller decides what to do. The graph engine itself needs no extra code for this.</p><p>The runner catches it, saves the state, and returns the question:</p><pre>private function execute(State $state): RunResult<br>{<br>    try {<br>        $state = $this-&gt;graph-&gt;run($state, &#39;classify&#39;);<br>    } catch (Interrupt $interrupt) {<br>        $state-&gt;resumeAt = $interrupt-&gt;resumeAt;<br>        $this-&gt;checkpointer-&gt;save($state);<br><br>        return RunResult::paused($state, $interrupt-&gt;question);<br>    }<br><br>    $this-&gt;checkpointer-&gt;save($state);<br><br>    return RunResult::completed($state);<br>}</pre><p>Next time, run() starts from resumeAt instead of the first node.</p><p>One mistake I made here. First I set resumeAt to clarify. So when the user replied, it asked the same question again. It has to be classify, because the question has changed now and it needs to be checked again.</p><h3>Saving the state</h3><p>I store it in Redis as JSON. Not PHP serialize().</p><pre>public function save(State $state): void<br>{<br>    $this-&gt;redis-&gt;setex(<br>        $this-&gt;prefix . $state-&gt;threadId,<br>        $this-&gt;ttl,<br>        json_encode($state-&gt;toArray(), JSON_THROW_ON_ERROR),<br>    );<br>}</pre><h3>Tool calling</h3><p>Symfony has symfony/ai now. You mark a normal PHP class with an attribute and the model can call it.</p><pre>#[AsTool(&#39;run_sql&#39;, &#39;Executes a read-only SELECT query and returns rows as JSON.&#39;)]<br>final readonly class RunSql<br>{<br>    public function __construct(private \PDO $pdo) {}<br><br>    public function __invoke(string $sql): string<br>    {<br>        $sql = trim($sql, &quot; \t\n\r;&quot;);<br><br>        if (!preg_match(&#39;/^(SELECT|WITH)\b/i&#39;, $sql)) {<br>            return &#39;ERROR: only SELECT statements are allowed.&#39;;<br>        }<br><br>        if (!preg_match(&#39;/\bLIMIT\s+\d+/i&#39;, $sql)) {<br>            $sql .= &#39; LIMIT 50&#39;;<br>        }<br><br>        try {<br>            $rows = $this-&gt;pdo-&gt;query($sql)-&gt;fetchAll(\PDO::FETCH_ASSOC);<br>        } catch (\PDOException $e) {<br>            return &#39;ERROR: &#39; . $e-&gt;getMessage();<br>        }<br><br>        return json_encode([&#39;row_count&#39; =&gt; count($rows), &#39;rows&#39; =&gt; $rows]);<br>    }<br>}</pre><p>The important line is the catch block. <strong>I return the error as a string. I do not throw it.</strong></p><p>That string goes back to the model. So when it writes SELECT SUM(revenue), MySQL says &quot;Unknown column &#39;revenue&#39;&quot;, the model reads it and writes total_amount instead. It fixes its own query. If I had thrown the exception, the whole run would stop and I would get a stack trace instead of an answer.</p><h3>About security</h3><p>I know this part is not optional, for now what I did is created read-only user to query the data, also implemented regex checking to make sure the model generated only select statements and to block any insert or delete operations. Regex checking is only a first guardrail, not a SQL security boundary. The database user is read-only, and the application should additionally validate the parsed SQL/AST, restrict accessible tables and operations, enforce query timeouts and resource limits, and ideally execute against a read replica or isolated analytics database.</p><h3>Working</h3><pre>$ bin/console app:ask &quot;How much did we sell last year?&quot;<br><br>I need one more detail<br>----------------------<br>Specify the order statuses (e.g., PAID, CONFIRMED, etc.) to include<br>in the sales total<br><br> // bin/console app:ask &quot;your answer&quot; --thread=40d87234bfc76bb2<br><br>$ bin/console app:ask &quot;DELIVERED&quot; --thread=40d87234bfc76bb2<br><br>Answer<br>------<br>We sold 1,132,046.00 in total for orders marked DELIVERED during last year.</pre><p>Look at what happened there, It did not guess. My orders table has statuses like CANCELLED and RETURNED. So the total changes depending on which ones you count. There is no correct answer without asking. Then the PHP process ended. I ran the second command separately. A different process continued the same conversation and gave the answer. <strong>Two processes. One conversation.</strong></p><h3>About the AI tools I used</h3><p>I used <strong>Qwen Coder, Trae AI and opencode, </strong>these were cheaper and worked fine for what I needed.</p><h3>What I did not build</h3><p>I think this part is important, so I will say it clearly.</p><p><strong>No RAG for the schema.</strong> My database has four tables. The whole schema fits inside the prompt easily. RAG over schema is useful when you have a few hundred tables. Below that it only makes things worse by hiding a table the query needed.</p><p><strong>Redis is not fully safe.</strong> When memory is full, Redis can remove a key. Then a paused conversation is gone. For production the correct way is MySQL as the main store and Redis as a cache. I kept it behind an interface so that change is small.</p><p><strong>No evaluation setup.</strong> I test with three questions manually. A real system needs a set of question and SQL pairs and a pass percentage in CI, because when you change the prompt or the model the accuracy drops silently.</p><h3>What I actually learned</h3><p>The model call is maybe 5 percent of the code. And AI tools wrote a good part of the rest. But the decisions were mine, and that is where the time went.</p><p>Everything else was normal engineering. Where does the state go. What happens when the output is broken. How much is this query allowed to touch. How do I stop an infinite loop.</p><p>That is the part that makes a demo into something usable. PHP just forced me to think about it on day one instead of finding out later in production.</p><h4>The thing that took me a full evening</h4><p>My classifier asks the model to reply in JSON. Something like this:</p><pre>{&quot;label&quot;: &quot;ambiguous&quot;, &quot;reason&quot;: &quot;...&quot;, &quot;missing&quot;: &quot;...&quot;}</pre><p>It kept failing. My parsing was using this regex:</p><pre>preg_match(&#39;/\{.*\}/s&#39;, $raw, $matches);</pre><p>Then I printed the raw response and understood the problem. New reasoning models write their thinking first, inside a &lt;think&gt; block. And inside that thinking, the model writes <strong>draft JSON</strong> two or three times before the final answer.</p><p>So \{.*\} was matching from the very first { to the very last }. It picked up several lines of normal text in between. Not valid JSON.</p><p>The fix:</p><pre>// Reasoning models write a &lt;think&gt; block first. Remove it.<br>if (false !== ($end = strripos($text, &#39;&lt;/think&gt;&#39;))) {<br>    $text = substr($text, $end + 8);<br>}<br>// Then take the last plain JSON object.<br>if (preg_match_all(&#39;/\{[^{}]*\}/s&#39;, $text, $matches)) {<br>    $text = end($matches[0]);<br>}</pre><p>[^{}]* cannot go across other braces, so it will not pick up the text in between.</p><p>If you use GPT-OSS, Qwen or DeepSeek models, you will hit this. I did not see it mentioned anywhere.</p><h4>Never trust the model output directly</h4><p>Even after parsing, I check the label against a fixed list:</p><pre>private const LABELS = [&#39;answerable&#39;, &#39;ambiguous&#39;, &#39;out_of_scope&#39;];<br>$label = strtolower(trim((string) ($data[&#39;label&#39;] ?? &#39;&#39;)));<br>if (!in_array($label, self::LABELS, true)) {<br>    return [<br>        &#39;label&#39; =&gt; &#39;ambiguous&#39;,<br>        &#39;reason&#39; =&gt; &#39;Unknown label&#39;,<br>        &#39;missing&#39; =&gt; &#39;Could you rephrase your question?&#39;,<br>    ];<br>}</pre><p>And see which side it falls back to. If something goes wrong, it falls back to <strong>ambiguous</strong>, not to <strong>answerable</strong>. So a question that was never properly classified can never reach the SQL step.</p><p>This is the general rule I followed everywhere: <strong>the model suggests, PHP decides.</strong></p><h3><strong>Stack</strong></h3><p>Symfony 8.1, PHP 8.4, symfony/ai, Groq, MySQL, Redis.</p><p><strong>Code:</strong> <a href="https://github.com/premsgdev/agentic-nl2sql-with-php">https://github.com/premsgdev/agentic-nl2sql-with-php</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27e265851b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How do you build a production system when every rupee matters?]]></title>
            <link>https://medium.com/@prem_sg/how-do-you-build-a-production-system-when-every-rupee-matters-1f18c73609b9?source=rss-370fcfbc36a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f18c73609b9</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Prem S Gangadharan]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 05:28:05 GMT</pubDate>
            <atom:updated>2026-07-04T08:23:15.833Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A story about engineering decisions, business constraints, and why “free” isn’t always free.</em></p><p>A few weeks ago, one of my friends called me with an exciting idea.</p><p>He had been working on a startup for quite some time and was finally getting close to launching it. Like many founders, he had already spent a significant amount of money before even thinking about software. There were warehouse expenses, government registrations, licenses, compliance work, logistics, and several other operational costs that every business has to deal with.</p><p>When we finally sat down to discuss the technology, he smiled and said,</p><blockquote><em>“I have one request. Please keep the infrastructure cost as close to zero as possible until we know the business works.”</em></blockquote><p>It sounded like a simple request.</p><p>It wasn’t.</p><p>The application itself is confidential, so I can’t share what the business does. What I can say is that it isn’t the kind of business where a simple website is enough. A large part of the business happens online, so we needed a proper web application, secure APIs, a database, file storage, and eventually mobile applications as well.</p><p>In other words, this wasn’t a weekend side project. We were building something that people would actually use.</p><p>The challenge wasn’t writing the code. The challenge was building an infrastructure that cost nothing today but wouldn’t become a headache tomorrow when we scale up according to the usage.</p><p>That question stayed in my mind throughout the project.</p><p><strong>How do you make infrastructure decisions when every rupee matters, without making future scaling painful?</strong></p><p>That became the real engineering problem.</p><h3>The cheapest option isn’t always the best option</h3><p>When people ask how to host an application for free, the internet is full of answers.</p><p>“Use Render.”</p><p>“Deploy on Railway.”</p><p>“Cloud Run is amazing.”</p><p>“Use Fly.io.”</p><p>“Just use AWS Free Tier.”</p><p>None of those answers are wrong.</p><p>But they answer the wrong question.</p><p>I wasn’t looking for the cheapest place to host an application. I was looking for the smartest place to build a business. There’s a huge difference between the two.</p><p>Saving ₹500 today isn’t a great decision if it forces you to spend weeks migrating your production system six months later.</p><p>So before opening pricing pages or watching YouTube comparisons, I decided to write down what success actually looked like.</p><h3>We started with principles, not platforms</h3><p>Whenever we design software, we usually begin with requirements.</p><p>I think infrastructure deserves the same treatment. Instead of comparing cloud providers immediately, I wrote down a few simple rules.</p><p>The monthly infrastructure cost should remain zero while the business is being validated.</p><p>The application should run inside Docker containers so it can move anywhere.</p><p>We should avoid vendor lock-in wherever possible.</p><p>The database should be easy to migrate if we ever need to.</p><p>Scaling should not require rewriting the application.</p><p>And most importantly, if the startup suddenly becomes successful, we should be able to grow without redesigning the architecture.</p><p>Once these principles were clear, evaluating hosting providers became much easier.</p><p>Instead of asking <em>“Which provider is the best?”</em>, I started asking <em>“Which provider fits these requirements?”</em></p><p>That small change completely changed the way I looked at every platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5xpnofMRYaiykdEyhPlhg.png" /><figcaption>Decision Matrix</figcaption></figure><h3>Looking at the hosting options</h3><p>The first few names that came to mind were probably the same ones most developers would think of.</p><h3>Render</h3><p>Render was one of the first platforms I looked at.</p><p>Honestly, I understand why so many developers recommend it. The onboarding experience is excellent. Connect your GitHub repository, push your code, and within minutes your application is running. If you’re building an MVP or an internal tool, it’s hard not to like.</p><p>The only concern for our use case was the free instances going to sleep when they aren’t being used. That means the first user after a period of inactivity has to wait while the application starts again.</p><p>For some applications, that’s completely acceptable.</p><p>For a customer-facing service, I wasn’t entirely comfortable with that experience.</p><h3>Railway</h3><p>Railway has one of the nicest developer experiences I’ve used.</p><p>The interface is clean, deployments are straightforward, and connecting databases is incredibly simple. It removes a lot of operational work so developers can focus on building features.</p><p>The challenge is that Railway has gradually moved away from being a truly free platform for long-running applications. It’s still a fantastic service, but it wasn’t the right fit for a project whose primary goal was keeping infrastructure costs at zero during the validation stage.</p><h3>Fly.io</h3><p>Fly.io was another interesting option.</p><p>I really like the idea behind it. Running applications closer to users around the world can significantly reduce latency, and its Docker-first approach makes deployments portable.</p><p>The trade-off is that it expects developers to be a little more comfortable with infrastructure. There’s more configuration involved compared to platforms like Render, and the free allowances have become more limited over time.</p><p>It’s a great platform, but perhaps not the simplest starting point for this particular project.</p><h3>Google Cloud Run</h3><p>Cloud Run impressed me more than I expected.</p><p>Container-based deployments, automatic scaling, and paying only when requests arrive make it a very elegant platform from an engineering perspective.</p><p>If I were building a production application where infrastructure cost wasn’t the primary concern, Cloud Run would definitely be high on my list.</p><p>However, our goal wasn’t finding the cheapest pay-as-you-go platform. Our goal was avoiding recurring costs altogether until the business proved itself.</p><h3>AWS Free Tier</h3><p>No cloud comparison would be complete without AWS.</p><p>The ecosystem is incredible. There is a managed service for almost everything you can imagine, and learning AWS is an investment that pays off throughout your career.</p><p>The only thing that didn’t fit our requirements was the word “free.” More accurately, it should be called <strong>“free for a while.”</strong></p><p>Eventually, the free period ends.</p><p>At that point you either start paying or begin planning a migration. Neither of those options matched what we were trying to achieve.</p><h3>Microsoft Azure</h3><p>Azure falls into a similar category.</p><p>Excellent infrastructure. Excellent tooling. Excellent enterprise support.</p><p>But like AWS, the free benefits are designed to help you get started rather than remain free indefinitely.</p><h3>Oracle Cloud Always Free</h3><p>Oracle Cloud was probably the most interesting platform we evaluated.</p><p>Unlike many providers, some of its resources are genuinely part of an Always Free offering.</p><p>That immediately caught my attention.</p><p>Of course, there is a trade-off.</p><p>Oracle gives you infrastructure, not convenience.</p><p>You’re responsible for configuring Docker, reverse proxies, SSL certificates, networking, firewalls, monitoring, updates, backups, and everything else that comes with running your own server.</p><p>For someone who enjoys understanding how systems work, it’s actually a great learning experience.</p><p>It gives you complete control, but it also expects you to take complete responsibility.</p><h3>Hosting is only one part of the story</h3><p>After looking at compute, I realized something.</p><p>Hosting an application is actually the easy part. The real challenge is everything around it.</p><p>Where will user uploads live?</p><p>How will we store backups?</p><p>What happens if the database becomes unavailable?</p><p>How do we deploy new versions safely?</p><p>How do we restore everything if the server fails?</p><p>Those questions are far more important than choosing between one cloud provider and another.</p><h3>Choosing a database deserves even more thought</h3><p>Changing where your application runs is usually manageable.</p><p>Changing your database is a completely different story.</p><p>That’s why we spent a lot of time looking at managed MySQL services.</p><p>We evaluated Aiven, PlanetScale, TiDB Cloud, Oracle MySQL HeatWave, and even the idea of hosting MySQL ourselves inside Docker.</p><p>Every option had something to offer.</p><p>Some provided an amazing developer experience. Some offered generous free storage. Some handled backups automatically. Some removed operational work completely.</p><p>But every solution also came with limitations.</p><p>Some free plans went to sleep after inactivity. Some no longer offered free tiers. Some had storage limits. Others introduced small compatibility differences that could matter later.</p><p>It reminded me that there is no perfect database platform.</p><p>There are only platforms that fit different priorities.</p><h3>Storage and deployments matter too</h3><p>We also looked at object storage, deployment pipelines, and security.</p><p>Cloudflare R2 stood out because it removes one of the hidden costs people often forget about — egress charges.</p><p>For deployment automation, GitHub Actions and GitHub Container Registry were easy choices. Having repeatable deployments from day one saves a surprising amount of time, even for small teams.</p><p>And for SSL certificates, Let’s Encrypt continues to prove that secure websites don’t have to be expensive.</p><h3>The biggest lesson wasn’t about cloud providers</h3><p>By the end of this exercise, I realized something interesting.</p><p>I hadn’t really been comparing cloud platforms.</p><p>I had been comparing trade-offs.</p><p>Every provider is good at something.</p><p>Some optimize for developer experience.</p><p>Some optimize for simplicity.</p><p>Some optimize for enterprise workloads.</p><p>Some optimize for flexibility.</p><p>None of them are objectively the best.</p><p>The right choice always depends on the problem you’re trying to solve.</p><h3>Good architecture outlives cloud providers</h3><p>Cloud pricing changes.</p><p>Free tiers disappear.</p><p>Companies change their business models.</p><p>New platforms emerge.</p><p>That’s normal.</p><p>Good software architecture survives all of those changes.</p><p>If your application runs inside containers, uses environment variables correctly, keeps backups independent of the hosting platform, and avoids unnecessary vendor lock-in, moving to another provider becomes an operational task instead of a six-month engineering project.</p><p>That should always be the goal.</p><h3>Final Thoughts</h3><p>This project reminded me that engineering isn’t only about writing clean code or choosing the newest technology.</p><p>Sometimes the best engineering decision is the one that helps a business survive its first year.</p><p>Every rupee we save during the validation phase is a rupee that can be invested somewhere else — bringing in new customers, improving operations, or building better features. Technology should help the business grow, not become another financial burden.</p><p>After evaluating several options, we ended up with a simple but solid stack: a Dockerized backend running on an Oracle Cloud Always Free VM, Oracle MySQL HeatWave Always Free for the database, Cloudflare Workers serving the frontend, Cloudflare R2 for media storage and backups, and GitHub Actions handling our deployments. The entire setup costs us <strong>₹0 per month</strong> while still giving us a clear path to scale when the business grows.</p><p>I’m not sharing the complete architecture or the project itself just yet because the startup is still in its early stages, and I’d like to respect my friend’s privacy. Once the product is public, I’ll be happy to write a follow-up article explaining the architecture, deployment pipeline, and the lessons we learned along the way.</p><p>Until then, I’d love to hear your thoughts.</p><p><strong>If you had to build a production-ready web application with a monthly infrastructure budget of ₹0, what stack would you choose, and why?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f18c73609b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How We Built a Better RAG Engine: An Agent That Asks Clarifying Questions]]></title>
            <link>https://medium.com/@prem_sg/how-we-built-a-better-rag-engine-an-agent-that-asks-clarifying-questions-5e405e598e37?source=rss-370fcfbc36a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e405e598e37</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Prem S Gangadharan]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 05:06:57 GMT</pubDate>
            <atom:updated>2025-12-23T05:13:58.161Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern AI chat systems often use <strong>Retrieval-Augmented Generation (RAG)</strong> to ground answers in real documents. But one thing most RAG systems miss is <strong>clarifying ambiguous questions</strong> — and that leads to wrong answers even when the model has access to data.</p><p>In this article, I share how I built a <strong>RAG engine</strong> that can:</p><ul><li>Detect whether the question can be answered from user documents</li><li>Ask for clarification when the intent is unclear</li><li>Resume the conversation naturally once clarification is given</li></ul><p>The full project is available on GitHub:<br> 🔗 <a href="https://github.com/premsgdev/rag-engine">https://github.com/premsgdev/rag-engine</a></p><h4>The Problem with Vanilla RAG</h4><p>Most RAG systems do this:</p><pre>User Question → Vector Search → LLM Answer    </pre><p>This sounds correct, but it only works when the query is <strong>clear and specific</strong>.</p><p>For example:</p><blockquote><em>“What is life?”</em></blockquote><p>What does “life” mean here?<br> In my data, “LIFE” refers to <strong>LIFE Mission</strong>, a Kerala government initiative to build house for poor. But the model doesn’t know that. If the RAG system matches “life” to “LIFE Mission” and answers with that, it’s technically grounded — yet <strong>semantically wrong</strong>.</p><p>The model wasn’t hallucinating; it was <strong>only matching vectors, not intent</strong>. That’s the flaw.</p><h4>The Missing Piece: A Query Validation Agent</h4><p>What we actually need is a layer between retrieval and generation that answers a single question:</p><blockquote>Can this question be answered correctly using these retrieved snippets?</blockquote><p>This requires:</p><ul><li>Retrieval of evidence (vector search)</li><li>Reasoning over that evidence</li><li>A decision: answer, reject, or ask for clarification</li></ul><p>This is exactly where an <strong>agent</strong> helps.</p><h4>How This Architecture Works</h4><p>Here’s a high-level diagram showing the overall flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zHpdcXPKNAyw-KWJ418-nw.png" /><figcaption>Agent-Driven RAG Architecture</figcaption></figure><ol><li>We run a vector search on the question</li><li>We give the top snippets to a <strong>validation agent</strong></li><li>The agent decides:</li></ol><ul><li><em>Valid</em> → carry on</li><li><em>Ambiguous</em> → ask a question</li><li><em>Invalid</em> → reject</li></ul><p>This is different from “just answer.”</p><h4>Example: Ambiguous Query</h4><p>Let’s walk through a real scenario.</p><p><strong>User:</strong></p><blockquote><em>“What is life?”</em></blockquote><p>My vector search returns documents about <strong>LIFE Mission (Livelihood Inclusion and Financial Empowerment Mission)</strong>. These are the closest matches, but they are about a government program, not the general meaning of life.</p><p>Now the validation agent must reason:</p><ul><li>Does the question match the documents?</li><li>Are they talking about the same thing?</li><li>If not, what clarification is needed?</li></ul><p>Instead of answering badly, the agent responds:</p><blockquote><em>“Did you mean </em><strong><em>LIFE Mission (Livelihood Inclusion and Financial Empowerment Mission)</em></strong><em>?”</em></blockquote><p>Yes, now we have a clarification question.</p><h4>Putting Clarification Into Real Chat Flow</h4><p>To support clarification in chat, we had to keep <strong>conversation state</strong>.</p><p>In back-end, we store what clarification was asked so that follow-up responses like “yes” or “no” make sense.</p><p>Here’s the multi-turn flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8HEpJPbXKreaUnozQiQ1g.png" /><figcaption>Clarification-Aware Multi-Turn Chat</figcaption></figure><p>Here’s what’s happening:</p><ol><li>The user asks something vague</li><li>We retrieve snippets just like usual</li><li>The agent sees intent mismatch and asks a clarification</li><li>We store that pending clarification in Redis</li><li>When the user responds “yes” or “no”, we read that state</li><li>We rewrite the intent and continue the pipeline</li></ol><p>No history embedding. No forcing the LLM to guess context. This is <strong>backend state</strong>, not LLM memory.</p><h4>Why This Matters</h4><p>Without this agent:</p><ul><li>RAG systems match vectors but don’t understand intent</li><li>They confidently answer wrong questions</li><li>Users get plausible but incorrect answers, which is not good for a long chat</li></ul><p>With this agent:</p><ul><li>You <strong>stop before answering incorrectly</strong></li><li>You ask for clarification when needed</li><li>You only answer when intent and evidence align</li></ul><p>For real systems — especially policy, law, compliance, or enterprise data — this is not a nice-to-have — it’s a necessity.</p><h4>The Code That Makes It Work</h4><p>This project is open-source and available here:</p><p>🔗 <a href="https://github.com/premsgdev/rag-engine">https://github.com/premsgdev/rag-engine</a></p><p>Some key components:</p><p>📌 <strong>Query Validation Agent</strong><br> This logic lives in:</p><pre>src/chat-agents/query-validator.agent.ts</pre><p>📌 <strong>Retriever and Context Assembly</strong><br> For real retrieval:</p><pre>src/chat-retrieval/retriever.service.ts<br>src/chat-retrieval/context-assembler.service.ts</pre><p>📌 <strong>Chat Orchestration + Clarification State Storage</strong><br> Managed here:</p><pre>src/chat/chat.service.ts<br>src/chat/chat-state.service.ts</pre><p>📌 <strong>Streaming LLM Answer (Gemini)</strong><br> Handled here:</p><pre>src/chat-llm/google-genai.client.ts<br>src/chat-llm/answer-generator.service.ts</pre><p>You can read all of this in the repo linked above.</p><h3>Final Thoughts</h3><p>RAG is powerful, but <strong>intelligence is more than matching.<br> It’s about understanding intent.</strong></p><p>By inserting a <strong>validation agent that reasons over retrieved evidence</strong>, and by supporting <strong>clarification in multi-turn chat</strong>, we make the system:</p><ul><li>Safer</li><li>More accurate</li><li>More human-like</li><li>Far less prone to silent errors</li></ul><p>If you’re building a RAG system for anything serious, this pattern is worth adopting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e405e598e37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern WordPress Development with Docker + Bedrock]]></title>
            <link>https://medium.com/@prem_sg/modern-wordpress-development-with-docker-bedrock-72d640067b81?source=rss-370fcfbc36a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/72d640067b81</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[local-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[wordpress-development]]></category>
            <dc:creator><![CDATA[Prem S Gangadharan]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 06:39:11 GMT</pubDate>
            <atom:updated>2025-12-08T06:39:11.641Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A simple, developer-friendly setup, built for clean and consistent WordPress projects.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*WfhWN_YmBxo_Qkx-TjGDKw.png" /><figcaption>Containerized WordPress development.</figcaption></figure><p>If you’ve ever worked on multiple WordPress projects, you know the setup can vary a lot from machine to machine. Different PHP versions, plugin folders mixed with core files, configuration repeating on every environment… it can get messy fast.</p><p>So I created <strong>wp-bedrock-container</strong> — a lightweight Docker + Bedrock starter that gives you a clean structure, better dependency management, and a consistent environment you can spin up instantly.</p><p>This article walks you through <em>what this stack is.</em></p><h4>What This Setup Gives You</h4><ul><li>A neat, organized folder structure with Bedrock — core, config, content separated cleanly.</li><li>Dependency management for WordPress, themes, plugins — via Composer (so no more manually copying plugin files).</li><li>Environment variables in a .env file (for database credentials, salts, environment type).</li><li>Docker containers for PHP, Nginx, MySQL — so everyone runs the same versions regardless of OS or local setup.</li><li>A reproducible development workflow: clone the repo, configure env, run one command, and you’re ready to go.</li></ul><p>In short: you get a WordPress stack that feels more like a modern web app — robust, consistent, and easy to maintain.</p><h4>Why Bedrock + Docker?</h4><p>You can install standard WordPress using Composer, and that works fine. But I prefer <strong>Bedrock</strong> because it adds a clean folder structure, environment variables, and a more maintainable approach to managing themes, plugins, and configuration. It’s basically the “organized version” of a Composer-based WordPress setup.</p><p>Now add <strong>Docker</strong>, and you get:</p><ul><li>Consistent PHP, MySQL, and Nginx versions across all environments</li><li>A fully isolated development setup</li><li>Zero installation of PHP/MySQL on your local machine</li><li>A predictable runtime that behaves the same everywhere</li></ul><h4>What’s Inside</h4><p>I combined a few ideas and tools to build this stack:</p><ul><li>Using Bedrock for a clean WordPress structure + Composer-based dependency management. This gives separation of concerns: WordPress core, configuration, and content live in their own folders.</li><li>Docker + Docker Compose to containerize everything: the web server (Nginx + PHP-FPM), database (MySQL), so the environment is the same everywhere — local, staging, or production.</li><li>A simple setup flow (clone → configure → start) to avoid long setup times or environment-specific bugs.</li></ul><p>The result: a plug-and-play WordPress starter that developers — especially backend or DevOps-oriented folks — will appreciate.</p><h4>Quick Start</h4><pre>git clone https://github.com/premsgdev/wp-bedrock-container.git<br>cd wp-bedrock-container</pre><ul><li>Copy .env.example to .env, edit credentials, salts, and environment variables.</li><li>Then run docker compose up -d (or similar per instructions).</li><li>That starts Nginx + PHP-FPM + MySQL, with Bedrock correctly configured and a clean /web root ready for your WordPress site.</li></ul><p>Within minutes, you have a working WordPress environment — without wrestling with server setup, PHP versions, or OS differences.</p><h4>Common Issues You Might See</h4><p>Even with Docker, small glitches happen. The two most common:</p><p><strong>502 Bad Gateway</strong></p><p>Usually caused when Nginx can’t reach PHP-FPM yet.<br> Check:</p><pre>docker compose logs php</pre><p><strong>403 Forbidden</strong></p><p>Often caused by pointing Nginx to the wrong webroot.<br> Confirm that your document root is /web.</p><p>Both issues are quick fixes and mostly come down to path or container readiness.</p><h4>Why I Did It — And Why You Might Care</h4><ul><li>WordPress setup that feels like a “real” web app: structured, maintainable, with dependencies under version control.</li><li>An environment-independent builds — local, staging, production all behave the same.</li><li>On-boarding (for other devs or future me) to be easy: clone → env setup → run — no fuss.</li><li>I also enjoy containerization, and Docker brings predictability and repeatability to WordPress which helps avoid “works on my machine but not on server” problems.</li></ul><p>If you enjoy structured projects, clean DevOps workflows, and reproducible builds, you’ll find this setup surprisingly refreshing.</p><h4>Final Thoughts</h4><p>WordPress is incredibly flexible — and when paired with Bedrock + Docker, it becomes much more developer-friendly. wp-bedrock-container is my take on combining these tools in a way that feels natural, fast, and easy to maintain. Feel free to explore it, fork it, or adapt it to your workflow.</p><p>This article walks you through <em>what this stack is</em>, <em>why I built it</em>, and <em>how you can use it</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72d640067b81" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>