<?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 Rosie Faulkner on Medium]]></title>
        <description><![CDATA[Stories by Rosie Faulkner on Medium]]></description>
        <link>https://medium.com/@faulknerproject?source=rss-96a0f1a7f783------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gg2vbKDMyQ4zJ2obqfNHPw.jpeg</url>
            <title>Stories by Rosie Faulkner on Medium</title>
            <link>https://medium.com/@faulknerproject?source=rss-96a0f1a7f783------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:57:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@faulknerproject/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[BMAD Method: Getting Started]]></title>
            <link>https://medium.com/@faulknerproject/bmad-method-getting-started-4739358c7502?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/4739358c7502</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 15:48:47 GMT</pubDate>
            <atom:updated>2026-03-30T15:56:00.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rBL8pIxjz6nGx1eAInmpg.png" /><figcaption>The current landscape of AI-assisted development is dominated by “vibe coding” — a reactive, unstructured approach where developers rely on fragmented prompts to generate isolated blocks of code. While this provides immediate tactical gratification, it lacks the strategic rigor required for enterprise-grade software. This unstructured “vibe” inevitably leads to technical debt, context drift, and architectural decay. To ensure long-term maintainability and system stability, organizations must transition from treating AI as a simple autocomplete utility to adopting a structured, agentic framework.</figcaption></figure><p>The <strong>BMAD (Breakthrough Method for Agile AI Driven Development)</strong> facilitates this shift by replacing sporadic prompting with a high-fidelity, persona-driven collaboration. This method ensures that AI agents operate as expert collaborators within strict architectural guardrails rather than generalist assistants.</p><p>Developing with AI today often feels like a race to the middle. Many developers are falling into the <strong>“Average Result” Trap</strong>, where they let traditional AI tools do the thinking for them, only to receive mediocre, middle-of-the-road outputs. This is the “Bell Curve” of AI: most responses represent the safe, uninspired slice of the training data. If you are just “vibe coding” — blindly following the AI’s lead — you are settling for the average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nE4_TQP9DLgCo_La0vfcmw.png" /><figcaption>Scale-Domain-Adaptive intelligence is the mechanism that allows the BMAD Method to modulate its cognitive load and planning depth based on the specific complexity of the target system. Unlike rigid templates, this engine ensures that the AI’s intensity matches the task at hand, preventing the “average” output typical of general-purpose LLM interactions.</figcaption></figure><p>I recently finished the <a href="https://www.youtube.com/watch?v=LorEJPrALcg">BMAD (Build More Architect Dreams) Method Masterclass</a>, and it is a total paradigm shift. BMAD isn’t just a set of prompts; it is a 100% free and open-source framework designed to be molded to your own way of working. It moves you from using AI as a simple taskmaster to an expert collaborator. As a Lead AI Architect, I’ve seen many frameworks, but these five lessons from the Masterclass represent the future of agentic development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lhf9kmqXgUGO7jYK4PEevQ.png" /><figcaption>A cornerstone of this intelligence model is <strong>Sharded Architectural Planning</strong>. By utilizing the shard command to explode monolithic Product Requirements Documents (PRDs) and Architecture files into smaller, context-aligned &quot;shards&quot; (targeted by <strong>Level 2 Markdown headers</strong>), we enforce a modular structure from the outset.</figcaption></figure><h3>1. The Business Analyst Agent is a Brainstorming Beast</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U3A8HpbPN0DRKmB0jPIYIA.png" /></figure><p>Most people think the magic of AI coding frameworks is in the actual code generation, but the real secret weapon here is Mary, the Business Analyst agent. She isn’t just a generic chatbot that spits out ideas for you- she acts as your personal brainstorming coach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3Ye6TLqIKIcKK5cYlW7gg.png" /></figure><p>Instead of doing the work <em>for</em> you, Mary pushes you to dig deeper using over 20 built-in brainstorming techniques, including the “Six Thinking Hats,” “The 5 W’s,” and some wild Role-Playing scenarios. She’ll force you to think about edge cases — like how an “overwhelmed freelancer” or an “ADHD creative” would use your app — pulling ideas out of you that you’d never come up with on your own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HSY3eUy0n9-oj9vsSt-iaA.png" /></figure><h3>2. Stop Hoarding Context (Context Engineering is Key)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gwf7NXEOdKRoEwnNCyBgFA.png" /></figure><p>We all love massive context windows, but hoarding context is a great way to confuse your AI. One of the biggest takeaways from the BMAD method is learning how to keep your AI’s brain clean and focused.</p><p>First, start a brand-new chat session whenever you switch<strong> tasks or agents</strong> (like moving from the Analyst to the Product Manager). Second, use the built-in shard command to split massive documents—like your Product Requirements Document (PRD) and Architecture file—into smaller, bite-sized pieces. This way, when the Developer agent (James) starts writing code, he only loads the exact context he needs to build that specific feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RI8lTRuREFV7F27drwBMqQ.png" /><figcaption><strong>The “So What?” of Sharding:</strong> Sharding is not merely an organizational preference; it is a strategic necessity for enforcing decoupling. If a document cannot be sharded, the underlying architecture is likely too tightly coupled. By sharding, we minimize the token-to-relevant-data ratio, ensuring the agent remains “context-locked” to specific modules.</figcaption></figure><p><strong>Primary benefits of sharding include:</strong></p><ul><li><strong>Context Window Optimization:</strong> Ensures that James (The Developer) and Quinn (The QA Agent) ingest only the data relevant to the active task, preventing cognitive overwhelm.</li><li><strong>Mitigation of Probabilistic Drift:</strong> By isolating specific constraints into files like tech-stack.md and coding-standards.md, agents are forced to stay within established guardrails.</li><li><strong>Idempotent Story Execution:</strong> Sharding facilitates granular tracking, ensuring that developer stories are sequential and dependency-aware.</li></ul><p>This intelligent modeling provides the framework for an ecosystem of specialized AI personas that mirror a high-performing engineering department.</p><h3>3. Torture Your LLM with “Advanced Elicitations”</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pjcj2h9jPkH22VrRpxHCiA.png" /></figure><p>If you ask an LLM a question, you’re usually going to get a “bell curve” response — the most average, safe answer possible. The BMAD Method fixes this with <strong><em>Advanced Elicitations</em></strong>, which basically let you stick a cattle prod to the AI and demand better results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zc9UP16a4deJrgc37UnpbQ.png" /></figure><p>Whenever an agent finishes drafting a section of a document, you can challenge it. You can use wild prompts like “Hindsight is 20/20” (where the AI imagines it’s 6 months post-launch and critiques what went wrong) or run “Critical Assumption Testing”. These exercises are incredible for stress-testing your ideas and aggressively cutting out unnecessary features to keep your MVP lean.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*ZS1IzyCu-g9U9x9zuRtScA.png" /></figure><h3>4. You Never Have to Leave Your IDE</h3><p>To break out of that “average slice” of the Bell Curve, the BMAD Method utilizes <strong>Advanced Elicitations.</strong> If you look at the system internals in data/elicitation-methods, you’ll see a library of techniques designed to &quot;stick the cattle prod&quot; to the agent, forcing it into high-level, critical thinking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXi-tHC2N5xlKUDmUa_gVw.png" /></figure><p>The Masterclass taught us to put the AI’s logic “through the fire” using these methods:</p><ul><li><strong>Hindsight is 2020:</strong> The agent imagines the project is six months post-launch and has either failed or succeeded. This retrospective allows the AI to identify “If Only” statements — requirements you might have missed in the present.</li><li><strong>Red Team vs. Blue Team:</strong> One persona attacks the logic while another defends it, exposing hidden weaknesses in the architecture.</li><li><strong>Tree of Thought:</strong> Forcing the agent to explore multiple reasoning branches simultaneously before settling on a technical path.</li><li><strong>The If Only Brainstorm:</strong> A deep dive into identifying scope creep or missing foundational elements by questioning what “should” have been done differently.</li></ul><p><strong>Context Engineering through “Sharding”</strong></p><p>As projects grow, “context pollution” and “compaction” become inevitable. When a Product Requirements Document (PRD) or Architecture file becomes too massive, the AI starts to lose track of details. This is where <strong>“Context Engineering”</strong> — the heart of the BMAD workflow — comes in.</p><p>The Masterclass introduced the shard and MD tree explode commands. These tools “explode” large documents into smaller, manageable pieces (shards). This ensures the agents load only the specific context they need. To keep the developer agent on the rails, the method utilizes <strong>“Dev Load Always”</strong> files. These are core shards that the agent must load every time:</p><ul><li><strong>Coding Standards</strong></li><li><strong>Tech Stack</strong></li><li><strong>Source Tree</strong></li></ul><p>This ensures that even a $20 version of Claude Code remains as effective as more expensive, gated alternatives by keeping the context lean and relevant.</p><p>Say goodbye to constantly copy-pasting code between a browser tab and your editor. The new BMAD workflow is designed to run entirely inside your IDE using Claude Code, Cursor, or vanilla VS Code.</p><p>Everything happens right in your terminal. As you chat with the AI agents, <strong>they build and update your markdown documents section-by-section directly in your project folder</strong>. It takes literally 5 seconds to install into any directory via npx bmad-method install, and you&#39;re off to the races.</p><h3>5. AI is a Partner, Not an Autopilot</h3><p>The core philosophy of the BMAD Method is <strong>“Scale-Adaptive Intelligence.”</strong> This isn’t about sitting back while the AI drives; it’s about elevating yourself and the LLM simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fyremfiy3rXZG1t6HylvLQ.png" /></figure><p>In this framework, the human remains the logical <strong>“anchor.”</strong> You are specifically responsible for reviewing story sequences and logical progression. While the AI is powerful, it lacks your innate understanding of the “why.” You must verify that the project’s foundation is sound before the first line of code is written. The Masterclass emphasizes that the human and AI are better collectively than each one on its own:</p><p>“The beauty of the BMAD method is not that you ask it for something and it spits out a whole document, but that it really works back and forth with you coming up with the best possible thing that you guys can come up with together.”</p><p><strong>Mary the Analyst is the “Secret Sauce”</strong></p><p>While developers naturally gravitate toward coding agents, <strong>Mary</strong>, the Business Analyst agent, is the most transformative part of the BMAD ecosystem. Mary facilitates a shift from mere “task management” to <strong>“behavioral intelligence.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ud6kcS3AWMW2oUVOwNIfQ.png" /><figcaption>The BMAD Method transforms the LLM into a suite of specialized consultants. Adopting specific roles — including specialized modules like <strong>TEA (Test Architect)</strong> for risk-based strategy, <strong>BMB (BMad Builder)</strong> for agent customization, and <strong>CIS (Creative Intelligence Suite)</strong> for innovation — prevents “average” outputs by enforcing domain-specific constraints.</figcaption></figure><p>Mary isn’t just for software; she is a personal coach for “life-brainstorming.” Whether you are planning a vacation, mapping out a 10-year retirement plan, or “unscrewing” something in your life, Mary uses sophisticated techniques to push your thinking. In the Masterclass, we saw her use the <strong>“Scamper”</strong> method, the <strong>“Six Thinking Hats,”</strong> and <strong>“Improv’s Yes-And”</strong> to move beyond obvious ideas. Mary’s goal isn’t to give you an answer, but to coach the best ideas out of you.</p><p>The agents are there to do the heavy lifting, but you are still the director. When the Scrum Master breaks down your user stories, read them. Does the sequence make logical sense? Did it remember to include project setup?. If you don’t understand why the Architect agent picked a specific database or API structure, ask it!. The agents are programmed to be highly explanatory, so take advantage of them to learn and guide the project perfectly.</p><p><strong>The BMAD SDLC Handoff Protocol</strong></p><p>To maintain high-fidelity results, the BMAD Method enforces a strict chain of responsibility and specific artifact outputs:</p><ul><li><strong>Mary (The Analyst):</strong> Operates in two distinct phases. First, she facilitates <strong>Brainstorming</strong> using techniques like the <strong>5 W’s</strong> and <strong>6 Thinking Hats</strong>. Second, she performs <strong>Advanced Elicitation</strong> to refine those ideas into a comprehensive project-brief.md.</li><li><strong>The Product Manager (PM):</strong> Translates the brief into a <strong>sharded PRD</strong> (stored in the /prd directory), defining the MVP scope and identifying functional and non-functional requirements to prevent feature creep.</li><li><strong>The Architect:</strong> Establishes the technical foundation, outputting critical files such as tech-stack.md, source-tree.md, and data-models.md. This ensures type safety and cross-module consistency.</li><li><strong>The Scrum Master:</strong> Drafts granular developer stories in the /stories folder. <strong>Critical Governance Gate:</strong> The Scrum Master must move a story status from draft to approved before the Developer agent can initiate execution.</li></ul><p>Furthermore, <strong>“Party Mode”</strong> enables collaborative discovery by bringing multiple personas (e.g., Architect and Developer) into a single session. This eliminates the silos of traditional development, allowing for real-time architectural validation before implementation begins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bXx_oem85eeVAkLUmyQe7Q.png" /></figure><p>With the evolution into V6 — featuring Cross-Platform Agent Teams and full Dev Loop Automation — the framework continues to prove that AI development belongs to everyone. It is 100% free and open source, and it always will be.</p><p>The BMAD Method is designed for tactical deployment within modern IDEs (Claude Code, Cursor) and terminal-based workflows. It integrates with existing Git-based repositories, supporting both greenfield innovation and brownfield maintenance of legacy systems.</p><h3><strong>The “Zero-to-Code” Implementation Roadmap</strong></h3><ol><li><strong>Installation &amp; Environment Prep:</strong> Ensure <strong>Node.js v20+</strong> is installed, then execute npx bmad-method install. This scaffolds the agentic configurations and directory structures.</li><li><strong>The Ideation Loop:</strong> Engage <strong>Mary (The Analyst)</strong> for Advanced Elicitation to stress-test assumptions and uncover hidden architectural risks.</li><li><strong>The Sharding Execution:</strong> Use the shard command to split documentation by <strong>Level 2 headers</strong>, creating context-ready files for the agents.</li><li><strong>The Development &amp; QA Loop:</strong> Utilize the dev-load-always file as a <strong>System Prompt Extension</strong>. This ensures James (The Developer) is context-locked to the architecture. Finally, Quinn (The QA Agent) performs a compliance check against the sharded requirements.</li></ol><p>This modular workflow ensures the BMAD Method can be adapted to any project scale without sacrificing the rigor of a structured SDLC.</p><h3><strong>Quality Governance and Risk Mitigation</strong></h3><p>BMAD operates on a “trust but verify” philosophy. Agentic drift — the tendency for LLMs to hallucinate or deviate from established standards — is mitigated by <strong>Quinn (The QA Agent)</strong> and the Product Owner’s <strong>“Run Checklist”</strong> command. These serve as the final safeguards for architectural integrity.</p><p>To force the LLM beyond the “average” response bell curve, the framework utilizes <strong>Recursive Reasoning</strong> through Advanced Elicitation:</p><ul><li><strong>Hindsight 2020:</strong> Imagining a project failure to identify current architectural weaknesses.</li><li><strong>Red Team vs. Blue Team:</strong> Simulating a conflict between architectural choices to find the most robust path.</li></ul><p>These techniques act as a “cattle prod,” ensuring high-fidelity decisions. Looking forward, <strong>V6 optimizations</strong> will introduce <strong>Sub-Agent inclusion</strong> and <strong>Dev Loop Automation</strong>, further automating governance and moving toward a self-correcting development cycle.</p><h3><strong>Building More Architect Dreams</strong></h3><p>The shift from manual, fragmented “vibe coding” to a structured, persona-driven architecture represents the next evolution of Agile. By leveraging the BMAD Method, organizations can transform AI from a simple tool into a specialized team of expert collaborators, ensuring enterprise stability and predictable delivery.</p><p>The shift is clear: stop being the one who just watches the code scroll by. Start being the one who directs the intelligence.</p><p>If you could stop being the one who writes the code and start being the one who architects the dream, what would you build tomorrow?</p><h3>Get Started: The Checklist</h3><ul><li>✅ <strong>Audit Current AI Usage:</strong> Identify where “vibe coding” is creating technical debt or context pollution.</li><li>✅ <strong>Deploy the BMAD Core:</strong> Execute npx bmad-method install (Node.js v20+) to establish the agentic framework.</li><li>✅ <strong>Enforce Sharded Planning:</strong> Transition from monolithic PRDs to sharded, context-aligned files to maximize token-to-relevant-data ratios.</li><li>✅ <strong>Activate Advanced Elicitation:</strong> Use Mary (The Analyst) to stress-test the project-brief.md before technical commitment.</li><li>✅ <strong>Implement Governance Gates:</strong> Ensure the Scrum Master approved status is used and all code is validated by Quinn (The QA Agent).</li></ul><p>Visit the <a href="https://github.com/bmad-code-org/BMAD-METHOD">BMAD-METHOD GitHub repo</a> to check out the docs, and don’t forget to drop a star on the project to support the open-source development!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4739358c7502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Correcting RAG for Beginners]]></title>
            <link>https://medium.com/@faulknerproject/self-correcting-rag-for-beginners-805be73a0275?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/805be73a0275</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 23:04:55 GMT</pubDate>
            <atom:updated>2025-12-29T23:53:52.423Z</atom:updated>
            <content:encoded><![CDATA[<p>Trust is the currency of AI applications. You cannot afford to serve true-sounding lies to your users. By implementing structured, deterministic grading loops, you implement prod-ready AI solutions.</p><p><strong>Two Github resources:</strong></p><ul><li><a href="https://github.com/rosiefaulkner/corrective-rag-researcher-agent">Corrective RAG researcher agent</a>: An intelligent research assistant that generates high-quality, well-researched answers through self-reflection and iterative improvement. The agent critiques its own responses, identifies knowledge gaps, conducts web research, and refines its answers in an iterative loop.</li><li><a href="https://github.com/rosiefaulkner/langgraph-rag-agentic-pipeline">Self-correcting RAG pipeline</a>: Implementation of Reflective RAG, Self-RAG &amp; Adaptive RAG tailored for production-oriented applications that need to make intelligent decisions about retrieving information, grade document relevance and detect hallucinations and can switch between local knowledge and web search.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4HX8xn4YRo0UbTkC731uQ.png" /></figure><p>Building RAG (Retrieval-Augmented Generation) systems is easy. Building <em>reliable</em> RAG systems is another story.</p><p>If you’ve spent any time developing applications using GenAI, you know the one thing we try to detect, circumvent and avoid at all costs: Hallucinations (…and context window exceeded exception but I digress…). You pull the right docs, your prompt is “optimized”, but the model still decides to “enhance” reality with something far-fetched and sounding far too deterministic. In a demo, it’s a quirk; in production, it’s quite possibly a P0.</p><p>In this simple workflow, the AI’s answer goes directly to you without any safety check. The process looks like this:</p><pre>[Your Question] ---&gt; [Finds Documents] ---&gt; [Generates Answer] ---&gt; [You See It]</pre><p>This process works well when everything is perfect, but what happens when the AI gets a little too creative with its answer? The move from a “vibe-based” prototype to a production-grade agent requires more than just a better model. It requires a safety net.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2PicgZkA44Y2sy_jjJTiA.png" /></figure><h3>The High Costs of the Hallucination Trust Gap</h3><p>The issue with standard RAG is that its linear. We retrieve, generate and ship. Engineers are assuming the LLM will stay within the guardrails we’ve drawn with our context. Here’s the caveat: models are trained to be helpful but sometimes “helpful” means filling in gaps with training data that isn’t in your retrieved documents.</p><p>When an AI delivers a hallucination, it doesn’t just provide bad information; it breaks the user’s trust. In areas like customer support, finance, or healthcare, this can have serious consequences.</p><p>Let’s look at a real-world example. A customer asks about a product’s warranty. The AI finds the correct document, but then generates an answer with a critical error.</p><pre><br>+----------------------------------------+----------------------------------------+<br>|   The Fact (from the document)         |   The AI&#39;s Hallucinated Answer         |<br>+----------------------------------------+----------------------------------------+<br>|  &quot;Product X has a 2-year warranty.&quot;    |   &quot;Product X has a lifetime warranty.&quot; |                              <br>+----------------------------------------+----------------------------------------+</pre><p>In a business setting, this isn’t a small mistake and it may even be considered an unacceptable liability. This kind of error makes the use of AI dangerous to a business and its customers- increasing risk enough to deter a company from modernizing because hallucinations erode user trust.</p><p>To resolve, we need to give the AI a way to grade its own work. This is where a “Hallucination Grader” comes in.</p><h3>Implement A Factual Grounding Layer</h3><p>Here is a clean, production-ready implementation using LangChain and Google Gemini. This isn’t just a wrapper; it’s an automated unit test for your AI’s brain.</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.runnables import RunnableSequence<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from pydantic import BaseModel, Field<br><br>load_dotenv()<br><br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash-lite&quot;, temperature=0, google_api_key=os.getenv(&quot;GEMINI_API_KEY&quot;))<br><br># Define the Contract<br>class GradeHallucinations(BaseModel):<br>    &quot;&quot;&quot;Binary score for checking if a generation is supported by facts.&quot;&quot;&quot;<br>    binary_score: bool = Field(<br>        description=&quot;Answer is grounded in the facts/documents, &#39;yes&#39; or &#39;no&#39;&quot;<br>    )<br><br># Force structured output to eliminate &#39;chatty&#39; LLM responses and ensure downstream systems can ingest response<br>structured_llm_grader = llm.with_structured_output(GradeHallucinations)<br><br># The Grading Prompt<br>system_msg = &quot;&quot;&quot;You are a grader assessing whether an LLM generation is grounded in a set of retrieved facts. <br>Give a binary score &#39;yes&#39; or &#39;no&#39;. &#39;Yes&#39; means the answer is strictly supported by the provided facts.&quot;&quot;&quot;<br><br>hallucination_prompt = ChatPromptTemplate.from_messages([<br>    (&quot;system&quot;, system_msg),<br>    (&quot;human&quot;, &quot;Set of facts: \n\n {documents} \n\n LLM generation: {generation}&quot;),<br>])<br><br># The Execution Chain<br>hallucination_grader: RunnableSequence = hallucination_prompt | structured_llm_grader</pre><p>If you look at the implementation above, there are three core things happening:</p><ul><li>By using with_structured_output, we stop the LLM from explaining <em>why</em> it chose a grade. We get a clean True/False boolean that our code can actually use to branch logic. This is called Pydantic enforcement. It can&#39;t give a confusing &quot;maybe&quot; or a long explanation. This is achieved using a &quot;structured output&quot; guardrail using a defined Pydantic model, which forces the AI&#39;s response into a predictable, binary format.</li><li>Grading isn’t a creative task — it’s <em>purely </em>a logical one. The grader’s “creativity” is set to zero (temperature=0). This means it acts like a strict referee who calls every play by the book, using the exact same logic every single time. This makes its verdict <strong>deterministic</strong> and reliable.</li><li>Grading is a cognitive task, but it’s a <em>classification</em> task. Using a “Lite” model (like Gemini 2.5 Flash Lite) significantly reduces latency without sacrificing accuracy for this specific job. This is called ‘strategic tiering’.</li></ul><p>A Hallucination Grader a specialized AI component with one simple job: to check if the answer the main AI generated is fully supported by the facts it was given. It answers the question: Is the LLM’s response grounded in the documents?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38X1M4boAUHdvynppU6V7A.png" /></figure><h3>Real World Implementation</h3><p>In a real agentic workflow, a hallucination grader acts as a gatekeeper. If the binary_score is False, the system doesn&#39;t show the answer to the user. Instead, it can:</p><ol><li><strong>Re-attempt:</strong> Go back to the generation node with a “stay in the lines” warning.</li><li><strong>Re-retrieve:</strong> Maybe the documents were irrelevant. Go back and try a different search query.</li><li><strong>Abstain:</strong> Admit it doesn’t know, which is infinitely better than a confident lie.</li></ol><p>By treating LLM outputs as untrusted data <em>until verified</em>, you prevent much of the hallucinations you may have gotten without it, but it doesn’t resolve 100% of the problem.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FADrUp2cEdKg%3Fstart%3D1%26feature%3Doembed%26start%3D1&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DADrUp2cEdKg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FADrUp2cEdKg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0ebaf67cc2d8f5dbd7647e734d6c58f/href">https://medium.com/media/d0ebaf67cc2d8f5dbd7647e734d6c58f/href</a></iframe><h3>What’s a Hallucination Grader and Why Do I Need It?</h3><p>Here, we’ll walk through two different situations to see how the grader makes its decisions.</p><p><strong>Scenario A: The Grader Gives a Green Light</strong></p><p>• <strong>The Fact (the document the AI found in your vector database):</strong> “Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &amp; Informatica (CWI) in the Netherlands as a successor to the ABC programming language”.</p><p>• <strong>The AI’s Answer:</strong> “Python was created by Guido van Rossum in the Netherlands as a successor to ABC”.</p><p><strong>Grader’s Verdict:</strong> <strong>True</strong>.</p><p><strong>Why?</strong> The grader confirms that every claim — the creator (Guido van Rossum), the location (the Netherlands), and the predecessor language (ABC) — is <em>directly supported by the retrieved document.</em> Because the answer is 100% grounded in the provided facts, it passes the “unit test”.</p><p><strong>Scenario B: The Grader Says No</strong></p><p>This scenario demonstrates what happens when the AI includes information that, while potentially accurate in the real world, is missing from the specific source text.</p><p>• <strong>The Fact (the same document):</strong> “Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde &amp; Informatica (CWI) in the Netherlands as a successor to the ABC programming language”.</p><p>• <strong>The AI’s Answer:</strong> “Python was created by Guido van Rossum in 1991, and it was heavily inspired by Java syntax”.</p><p><strong>Grader’s Verdict:</strong> <strong>False</strong>.</p><p><strong>Why?</strong> The grader’s sole purpose is to verify grounding within the provided context. Even though “1991” is a historically correct date, it does not appear in the source document. Furthermore, the mention of “Java” is entirely absent from the text. The grader flags this as a hallucination because the AI used outside knowledge instead of relying exclusively on the trusted data source.</p><p>Think of the hallucination grader as a strict professor marking an open-book exam. Even if a student provides a “correct” answer based on what they learned elsewhere, the professor will fail them if the answer cannot be found on the specific pages of the textbook. This ensures the student (or the AI in our case) is only using the <em>approved materials</em> to reach their conclusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z0WPq-dR8WGqpBFtf0Sg1w.png" /><figcaption>The problem: The RAG trust gap</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BY0w-puozL9gmzi5MFsuqw.png" /><figcaption>The solution: a self-correcting RAG workflow</figcaption></figure><h3>Self-Correcting RAG</h3><p>By adding the grader, we transform the risky, straight-line process into a smart, self-correcting loop.</p><p>The Standard (Fragile) Flow was a one-way street: Question -&gt; Find -&gt; Answer -&gt; User.</p><p>The Self-Correcting Flow implements a checkpoint: if the LLM’s response is not grounded in the fact <em>you’ve defined</em>, regenerate.</p><pre>[Your Question]<br>      ↓<br>[AI Finds Documents]<br>      ↓<br>[AI Generates Initial Answer]<br>      ↓<br>[HALLUCINATION GRADER] → (Is it Grounded?) → [No: Hallucination Detected]<br>                                ↓                       ↓<br>                              [Yes]          [Retry or Fallback Answer]<br>                                ↓<br>                   [You See the Final, Vetted Answer]</pre><p>This loop is what makes the AI reliable. If the system generates a bad answer, the grader catches it. The system can then decide to try generating the answer again (perhaps with stricter instructions) or simply inform the user that it couldn’t find a supported answer in its documents. If we’re regenerating a hallucinated response, it’s wise to implement a <em>retry limit</em>. If the LLM’s response is detected to be a hallucination 3 times, display a fallback response to the user (e.g. “Something went wrong…”). The most important thing is that a <em>confident falsehood</em> <em>never reaches the user.</em></p><h3>What’s Next: The Answer Grader</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2c4xWVunVcQnhbhIomzwjA.png" /><figcaption>Photo credit: <a href="https://github.com/langchain-ai/langgraph/blob/main/examples/rag/langgraph_adaptive_rag.ipynb">LangChain</a></figcaption></figure><p>By building in a simple, automated grading step, the system gains the ability to check its own work. It teaches our over-eager student to pause, look back at the textbook, and ensure every claim is supported by facts before raising their hand. This self-correction mechanism is what elevates an AI from a fascinating experiment into a system worthy of a user’s confidence.</p><p>Next comes the need to check if the LLM’s response is grounded in the users question. Is the response relevant to their question? Does it fully answer their question? Is anything missing? What clarification is needed in order to bridge the gap?</p><p>A model can be perfectly grounded in facts but still fail to be helpful. For example, if a user asks “How do I reset my password?” and the model provides a perfectly factual history of password security without the reset steps, it has zero hallucinations but also zero relevance.</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.runnables import RunnableSequence<br>from langchain_google_genai import ChatGoogleGenerativeAI<br>from pydantic import BaseModel, Field<br><br>load_dotenv()<br><br>llm = ChatGoogleGenerativeAI(model=&quot;gemini-2.5-flash-lite&quot;, temperature=0, google_api_key=os.getenv(&quot;GEMINI_API_KEY&quot;))<br><br>class GradeAnswer(BaseModel):<br>    &quot;&quot;&quot;<br>    Binary score to check if the answer addresses the user&#39;s question.<br>    &quot;&quot;&quot;<br>    binary_score: bool = Field(<br>        description=&quot;Answer addresses the question, &#39;yes&#39; or &#39;no&#39;&quot;<br>    )<br><br>structured_llm_answer_grader = llm.with_structured_output(GradeAnswer)<br><br>system = &quot;&quot;&quot;You are a grader assessing whether an LLM generation addresses / answers a user question. \n <br>     Give a binary score &#39;yes&#39; or &#39;no&#39;. &#39;Yes&#39; means that the answer addresses the question.&quot;&quot;&quot;<br><br>answer_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, system),<br>        (&quot;human&quot;, &quot;User question: \n\n {question} \n\n LLM generation: {generation}&quot;),<br>    ]<br>)<br><br>answer_grader: RunnableSequence = answer_prompt | structured_llm_answer_grader</pre><h3>The Self-Correction Flow</h3><p>In a production LangGraph app, these checkpoints act as gates. You only present the answer to the user if the answer is grounded in the facts your RAG has defined <em>and</em> the response truly answers the user’s question. If the first gate (Groundedness) fails, you might re-retrieve; if the second gate (Answer Relevance) fails, you might rewrite the query.</p><ol><li><strong>Retrieve:</strong> Get documents from Chroma (or whatever vector store you’re using).</li><li><strong>Generate:</strong> Produce a candidate answer.</li><li><strong>Gate 1 (Hallucination Check):</strong> Is the answer grounded in the documents?<br>- <em>If No:</em> Re-run generation with a stricter temperature or different context.</li><li><strong>Gate 2 (Relevance Check):</strong> Does the answer actually address the user’s prompt?<br>- <em>If No:</em> This suggests the retrieved documents were factually correct but irrelevant. Trigger a <strong>Query Rewrite</strong> and try retrieval again.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FpbAd8O1Lvm4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DpbAd8O1Lvm4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FpbAd8O1Lvm4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f10584b65ea316adf82821d28ecfdfe/href">https://medium.com/media/6f10584b65ea316adf82821d28ecfdfe/href</a></iframe><p>From LangChain:</p><blockquote>Self-reflection can greatly enhance RAG, enabling correction of poor quality retrieval or generations. Several recent RAG papers focus on this theme, but implementing the ideas can be tricky. Here, we show that LangGraph can be easily used for “flow engineering” of self-reflective RAG pipelines. We provide cookbooks for implementing ideas from two interesting papers, Self-RAG and C-RAG.</blockquote><h3>Handling the “No” Logic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zx1yVt1WjhfBDF8HUTniqw.png" /><figcaption>Photo credit: <a href="https://github.com/langchain-ai/langgraph/blob/main/examples/rag/langgraph_adaptive_rag.ipynb">LangChain</a></figcaption></figure><p>When answer_grader returns False, it’s a signal that your retrieval step failed to find the right information, even if it found <em>some</em> information. This is where you would typically route the state to a transform_query node to refine the user&#39;s search terms, or execute a human in the loop flow that asks the user for further clarification.</p><p>While the hallucination grader ensures the model isn’t making things up, the answer grader ensures the model is actually staying on topic and answering the user’s specific intent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=805be73a0275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Engineering: Managing Agent State]]></title>
            <link>https://medium.com/@faulknerproject/context-engineering-managing-agent-state-a416f53424ca?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/a416f53424ca</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 22:00:47 GMT</pubDate>
            <atom:updated>2025-11-28T22:00:47.905Z</atom:updated>
            <content:encoded><![CDATA[<h4>The biggest mistake engineers make when using LangGraph is treating the State like a simple dictionary. It’s not. It’s your application’s short-term memory, and if you don&#39;t garbage collect it, it <em>will</em> crash your application. Remember: “hope” isn’t a scalable architectural pattern. We need to move from Prompt Engineering to Context Engineering.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmE7lOCDRKjykzKPYySP4A.png" /></figure><p>If you are a software engineer building Agentic AI, you have likely realized that “Prompt Engineering” is a misnomer. Prompt engineering implies a static, one-time optimization of a string. But agents don’t live in static strings; they live in loops. They operate in a continuous, mutating state of information.</p><p>We are leaving the era of “Chains”, or stateless DAGs, and entering the era of Context Engineering.</p><p>In LangGraph, the StateGraph replaces the opaque AgentExecutor, exposing the internal decision loop as a mutable state object. This post is a rigorous engineering analysis of the primitives you need to control that state: MessagesPlaceholder for input hydration, trim_messages for compression, and PydanticToolsParser for deterministic, self-correcting actions.</p><p>We will build three architectural patterns: Compress, Select, and Plan . These aim yo fix common production pitfalls like “Infinite Context” crashes, brittle parsing, and unoptimized resource connections.</p><h3>The Input Layer: Hydrating and Compressing State</h3><p>The bridge between your structured application state (e.g., a TypedDict) and the unstructured LLM context window is the ChatPromptTemplate.</p><p><strong>ChatPromptTemplate and </strong><strong>MessagesPlaceholder</strong></p><p>Your agent’s cognitive scaffolding is defined here. Unlike f-string injection, MessagesPlaceholder is critical because it preserves the <em>semantic structure</em> of the conversation. It treats SystemMessage, HumanMessage, AIMessage, and ToolMessage as distinct objects, not a flattened text blob. This is essential for the model to distinguish between its own reasoning and external tool outputs.</p><pre>from datetime import datetime<br>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br><br># Define the invariant structure also known as the the &quot;Kernel&quot; of your agent<br>actor_prompt = ChatPromptTemplate.from_messages()<br><br># Production pattern used here is partial Binding for Runtime Constants<br># We bind &#39;time&#39; now so we don&#39;t have to pass it through every node later.<br>runnable_prompt = actor_prompt.partial(<br>    time=datetime.now().isoformat()<br>)</pre><h3>The “Compress” Strategy: Implementing a Sliding Window</h3><p><strong>The Pitfall:</strong> A naive implementation just appends messages forever. Eventually, you hit the model’s context limit (e.g., 128k tokens) or, more likely, your latency and cost explode.</p><p>To resolve,<strong> </strong>you cannot simply slice the list messages[-10:]. If you slice in the middle of a ToolCall and its corresponding ToolMessage (the result), the model sees a &quot;dangling&quot; result for a tool it doesn&#39;t remember calling. This causes hallucinations.</p><p>We must use Context Compression via a dedicated trim_messages node that respects tool boundaries.</p><pre>from langchain_core.messages import trim_messages, BaseMessage<br>from langgraph.graph import StateGraph, START, END<br>from typing import TypedDict, Annotated<br>from langgraph.graph.message import add_messages<br><br>class AgentState(TypedDict):<br>    # &#39;add_messages&#39; ensures new messages append to history<br>    history: Annotated, add_messages] <br>    input: str<br><br>def context_compressor_node(state: AgentState):<br>    &quot;&quot;&quot;<br>    Implements the &#39;Compress&#39; strategy.<br>    Trims history to ~3000 tokens but guarantees we never <br>    break a ToolCall/ToolMessage pair.<br>    &quot;&quot;&quot;<br>    raw_history = state[&quot;history&quot;]<br>    <br>    # trim_messages is smarter than list slicing<br>    trimmed = trim_messages(<br>        raw_history,<br>        max_tokens=3000,<br>        strategy=&quot;last&quot;,<br>        token_counter=len, # In prod, use: model.get_num_tokens_from_messages<br>        include_system=True, # Always keep the system prompt<br>        start_on=&quot;human&quot;,    # Ensure conversation starts with a user query<br>        end_on=(&quot;human&quot;, &quot;tool&quot;) # Don&#39;t cut off after an AI thought<br>    )<br>    <br>    # We return the NEW trimmed list. <br>    # NOTE: In LangGraph, to overwrite &#39;add_messages&#39; fields, <br>    # typically you might need to use a separate &#39;overwrite&#39; channel <br>    # or explicit RemoveMessage logic, but for simple sliding windows,<br>    # re-injecting the trimmed list is the pattern.<br>    return {&quot;history&quot;: trimmed}</pre><p>By placing this node <em>before</em> your model execution node, you guarantee the context window stays bounded and semantically valid.</p><h3>The Output Layer: Deterministic Action &amp; Self-Correction</h3><p>Once the model generates a tool_call, we leave the probabilistic world of LLMs and enter the deterministic world of software. We need to parse that call.</p><p><strong>PydanticToolsParser vs. </strong><strong>JsonOutputToolsParser</strong></p><ul><li><strong>JsonOutputToolsParser</strong>: Returns a raw dict. Good for streaming to a UI because it yields partial JSON as it arrives.</li><li><strong>PydanticToolsParser</strong>: Returns a validated Pydantic object. This is &quot;Blocking&quot; (waits for full JSON), but it guarantees type safety.</li></ul><p><strong><em>There exists an engineering tradeoff here.</em></strong>Use JsonOutputToolsParser for the frontend (fast UI feedback) and PydanticToolsParser for the backend (logic safety).</p><h3>Implementing the Self-Correction Loop</h3><p><strong>The Pitfall:</strong> Most tutorials show try/except blocks that print the error. In an autonomous agent, <strong>printing an error does nothing.</strong> The agent needs to <em>see</em> the error to fix it.</p><p>We must catch the ValidationError, format it as a ToolMessage with is_error=True, and feed it back into the graph. This triggers the model&#39;s internal &quot;System 2&quot; reasoning to retry with corrected arguments.</p><pre>from langchain_core.output_parsers.openai_tools import PydanticToolsParser<br>from langchain_core.messages import ToolMessage, AIMessage<br>from pydantic import BaseModel, Field, ValidationError<br><br>class DatabaseQuery(BaseModel):<br>    # Schema enforcement: &#39;limit&#39; must be &lt;= 10<br>    query: str<br>    limit: int = Field(..., le=10, description=&quot;Max 10 records allowed&quot;)<br><br>def tool_execution_node(state: AgentState):<br>    last_message = state[&quot;history&quot;][-1]<br>    <br>    # Ensure the last message actually has tool calls<br>    if not isinstance(last_message, AIMessage) or not last_message.tool_calls:<br>        return {&quot;history&quot;:}<br><br>    tool_call = last_message.tool_calls<br>    tool_call_id = tool_call[&#39;id&#39;]<br>    <br>    # Initialize strict parser<br>    parser = PydanticToolsParser(tools=)<br>    <br>    try:<br>        # 1. Attempt Validation<br>        # Pydantic will throw if &#39;limit&#39; &gt; 10 or types are wrong<br>        # We wrap the single message in a list because the parser expects a list-like input<br>        parsed_output = parser.invoke([last_message]) <br>        <br>        # 2. Execute Logic (Simulated)<br>        # Only runs if validation passes<br>        result_content = f&quot;Query &#39;{parsed_output.query}&#39; executed with limit {parsed_output.limit}&quot;<br>        <br>        return {&quot;history&quot;:}<br><br>    except ValidationError as e:<br>        # 3. The Self-Correction Mechanism<br>        # We convert the Python exception into a structured message for the LLM<br>        error_payload = (<br>            f&quot;Validation Error in tool arguments:\n&quot;<br>            f&quot;{str(e)}\n&quot;<br>            &quot;Please fix the arguments and retry.&quot;<br>        )<br>        <br>        # is_error=True signals LangGraph/LangSmith that this step failed<br>        # The LLM sees this in the history and will attempt to fix &#39;limit&#39; in the next turn<br>        return {&quot;history&quot;:}</pre><p>This effectively turns Python runtime errors into constructive prompts.</p><h3>When LLM Response Parsing Fails</h3><p>Standard tutorials show you how to parse output. They rarely show you what to do when parsing <em>fails</em>. If an agent generates invalid arguments (e.g., a string for an integer field), crashing the app is unacceptable.</p><p>We must catch the error and feed it <em>back</em> to the agent. This forces the LLM to perform “Reflexion” on its own error and retry.</p><p><strong>The Pattern:</strong></p><ol><li>Define the Tool Schema (Pydantic).</li><li>Bind tool to Model.</li><li>Parse output.</li><li>Catch ValidationError → Convert to ToolMessage(is_error=True).</li></ol><pre>from langchain_core.output_parsers.openai_tools import PydanticToolsParser<br>from langchain_core.messages import ToolMessage, AIMessage<br>from pydantic import BaseModel, Field, ValidationError<br><br># 1. Define strict schema<br>class SearchQuery(BaseModel):<br>    query: str<br>    year: int = Field(..., description=&quot;Year must be an integer, e.g., 2024&quot;)<br><br># 2. The Node Logic<br>def tool_execution_node(state: AgentState):<br>    last_message = state[&quot;messages&quot;][-1]<br>    <br>    # Guard clause: ensure we actually have tool calls<br>    if not isinstance(last_message, AIMessage) or not last_message.tool_calls:<br>        return {&quot;messages&quot;:}<br><br>    # We use PydanticToolsParser for strict validation<br>    parser = PydanticToolsParser(tools=)<br>    <br>    try:<br>        # ATTEMPT VALIDATION<br>        # This will raise ValidationError if the LLM output &quot;year&quot;: &quot;twenty-twenty-four&quot;<br>        tool_calls = parser.invoke(last_message)<br>        <br>        # If successful, execute the logic (Mocked here)<br>        results =<br>        for call in last_message.tool_calls:<br>            # Execute actual search logic here...<br>            results.append(<br>                ToolMessage(tool_call_id=call[&#39;id&#39;], content=f&quot;Search results for {call[&#39;args&#39;]}&quot;)<br>            )<br>        return {&quot;messages&quot;: results}<br><br>    except ValidationError as e:<br>        # THE SELF-CORRECTION MECHANISM<br>        # We assume the last message had the bad tool call.<br>        # We create a ToolMessage that signals failure.<br>        <br>        # Note: We need the tool_call_id to link the error to the request.<br>        # We extract it safely from the raw message.<br>        bad_call_id = last_message.tool_calls[&#39;id&#39;]<br>        <br>        error_message = ToolMessage(<br>            tool_call_id=bad_call_id,<br>            content=f&quot;Validation Error: {str(e)}. Please correct the arguments and retry.&quot;,<br>            is_error=True, # Flags this as an error to the model<br>            name=&quot;SearchQuery&quot;<br>        )<br>        <br>        # Returning this message updates the state. <br>        # The graph will loop back to the model, which sees the error and retries.<br>        return {&quot;messages&quot;: [error_message]}</pre><p>This pattern turns a runtime exception into a constructive prompt, closing the autonomous loop.</p><h3>Pattern 1: The “Select” Strategy (RAG with Dependency Injection)</h3><p>Initializing a vector store (like FAISS) inside a node is a performance killer. It re-loads the index into RAM on every single execution step.</p><p>To solve for this, use Dependency Injection. Initialize the heavy resource <em>once</em> at the application startup and pass it into the graph via the configurable config dictionary. This keeps your graph nodes pure and your application efficient.</p><pre># app.py (Initialization Layer)<br>from langchain_community.vectorstores import FAISS<br>from langchain_openai import OpenAIEmbeddings<br><br># 1. Heavy Initialization happens ONCE<br>embeddings = OpenAIEmbeddings()<br># Assume &#39;index&#39; is loaded from disk<br>vector_store = FAISS.load_local(&quot;faiss_index&quot;, embeddings, allow_dangerous_deserialization=True) <br>retriever = vector_store.as_retriever()<br><br># 2. The Node Logic (Lightweight)<br>def retrieval_node(state: AgentState, config: dict):<br>    &quot;&quot;&quot;<br>    Extracts the retriever from the config. <br>    Does NOT instantiate the DB.<br>    &quot;&quot;&quot;<br>    # Dependency Injection pattern<br>    store = config[&quot;configurable&quot;][&quot;retriever_resource&quot;]<br>    <br>    last_user_msg = state[&quot;history&quot;][-1].content<br>    docs = store.invoke(last_user_msg)<br>    <br>    # Format docs for the context window<br>    context_str = &quot;\n&quot;.join([d.page_content for d in docs])<br>    <br>    return {<br>        &quot;history&quot;:<br>    }<br><br># 3. Graph Compilation<br>workflow = StateGraph(AgentState)<br>workflow.add_node(&quot;retrieve&quot;, retrieval_node)<br>#... add edges...<br>app = workflow.compile()<br><br># 4. Runtime Execution<br># We pass the heavy object via &#39;configurable&#39;<br>app.invoke(<br>    {&quot;history&quot;: [(&quot;human&quot;, &quot;How do I use Pydantic?&quot;)]},<br>    config={&quot;configurable&quot;: {&quot;retriever_resource&quot;: retriever}}<br>)</pre><p>This pattern decouples your <em>Data Infrastructure</em> from your <em>Agent Logic</em>, a requirement for any scalable system.</p><p>In many tutorials, you see vectorstore = FAISS.from_documents(...) <em>inside</em> the graph node. This is <em>catastrophic</em> for production. It means you are reloading your index into RAM every single time the agent takes a step.</p><p>We resolve this with<strong> </strong>dependency injection via configurable. We load the heavy resources (Database connections, Vector Stores) <em>once</em> at startup and pass them into the graph at runtime.</p><pre># app_setup.py (Run this once)<br>from langchain_community.vectorstores import FAISS<br>from langchain_openai import OpenAIEmbeddings<br><br># Initialize Heavy Resources ONCE<br>embeddings = OpenAIEmbeddings()<br># Assume we load a pre-built index from disk<br>vector_store = FAISS.load_local(&quot;faiss_index_folder&quot;, embeddings, allow_dangerous_deserialization=True)<br>retriever = vector_store.as_retriever()<br><br># --- Inside your LangGraph Definition ---<br><br>def retrieval_node(state: AgentState, config: dict):<br>    &quot;&quot;&quot;<br>    RAG Node that uses the &#39;Select&#39; strategy.<br>    It retrieves context but DOES NOT instantiate the DB.<br>    &quot;&quot;&quot;<br>    # 1. Dependency Injection<br>    # We fetch the retriever from the runtime config<br>    retriever_svc = config[&quot;configurable&quot;][&quot;retriever_service&quot;]<br>    <br>    last_user_msg = state[&quot;messages&quot;][-1].content<br>    <br>    # 2. Execution<br>    docs = retriever_svc.invoke(last_user_msg)<br>    <br>    # 3. Format for Context Injection<br>    # We perform the &#39;Select&#39; strategy here, only returning the text chunks<br>    context_str = &quot;\n&quot;.join([d.page_content for d in docs])<br>    <br>    # Return as a ToolMessage or SystemMessage depending on your architecture<br>    return {<br>        &quot;messages&quot;:[-1].tool_calls[&#39;id&#39;],<br>                content=f&quot;Retrieved Context:\n{context_str}&quot;<br>            )<br>        ]<br>    }<br><br># --- Runtime Execution ---<br># When we invoke the graph, we inject the dependency<br># app.invoke(inputs, config={&quot;configurable&quot;: {&quot;retriever_service&quot;: retriever}})</pre><p>This adheres to the <strong>Select</strong> strategy: we selectively retrieve data and inject it, keeping the State object purely serializable (strings/dicts) while keeping the heavy logic in the config.</p><h3>Pattern 2: The “Plan” Strategy (ReWOO with Robust Parsing)</h3><p>ReWOO (Reasoning WithOut Observation) decouples planning from execution. The Planner generates a blueprint with variables (#E1, #E2), and the Executor fills them in.</p><p>ReWOO is an advanced pattern where the planner generates a blueprint with variables (e.g., #E1), and the executor fills them in.</p><p>Most implementations use fragile regex that breaks if the LLM adds a space or a newline. Below is a robust parser for the planner output Plan:... #E1 = Tool[args].</p><p>If the LLM output Plan: Step 1..., a strict regex failed. Below is a robust parser that handles the variable assignment syntax and performs the actual substitution logic, which is the hardest part of ReWOO.</p><h3>Pattern 3: The Reflexion Loop</h3><p>Reflexion is a pattern where the agent acts as its own critic. It generates a draft, critiques it, and generates a revised version.</p><p>We use PydanticToolsParser to force the critique into a structured format. This is vital because we want to programmatically check if the critique passed or failed (e.g., score &gt; 7).</p><pre>from typing import Literal<br>from langgraph.graph import StateGraph, END<br><br># 1. The Structure of Critique<br>class Critique(BaseModel):<br>    missing_info: str = Field(..., description=&quot;What is missing?&quot;)<br>    score: int = Field(..., description=&quot;Quality score 1-10&quot;)<br>    recommendations: str<br><br>def reflection_node(state: AgentState):<br>    messages = state[&quot;messages&quot;]<br>    # We create a specialized chain just for critique<br>    # It uses the actor_prompt_template we defined earlier<br>    critique_chain = (<br>        actor_prompt_template <br><br>| llm.bind_tools([Critique], tool_choice=&quot;Critique&quot;) <br>| PydanticToolsParser(tools=[Critique])<br>    )<br>    <br>    # Generate structured critique<br>    try:<br>        critique_result = critique_chain.invoke(state) # state matches prompt keys<br>        # We append the critique as an AIMessage to history so the model &#39;remembers&#39; it<br>        # for the next revision step<br>        return {<br>            &quot;messages&quot;: [<br>                AIMessage(content=f&quot;Critique: {critique_result.recommendations}. Score: {critique_result.score}&quot;)<br>            ]<br>        }<br>    except Exception as e:<br>        return {&quot;messages&quot;: [AIMessage(content=&quot;Failed to generate critique.&quot;)]}<br><br>def should_continue(state: AgentState) -&gt; Literal[&quot;revise&quot;, &quot;end&quot;]:<br>    &quot;&quot;&quot;Conditional Edge Logic&quot;&quot;&quot;<br>    last_msg = state[&quot;messages&quot;][-1]<br>    <br>    # Simple heuristic: Check if the last message contains a high score<br>    # In a real app, you&#39;d store the &#39;score&#39; in a separate state key.<br>    if &quot;Score: 10&quot; in last_msg.content:<br>        return &quot;end&quot;<br>    <br>    # Stop infinite loops<br>    if len(state[&quot;messages&quot;]) &gt; 6: <br>        return &quot;end&quot;<br>        <br>    return &quot;revise&quot;</pre><h3>What’s a Plan Parser?</h3><p>According to OpenAI’s <a href="https://openai.com/index/introducing-structured-outputs-in-the-api/">post “Introducing Structured Outputs in the API”</a>:</p><blockquote>Last year at DevDay, we introduced JSON mode — a useful building block for developers looking to build reliable applications with our models. While JSON mode improves model reliability for generating valid JSON outputs, it does not guarantee that the model’s response will conform to a particular schema. Today we’re introducing Structured Outputs in the API, a new feature designed to ensure model-generated outputs will exactly match JSON Schemas provided by developers.</blockquote><p>In agentic pipelines like our example, we need to parse lines like: Plan: Search for X #E1 = Google[X].</p><pre>import re<br><br>def parse_rewoo_plan(plan_string: str):<br>    &quot;&quot;&quot;<br>    Robust regex to capture:<br>    1. The descriptive plan text (optional)<br>    2. The Variable ID (#E1, #E2)<br>    3. The Tool Name<br>    4. The Tool Arguments (inside brackets)<br>    &quot;&quot;&quot;<br>    # Regex Breakdown:<br>    # (.*?): Non-greedy match for the plan description<br>    # (#E\d+): Capture the variable ID (e.g., #E1)<br>    # \s*=\s*: Matches the equals sign with optional whitespace<br>    # (\w+): Capture the Tool Name (e.g., Google)<br>    # \[(.*)\]: Capture everything inside the brackets as arguments<br>    pattern = re.compile(r&quot;(.*?)(#E\d+)\s*=\s*(\w+)\[(.*)\]&quot;)<br>    <br>    steps =<br>    for line in plan_string.split(&quot;\n&quot;):<br>        match = pattern.search(line)<br>        if match:<br>            steps.append({<br>                &quot;description&quot;: match.group(1).strip(),<br>                &quot;var_name&quot;: match.group(2),<br>                &quot;tool_name&quot;: match.group(3),<br>                &quot;tool_args&quot;: match.group(4)<br>            })<br>    return steps</pre><h3>The Variable Substitution Loop</h3><p>This is the engine of ReWOO. We iterate through the parsed steps, executing tools and — crucially — swapping #E tokens in future arguments with actual results.</p><pre>def execution_node(state):<br>    &quot;&quot;&quot;<br>    Executes the plan and handles variable substitution.<br>    &quot;&quot;&quot;<br>    plan_steps = state[&quot;plan_steps&quot;] # List of dicts from parser above<br>    results = {} # The &quot;Scratchpad&quot; memory: {&#39;#E1&#39;: &#39;Search Result...&#39;}<br>    <br>    for step in plan_steps:<br>        tool_name = step[&quot;tool_name&quot;]<br>        raw_args = step[&quot;tool_args&quot;]<br>        <br>        # --- VARIABLE SUBSTITUTION LOGIC ---<br>        # Look for any #E variable in the arguments<br>        # e.g., &quot;Summarize #E1&quot; -&gt; &quot;Summarize &#39;Search Result...&#39;&quot;<br>        for var_name, var_value in results.items():<br>            if var_name in raw_args:<br>                raw_args = raw_args.replace(var_name, str(var_value))<br>        <br>        # Execute the tool (Mocked for brevity)<br>        # In prod, you&#39;d lookup tool_name in a dictionary of functions<br>        print(f&quot;Executing {tool_name} with args: {raw_args}&quot;)<br>        <br>        # Simulate execution result<br>        observation = f&quot;Result of {tool_name}({raw_args})&quot;<br>        <br>        # Store result in the scratchpad for future substitution<br>        results[step[&quot;var_name&quot;]] = observation<br>        <br>    return {&quot;results&quot;: results}</pre><p>This code explicitly implements the substitution logic often glossed over in tutorials. It ensures that step #3 can actually use the data from step #1.</p><h3>Architectural Critique: The Cost of State</h3><p>While LangGraph gives us control, it introduces significant engineering friction.</p><p><strong>The Serialization Bottleneck</strong></p><p>LangGraph relies on checkpointers (usually Postgres or Redis) to save state between steps.</p><ul><li>Our problem is that Pydantic v2 models, generic types, and complex objects (like open DB connections) often fail to serialize with standard pickling. You might see AttributeError: Can&#39;t pickle local object.</li><li>To resolve this, keep your State object purely primitive (dicts, lists, strings). Never store a client object or a socket in the graph state. Use the Dependency Injection pattern shown in Section 3 to pass these runtime objects via config [].</li></ul><h3><strong>Debugging Async Complexity</strong></h3><p>ReWOO and other parallel architectures run asynchronously.</p><ul><li>Our problem here is that standard Python debuggers (pdb) struggle with asyncio.gather inside a graph traversal. Stack traces often point to the graph engine internals rather than your node logic.</li><li>To resolve, you effectively <em>must</em> use a tracing tool (like LangSmith) or structured logging that emits a correlation ID for every node entry/exit. “Print debugging” is dead in graph architectures.</li></ul><h3>The Good, The Bad, and The Serialized</h3><p>The summarization strategy compresses older history into a single narrative summary, preserving semantic meaning while discarding the raw dialogue tokens.</p><h3><strong>Action</strong></h3><p>A conditional edge checks if the message count exceeds a threshold (e.g., &gt; 6 messages).</p><ul><li>If triggered, the flow routes to a “Summarize Node” where an LLM generates a synopsis of the conversation so far.</li><li>The node returns a state update that appends the new summary and deletes the old messages using RemoveMessage.</li></ul><h3><strong>Result</strong></h3><p>The delete_messages logic typically uses RemoveMessage(id=msg.id) or the special REMOVE_ALL_MESSAGES constant to explicitly purge the list in the Annotated[list, add_messages] reducer.</p><p><strong>State Update:</strong> The delete_messages logic typically uses RemoveMessage(id=msg.id) or the special REMOVE_ALL_MESSAGES constant to explicitly purge the list in the Annotated[list, add_messages] reducer.</p><p>According to Langgraph’s <a href="https://docs.langchain.com/oss/python/langchain/middleware/built-in#summarization">documentation on its built-in Summarization middleware</a>:</p><blockquote>Automatically summarize conversation history when approaching token limits, preserving recent messages while compressing older context. Summarization is useful for the following:</blockquote><blockquote>- Long-running conversations that exceed context windows.</blockquote><blockquote>- Multi-turn dialogues with extensive history.</blockquote><blockquote>- Applications where preserving full conversation context matters.</blockquote><h3>3. Context Selection (Filtering)</h3><p>Instead of reducing the history <em>after</em> it accumulates, this strategy prevents irrelevant information from entering the context window in the first place (The “Select” Strategy).</p><h3>Action</h3><p>Before calling the model, a specific node filters the state. For example, if the user asks a question about “SQL,” the node might filter the tool_outputs list to only include schema definitions, excluding irrelevant logs from previous &quot;Web Search&quot; tool calls.</p><h3>Result</h3><p>This is often done by creating a custom function that formats the prompt, selecting only specific message types (e.g., HumanMessage and AIMessage) and excluding bulky ToolMessage artifacts unless they are immediately relevant.</p><h3>4. Offloading (The “Write” Strategy)</h3><p>This involves moving information out of the active graph state (Short-term Memory) and into a database or vector store (Long-term Memory).</p><h3>Action</h3><p>When the conversation graph finishes a turn, a “Memory Node” writes key facts to a vector store (like FAISS or Pinecone).</p><h3>Result</h3><p>In future turns, instead of loading the entire history, the agent uses a Retriever to fetch only the top-k relevant facts based on the current query. This essentially compresses the user&#39;s entire history into a few relevant paragraphs.</p><h3>Latency Overhead</h3><p>For a simple “Retrieve and Generate” app, LangGraph is overkill. The overhead of state validation, graph traversal, and checkpointing adds latency (sometimes 200–500ms per step) compared to a raw OpenAI API call. Use LangGraph only when you need <strong>Loops</strong> (retries, feedback) or <strong>Persistence</strong> (human-in-the-loop).</p><h3>What I left out from this post:</h3><ol><li><strong>Pydantic Parser Blocking:</strong> I recommended PydanticToolsParser for backend logic, but I didn&#39;t fully solve the streaming latency issue. In a real app, users want to see the tool arguments appearing in real-time. The hybrid approach (stream JSON for UI, validate Pydantic for logic) creates code duplication that is hard to maintain.</li><li><strong>Missing “Isolate” Implementation:</strong> While I mentioned the “Isolate” strategy (Subgraphs), I didn’t provide a code snippet for it due to not wanting to veer off too far from the main idea of the article. Managing state schema mapping between a Parent Graph and a Subgraph is one of the hardest parts of LangGraph (e.g., mapping parent_state[&quot;query&quot;] to child_state[&quot;input&quot;]), and it deserves its own dedicated post.</li><li><strong>ReWOO Regex is Still Fragile:</strong> While I improved the regex to capture #E variables, regex parsing of LLM output is inherently risky. If the LLM decides to wrap the output in Markdown (**#E1**) or change the spacing, the regex r&quot;(.*?)(#E\d+)...&quot; might fail. A truly robust production system might force the LLM to output JSON (e.g., [{&quot;id&quot;: &quot;#E1&quot;, &quot;tool&quot;: &quot;Google&quot;, &quot;args&quot;: &quot;...&quot;}]) using with_structured_output rather than parsing raw text.</li></ol><h3>Further Reading</h3><ul><li><a href="https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-manage-message-history/">How to manage conversation history in a ReAct Agent</a></li><li><a href="https://community.latenode.com/t/current-limitations-of-langchain-and-langgraph-frameworks-in-2025/30994">Current limitations of LangChain and LangGraph frameworks in 2025</a></li><li><a href="https://www.ibm.com/think/topics/directed-acyclic-graph">What is Directed Acyclic Graph (DAG)</a></li><li><a href="https://github.com/langchain-ai/langgraph/issues/2938">JsonOutputToolsParser and PydanticToolsParser fails while used with Groq And Llama in Langgraph</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a416f53424ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Code to Cloud: How Fullstack Engineers Are the New DevOps]]></title>
            <link>https://medium.com/@faulknerproject/from-code-to-cloud-how-fullstack-engineers-are-the-new-devops-e1ff1fa13e03?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ff1fa13e03</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 20:00:00 GMT</pubDate>
            <atom:updated>2025-11-27T20:09:54.024Z</atom:updated>
            <content:encoded><![CDATA[<h4>In the modern era of software development, being a fullstack engineer no longer means just writing backend APIs and frontend interfaces. The role increasingly overlaps with what used to be considered pure DevOps responsibilities — managing infrastructure, ensuring reliability, automating deployments, and even thinking about security and cost optimization.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKiP3XJn99EbFL0eolTFKQ.png" /><figcaption>Interviews reflect the shift that consolidates DevOps and software engineering. Modern fullstack engineers are expected to discuss CI/CD pipelines, blue-green vs. canary deployments, Terraform and Ansible for infrastructure as code, and even troubleshooting failing load balancers using logs and metrics. Knowledge of serverless vs. traditional servers, AWS services (Lambda, API Gateway, S3), monitoring stacks (Prometheus, Grafana, Splunk), automation scripts, and basic security practices are increasingly table stakes.</figcaption></figure><p>The title “fullstack engineer” has long been a staple in our industry, typically bringing to mind a developer who can write a backend API and build a frontend interface to consume it. For years, that definition held up. You wrote the code, and a separate operations team was responsible for deploying and running it.</p><p>That era is over. The neat line between development and operations has dissolved, and the boundaries of the fullstack role have expanded dramatically. If you’re building applications today, your job doesn’t end when the code is pushed. In fact, that’s where the most critical part of your modern skill set begins.</p><h3>DevOps Isn’t Someone Else’s Job Anymore</h3><p>The modern fullstack role now encompasses a wide range of responsibilities that were once the exclusive domain of operations. This includes managing infrastructure, automating deployments, ensuring reliability, and even considering security and cost optimization from the outset. In today’s landscape of leaner platform teams, a single operations-focused engineer might support hundreds of developers, making the old “yaml-only” DevOps specialist a relic of a bygone era.</p><p>This isn’t just about adding tasks; it’s about shifting from a “code-first” to a “system-first” mindset. Engineers who internalize operational constraints don’t just write better code — they architect for profitability, prevent outages, and reduce the total cost of ownership before a single line of code is deployed.</p><h3>Your Impact is Measured in Operations, Not Just Lines of Code</h3><p>To understand your value as a modern engineer, you have to reframe operational work as direct software engineering impact. Consider a Senior DevOps Engineer whose resume was transformed to reflect this new reality due to the decline of Ops positions industry-wide. Her deep operational expertise in deployment pipelines and infrastructure automation was translated into measurable engineering outcomes.</p><p>The results weren’t just a list of duties but a catalog of achievements:</p><p>• <strong>Reduced deployment time from 45 minutes to 5 minutes</strong> by re-architecting the CI/CD pipeline.</p><p>• <strong>Cut production rollback incidents by 90%</strong> by implementing automated canary deployments.</p><p>• <strong>Lowered monthly cloud spend by 30%</strong> through infrastructure-as-code-driven instance right-sizing.</p><p>This reframing is a crucial mental model for any engineer looking to prove their worth in today’s market. Paraphrased from a <a href="https://aws.amazon.com/blogs/machine-learning/claude-code-deployment-patterns-and-best-practices-with-amazon-bedrock/">blog published by AWS</a>:</p><blockquote>“Metrics like deployment time saved, error reductions, and cost optimizations became proof of coding-driven impact rather than just process management.”</blockquote><p>Modern fullstack engineering requires bridging the gap between code and operations. Delivering end-to-end features, which includes automating deployments, is now tied to ensuring security and reliability at scale. Therefore, successful deployment automation should be measured by its contribution to these large-scale system objectives.</p><p>Engineers should translate operational duties, such as deployment automation, into measurable engineering outcomes by distilling these duties into quantifiable results that demonstrate software-engineering impact.</p><p>This process involves reframing traditional operational work as fullstack development accomplishments. Instead of merely viewing these duties as process management, the impact must be proven through coding-driven results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*697xgNnyvg_tQl96JFlXSQ.png" /><figcaption>Ultimately, fullstack software engineering today is about bridging the gap between code and operations. Delivering end-to-end features now includes architecting scalable systems, instrumenting them for observability, automating deployments, and ensuring security and reliability at scale. The engineers who master both development and operations are the ones shaping the next generation of robust, high-performing applications.</figcaption></figure><h3>The Interview Loop Has Moved Beyond Algorithms</h3><p>Unsurprisingly, technical interview expectations for fullstack engineers have evolved to reflect these new responsibilities. While algorithms and data structures are still important, they are no longer sufficient. Candidates are now expected to discuss the entire delivery pipeline with confidence.</p><p>Be prepared to field questions on CI/CD pipelines, the trade-offs between blue-green vs. canary deployments, Infrastructure as Code using tools like Terraform and Ansible, troubleshooting failing load balancers using logs and metrics, automation scripts, and core cloud services such as AWS Lambda, API Gateway, and S3. A working knowledge of modern monitoring stacks like Prometheus, Grafana, and Splunk, along with basic security practices, are increasingly becoming table stakes. Furthermore, recent security-focused credentials and hands-on experience in regulated industries (HIPAA, PCI) now provide a measurable advantage that traditional certifications alone may not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JoJB2yMJ2pM4OsRsQwrrnQ.png" /><figcaption>The expanded operational duties of modern fullstack engineering reflect a shift where the role bridges the gap between traditional development and operations. This means fullstack engineers are expected to take on responsibilities that were previously considered pure DevOps.</figcaption></figure><h3>Bridging the Gap</h3><p>True fullstack engineering today is about bridging the gap between writing code and operating that code reliably at scale. Delivering an end-to-end feature is no longer just about the application logic; it includes architecting a scalable system, instrumenting it for observability, automating its deployment, and ensuring its security.</p><p>The engineers who embrace this expanded definition — who master both development and operations — are the ones who will build the next generation of robust, high-performing applications. They are the architects of production, not just features, and in today’s landscape, they are the only true fullstack engineers left.</p><p>As the line between code and operations continues to blur, what’s the first operational skill you plan to learn next?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ff1fa13e03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How AI Teaches Itself: A Beginner’s Guide to the Reflexion Framework]]></title>
            <link>https://medium.com/@faulknerproject/how-ai-teaches-itself-a-beginners-guide-to-the-reflexion-framework-98935c9f6259?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/98935c9f6259</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 18:39:16 GMT</pubDate>
            <atom:updated>2025-11-27T18:39:16.325Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction: Learning from Mistakes, AI-Style</h3><p>Think about the last time you learned a new skill — maybe riding a bike or solving a tricky puzzle. Your first attempt probably wasn’t perfect. You might have wobbled, made a wrong move, and had to try again. Each failure gave you a piece of information: “lean the other way,” “don’t put that piece there.” This cycle of trial, error, and adjustment is the foundation of human learning.</p><p>Recently, AI researchers have been teaching language agents — AI systems designed to interact with environments like games or coding tools — to do the same thing. A groundbreaking new method called the <strong>Reflexion framework</strong> allows these agents to learn from their mistakes without the need for costly and time-consuming retraining. This article will break down exactly how Reflexion works, using a simple example to show how an AI agent can teach itself to succeed through self-correction.</p><p>This process of learning from experience is powered by a unique form of reinforcement that feels surprisingly human.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqI2otbCFbFL6KRNKLax_g.png" /><figcaption>Reinforcement through self-talk</figcaption></figure><h3>2. The Big Idea: Reinforcement Through “Self-Talk”</h3><p>One of the biggest challenges in AI is teaching a model to improve. Traditional methods, like reinforcement learning, often require running thousands of simulations and slowly updating the model’s internal “weights” (its core parameters). This process, known as fine-tuning, is incredibly expensive and slow, especially for massive language models.</p><p>Reflexion introduces a revolutionary alternative: <strong>verbal reinforcement</strong>. Instead of tweaking the model’s code, the Reflexion framework teaches an agent to learn through a kind of “self-talk.” Here’s how it works:</p><ul><li>After an agent fails a task, it doesn’t just get a simple “fail” score.</li><li>Instead, it receives linguistic feedback and generates a short, written summary for itself about what went wrong and why.</li><li>This summary, or “reflection,” is stored in the agent’s memory. On the next attempt, the agent uses this note to inform its decisions and avoid making the same mistake twice.</li></ul><p>It’s a lot like a person making a mental note after messing up a recipe: “Next time, add the salt <em>before</em> the flour.” This lightweight approach uses language itself as the tool for learning. While we’ll focus on text-based feedback, this “self-talk” can be generated from different kinds of signals — from a simple numerical score to feedback from another AI or a pre-written rule.</p><p>To make this “self-talk” happen, Reflexion uses a team of specialized models, each with a distinct job to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5zjWTCtTgMs599YFJ79Nzw.png" /><figcaption>Instead of updating weights, Reflexion agents are reinforced through linguistic feedback. They verbally reflect on task outcomes, store these reflections in memory, and use them to make better decisions in the future.</figcaption></figure><h3>3. The Reflexion Team: An Introduction to the Three Key Models</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APvqZSipSrchOgI3ssBJlQ.png" /><figcaption>The Reflexion framework isn’t a single AI model but a coordinated system of three distinct models working together. Think of them as a small, efficient team dedicated to solving a problem.</figcaption></figure><h3>4. Learning in Action: An Agent’s Journey to Success</h3><p>To understand how Reflexion works in practice, let’s follow an agent trying to complete a task in a simulated household environment called ALFWorld.</p><h4>The Goal</h4><p>The agent receives a simple instruction: <strong>“examine the mug with the desklamp.”</strong></p><h4>Attempt #1: The Failure</h4><p>The <strong>Actor</strong> model begins its first trial. It successfully navigates the environment and locates both a mug and a desklamp on a desk. However, it misunderstands the final step of the task. It picks up the mug but then tries to “use” the desklamp as a separate, unconnected action, which fails.</p><p><strong>Agent’s Incorrect Actions:</strong> After a series of correct steps to locate the objects…</p><p><strong>Status: Fail</strong></p><p>The <strong>Evaluator</strong> model grades this attempt as a failure because the task was not completed.</p><h4>The “Aha!” Moment: Self-Reflection</h4><p>With the trial marked as a “Fail,” the <strong>Self-Reflection</strong> model steps in. It analyzes the history of actions and the final outcome to figure out what went wrong. It then generates a concise, actionable piece of advice.</p><p><strong>Agent’s Generated Reflection:</strong></p><p>“In this environment, my plan was to find a mug then find and use a desklamp. However, the task says to examine the mug with the desklamp. I should have looked for the desklamp first, then looked for the mug. I noticed that the desklamp was found on desk 1. In the next trial, I will go to desk 1, find the lamp, then look for the mug and examine it with the desklamp.”</p><p>This reflection is saved into the agent’s long-term memory.</p><h4>Attempt #2: The Success</h4><p>The <strong>Actor</strong> begins a new trial. This time, it has access to the reflection from its first attempt. Armed with this new plan, it performs the final actions correctly. In the ALFWorld environment, the command “use desklamp 1” after picking up the mug is the correct way to “examine the mug with the desklamp.”</p><p><strong>Status: Success</strong></p><p>By reflecting on its failure, the agent turned a mistake into a lesson and succeeded on its very next try. This example illustrates the simple yet powerful iterative loop at the heart of the Reflexion framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HuWh0Q__OUjMxMG6xAHkrg.png" /><figcaption>Actively generating a verbal explanation of the mistake is significantly more effective than just seeing the mistake again. Refinement guided by self-reflection is superior.</figcaption></figure><h3>5. The Reflexion Loop: Try, Evaluate, Reflect, Repeat</h3><p>The journey from failure to success follows a continuous learning loop that combines the three models and two types of memory. The process is straightforward:</p><ol><li><strong>Try:</strong> The <strong>Actor</strong> attempts the task. The history of its actions and observations during this attempt forms its <strong>short-term memory</strong>.</li><li><strong>Evaluate:</strong> The <strong>Evaluator</strong> scores the attempt. If it’s a success, the process stops.</li><li><strong>Reflect:</strong> If it’s a failure, the <strong>Self-Reflection</strong> model analyzes the short-term memory (what just happened) and writes a piece of advice — a self-reflection.</li><li><strong>Remember &amp; Repeat:</strong> This new reflection is stored in the agent’s <strong>long-term memory</strong>, which is a collection of distilled insights from all past failures. The <strong>Actor</strong> then starts a new trial, using its long-term memory to make better decisions.</li></ol><p>The distinction between the two memory types is crucial:</p><ul><li><strong>Short-Term Memory:</strong> Think of this as the raw, moment-by-moment memory of what you just did. It’s the full, messy log of every action and observation in the current attempt, like remembering every single wobble and turn when you first rode a bike.</li><li><strong>Long-Term Memory:</strong> This is the collection of distilled “aha!” moments. Instead of remembering every mistake, you remember the <em>lesson</em> learned. It’s not the memory of wobbling, but the conclusion: “I need to lean into the turn.” This curated list of reflections is what prevents the agent from repeating past failures.</li></ul><p>This elegant loop is what makes the Reflexion framework so powerful and efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xWd-31ADyMP0R650OLsfA.png" /><figcaption>For programming, Reflexion agents don’t rely on abstract evaluation. They employ a more grounded practice…1. Generate Tests: The agent uses Chain-of-Thought prompting to produce a diverse suite of unit tests for the given function description.<br>2. Filter Tests: It filters for syntactically valid tests by attempting to construct a valid Abstract Syntax Tree.<br>3. Execute &amp; Evaluate: The agent runs its generated code against its self-generated test suite to get immediate, actionable feedback.</figcaption></figure><h3>6. So What? The Power of Learning to Reflect</h3><p>The Reflexion framework is more than just a clever idea; it delivers significant advantages that are helping to push the boundaries of what AI agents can do.</p><ul><li><strong>It’s Lightweight and Efficient</strong> It doesn’t require retraining the entire massive language model, which saves enormous amounts of time and computational resources. Learning happens through text, not by changing the model’s fundamental architecture.</li><li><strong>It Provides Smarter Feedback</strong> Traditional AI reinforcement often relies on a simple numerical score (a scalar reward). Reflexion uses nuanced, verbal feedback that tells the agent <em>why</em> it failed, providing a much clearer path to improvement.</li><li><strong>It Creates Interpretable Memory</strong> Unlike “black-box” approaches where the model’s learning is hidden within complex numerical weights, we can read an agent’s self-reflections. This makes its learning process transparent and allows us to understand its “thought process.”</li><li><strong>It Gets Results</strong> The performance improvements are striking across a wide range of tasks, from reasoning to complex code generation.</li><li>On the <strong>HumanEval</strong> coding benchmark, Reflexion boosted a GPT-4 agent’s accuracy from 80.1% to an incredible <strong>91.0%</strong>.</li><li>In the <strong>AlfWorld</strong> decision-making environment, it achieved an absolute improvement of <strong>22%</strong>.</li><li>For the <strong>HotPotQA</strong> reasoning task, it improved performance by <strong>20%</strong>.</li></ul><h3><strong>It’s Not a Magic Bullet</strong></h3><p>Reflexion is powerful, but it’s not perfect. An agent can still get stuck on a bad idea, reflecting on minor variations of the same mistake without finding the true solution. This is like trying to open a locked door by jiggling the key in slightly different ways instead of realizing you need a different key entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RS_-2u3LEojjxwED08CbtQ.png" /><figcaption>Reflexion teaches agents not just to act, but to learn. It turns failure from a dead end into a dialogue for improvement… but there is still room for even more improvement.</figcaption></figure><h3>7. Conclusion: The Dawn of Self-Correcting AI</h3><p>The Reflexion framework marks a significant step toward creating more autonomous and adaptable AI systems. By giving language agents a human-like ability to learn from experience, it moves beyond rigid, pre-programmed instructions. This method of “verbal reinforcement learning” enables an AI to engage in a cycle of trial, error, and self-correction that is efficient, effective, and surprisingly intuitive.</p><p>As this technology develops, we can expect to see AI systems that are not only more capable but also more interpretable and aligned with their goals, paving the way for the next generation of intelligent, self-improving agents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98935c9f6259" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reflexion: Actor, Evaluator and Reflector Agents]]></title>
            <link>https://medium.com/@faulknerproject/reflexion-actor-evaluator-and-reflector-agents-12dc26979de6?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/12dc26979de6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 23:04:44 GMT</pubDate>
            <atom:updated>2025-11-22T23:13:15.507Z</atom:updated>
            <content:encoded><![CDATA[<h3>Think about the last time you made a mistake while trying something new — maybe you botched a recipe or took a wrong turn. You likely paused, reflected on what went wrong (“I should have added the eggs <em>before</em> the flour”), and made a mental note for next time. This trial-and-error loop is fundamental to how humans learn.</h3><p>For AI agents, however, learning from mistakes isn’t so simple. This process has traditionally been very difficult, often requiring “extensive training samples and expensive model fine-tuning.” But what if an AI could learn more like us?</p><p>A new framework called “Reflexion” introduces a surprisingly simple and powerful idea: give an AI agent the ability to verbally reflect on its own errors. Instead of complex reprogramming, the agent analyzes its failures, generates a short written explanation of what to do differently, and uses that note as a guide for its next attempt. This seemingly basic concept has led to significant performance improvements across a wide range of complex tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*71H2x-Ipoeejk1DPQ61yVQ.png" /><figcaption>Reflexion offers a powerful, lightweight, and significantly more interpretable alternative to traditional reinforcement learning methods that rely on computationally expensive model fine-tuning. By verbally reflecting on its experiences, a Reflexion agent can learn rapidly from its mistakes, achieving improved performance across domains like decision-making, reasoning, and programming.</figcaption></figure><p><strong>AI Agents Can Learn by Literally Talking to Themselves</strong></p><p>The Reflexion framework operates on a continuous loop of action and reflection, using three distinct models to create a form of “verbal reinforcement.”</p><p>Here’s how it works:</p><ol><li>The <strong>Actor</strong> (a large language model or LLM) attempts a task, like writing a piece of code.</li><li>The <strong>Evaluator</strong> scores the attempt, often with a simple pass/fail signal.</li><li>If the attempt fails, the <strong>Self-Reflection</strong> model generates a short, written summary — a “verbal self-reflection” — analyzing what went wrong and suggesting a better approach.</li><li>This reflective text is then stored in the agent’s <strong>episodic memory</strong>.</li><li>On the next attempt, the Actor uses this memory as a crucial piece of context, helping it avoid the same mistake.</li></ol><p>The true innovation here is how Reflexion transforms a low-information signal into rich, actionable advice. Traditional AI learning often relies on a simple “scalar reward” — a single number or a binary pass/fail — that doesn’t explain <em>why</em> something went wrong. Reflexion converts this into what the paper calls a “semantic gradient signal.” In essence, it turns a simple score into a nuanced, textual summary that provides a clear path for improvement. It’s the difference between a computer saying “Error” and a mentor explaining, “You tried to pick up the item before you were in the right room; find the item first.”</p><p>This method is designed to mimic a core aspect of human intelligence. As researchers state in a<a href="https://arxiv.org/pdf/2303.11366">rXiv’s white paper on language agents that leverage verbal reinforcement learning</a>:</p><blockquote>“This is akin to how humans iteratively learn to accomplish complex tasks in a few-shot manner — by reflecting on their previous failures in order to form an improved plan of attack for the next attempt.”</blockquote><p><strong>This Simple Technique Achieved a Startling Breakthrough in AI Coding</strong></p><p>The most striking result of the Reflexion framework comes from a notoriously difficult coding challenge. The Reflexion agent achieved <strong>91% pass@1 accuracy on the HumanEval coding benchmark</strong>.</p><p>To understand the significance of this, it’s crucial to look at the reigning champion it dethroned. The previous state-of-the-art record was held by GPT-4, with a score of 80.1% on the same benchmark. An 11% absolute improvement represents a major leap forward in automated code generation, achieved not by building a bigger model, but by teaching an existing one to think about its failures.</p><p>This success wasn’t confined to a single task. The framework demonstrated its versatility by producing massive gains in other domains as well:</p><ul><li>An absolute <strong>22% improvement</strong> over strong baseline models in AlfWorld sequential decision-making tasks.</li><li>An absolute <strong>20% improvement</strong> over strong baseline models in HotPotQA reasoning tasks.</li></ul><p><strong>It’s Not Just Remembering Mistakes — It’s <em>Understanding</em> Them</strong></p><p>A key question is whether the benefit comes from simply remembering past failures or from the specific act of generating a verbal reflection. To isolate this variable, the researchers ran a clever experiment.</p><p>In an “ablation study” on the HotPotQA reasoning task, they compared two agents:</p><ul><li><strong>Agent A (Reflexion):</strong> Used the full process of failing, verbally reflecting, and storing that reflection in memory.</li><li><strong>Agent B (Episodic Memory Only):</strong> The researchers then created a second agent that had access to the same memory of its last failed attempt but was stripped of the ability to generate a verbal self-reflection.</li></ul><p>The results were clear. The study found that “self-reflection improves learning by an 8% absolute boost over the episodic memory learning advantage.” This finding supports the argument that the agent’s ability to create a linguistic explanation of its failure is a critical part of the learning process. Simply being shown a previous mistake is not nearly as effective as a “self-reflection-guided refinement approach.”</p><p><strong>A More Interpretable Future for AI</strong></p><p>Reflexion introduces a lightweight yet powerful method for improving AI agents through “verbal reinforcement.” By equipping them with a mechanism to reflect on their failures in natural language, it creates agents that can learn from their mistakes in a remarkably human-like way, without needing costly model updates.</p><p>Unlike traditional “black-box” methods where learning is hidden within complex weight adjustments, Reflexion’s learning process is written in plain English, making it far more interpretable. This not only pushes the boundaries of performance but also points toward a more diagnosable and understandable form of AI, leading to a crucial question for the future: As AI agents become better at self-correction through their own internal monologues, how can we ensure that their self-guided learning process remains safe, interpretable, and aligned with human goals?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12dc26979de6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Truths About How AI Agents Actually Learn to Think]]></title>
            <link>https://medium.com/@faulknerproject/5-mind-bending-truths-about-how-ai-agents-actually-learn-to-think-982bf4a70aed?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/982bf4a70aed</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 22:44:59 GMT</pubDate>
            <atom:updated>2025-11-22T23:11:27.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRE-lJpiaa2bBJz7tPTa8A.png" /><figcaption>Reflection is an agent’s ability to <strong>think about its own actions and results</strong> in order to self-correct and improve. Instead of just following a rigid set of instructions, a reflective AI can analyze its performance, identify mistakes, and refine its strategy for the next attempt.</figcaption></figure><h3>From Chatbots to Agents</h3><p>Most of us have interacted with AI through chatbots, getting answers to questions or help with simple tasks. But a new frontier is emerging: AI agents. These systems don’t just talk; they autonomously reason, plan, and act in the world to achieve complex goals. They can write software, control a web browser, or manage a complex workflow without step-by-step human guidance. This leap in capability raises a fundamental question: When an agent makes a mistake, how does it learn? Unlike a simple program that hits an error and stops, these advanced agents can analyze their failures and get smarter over time. The answers reveal a rapid evolution in how agents plan, reflect, and learn — often in ways that are deeply counter-intuitive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruxnC7UAjqTdVNZlEGMgpA.png" /><figcaption>Learning from past mistakes is powerful, but avoiding them in the first place is even better. This requires a shift from reactive to strategic thinking. Early agent designs like ReAct (Reason + Act) were groundbreaking, but they have a critical limitation: they require a call to the large language model (LLM) for every single step. This serial &quot;think-then-act&quot; loop can be slow, expensive, and shortsighted, as the agent only plans one action at a time.</figcaption></figure><h3>1. AI Can Learn from Mistakes Instantly — Using Just Words.</h3><p>One of the most surprising truths is that an AI agent can learn and self-correct without the costly, time-consuming process of retraining the entire model. This is achieved through a technique called “verbal reinforcement learning,” a core component of frameworks like Reflexion.</p><p>Imagine making a mistake and immediately writing a mental “sticky note” to yourself: “That didn’t work because I forgot to open the file first. Next time, open the file before trying to read it.” The agent does something very similar. When an action fails, it verbally reflects on the feedback it received, generates a short, textual summary of the lesson learned, and stores that summary in its memory. On the next attempt, this “sticky note” is included in its context, guiding it away from the previous error.</p><p>This process of reinforcing behavior through linguistic feedback, rather than by updating model weights, is incredibly effective. On the HumanEval coding benchmark, a Reflexion-augmented GPT-4 agent achieved a <strong>91% success rate</strong>, a massive jump from the 80% achieved by the baseline GPT-4 on its own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j37GCeIzqUCip5TyvlHq1g.png" /><figcaption>Reinforce language agents not by updating weights, but instead through linguistic feedback. This basic loop is powerful, but it has a critical weakness. What happens if the ‘Think’ step is shortsighted or flawed? Without a way to learn from a failed action, the agent is likely to get stuck or repeat the same mistakes over and over. This is where two pioneering frameworks, ReAct and Reflexion, offer different solutions.</figcaption></figure><h3>2. The Smartest Agents Don’t Just Act — They Create a Detailed Plan First.</h3><p>Learning from past mistakes is powerful, but avoiding them in the first place is even better. This requires a shift from reactive to strategic thinking. Early agent designs like ReAct (Reason + Act) were groundbreaking, but they have a critical limitation: they require a call to the large language model (LLM) for every single step. This serial &quot;think-then-act&quot; loop can be slow, expensive, and shortsighted, as the agent only plans one action at a time.</p><p>To overcome this, a more advanced “Plan-and-Execute” design pattern has emerged. Here, an AI <strong>planner</strong> first creates a complete, multi-step plan to achieve the goal. Then, a separate, often simpler <strong>executor</strong> carries out that plan. This strategic foresight leads to more efficient and reliable task completion. Two key innovations have supercharged this approach:</p><ul><li><strong>ReWOO (Reasoning Without Observation):</strong> This method elevates planning by allowing the planner to create tasks where later steps can use the results from earlier ones. It does this through “variable substitution” (e.g., “Step 2: Search for the hometown of the person found in #Step1”). This allows the agent to execute a complex chain of dependent tasks without having to stop and consult the planner again.</li><li><strong>LLMCompiler:</strong> This architecture takes speed to another level. Its planner streams a DAG (a flow-chart of tasks where some can be executed in parallel) of tasks with explicit dependencies. A “Task Fetching Unit” monitors this graph and executes tasks in parallel as soon as their prerequisites are met.</li></ul><p>The most counter-intuitive part of the LLMCompiler is its efficiency: it can start executing the first steps of a plan <em>while the LLM is still generating the rest of the plan</em>. This parallel, eager execution dramatically reduces the time a user has to wait for a result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oddP-P7ByCSf9YBo3Ruzjg.png" /><figcaption>The reflexion architecture create a self-improvement loop</figcaption></figure><h3>3. A Simple Shift in “Thinking” Makes AI Dramatically More Reliable.</h3><p>Better planning improves strategy, but what if the very structure of an agent’s moment-to-moment “thought” process is flawed? The popular ReAct framework follows a simple and intuitive loop: Thought -&gt; Action -&gt; Observation. The agent thinks about what to do next, performs an action, and observes the result. However, research has identified a core flaw in this design: the &quot;thoughts&quot; are often ungrounded. They can lack a coherent connection to the agent&#39;s actual state or its ultimate goal, leading to compounding errors, shortsighted planning, and hallucinations.</p><p>To solve this, the ReflAct framework doesn&#39;t just add a new module—it fundamentally replaces ReAct&#39;s core &#39;Thought&#39; step. Instead of having the agent&#39;s thought process focus on planning the <em>next action</em>, it is redesigned to continuously reflect on its <strong>current state in relation to its goal</strong>. While the Reflexion framework learns by reflecting <em>after a task is complete</em>, ReflAct&#39;s innovation is to embed this reflection directly into each step of the agent&#39;s real-time &#39;thought&#39; process, making it far more dynamic.</p><p>This is the difference between a driver asking, “Should I turn left now?” versus a more strategic driver asking, “Looking at my current location on the map, and remembering my final destination, is my next turn still the correct one?”. By forcing the agent to constantly re-ground itself in its high-level objective and its current reality, ReflAct dramatically improves strategic reliability. The impact is significant: on benchmark tasks, ReflAct surpasses the performance of ReAct by an average of <strong>27.7%</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uv29TaZPqioj5xS7PMZ6Ww.png" /><figcaption>ReflAct improves upon ReAct by focusing on goal-state reflection at every timestep to maintain coherence in partially observable environments.</figcaption></figure><h3>4. An AI’s “Memory” Is Not What You Think It Is.</h3><p>All these advanced architectures for planning and reflection rely on some form of “memory” to function. However, it’s a common misconception to think that a larger context window — the amount of text an LLM can process at once — is the same as having a better memory. Research from the MemoryAgentBench paper shows this is not the case. A massive context window is like having a perfect transcript of every conversation you&#39;ve ever had, while true memory is the ability to recall the important takeaways.</p><p>Memory is not about storing history verbatim; it is a <a href="https://www.ibm.com/think/topics/knowledge-distillation">compressed and distilled representation of past information.</a><strong> </strong>An effective memory agent doesn’t just hold on to raw data; it selectively extracts important details, removes irrelevant noise, and consolidates what it has learned.</p><p>Researchers have identified four core competencies that a true memory agent must possess:</p><ol><li><strong>Accurate Retrieval:</strong> The ability to pull the correct piece of information from its stored history.</li><li><strong>Test-Time Learning:</strong> The capacity to acquire new skills or behaviors from interactions during deployment, without retraining.</li><li><strong>Long-Range Understanding:</strong> The ability to integrate information distributed across a long history to answer questions requiring a global understanding.</li><li><strong>Conflict Resolution:</strong> The skill to revise, overwrite, or remove previously stored information when faced with new, contradictory facts.</li></ol><p>The most surprising finding is how much current advanced memory agents struggle with these competencies. They perform particularly poorly at conflict resolution, highlighting a major challenge in building truly adaptive and reliable AI systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7zhhZqBjFpxLryuuf1eE5Q.png" /><figcaption>Reflexion uses verbal reinforcement learning where agents generate self-reflective feedback on failures and store these experiences in episodic memory to guide future attempts.</figcaption></figure><h3>5. The Frontier: AI That Learns New Tasks With Zero Examples.</h3><p>So far, we’ve seen agents learn from mistakes after a task, plan more strategically, and reflect in real-time. But what’s the ultimate goal? Creating agents that can achieve high performance on a task they’ve never seen before, with zero examples. While many advanced agents can learn, most still rely on a “few-shot” approach, where they need to be shown a few demonstrations of how to perform a new task.</p><p>The <strong>ReflexGrad</strong> architecture is a system designed for this kind of true zero-shot generalization. Its core innovation is a “triple synergistic coupling” — a tight, three-way feedback loop between distinct learning mechanisms:</p><ol><li><strong>Hierarchical Planning:</strong> An LLM planner breaks a high-level goal down into a sequential “TODO” list of subgoals.</li><li><strong>Causal Reflection:</strong> The agent actively analyzes its last few actions <em>during a task</em> to understand the root cause of a failure, enabling it to learn and correct its course mid-task. This “Causal Reflection” is a powerful evolution of the self-correction ideas seen earlier; it happens <em>mid-task</em> by analyzing the root cause of recent failures, allowing the agent to correct its course on the fly.</li><li><strong>Prompt Optimization:</strong> The system systematically refines its own instructions (its internal policy prompt) based on performance, in a process similar to gradient descent in traditional machine learning.</li></ol><p>This tight integration allows the agent to plan, reflect, and optimize simultaneously. The results are stunning: on complex ALFWorld benchmark tasks, <a href="https://arxiv.org/pdf/2511.14584">ReflexGrad achieves a <strong>67% success rate</strong> on its <strong>very first attempt (Trial 0)</strong></a>, with absolutely no demonstration examples. This performance, driven by architectural design alone, pushes the boundaries of what we thought was possible for autonomous learning and poses a forward-looking question:</p><p>Can agents achieve robust generalization in truly zero-shot settings through architectural synergy alone?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZX7d7tYn2F4R7n3WDCYgg.png" /><figcaption>The future of reflection is persistent, multimodal and integrated.</figcaption></figure><h3>Conclusion: The Dawn of Self-Improving AI</h3><p>The truths behind how AI agents learn reveal a clear and powerful trend. The cutting edge of AI is moving beyond simple instruction-following and into the realm of building agents with sophisticated, built-in mechanisms for strategic planning, deep reflection, memory distillation, and on-the-fly learning. These systems are designed not just to act, but to understand their own actions and improve from every experience, instantly and autonomously.</p><p>As these agents move from simulated worlds to our own, how will we adapt to collaborators that not only execute our commands but actively learn and improve with every action they take?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=982bf4a70aed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Government Impact on Economic Growth]]></title>
            <link>https://medium.com/@faulknerproject/government-impact-on-economic-growth-9b045aa96db9?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b045aa96db9</guid>
            <category><![CDATA[economic-growth]]></category>
            <category><![CDATA[government]]></category>
            <category><![CDATA[economy]]></category>
            <category><![CDATA[fiscal]]></category>
            <category><![CDATA[stimulus]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 16:07:13 GMT</pubDate>
            <atom:updated>2024-06-30T16:19:10.792Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An analysis of the common trope: “Economies grow faster &amp; are more efficient when the government (public) sector is large and dominant over the other sectors of the economy. Stimulus helps raise income.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHYXjNyXCZ7aMcQQ0XQRWw.png" /></figure><p>The first sentence of this statement has some interesting connotations, and I both agree and disagree. I believe the following examples will shed some light as to why. There are many different ways that the public sector can be an active and at times dominant force in the economy; however, it depends on the circumstances of this involvement. When I first read the statement, three very different types of economic arrangements came to mind which have all had very different outcomes. The first is the Soviet Union, whose almost complete government dominance of the economy ultimately led to its collapse and much suffering for its citizens. The second was the economies of Japan and South Korea where the respective governments have directed their large clout in their economies to yield amazing levels of growth and therefore raised the standard of living for their populations in a very fast amount of time. The final real-world example is Syria, where the government is a big player in the economy, but the results, due to corruption and misallocation have led to stagnation. I think by examining these examples, I can go into why the second statement, “stimulus helps raise income,” is not a fact but again circumstantial to the way that a government uses its clout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tneHO68fUugjypdGBs7gZQ.png" /></figure><p>Since the end of the Classical period of economics, it seems the biggest debate is how much society, or the “public sector,” should intervene in the market. One of the most radical ideas was Marxism, that the market should be completely subservient to society if not eliminated outright. The Soviet Union, attempted to run its economy on this model, and, in the end, its strict adherence to this as well as its commitment to ideological windmills caused it to implode almost overnight. The reasons for this are varied, and still debated to this day. The Soviet Union made great strides through history transforming itself from a peasant society to an industrialized nuclear power, though through often brutal means, in about 30 years. However, its ideological inflexibility seems to have caused it to bleed itself dry to maintain adherence to Marxist ideals and desire to export this system throughout the world. The brittle, command economy that it developed was unable to cope with or keep up with the changes that developed in the world over the years, and when these changes forced an end to the political system, the economy collapsed just as quickly with nothing else to take its place. The lesson here seems to be that an economy should not just be managed by one entity, if any player achieves a monopoly position, things are bound to not end well.</p><p>Japan and South Korea are examples where large government intervention in the economy worked well. So much so, that almost all the countries in the region, from the “Asian Tigers” to the People’s Republic of China are following suit to various degrees. In these countries, it seems the public sector, through strategic spending, monetary policies and subsidies was able to encourage key private sector industries and services to thrive. That both countries were almost completely decimated by war within 5 years of each other and now have “first world” standards of living today is telling. Though certainly not fool-proof, Japan’s economy has been a source of low to zero growth for years (though the causes of this seem to be based in overinvestment in financial markets rather than productive industry) it does appear that, intelligent, long term government intervention in the economy can have very beneficial outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Awe_BU7p9KSCW-cD9iP0A.png" /></figure><p>The third example that came to mind again was Syria. The situation there seems to be an unproductive, corrupt, but large government influence in the economy. No one expects Syria to collapse into economic chaos in the future, but it seems destined to a kind of permanent stagnation. Unlike the Soviet Union, there is a counterbalancing private sector. But the aimless government direction in the economy, pursuit of military armaments and desire of the ruling government to remain in power and enrich itself is a recipe for not death, but economic paralysis. I think this is a good example of how a large government presence in the economy does no good, but doesn’t necessarily destroy the economy either.</p><p>So does stimulus help raise income? From a short term Keynesian perspective it does, almost undoubtedly. But whose income and for what ends? In the United States, stimulus is a buzz word right now. This country’s own recent ideological obsession with the Chicago School of economic theory has caused a quite vocal group of public figures to rail against almost any government interference in the economy. But the United States has always been a big player in the economy. A country’s government can’t spend more on defense than the rest of the world combined and not be a big player in the economy-in just one instance of the massive influence the public sector in the U.S. has on the way its economy is organized and funded. Granted, the globalized and interconnected nature of the world economy makes it harder to make strictly autonomous decisions in a vacuum now, but still choices can be made. Government interaction with, and stake in the economy is a fact of life, how the public sector uses this influence and to what extent, is where this can lead to growth or stagnation, and quite possibly collapse. The public sector has a potential attribute that most private sector interests don’t have. It has the clout and patience to look at the long term picture. If a government chooses to wisely develop industries and services that are beneficial to future growth and development in a strategic way, this spending will not only have immediate Keynesian impact but will benefit income and economic stability in the future as in the case of South Korea and Japan. On the other hand, if a government squanders the money on unproductive pursuits, either ideologically or corruptly, its presence in the economy is either a drag or potential downfall.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b045aa96db9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Tale of Two Networks]]></title>
            <link>https://medium.com/@faulknerproject/a-tale-of-two-networks-a63b8bbe4ae3?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/a63b8bbe4ae3</guid>
            <category><![CDATA[fox-news]]></category>
            <category><![CDATA[medium]]></category>
            <category><![CDATA[al-jazeera]]></category>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 15:59:19 GMT</pubDate>
            <atom:updated>2024-06-30T16:00:13.477Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*0s6x-lXvIdxXWx2iQ3Pwbg.png" /></figure><p>If you wish to set off a debate about the accuracy and/or bias of the media in the United States, just mention either Al Jazeera or Fox News. These two news outlets have become lightning rods in a much larger discussion of the place and evolution of news organizations in a newly ‘globalized’ world that is still coming to grips with rapid changes in technology and the erosion of a long standing international order. At first glance, and certainly in two dimensional media analysis, the two outlets seem to be on opposite ends of competing ideological spectrums that pit a naive and nativist middle America against decades of pent up frustrations in the Arab world. The truth is much more nuanced; both Al Jazeera and Fox News are relative newcomers to the global media scene, each catering to entirely different audiences in ways that are unique to the situations that allowed them to grow and become influential. The differing pressures and stratagems in which these different organizations developed has shaped them not into polar opposites in some ‘clash of civilization,’ but instead reveals two very different paths that news media as whole will be forced to choose between in the years ahead.</p><p>This essay will first discuss the post Cold War environment, the rise of globalization and the changes in technology and information dissemination that gave space for these two new media outlets to originate and thrive. Next, we’ll examine what happened when these different models collided in the early years of this decade, and finally we’ll look at the implications of both models and the future of news in general.</p><p>Symbolized by the fall of the Berlin Wall in 1989, the Cold War that had defined international relations for the previous 40 years dissolved almost overnight. The disintegration of the Soviet Union heralded a stunning change in foreign relations worldwide, no longer constrained by an antagonistic fellow superpower; the United States was left the sole ‘big’ actor on the world stage. Countries that had hedged their bets by aligning with the USSR or by non-alignment trying to play the competing superpowers against each other (such as India and the former Yugoslavia) found themselves adrift without support or counterbalance. However, this change in the static relations of the previous four decades seemed to unleash a popular tide of enthusiasm for more open societies and greater freedom for much of the world. At the same time, media technology was changing at an almost frantic pace. The 1980s saw an explosive growth in cable and satellite television broadcasting. In the United States, what once seemed an impenetrable system of three major broadcasters over the air gradually gave way as, according to the National Cable &amp; Telecommunications Association (NCTA), “[s]atellite delivery, combined with the federal government’s relaxation of cable’s restrictive regulatory structure, allowed the cable industry to become a major force in providing high quality video entertainment and information to consumers. By the end of the decade, nearly 53 million households subscribed to cable, and cable program networks had increased from 28 in 1980 to 79 by 1989.” Throughout much of the rest of the world single state run television stations became obsolete, with satellite technology allowing anyone anywhere to watch practically anything. Cable news was one of the most exciting concepts during this time. Channels devoted to nothing but the news, practically unfiltered, 24 hours a day, seven days a week documenting a volatile new world in real time to the entire planet. The Atlanta, Georgia based CNN was a successful pioneer in this new format and quickly became the go-to source for information whenever a large story broke, gaining particular prestige during the first Gulf War. As the 1990s unfolded, CNN gained competitors in their home US market as well as abroad.</p><p>In the United States, the emerging cornucopia of multiple media options was matched with a contradictive consolidation of media outlets. Starting with newspapers, then moving to radio and television broadcasting, a few large companies had succeeded in consolidating the nations into just a few hands. One of these players was Rupert Murdoch’s News Corporation, the U.S. branch of an international media behemoth, that even in the waning days of broadcast television had managed to muscle in with its’ Fox Network to become a major player against the long established ‘big three’ (ABC, CBS and NBC). Rupert Murdoch has long had a reputation for using his media empire to advance his conservative political agenda, Robert Fisk, a renowned Middle East reporter, describes creeping political interference in his stories after Murdoch’s acquisition of the Times in his book, The Great War for Civilization. In 1996 News Corporation decided to launch its own 24 hour cable news channel, Fox News. Citing a perceived left-wing slant in much of the mainstream media, Fox News pledged “to provid[e] viewers with more factual information in a balanced, fair presentation. Fox believes viewers should make their own judgments on important issues based on unbiased coverage. We Report. You Decide.” However, the shape of this more “balanced, fair presentation” was to take a decided right wing angle. This was evidenced by its first (and still current) president Roger Ailes, a longtime Republican Party operative who’d worked as a media consultant for the party since Nixon. As Fairness and Accuracy in Reporting (FAIR) said in it’s 2001 report by Spencer Ackerman “Since its 1996 launch, Fox has become a central hub of the conservative movement’s well-oiled media machine. Together with the GOP organization and its satellite think tanks and advocacy groups, this network of fiercely partisan outlets — such as the Washington Times, the Wall Street Journal editorial page and conservative talk-radio shows like Rush Limbaugh’s — forms a highly effective right-wing echo chamber where GOP-friendly news stories can be promoted, repeated and amplified. Fox knows how to play this game better than anyone.”</p><p>In the same year, halfway around the world the Emir of Qatar helped fund a new and innovative Arab-language news channel, Al Jazeera. Many of the personnel in the new network were recruited from a joint program involving the highly esteemed BBC World Service and the government of Saudi Arabia which fell apart due to the BBC’s insistence on editorial independence, which the Saudi Kingdom was unwilling to allow. In a region of the world used to heavily censored, state run media Al Jazeera quickly made a name for itself as a trusted source of news and information for its’ willingness to air a range of opinions and sources. Thomas Friedman in a 1999 New York Times editorial stated: “[Al Jazeera] is now the freest, most widely watched TV network in the Arab world. It was al-Jazeera that broadcast Saddam Hussein’s recent call for the elimination of all the Arab leaders — particularly the Saudis — at a time when no state-owned Arab television would broadcast such a threat. Little Qatar’s satellite station is now driving the rest of the Arab world crazy.” This willingness to report on controversial stories cemented Al Jazeer’s credibility in the Arab world and beyond. With its’ only competitors being CNN International and the BBC World Service, it had little choice but to abide by the same professionalism if it wished to be take seriously by its target audience.</p><p>Five years after Al Jazeera and Fox News’ inception, their different media practices and formats were thrown in stark relief against each other after the September 11th attacks. The United States media had paid scant attention to the Arab world after the first Gulf War, mostly focusing on occasional bombings and inflammatory remarks by Saddam Hussein, ruler of Iraq. On the other hand Al Jazeera had become a trusted resource in the region, relied on for its’ objective reporting. Once the American media regained interest in the region due to U.S. actions in Afghanistan and the build up to the war in Iraq, it discovered this well-informed and relatively neutral source of information. In the jingoist mood at the time, well summarized by White House Press Secretary Ari Fliescher’s remarks to journalists “that that they need to watch what they say, watch what they do,” the thought that a news outlet would dare interview Osama Bin Laden and fighters resisting American military action or point out American excesses against civilians in its’ military response in the region quickly drew ire. “You’re either with us or against us in the fight against terror.” as President George W. Bush is reported to have stated by CNN. This atmosphere stifled dissent in the United States journalist community and led to increasing vilification of the Arab language news broadcaster. Fox news commentators were at the forefront of this call for silencing Al Jazeera, often alluding to violent means to do so. In an opinion piece, typical of many instances, commentator Frank Gaffney, Jr., said ominously; “Under present wartime circumstances, though, the United States has the ability — and, indeed, an urgent responsibility — to take more comprehensive action against Al Jazeera and Al Arabiya. Unless the two networks adjust their behavior so as no longer to act as the propaganda arm of our enemies, they should be taken off the air, one way or another.” However, as portrayed in the award winning documentary, Control Room, Al Jazeera was trying to tell the story of the events leading up to the Iraq war in an honest way, taking in all sources including the U.S. military and State Department. Their reporters appear to treat every source with equal skepticism but to listen to all sides and try to present their views fairly. The biggest complaint that seems to emerge from their critics is that they’re <em>not</em> onboard the bandwagon for war, but instead representing their regional audience by asking tough questions about what the implications of this impending war will be.</p><p>In the aftermath of the invasion of Iraq the performance of the United States media was heavily criticized; a lack of investigation into the pretexts for going to war and a cheerleading role during the invasion often being cited. As could be expected, Fox News was one of the worst offenders, in a polling study carried out by Program on International Policy Attitudes exploring public misperceptions about the reasons for going to war they found by far viewers of Fox News were the most misinformed regardless of political leanings. “For example, 78% of Bush supporters who watch Fox News thought the US has found evidence of a direct link to al-Qaeda, but only 50% of Bush supporters in the PBS and NPR audience thought this.” Despite this atrocious record, the Fox News model is looked at favorably by other U.S. cable news networks because of its high viewership and resulting profitability. Jim Rutenberg reports regarding MSNBC emulating Fox tactics: “… MSNBC’s moves have news executives and some liberal critics worried that Fox’s success will push TV news too far from a neutral tone. “I’m a huge believer in the forces of the market and the audience’s ability to make choices among various channels,” Mr. Heyward of CBS said. “What I would not like to see happen is legitimate debate stifled, or journalists’ skepticism, heated journalistic inquiry, somehow dampened by a flock of Fox imitators.’’’<strong> </strong>On the other hand, Al Jazeera’s success as a legitimate source of news in the Arabic world has inspired other News channels to try to provide an alternative to the previously powerful, though now somewhat compromised US (CNN, Fox, etc.) and UK (BBC) news agencies. As well as the competing Al Arabiya, based in Dubai that began broadcasting in 2003, the government of France entered the market with the joint private venture France 24 in 2006 joining Russia Today, a similar enterprise of the Russian government, which started airing in 2005, as serious competitors in the 24 hour cable news industry bringing internationally diverse views and opinions to an audience that seems jaded by the circus tent atmosphere that has enveloped the American offerings. As the world continues to grow more interconnected with internet technology allowing an even broader choice of media and news options, it is yet to be determined if the openness and freedom that the end of the Cold War seemed to promise will materialize into a multi-polar world of diverse opinions or will continue along the dumbed down, profit driven path that has defined the direction of American media for the last 20 years.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a63b8bbe4ae3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[21 Most Commonly Asked Interview Questions about Operating Systems and CPU]]></title>
            <link>https://medium.com/@faulknerproject/21-most-commonly-asked-interview-questions-about-operating-systems-and-cpu-59d1fae062c1?source=rss-96a0f1a7f783------2</link>
            <guid isPermaLink="false">https://medium.com/p/59d1fae062c1</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Rosie Faulkner]]></dc:creator>
            <pubDate>Mon, 17 Apr 2023 15:26:17 GMT</pubDate>
            <atom:updated>2023-04-17T15:26:17.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*w78po3an2Fh_VFF2JdNp7Q.png" /><figcaption>An operating system (OS) is a software that manages computer hardware and software resources and provides common services for computer programs. Image Credit: Naso Academy</figcaption></figure><p>This article explores the most commonly asked interview questions for architects regarding operating systems. It discusses the importance of understanding operating systems and their role in managing computer hardware and software resources. We will discuss what a CPU is and how it works with an operating system, the different types of operating systems, the role of the kernel, multitasking, threads, processes, virtual memory, and system calls, which are critical concepts for architects working in modern IT environments. Additionally, it examines the differences between various operating systems, including Windows, macOS, and Linux, and how they affect system architecture and design decisions. Through exploring these topics, the article provides insight into the technical knowledge and skills architects need to possess to design and implement robust operating systems that meet the needs of modern enterprises.</p><p>By the end of this reading, readers will have a better understanding of these crucial components and their interactions, and be better equipped to discuss operating systems during architectural interviews as well as troubleshoot issues that may be given to you in order to whiteboard or discuss solutions during your discussions about computer systems.</p><h3>What is a CPU?</h3><p>A CPU (Central Processing Unit) is the main component of a computer system responsible for carrying out instructions of computer programs.</p><h3>What is an operating system?</h3><p>An operating system (OS) is a software that manages computer hardware and software resources and provides common services for computer programs.</p><h3>How does a CPU work with an operating system?</h3><p>The CPU executes instructions given by the operating system, which in turn manages the resources of the computer and provides a platform for software to run on.</p><h3>What are the different types of operating systems?</h3><p>The different types of operating systems include Windows, macOS, Linux, Android, iOS, and more.</p><h3>What is the role of a kernel in an operating system?</h3><p>The kernel is the core component of an operating system that manages memory, processes, and other system resources.</p><h3>What is multitasking?</h3><p>Multitasking is the ability of an operating system to run multiple tasks or processes simultaneously.</p><h3>What is a thread?</h3><p>A thread is a sequence of instructions that can be executed independently by a CPU and is part of a larger process.</p><h3>What is a process?</h3><p>A process is a program or application that is currently executing in memory, with its own memory space and resources.</p><h3>What is virtual memory?</h3><p>Virtual memory is a technique used by operating systems to allow programs to use more memory than is physically available by temporarily transferring data from RAM to a hard drive.</p><h3>What is a system call?</h3><p>A system call is a request made by a program to the operating system for a service or resource. Common system calls include file I/O, process management, and memory management.</p><h3>Ready for a selection of advanced questions about operating systems and CPUs?</h3><p>This research explores the most commonly asked <em>advanced </em>questions and answers about CPUs and operating systems. It discusses the function of a CPU as the main component of a computer system responsible for executing instructions of computer programs, as well as the role of an operating system in managing computer hardware and software resources. The study also covers topics such as context switching, how CPU works to execute tasks, and virtual machines, providing readers with a basic understanding of the fundamental concepts of CPUs and operating systems and how they work together to provide the user experience we know and love. With this knowledge, readers can gain a better understanding of how computer systems work and how they can optimize their computer’s performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s6Nc3hK98loPXP_D5GVxlw.jpeg" /></figure><h3>Explain in the windows operating system how the operating system changes from one process to the next, basically the context switch.</h3><p>In the windows operating system, the operating system changes from one process to the next by first stopping the execution of a process and subsequently beginning the execution of a different process. Context switching, where the CPU changes from executing a process in exchange for shifted focus and the execution of a different process, is a low level kernel operation. When context switching occurs, the operating system saves the current process’ state, loads the state of the newly started or prioritized process, and continues the execution of the prioritized process. Context switching makes the operating system more efficient by allowing a myriad of processes to run concurrently while offering an interactive user interface. Typically, context switching occurs when the operating system scheduler (We will not be delving into specifics on the scheduler) responds to a process that is prioritized higher than the current process or when the process currently executing has exhausted its time slice. After the operating system initiates a context switch, a few steps occur:</p><ol><li>Current process state is saved in the memory’s context block. Register values and stack and instruction pointers are also saved.</li><li>Context and state of the higher-prioritized process is loaded from its previously saved state from the context block of the process. The pointers and state are loaded into the CPU. The state for other kernels are updated as a result of the newly prioritized process that is now executing.</li><li>The memory management unit is then updated by the operating system. The operating system makes sure that the newly executing process has the memory mapped that it needs to run. This memory needs to be protected so that the process executes without issues.</li><li>The operating system continues to execute the process via the instruction pointer from the process’ context block.</li></ol><p>The above steps represent an internal progression performed for the purpose of juggling numerous processes via CPU. CPU needs to switch between processes quickly and efficiently and depends on context switching for that. Context switching relies on a variety of system details as well, such as the size of the processes and their context blocks, the amount of applications or processes concurrently running and the architecture of the CPU itself.</p><h3>Explain in the windows operating system how an interrupt is handled (for example a keyboard entry)</h3><p>In the Windows operating system, interrupts can be defined as signals sent to the CPU by external devices. These external devices can be hardware, or input/output devices, such as a keyboard. When an interrupt occurs using our keyboard example, the signal is sent to the CPU by the keyboard. The process currently being executed by the CPU is stopped. While only temporary, the stopping of this current process allows the CPU to handle the interrupt by switching to an interrupt handler routine. The Windows operating system performs a series of steps when a keyboard entry causes an interrupt to occur:</p><ol><li>The keyboard controller signals the interruption to the CPU, letting the CPU know that a keyboard entry has been made.</li><li>The CPU saves the state of the current process and suspends execution. The CPU then switches to an interrupt handler routine found in the interrupt vector table, which stores the interrupt handler addresses for I/O devices.</li><li>Loss of data for the current process is prevented by the interrupt handler routine, which saves the register values and program counter as well as the process context.</li><li>The interrupt handler routine identifies the source of the signal, the keyboard controller.</li><li>The interrupt handler routine stores the keyboard entry. Sometimes, the interrupt handler routine confirms entry validity and filters erroneous entries.</li><li>The interrupt handler routine then restores the previous processes execution from the state saved in the context block of the process.</li><li>Finally, the keyboard entry data becomes accessible to the operating system function or application that originally requested it.</li></ol><p>For the Windows operating system, interrupt handling helps to ensure that the I/O or hardware device’s request is processed quickly and efficiently. Interrupts can happen when an external device, such as a keyboard, creates an interrupt signal and requires CPU. Interrupt handling also helps the operating system to manage I/O device requests without interruption to the expected behavior of the operating system.</p><h3>Of the three basic operating systems we have covered, windows, Linux and mac, if you had a customer that was new to PC systems, what questions would you ask them to determine which operating system they should use/purchase.</h3><p>If I had a customer who was new to PC systems, I would ask them a few questions to determine which operating system they should use/purchase:</p><ol><li>Why do you want a computer? For what do you imagine yourself using it? The answer to this question will give me an indication for what kind of software, inputs and memory the customer may need. For example, if they are a graphic designer and aim to have Photoshop and the Adobe Suite and other large applications running concurrently, they may need to use Mac, which will be able to manage the different concurrent tasks that the user may need to run concurrently such as photo and video editing.</li><li>I would also ask the customer what kind of software they were planning on installing. Asking this question will help me understand specifics for needs surrounding CPU, RAM, and display refresh rate.</li><li>I would ask the customer if they are already using an operating system currently. If they are, they may be hoping to continue using it as it is more familiar to them. For instance, an iOS user may want to continue having their iPhone connected to their MacbookPro. Conversely, an Android user might prefer a Linux machine more familiar and therefore easier to transition.</li><li>What is your price range? This would be my next question because of the different prices for different machines. For example, typically Apple computers cost a far greater amount than many Linux or Windows based machines.</li><li>Lastly, I would ask the user how much they really knew about computers. Would they prioritize the user experience over greater customizability over their system? Linux is highly interactable for users who want to delve deeper into the inner-workings of the Linux processes. Mac, on the other hand, is far more user-friendly and much more pleasing to the average user’s sensibilities than it is in generosity of sharing control with the user.</li></ol><h3>What are all the file systems types that Windows and a Mac uses by the operating system and how large of a file is supported in each (max size), What file systems are supported by Linux.</h3><ol><li>Windows, Mac and Linux use file systems for storage. For example, an operating system may use a file system to store data on an SSD. The file systems of Windows, Mac and Linux and the respective max size supported by them are as follows:</li><li>Windows: FAT32–4gb max, NTFS — 16eb max, exFAT — 16eb max</li><li>Mac: HFS+ — 8eb max, APFS — unlimited max</li><li>Linux: btrfs — 16eb max, exFAT — 16eb max, NTFS — 16eb max, XFS — 8eb max, ext2–2tb max, ext3–2tb max, ext4–16tb max</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*TT1a_BvA-HxdSNwY2lOxSA.png" /><figcaption>In the Windows operating system, interrupts can be defined as signals sent to the CPU by external devices. These external devices can be hardware, or input/output devices, such as a keyboard. When an interrupt occurs using our keyboard example, the signal is sent to the CPU by the keyboard. The process currently being executed by the CPU is stopped. While only temporary, the stopping of this current process allows the CPU to handle the interrupt by switching to an interrupt handler routine. The Windows operating system performs a series of steps when a keyboard entry causes an interrupt to occur.</figcaption></figure><h3>A customer running Windows 10, wants to use Windows XP for older applications, it has been suggested that they use a VM (Virtual Machine). Explain the steps should the customer take to install a XP operating system into a VM running on the windows 10/11 machine.</h3><p>In order to install Windows XP on a virtual machine on an Windows 10/11 operating system, there are a few steps of which the user should be made aware:</p><ol><li>Firstly, the user must download a virtual machine as well as the intended operating system. In this case, the user will download Windows XP. There are a few popular virtual machine softwares that the user can consider, such as: VMware Workstation and Oracle VM VirtualBox.</li><li>After the operating system and the virtual box software has finished downloading, the user must then execute the application and go through the installation wizard. Then, they will be able to create a new virtual machine. Because of the new virtual machine, the user needs to augment their disk size and RAM configurations for Windows XP in the virtual machine.</li><li>The user can then execute the operating system from the virtual machine and run through the installation wizard. The virtual machine will then, upon completion, have Windows XP.</li></ol><h3>Describe at least 10 reasons why a server operating system is more robust than your standard pc based operating system.</h3><p>An operating system that is standard PC based offers and supports less than a server’s operating system. The following reason will depict a few reasons to support this:</p><ol><li>Performance: Standard PC based operating systems are not meant to be used for the heavy loads that server operating systems are designed to manage. For instance, servers are relied upon for managing large amounts of data and fluctuating traffic from the network.</li><li>Hardware management: The operating systems for servers are tasked with handling disk space, CPU and memory and therefore, require an efficient system that is beyond the scope of what a standard PC necessitates.</li><li>Security: Server security tends to be far more robust than PC standards. This is because of the high volume of network traffic and the high volume of data handled by the server. There are security minimums servers have to meet according to government requirements as well, for instance, a medical insurance company may utilize servers that have increased security in order to meet HIPAA server security standards.</li><li>AD or active directory: Active directory is a centralized permissions, authentication etc. resource that is present in server operating systems but unnecessary in standard PC based operating systems.</li><li>Virtualization: Most standard PC-based operating systems do not require the use of multiple operating systems that run different applications. Servers, however, often need this higher level of virtualization.</li><li>Scalability: Server operating systems need to be able to balance the load of multitudes of users. Standard PC based operating systems are meant to be used by one user at a time and would most likely be unable to manage the larger applications or load server operating systems support.</li><li>Data loss prevention: Servers typically have heartier recovery routes than the PC-based operating system. For instance, a server may need to backup and recover large amounts of data and therefore requires tools to help in the event that a system failure occurs.</li><li>Redundancy: Because PC-based operating systems were created with having a single user at any given time, they do not possess the same level of redundancy that server operating systems do. Servers typically allow RAID configurations or include clustering that helps to increase reliability.</li><li>Remote access: Servers support a more robust experience for remote management than standard PC-based operating systems.</li><li>Reliability: Servers tend to require higher standards due to handling more data and concurrent users. Therefore, server operating systems typically have less downtown and have a greater ability to process and handle errors to prevent system failures.</li></ol><h3>What is the max number of simultaneous users that the windows 10 operating system supports, what is the max number of simultaneous users that a Mac operating system supports? In your opinion why is there a limit?</h3><ol><li>Windows 10: Enterprise and education (up to 100 simultaneous users), pro (up to 10 simultaneous users), home (1 user only)</li><li>Mac: home (1 user only), pro (up to 12 simultaneous users)</li><li>There are many reasons, in my opinion, that the maximum number of simultaneous users supported by the operating systems are limited. For example, the hardware may have limitations. The CPU, memory and processing power is limited. As additional users are added, CPU is allocated and network bandwidth is used. The limitations of the operating system are one of the core reasons for the maximum simultaneous user limitations.</li></ol><h3>Explain the steps that should be taken to install a device driver into a windows operating system, (you can use an example). What steps should be taken to install a new device into a Mac.</h3><p>In order to install a device driver into a Windows operating system, the user must:</p><ol><li>Install a driver for the device. The user can download this from the vendor’s documentation page online.</li></ol><p>2. If necessary, connect the needed hardware. Then select “Device Manager” from the start menu to open the application.</p><p>3. Identify the device in the Device Manager application and go through the driver’s installation wizard after the user clicks on the device to run it.</p><p>4. The user may let the computer restart in order to see the update.</p><p>In order to install a device driver into a Mac operating system, the user must:</p><ol><li>Make sure that the device is connected to the Mac. It has to be discoverable via Bluetooth or Airplay, plugged in or installed in the Mac computer.</li><li>The user must now navigate to “System Preferences” from the main menu on the upper left hand side of the screen when the computer is turned on. Click on Bluetooth.</li><li>The device you’d like to connect, which in our example is a Logitec Bluetooth mouse, is clickable from the dropdown. Click to connect.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRobKHgOSngmALZALt8blQ.jpeg" /></figure><h3>You want to upgrade your PC from windows XP to windows 10/11, is there an upgrade path?</h3><p>If you want to upgrade your PC from Windows XP to Windows 10/11, unfortunately, there is no formal path to upgrade. Rather, the upgrade process requires a 100% wipe of the PC. This fresh install of Windows 10/11 deletes all the users files and applications. Windows XP is an old operating system. Most old systems like this one are not compatible with the hardware or software of newer operating system requirements.</p><p>If I wanted to upgrade from windows 8.1 to windows 10, I would:</p><ol><li>Check that my hardware and software was compatible with windows 10.</li><li>I would backup my important files to my Google Cloud or Apple Cloud.</li><li>I would then follow the Windows 10 installation wizard after I execute the driver.</li></ol><h3>What does windows 11 zero Trust do? How does this affect you if you are going to upgrade to Microsoft windows 11?</h3><p>Windows 11 Zero Trust adds security under the principle of “never trust, always verify”. It continually requires authentication between devices, services and applications in order to increase security. Upgrading to Microsoft 11 means my files will be more secure.</p><h3>What fundamental change has occurred in windows that it is no longer necessary to install drivers?</h3><p>More recent windows operating system versions are trying to automate the driver installation process and give users an easier time installing devices. For example, the plug-and-play support received a revamp. When a user connects a device to their computers, the operating system will install drivers automatically.</p><h3>Explain the differences between the Von Neumann vs. Harvard architecture? If you want to modify instructions, which architecture should be chosen?</h3><p>The Von Neumann architecture and Harvard architecture are two different computer architectures. The Von Neumann architecture stores both data and instructions in the same memory unit. Where the Harvard architecture stores instructions and data in separate memory units that are connected by different buses. The Harvard architecture is designed to overcome the bottleneck of the Von Neumann architecture, allowing for simultaneous access to data and instructions. If you want to modify instructions, I would choose the Harvard architecture because it allows you to modify the instruction memory while preserving the integrity of the data memory. This is because Harvard architecture treats instruction memory as read-only. Which can be a security benefit, but also means you can’t do self-modifying code. The Von Neumann architecture does not offer this capability since it stores both data and instructions in the same memory unit.</p><h3>How is a CPU cache used to increase the performance of the Operating system? Who controls the usage, the operating system or the CPU.</h3><p>The CPU cache is an important part of a system as it works to improve computer performance by storing viewed or previously accessed data for faster access. The operating system and the CPU manage the allocation of cache. The OS handles the memory management unit, and controls the MMU. This indicates that it makes decisions on which data to keep in cache and when to remove it. The CPU cache controller predicts which data will be requested and query it into the cache so that it is available. The CPU determines when data should be written back from the cache to the main memory. This indicates that the CPU has some influence over how the cache is used. Generally, the operating system and the CPU want to minimize the number of cache misses that force data to be retrieved from main memory. It also increases the quantity of data that can be accessed fast from the cache.</p><h3>What is the difference between a UNIX operating system and a Linux Operating system? Which was developed first?</h3><p>The UNIX operating system and the Linux operating system are quite different. UNIX is not open-source and LINUX is. Linux is far more prevalent than UNIX because it can be installed on a range of sizes of systems but UNIX is for large-scale systems. The first version of UNIX was developed in 1969 whereas Linux was first created in 1991.</p><h3>What is a “Page Fault” in an operating system and why is it used and how does the operating system deal with this.</h3><p>A page fault happens when a process or application requests a page that is not stored in the machines physical memory.​​ As a result, the page is accessed by the operating system from external storage or hardware and transferred to the system’s memory. This also throws a system exception to which the operating system responds. This happens in order to, as efficiently as possible, handle many applications running at once and the handling of the memory allotment for each application. It enables the operating system to deal with the exception and then re-continue the process that had been executing when the page fault occurred.</p><h3>Explain the difference between Multitasking and Multi-Processing and why and when are they used?</h3><p>Multitasking and multi-processing both aim to allow users to run multiple tasks at the same time. The computer quickly moves between various processes as multitasking happens, giving the user a seamless impression that everything is happening fluidly. On the other hand, multi-processing refers to the concurrent running of numerous processors or CPU cores at once. If a person needs to run numerous small processes at once, multitasking is recommended. Your computer can manage both tasks without slowing down, for instance, if you want to browse the internet while playing music. Multiprocessing is useful when you need to do multiple tasks that require a lot of processing power. For example, you might need to render a video while running a simulation that needs a lot of resources. Multiprocessing can help you split the work between different processors or cores, so you can finish everything faster.</p><h3>What is the difference between a SoC and a multiprocessor</h3><p>A SoC usually contains a GPU (graphics processor), memory, USB controller, power management circuits, and more. Due to the fact that a single chip combines both hardware and software with SoC, it will use less power, have a better performance, require less space, and will be more reliable than a multichip system because it includes both hardware and software. Smartphones and smartwatches are examples of users of a SoC and supercomputers are an example of a multiprocessor user that requires many processes to run concurrently.</p><h3>What is the difference between time-sharing processing and Multi-user processing. When are they used, and is it important to make sure you work with one or the other?</h3><p>The terms “time sharing” and “multi-user processing” are two distinct ideas that are frequently mixed together. The ability to share computing resources, such as a computer’s CPU, among numerous users simultaneously is referred to as time sharing. Since a single computer system must be utilized by numerous users simultaneously, it is frequently used when discussing personal computing. Multi-user processing is used in corporate and enterprise settings when numerous users must simultaneously access shared resources like a server or database. Each user logs in and has their own set of resources to use. Because time sharing and multi-user processing require different approaches to resource management and security, it is important to make this distinction. A time-sharing system must control several users who are using the same resources concurrently. In contrast, a multi-user system must control several users who are simultaneously accessing various resources. Security precautions must also be in place in a multi-user system to guarantee that each user only has access to the resources they are allowed to use.</p><h3>What is the difference between soft real-time and Hard real-time operating systems, what does windows server and non-server support? What does Linux support?</h3><p>The main difference between soft real-time and hard real-time operating systems is the level of importance placed on meeting timing deadlines. A soft real-time system is designed to meet timing deadlines most of the time, but if an occasional deadline is missed, it is not a critical issue. In contrast, a hard real-time system is designed to meet timing deadlines 100% of the time. If a deadline is missed in a hard real-time system, it could lead to a system failure or even endanger human life. Windows Server and non-Server versions both support soft real-time capabilities, but they are not designed to be used as hard real-time systems. Windows Server includes some real-time features, such as real-time priority levels and thread affinity, which allow for prioritization of certain tasks. Windows 10 IoT is designed to support real-time capabilities for IoT devices and embedded systems, but it is not designed to be a hard real-time system. Both soft and hard real-time systems have utilized Linux. A well-known real-time Linux operating system is the Real-Time Linux project (RTLinux). In addition, there are a number of Linux distributions like Xenomai and RTAI that are created expressly for real-time use. These systems have been employed in a range of application, including industrial control, the military and aerospace, as well as medical equipment.</p><h3>Is an Intel I7 CPU a microprocessor, a microcomputer or a system on a chip? Explain what it is and why is it not the other two.</h3><p>Intel i7 CPUs are microprocessors. The CPU of a computer is housed on an integrated circuit known as a microprocessor. A microcomputer is a small computer that has a microprocessor as its central processing unit. It also has additional parts including input and output devices, memory, and storage. Due to the absence of these additional components, the Intel i7 by itself doesn’t qualify as a microcomputer. A system on a chip is an integrated circuit that houses several computer system parts on a single chip, including a CPU, memory, and input/output interfaces. The i7 is not a SoC since it lacks some essential components of a full system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59d1fae062c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>