<?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 Kiran Manjrekar on Medium]]></title>
        <description><![CDATA[Stories by Kiran Manjrekar on Medium]]></description>
        <link>https://medium.com/@manjrekar.kiran.82?source=rss-3024e2f2fadf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*AZOULrdL0F5LUe-5</url>
            <title>Stories by Kiran Manjrekar on Medium</title>
            <link>https://medium.com/@manjrekar.kiran.82?source=rss-3024e2f2fadf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:27:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manjrekar.kiran.82/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[Prompts Are Not Enough: The Stack Behind Reliable AI Agents]]></title>
            <link>https://medium.com/@manjrekar.kiran.82/prompts-are-not-enough-the-stack-behind-reliable-ai-agents-0736fd94af87?source=rss-3024e2f2fadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0736fd94af87</guid>
            <category><![CDATA[prompt-engineering]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[loop-engineering]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[Kiran Manjrekar]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 13:02:39 GMT</pubDate>
            <atom:updated>2026-07-04T13:02:39.847Z</atom:updated>
            <content:encoded><![CDATA[<p>When teams first started building with LLMs, most of the attention went to prompts. That made sense. A small change in wording could produce a noticeably better answer, and it felt like the prompt was the main thing to optimize.</p><p>But once you move from demos to real applications, prompts quickly stop being enough. A production AI system needs the right information at the right time. It needs safe access to tools and APIs. It needs logging, permissions, retries, state management, and clear stop conditions. In practice, the model is only one part of the system. The engineering around the model is what decides whether the application works reliably.</p><p>I find it useful to think about this as a four-layer stack: Prompt Engineering is the message, Context Engineering is the knowledge, Harness Engineering is the runtime, and Loop Engineering is the workflow. The model is the engine. The context is the fuel and map. The harness is the car around it: steering, brakes, sensors, and safety systems. The loop is the driver deciding what to do next based on what happens on the road.</p><p>This post walks through each layer, the common ways it fails, and how the layers fit together in practical multi-agent architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*2zRm2m3hlf99NVeU6aaFzA.png" /><figcaption><strong>🧭 FIGURE 1 · THE FOUR-LAYER AI ENGINEERING STACK — </strong><em>From one prompt to a governed autonomous system</em></figcaption></figure><h3>Comparative Analysis of the Four Engineering Disciplines</h3><p>Going from one LLM call to a reliable agent is not just a matter of adding more prompt text. Each layer solves a different problem. Prompting shapes the immediate response. Context gives the model the facts it needs. The harness controls how the model uses tools. The loop decides how the system keeps moving until the task is done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*rhqwH-zbROZ4_yMr9ZDwng.png" /></figure><h3>1. Prompt Engineering (The Message)</h3><p>Prompt Engineering is the layer most people meet first. It is the practice of writing instructions that help the model produce the response you want. Early prompts were often simple questions. In production work, prompts usually become more explicit: they define the role, the task, the constraints, examples, and the expected output format.</p><p><strong>Deep Dive: Prompt Engineering Failure Modes and Mitigation</strong></p><p>Prompt failures can be tricky because they often look like small quality issues rather than hard errors. A wording change may fix one case and break another. That is why production prompts need to be tested and versioned like code, not edited casually in isolation.</p><p><em>Inherent Failure Modes:</em></p><ul><li>Prompt Brittleness &amp; Drift: Minor, semantically irrelevant changes in wording can cause drastically different outputs. Over time, uncoordinated edits lead to “prompt drift,” where performance slowly degrades. A prompt that works with one model version may also fail with a newer one, a phenomenon known as “prompt rot”.</li><li>Instruction Conflict and Ambiguity: As prompts become more complex, new instructions can conflict with existing ones (e.g., “be concise” vs. “explain your reasoning”). Vague prompts lead to generic, unusable responses.</li><li>Hallucination Under Constraint: When a model is forced to adhere to a specific format (like JSON) but lacks the necessary information, it may invent data to fill the required fields, leading to structured but factually incorrect outputs.</li><li>Prompt Injection: A significant security vulnerability where malicious user input overrides original instructions, causing the model to behave in unintended ways.</li></ul><p><em>Advanced Mitigation Techniques:</em></p><ul><li>Systematic Prompt Evaluation and Versioning: Track every change to a production prompt in a source control system like Git. Before deploying a new prompt, run it against a “golden set” of inputs to automatically flag performance declines on critical cases. Use A/B testing to measure real-world impact before a full rollout.</li><li>Model-Native Structured Outputs &amp; Guardrails: Use the model provider’s native features (e.g., Open-AI’s JSON mode) to force the output to conform to a provided schema, dramatically reducing parsing errors. Clearly separate instructions from user-provided content using XML tags or other delimiters to mitigate prompt injection attacks.</li><li>Meta-prompting and Self-Refinement: Use an initial prompt to ask the LLM to act as a “prompt engineer,” taking a simple goal and generating a detailed, optimized prompt for the actual task. Implement a multi-step process like Chain of Verification (CoVe), where the model first generates an answer, then creates and answers probing questions to verify its own work before producing a final, refined response.</li></ul><h3>2. Context Engineering (The Knowledge)</h3><p>Context Engineering is about controlling what the model sees before it answers. The prompt is what you ask. The context is the information available when you ask it. In many real systems, this is where most of the quality comes from. Retrieval-Augmented Generation, or RAG, is the common pattern: retrieve relevant content from an external source and place it into the model context so the answer is grounded in actual data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnmdP4Z3p4icAWf36tc5-w.png" /><figcaption><strong>📚 FIGURE 2 · RAG PIPELINE FOR CONTEXT ENGINEERING — </strong><em>Turning messy enterprise knowledge into high-signal model context</em></figcaption></figure><p><strong>Optimal Data Preprocessing and Chunking</strong></p><p>A RAG system is only as good as its ingestion pipeline. If the source data is noisy, stale, badly chunked, or hard to retrieve, the model will struggle no matter how good the prompt is.</p><p>Ø <em>Preprocessing:</em></p><p>Raw text must be meticulously cleaned of structural clutter like HTML tags, headers, and footers that add no semantic value. Text should also be normalized (e.g., converting to lowercase) to ensure consistency.</p><p>Ø <em>Chunking Strategies:</em></p><p>This involves breaking down large documents into smaller, semantically meaningful pieces.</p><ul><li>Fixed-Size Chunking: The simplest method, but it often splits text mid-sentence, leading to semantic fragmentation.</li><li>Recursive Chunking: A more robust approach that attempts to split text along natural boundaries like paragraphs and then sentences.</li><li>Semantic Chunking: An advanced method that uses an AI model to group text by topic, ensuring chunks are thematically coherent, which is highly effective for dense, specialized documents.</li></ul><p><strong>Advanced RAG Failure Modes and Mitigation</strong></p><p>Ø <em>The ‘Lost in the Middle’ Problem:</em></p><ul><li>Root Cause: LLMs exhibit a positional bias, paying more attention to information at the beginning and end of the context window while neglecting information in the middle. This is an architectural artifact of how transformer attention works.</li><li>Mitigation: Use a re-ranking model to identify the most relevant retrieved chunks and strategically place them at the beginning and end of the context window. Limiting the number of retrieved documents to the most essential (e.g., 3–5) also prevents critical information from being pushed into the ignored middle section.</li></ul><p>Ø <em>Context Poisoning:</em></p><ul><li>Root Cause: This occurs when outdated (“context rot”), irrelevant, or malicious information is ingested into the knowledge base and retrieved, leading to incorrect or harmful responses.</li><li>Mitigation: Employ hybrid search, which combines keyword-based (lexical) and vector-based (semantic) retrieval to improve relevance and reduce noise. Implement rigorous data quality gates and sanitization pipelines during data ingestion. Enriching data with metadata filters (e.g., creation date, source) allows the system to retrieve the most current and authoritative information.</li></ul><p>Ø <em>Context Window Overflow:</em></p><ul><li>Root Cause: The combined length of the prompt, chat history, and retrieved chunks exceeds the LLM’s maximum context window, forcing truncation or causing the model to ignore parts of the input.</li><li>Mitigation: Use dynamic context pruning to identify and remove irrelevant sentences or passages from retrieved chunks before sending them to the LLM. For conversational agents, use a sliding window with summarization, keeping recent turns verbatim and summarizing older ones. For critical information, use structured memory (like a JSON object) that is passed to the agent at each step, separate from the conversational context.</li></ul><h3>3. Harness Engineering (The Runtime &amp; Toolkit)</h3><p>Harness Engineering is the runtime layer around the model. It is the software that decides which tools the agent can use, whether it is allowed to use them, how credentials are handled, how calls are logged, and how failures are surfaced. Without a harness, an LLM is just generating text. With a good harness, it can become a controlled part of a larger software system.</p><p><strong>Core Architectural Components</strong></p><p>A production harness usually has a few core components. These components are not optional extras; they are what make tool-using agents safe enough to run outside a demo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBf9gRoqbZZK5aKKEigmrw.png" /><figcaption><strong>🛡️ FIGURE 3 · PRODUCTION HARNESS ARCHITECTURE — </strong>The control plane that turns model output into safe, observable action</figcaption></figure><ul><li><em>Tool Registry:</em> A centralized catalog of all available tools (APIs, functions) an agent can use. It stores rich metadata for each tool, including a natural language description, input/output schema, and potential side effects (e.g., “read-only”). This metadata is crucial for the LLM to make intelligent decisions about which tool to use.</li><li><em>Permissions Manager (RBAC):</em> A critical security component that enforces Role-Based Access Control, governing what actions an agent is authorized to perform. It maps principals (users, agents) to roles and resources, ensuring the principle of least privilege is upheld. Every tool execution is intercepted and verified against these permissions.</li><li><em>Secure API Gateway &amp; Credential Vault:</em> The gateway acts as a single, fortified entry point for all external tool calls, handling authentication, rate limiting, and logging. It is integrated with a Credential Vault (e.g., HashiCorp Vault, AWS Secrets Manager), which securely stores and manages API keys and other secrets, preventing them from ever being exposed to the agent or application code.</li><li><em>Sandboxed Execution Environment:</em> A non-negotiable component for agents that generate and execute code. It is an isolated runtime (using technologies like Docker or Firecracker micro-VMs) where untrusted code can run without any access to the host system, mitigating risks like code injection or infinite loops.</li></ul><p><strong>Implementation Best Practices</strong></p><ul><li><em>Tool-Use Orchestration:</em> Production systems are moving towards multi-agent designs where a “planner” agent decomposes a task and delegates to specialized “worker” agents. This separation of concerns avoids context bloat and makes the system more robust and maintainable.</li><li><em>Long-Term State Management</em>: To prevent “context rot” where an agent loses track of its goal over long interactions, critical state (like the plan or partial results) should be externalized to a dedicated database or state store. This allows for long-running, multi-session tasks without overflowing the context window.</li></ul><h3>4. Loop Engineering (The Workflow)</h3><p>Loop Engineering turns a one-shot model call into an iterative workflow. The system thinks about the next step, acts, observes the result, and then decides what to do next. This is what allows an agent to recover from errors, keep track of progress, and continue working toward a larger goal instead of producing a single answer and stopping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M2KnOHYyoGDnT4XHegAmQ.png" /><figcaption><strong>🔁 FIGURE 4 · THINK → ACT → OBSERVE LOOP — </strong><em>The feedback cycle that converts prompting into autonomous progress</em></figcaption></figure><p>An autonomous agent loop operates on a continuous “<strong>Think-Act-Observe</strong>” cycle, guided by four essential components:</p><ul><li><em>Think:</em> The agent begins by considering its Goal State, which is a specific and verifiable objective, such as “P99 latency is below 500ms.” It then uses a reasoning process, often following a ReAct (Reason + Act) framework, to determine the best next action to achieve that goal.</li><li><em>Act: </em>Based on its reasoning, the agent executes the chosen action, such as calling a tool or running a command.</li><li><em>Observe:</em> The agent then observes the outcome of its action, which serves as a Feedback Mechanism. This could be the output of a successful tool call, an error message from a failed test, or even a critique from another AI model in an AI-in-the-Loop (AITL) pattern. This observation informs the next “Think” cycle.</li></ul><p>The entire loop continues until a Termination Condition is met, such as the successful achievement of the goal, exceeding a time limit, or encountering an unrecoverable error that requires human escalation. This ensures the agent operates with clear direction and avoids endless, costly cycles.</p><p><strong>Common Failure Modes in Loop Engineering</strong></p><ul><li><em>Infinite Loops or Resource Draining:</em> The most common failure, where an agent with an unclear goal enters a repetitive cycle that makes no progress.</li><li><em>Context Drift:</em> In long-running loops, the agent’s context can become cluttered, causing it to “forget” or lose focus on the original high-level goal.</li><li><em>Weak Verification:</em> The agent terminates prematurely, believing it has succeeded because the success condition was too easy or didn’t accurately reflect the true goal.</li><li><em>Inability to Recover from Errors:</em> A brittle loop may fail completely when a tool returns an unexpected error, rather than reasoning about the error and trying an alternative approach.</li></ul><h3>The Integrated Architectural Pattern: The Orchestrated Multi-Agent Loop</h3><p>Combining all four layers gives us a practical pattern for building autonomous systems: the “Orchestrated Multi-Agent Loop.” In this pattern, a central Orchestrator Agent manages a team of specialized Sub-Agents to achieve a complex goal. This pattern is especially useful in high-stakes, real-time environments such as IT Operations (ITOps).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tl1MPioUJ5SaVyXoD_f44Q.png" /><figcaption><strong>🤖 FIGURE 5 · ORCHESTRATED MULTI-AGENT LOOP ARCHITECTURE — </strong>A production pattern for delegating complex goals to specialized agents</figcaption></figure><p><strong>Scenario:</strong> An Autonomous ITOps Agent is given the high-level goal: “Maintain the health of the production database cluster and resolve any performance degradation incidents.”</p><ol><li><em>Trigger and Goal Definition (Loop Engineering):</em></li></ol><ul><li>An alert fires from a monitoring system: CRITICAL: P99 Query Latency &gt; 2000ms. The Orchestrator Agent receives this and formulates a specific goal: “Resolve the high latency incident and restore P99 latency to &lt; 500ms.” The loop is now active.</li></ul><p>2. <em>Diagnosis via Context and Prompt Engineering:</em></p><ul><li>The Orchestrator delegates to a specialized Diagnosis Agent.</li><li>Context Engineering: The agent is provided with real-time context, including the alert payload, live performance metrics, and relevant snippets from company runbooks retrieved via RAG.</li><li>Prompt Engineering: The agent’s prompt is engineered for root cause analysis: <em>“You are an expert SRE. Based on the provided metrics and runbooks, determine the most likely root cause.”</em> The agent analyzes the context and identifies a “long_running_query”.</li></ul><p>3. <em>Remediation via Harness Engineering:</em></p><ul><li>The Orchestrator receives the diagnosis and delegates to a Remediation Agent.</li><li>Harness Engineering: The Harness provides the agent with a “kill_query(query_id)” tool. Before execution, the Permissions Manager (RBAC) verifies the agent has the authority for this action. The call is made through a Secure API Gateway, using credentials from a Credential Vault.</li></ul><p>4. Verification and Iteration (Loop Engineering):</p><ul><li>The Orchestrator starts verification by monitoring latency metrics. If latency does not recover, the loop repeats. The new context now includes “Initial attempt to kill query failed.” The agent can then try a different solution, such as restarting a faulty service.</li><li>Once latency returns to normal and stays there, the Orchestrator verifies the goal is met and terminates the loop, posting a “Resolved” message to the appropriate channel.</li></ul><p><strong>Synergistic Benefits of the Integrated ITOps Approach:</strong></p><p>This integrated system is far more than a simple script. It can diagnose and resolve common incidents in minutes, 24/7. The Harness provides a critical safety layer, preventing the agent from taking overly drastic actions. The Loop allows the agent to be resilient, re-evaluating the situation if its first attempt fails. This creates a scalable, self-healing system that reduces downtime and frees up human engineers for more complex problems.</p><p>But this only works if the system has hard reliability controls. The architecture needs clear rules for what can be changed, what must be verified, and when a human should be brought back into the loop.</p><h3>What Makes This Reliable in Practice?</h3><p>This is where the stack moves from a good architecture diagram to something teams can actually trust.</p><p>Prompts should be versioned and tested against a small golden set, not edited casually in production. Context quality should be measured through freshness, relevance, and coverage, not just by whether the final answer sounds convincing. Tool access should sit behind RBAC, approval policies, and a secure gateway. Credentials should never be exposed to the model. Every tool call should be logged with the request, decision, result, and failure mode.</p><p>The loop also needs boundaries. A useful agent needs retry budgets, clear stop conditions, escalation paths, and external verification. The model should not be allowed to declare success just because its own response sounds confident. Success should come from an observable signal: latency recovered, ticket updated, deployment passed, report generated, customer record changed, or the requested action completed.</p><p>That is usually the difference between a good demo and a system that can be trusted in production.</p><h3>Executive Summary</h3><p>Building useful Gen-AI applications has moved well beyond prompt writing. Prompts still matter, but they are only one part of the system. Reliable applications need grounded context, a safe runtime, and workflows that can verify progress and recover from failure.</p><ul><li><strong>Prompt Engineering (The Message):</strong> Crafting clear instructions that guide model behavior and intent, while rigorously testing for failures like brittleness and drift.</li><li><strong>Context Engineering (The Knowledge):</strong> Providing the right information at the right time, primarily through advanced RAG techniques like hybrid search and strategic re-ranking, to ensure fact-based, relevant outputs.</li><li><strong>Harness Engineering (The Runtime):</strong> Building the runtime infrastructure with components like a Tool Registry, RBAC, and Sandboxed Execution Environments to connect the model to the real world reliably and safely.</li><li><strong>Loop Engineering (The Workflow):</strong> Creating iterative, self-correcting workflows with feedback mechanisms that enable autonomous operation and continuous improvement.</li></ul><p>These layers are connected. The prompt works inside the context. The harness controls how the model acts. The loop keeps the system moving, checking, and correcting itself. Teams that understand this full stack will be better prepared to build AI systems that survive real production conditions instead of only working in a demo.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0736fd94af87" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Power of Vision: How Microsoft’s OmniParser is Transforming UI Parsing]]></title>
            <link>https://medium.com/@manjrekar.kiran.82/the-power-of-vision-how-microsofts-omniparser-is-transforming-ui-parsing-047ba46e3b91?source=rss-3024e2f2fadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/047ba46e3b91</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[ui-automation-tools]]></category>
            <category><![CDATA[genai]]></category>
            <dc:creator><![CDATA[Kiran Manjrekar]]></dc:creator>
            <pubDate>Fri, 21 Feb 2025 14:29:05 GMT</pubDate>
            <atom:updated>2025-02-21T14:42:13.128Z</atom:updated>
            <content:encoded><![CDATA[<p>When intelligent agents like GPT-4V take center stage in automating tasks across desktops, mobile devices, and the web, one challenge has consistently blocked their full potential: correctly interpreting the complex universe of user interfaces. Traditional OCR engines — such as those from AWS, Azure, and Google Cloud — excel at reading text from documents, forms, and static images. However, when it comes to parsing interactive, dynamic screens where clickable icons and functional elements play a critical role, these solutions fall short. Enter OmniParser, a revolutionary tool developed by Microsoft Research, designed to provide a comprehensive, vision-only approach to UI screen parsing that goes far beyond mere text extraction.</p><h3>A New Paradigm in UI Understanding</h3><p>OmniParser addresses two core challenges that have long limited the deployment of multimodal agents in real-world settings. First, it consistently identifies interactable icons within a screenshot, and second, it understands the semantics of these elements, linking them to the proposed user action. Rather than relying on additional information like HTML or view hierarchies, OmniParser leverages only the raw visual input; a screenshot and transforms it into a structured, DOM-like representation that any large language vision model can use to perform tasks accurately.</p><h3>The Technology Behind OmniParser</h3><p>At its heart, OmniParser is built upon finely tuned components:</p><p>· Interactable Region Detection: By curating a dataset of 67,000 unique screenshots — with bounding boxes obtained from real web pages’ DOM trees; OmniParser trains a detection model that zeroes in on every clickable icon, button, or widget present on the screen. This approach shifts the dependency away from traditional HTML, making the model more platform-agnostic.</p><p>· Local Semantics Incorporation: Recognizing that a bounding box alone isn’t enough, a second finetuned model is dedicated to generating a functional description of each detected icon. Trained on a dataset of 7,000 icon-description pairs, this caption model introduces the “why” and “what for” behind each element, thus eliminating uncertainty for downstream action generation by GPT-4V.</p><p>· OCR Module: While traditional OCR systems can extract texts with high accuracy, OmniParser integrates an OCR module to capture textual elements. The clever post-processing step merges these OCR results with the detection outputs, ensuring that overlapping or redundant information is minimized.</p><h3>Innovative Prompting and Structured Results</h3><p>One innovative twist in OmniParser’s design is the use of the “set-of-marks” prompting strategy. Instead of asking GPT-4V to pinpoint an exact (x, y) coordinate — an extremely challenging task — the system overlays bounding boxes labelled with unique numeric IDs. When a user task is described (for instance, “click on the settings icon”), the model simply needs to select the appropriate ID. This approach has shown dramatic improvements in performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*ikBDDoDo2oFIWPOzJor3Ew.jpeg" /><figcaption>Reference taken from Microsoft OmniParser v2 Blog</figcaption></figure><h3>Benchmarking Across Real-World Scenarios</h3><p>OmniParser has been thoroughly tested across multiple benchmarks:</p><p>· ScreenSpot Benchmark: OmniParser significantly outperforms GPT-4V baselines across mobile, desktop, and web platforms. With the incorporation of both interactable region detection and local semantics, the tool surpasses even models specifically finetuned for GUI tasks.</p><p>· Mind2Web Evaluation: In web navigation scenarios, OmniParser’s vision-only approach surpasses methods that rely on HTML-derived element data. It provides higher element accuracy, better operation F1 scores.</p><p>· AITW Benchmark: On mobile navigation tasks, replacing traditional methods (like those based on IconNet) with OmniParser’s finetuned detection and descriptive models produces an overall performance boost — and a 4.7% increase over the best GPT-4V plus history baseline.</p><h3>Contrast with Traditional OCR Tools from AWS, Azure, and GCP</h3><p>Cloud providers have long offered OCR solutions that are incredibly efficient at document analysis, form-filling, and even extracting structured data from various text-heavy images. Yet, these tools have intrinsic limits when applied to the world of user interfaces:</p><p>· Focus on Text, Not Interaction: Traditional OCR engines extract text content with pinpoint accuracy. However, user interfaces are more than words; they include icons, buttons, and other interactive elements that require context-aware interpretation. While AWS Textract, Azure’s Computer Vision, and Google Cloud Vision reliably segment and extract text, they miss the underlying functionality and interactivity present in modern applications.</p><p>· Lack of Fine-Grained Elemental Semantics: OmniParser’s dual-model approach — detecting interactable regions and providing local icon descriptions — delivers a structured breakdown of UI elements that traditional OCR systems do not offer. This structured output is critical for robotic process automation or interactive task agents that need to understand “what to click” rather than just “what is written.”</p><p>· Platform-Agnostic Versatility: Traditional OCR frameworks are typically optimized for well-scanned documents or static images. OmniParser, by plainly relying on pure vision input without a need for additional HTML or view hierarchy data, is inherently more flexible across diverse platforms such as Windows, macOS, mobile environments, and even complex web applications.</p><h3>Integrating OmniParser with AI/LLM Agents</h3><p>OmniParser’s structured output; comprising interactable regions, bounding boxes with unique IDs, and semantic annotations, lends itself seamlessly to integration with autonomous AI and LLM-driven agent frameworks like AutoGen and Semantic Kernel. By feeding the parsed screen elements directly into these agents, the system can convert rich visual insights into actionable commands in real-time.</p><p>For instance, AutoGen can orchestrate multiple agents where one component focuses on interpreting user instructions and another handles execution, with OmniParser acting as the adapter that translates UI snapshots into a structured format easily digestible by LLMs.</p><p>This tight integration not only bolsters decision-making accuracy but also scales to support more complex, cross-platform workflows, establishing a new paradigm in intelligent UI automation.</p><p><a href="https://youtu.be/_NvsvzeUQz8">https://youtu.be/_NvsvzeUQz8</a></p><h3>The Road Ahead</h3><p>Like any innovative technology, OmniParser comes with challenges. Issues such as handling repeated icons, extracting precise bounding box coordinates, and resolving icon misinterpretation (when context is limited) continue to drive future research. However, the progresses made so far demonstrate that robust, vision-only parsing can transform how intelligent agents interact with complex UIs.</p><h3>Conclusion</h3><p>Microsoft’s OmniParser represents a transformative rise in screen parsing technology; one that bridges the gap between raw visual data and actionable, context-enriched UI elements. By coupling the power of specialized interactable region detection and local semantic understanding, OmniParser enables multimodal agents like GPT-4V to perform reliably across diverse platforms. Compared to traditional OCR systems offered by AWS, Azure, and GCP — which are built for text extraction rather than interactive comprehension, OmniParser overlays the way for a new era of autonomous, intelligent interface control.</p><p>Whether you’re a researcher, developer, or simply a tech enthusiast fascinated by the future of artificial intelligence in real-world applications, OmniParser indicates a future where machines can not only read a screen but truly understand and act upon it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=047ba46e3b91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SUPERCHARGING RAG: EVALUATION WITH RAGAS AND LANGCHAIN]]></title>
            <link>https://medium.com/@manjrekar.kiran.82/supercharging-rag-evaluation-with-ragas-and-langchain-05e0517875f0?source=rss-3024e2f2fadf------2</link>
            <guid isPermaLink="false">https://medium.com/p/05e0517875f0</guid>
            <category><![CDATA[llm-evaluation]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[rag-evaluation]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <dc:creator><![CDATA[Kiran Manjrekar]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 14:46:09 GMT</pubDate>
            <atom:updated>2025-02-07T14:46:09.254Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Retrieval-Augmented Generation (RAG) has emerged as a powerful technique for answering domain-specific questions accurately. It augments traditional model generation with a retrieval step to incorporate authoritative, external documents. However, evaluating a RAG pipeline requires specialized metrics to ensure that the system is both factually correct and contextually relevant. That is precisely where the RAGAS framework excels.</p><p>This blog explains:<br>• The fundamentals of RAG and how it benefits QA tasks.<br>• Key metrics in the RAGAS framework.<br>• How to integrate RAG, RAGAS, LangChain, with LLM into a cohesive pipeline.<br>• Practical code snippets in Python for a hands-on demonstration.</p><h3>Key Concepts</h3><h4>2.1 What Is RAG?</h4><p>RAG (Retrieval Augmented Generation) is an approach that enhances generative models by integrating a document retrieval process. It works by:</p><ul><li><strong>Retrieval</strong>: Given a user query, a retriever fetches relevant documents or passages from an external knowledge source.</li><li><strong>Augmentation</strong>: These retrieved texts are added as context to the input of the generative model.</li><li><strong>Generation</strong>: The model then produces responses that better reflect up-to-date or factual information by leveraging the additional context.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*e71iD4_5XCh5yiXn.png" /></figure><p>By combining retrieval with generation, RAG significantly reduces hallucinations and improves the factual correctness of answers. This approach is ideal for enterprise applications where trust and reliability are paramount.</p><h4>2.2 RAGAS Framework</h4><p>The RAGAS framework is a specialized toolkit for evaluating RAG pipelines. It focuses on the following core metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLhUMpVmvyohNmLot6lUqA.png" /><figcaption>Base Metrics for RAG</figcaption></figure><p><em>Faithfulness</em>: Assesses whether the generated response aligns correctly with the content of the retrieved documents rather than speculating or inventing information.</p><p><em>Answer/Response Relevancy</em>: Evaluates how relevant the generated response is to the original query.</p><p><em>Context Precision</em>: Measures the precision of the retrieved documents in providing relevant information to the query.</p><p><em>Context Recall</em>: Assesses how well the retrieved documents cover all relevant aspects of the query.</p><h4>2.3 LangChain and Azure OpenAI</h4><p>• LangChain: A Python library that simplifies building end-to-end RAG workflows by providing modular components such as retrievers, vector stores, prompt templates, and chains.<br>• Azure OpenAI: Offers enterprise-grade capabilities of OpenAI’s GPT models within Microsoft’s Azure ecosystem. This makes it easier to deploy, manage, and scale advanced language models for production-level solutions.</p><h3>RAG Pipeline Overview</h3><p>A typical RAG pipeline includes these steps —</p><p><em>Knowledge Base Construction</em>: Collect relevant documents or data and generate embeddings to store in a vector database (or an in-memory vector store).</p><p><em>Retrieval</em>: For each incoming query, the retriever locates and returns the most relevant documents from the vector store.</p><p><em>Generation</em>: An LLM uses the retrieved text snippets as context to produce an answer that is both context-aware and factually correct.</p><p><em>Evaluation</em>: Use the RAGAS framework to measure important metrics like Faithfulness, Context Recall, and Factual Correctness.</p><p>LangChain modular components help assemble this pipeline with minimal overhead, enabling quick development and iterative testing.</p><h3>Practical Implementation</h3><p>Below is a conceptual outline for implementing a RAG pipeline using LangChain, Azure OpenAI, and the RAGAS framework. The example focuses on building a knowledge base of information about notable AI leaders (e.g., Andrew Ng, Sam Altman).</p><blockquote><strong>NOTE:</strong> The working implementation shared below works well with popular LLM models like OpenAI, Azure OpenAI, Gemini. I have tried to make the similar example work with locally deployed (CPU laptop) Ollama model which failed to run the evaluations with “Timeout Errors”. RAGAS expects the evaluation job runs to be completed in predefined time and has open issue with Ollama integration.</blockquote><p>I have attached the references of the source code below at the end, for both Azure OpenAI and Ollama execution. You can have a look and benefit from it.</p><p>So Let’s get started..</p><h4>4.1 Environment Setup</h4><p>To run this evaluation, make sure you have created Python virtual environment necessary for the execution (preferrable python version &gt;3.10).</p><p>Install below python dependencies in your environment to activate LangChain and RAGAS frameworks.</p><pre>pip install langchain langchain-core langchain-huggingface langchain-openai<br>pip install ragas</pre><h4>4.2 Setting Up Azure OpenAI and Embeddings</h4><ul><li>Azure OpenAI: Set up your Azure OpenAI resource and retrieve the endpoint, API key, and deployment name.</li><li>Embeddings: Use a Hugging Face embedding model (or any other supported model) to generate embeddings for your documents.</li></ul><p>Configure environment variables for Azure OpenAI subscription and initialize Azure OpenAI LLM.</p><pre>import os<br>from langchain.llms.azure_openai import AzureOpenAI<br><br>os.environ[&quot;AZURE_OPENAI_ENDPOINT&quot;] = &quot;&lt;YOUR_AZURE_OPENAI_ENDPOINT&gt;&quot;<br>os.environ[&quot;AZURE_OPENAI_API_KEY&quot;] = &quot;&lt;YOUR_AZURE_OPENAI_API_KEY&gt;&quot;<br>os.environ[&quot;OPENAI_API_VERSION&quot;] = &quot;&lt;YOUR_OPENAI_API_VERSION&gt;&quot;<br><br>llm = AzureChatOpenAI(<br>        azure_deployment=&quot;&lt;YOUR_AZURE_DEPLOYMENT_NAME&gt;&quot;,<br>    )</pre><p>Initialize embedding model. Using Sentence Transformer’s embedding model here. You can opt for OpenAI embedding model or others.</p><pre>from langchain.embeddings import HuggingFaceEmbeddings<br><br>embed_model = HuggingFaceEmbeddings(model_name=&quot;sentence-transformers/all-MiniLM-L6-v2&quot;)</pre><h4>4.3 Building the Knowledge Base</h4><p>Prepare a list of documents (e.g., text files or strings about Andrew Ng, Sam Altman, etc.). Convert these documents into embeddings and store them in a vector store.</p><p>Using In-memory vector store for easy implementation. You can choose from variety of vector stores like FAISS, Elasticsearch, PG Vector etc. based on your requirements.</p><pre>from langchain_core.documents import Document<br>from langchain_core.vectorstores import InMemoryVectorStore<br><br>vector_store = InMemoryVectorStore(embed_model)<br><br>content_list = [<br>    &quot;Andrew Ng is the CEO of Landing AI and is known for his pioneering work in deep learning. He is also widely recognized for democratizing AI education through platforms like Coursera.&quot;,<br>    &quot;Sam Altman is the CEO of OpenAI and has played a key role in advancing AI research and development. He is a strong advocate for creating safe and beneficial AI technologies.&quot;,<br>    &quot;Demis Hassabis is the CEO of DeepMind and is celebrated for his innovative approach to artificial intelligence. He gained prominence for developing systems that can master complex games like AlphaGo.&quot;,<br>    &quot;Sundar Pichai is the CEO of Google and Alphabet Inc., and he is praised for leading innovation across Google&#39;s vast product ecosystem. His leadership has significantly enhanced user experiences on a global scale.&quot;,<br>    &quot;Arvind Krishna is the CEO of IBM and is recognized for transforming the company towards cloud computing and AI solutions. He focuses on providing cutting-edge technologies to address modern business challenges.&quot;,<br>]<br><br>langchain_documents = []<br><br>for content in content_list:<br>    langchain_documents.append(<br>        Document(<br>            page_content=content,<br>        )<br>    )<br><br>_ = vector_store.add_documents(langchain_documents)</pre><h4>4.4 RAG Workflow</h4><p>With the embeddings stored, configure a retriever that fetches the top “k” relevant documents for a user query. Then, create a QA chain that combines retrieved documents with a generative model prompt.</p><pre>from langchain_core.prompts import ChatPromptTemplate<br>from langchain_core.output_parsers import StrOutputParser<br><br>retriever = vector_store.as_retriever(search_kwargs={&quot;k&quot;: 1})<br><br>template = &quot;&quot;&quot;Answer the question based only on the following context:<br>{context}<br>Question: {query}<br>&quot;&quot;&quot;<br>prompt = ChatPromptTemplate.from_template(template)<br><br>qa_chain = prompt | llm | StrOutputParser()</pre><h4>4.5 Evaluating with the RAGAS Framework</h4><p>Finally, we use a dataset of queries and expected answers to compute RAGAS metrics.</p><pre>from ragas import EvaluationDataset, evaluate<br>from ragas.metrics import Faithfulness, LLMContextRecall, FactualCorrectness<br><br>def rag_query(question: str) -&gt; str:<br>  docs = retriever.get_relevant_documents(question)<br>  context = &quot;\n&quot;.join([d.page_content for d in docs])<br>  return qa_chain.run(context=context, question=question)<br><br>#Prepare sample dataset: a list of dictionaries with query, answer, and optionally reference<br>sample_data = [<br>{<br>&quot;query&quot;: &quot;Who is Andrew Ng?&quot;,<br>&quot;answer&quot;: rag_query(&quot;Who is Andrew Ng?&quot;),<br>&quot;reference&quot;: &quot;Andrew Ng is a Chinese American computer scientist...&quot;<br>},<br># Add more questions and references as needed...<br>]<br><br>evaluation_dataset = EvaluationDataset.from_list(sample_data)</pre><p>EvaluationDataset standardizes the collected evaluation examples into a structured format. In this code, it encapsulates user inputs, the model&#39;s generated responses, and the reference answers. This organization facilitates computing metrics and running evaluations on a consistent dataset, streamlining the analysis and comparison process.</p><p>Run evaluation on evaluation dataset for metrics like Faithfulness, Context recall, Factual correctness etc.</p><pre>from ragas.llms import LangchainLLMWrapper<br>from ragas.embeddings import LangchainEmbeddingsWrapper<br>from ragas.run_config import RunConfig<br>from langchain_core.callbacks import BaseCallbackHandler<br><br><br>evaluator_llm = LangchainLLMWrapper(llm)<br>evaluator_embed = LangchainEmbeddingsWrapper(embed_model)<br><br>my_run_config = RunConfig(max_workers=5, timeout=60, max_retries=3)<br><br>class TestCallback(BaseCallbackHandler):<br><br>    def on_llm_start(self, serialized, prompts, **kwargs):<br>        pass<br>        #print(f&quot;**********Prompts*********:\n {prompts[0]}\n\n&quot;)<br><br>    def on_llm_end(self, response, **kwargs):<br>        pass<br>        #print(f&quot;**********Response**********:\n {response}\n\n&quot;)<br><br>result = evaluate(<br>    dataset=evaluation_dataset,<br>    metrics=[Faithfulness(), LLMContextRecall(), FactualCorrectness()],<br>    llm=evaluator_llm,<br>    embeddings=evaluator_embed,<br>    run_config=my_run_config,<br>    raise_exceptions=True,<br>    callbacks=[TestCallback()]<br>)<br><br>print(result)</pre><p><strong>LangchainLLMWrapper</strong><br>Wraps the provided LLM to conform to Langchain’s expected interface. This allows the evaluation framework to interact uniformly with the LLM, making it easier to integrate into the pipeline.</p><p><strong>LangchainEmbeddingsWrapper</strong><br>Wraps the embedding model so that its embeddings can be used seamlessly within the LangChain ecosystem. It standardizes the embedding output, ensuring compatibility with other components (like metrics) in the evaluation.</p><p><strong>TestCallback</strong><br>Inherits from BaseCallbackHandler and provides hooks (callbacks) during the evaluation process. The methods (“<em>on_llm_start</em>” and “<em>on_llm_end</em>”) allow inspection or logging of the prompts and responses generated by the LLM. Although the print statements are currently commented out, they can be enabled for debugging or tracking the evaluation flow.</p><h4>4.6 Ollama integration for running locally</h4><p>To run RAGAS evaluation locally on your development machine, you need to have below pre-requisites.</p><p>· Install Ollama application on your machine. (<a href="https://ollama.com/download">download</a>)</p><p>· Once Ollama server starts, download any of your favorite open source LLM model which will help you perform RAG operation efficiently (I tried to use llama3.2 model from meta for my usage).</p><p>Run Ollama server once the model is downloaded.</p><pre>ollama pull llama3.2<br><br>ollama run llama3.2</pre><p>· Install below python libraries in your python environment</p><pre>pip install ollama<br>pip install langchain-ollama</pre><p>· Define chat based Ollama model so that it is used further within RAG as well as within RAGAS evaluation as LLM retriever.</p><pre>llm = ChatOllama(<br>    model=&quot;llama3.2&quot;,<br>    temperature=0,<br>    top_k=10,<br>)</pre><h3>Key Metrics and Why They Matter</h3><p>Below are several key metrics from the RAGAS framework and why they matter —</p><p>· <em>Context Precision and Context Recall</em>: These metrics measure the quality of the retrieval component by evaluating how accurately (precision) and comprehensively (recall) the relevant information is brought in. High precision ensures that only closely related information is used, while high recall guarantees that important context isn’t missed — both are essential for producing reliable responses.</p><p>· <em>Response Relevancy</em>: This evaluates how well the generative output addresses the user’s query using the provided context. It’s crucial because the final answer must not only be coherent but also directly useful to the user, reflecting an effective integration of retrieval and generation.</p><p>· <em>Faithfulness and Factual Correctness</em>: These metrics ensure that the generated response is firmly grounded in the retrieved source material, avoiding hallucinations or distortions. In applications where accuracy is paramount (like legal or medical domains), ensuring factual correctness builds trust and reliability.</p><p>· <em>Multimodal Faithfulness (for systems using multiple data types)</em>: When working with inputs like images or audio in addition to text, this metric confirms that each modality contributes correctly to the final output. This is key for applications that rely on a rich mix of data to provide robust, context-aware answers.</p><p>For agent or tool-based workflows, additional metrics such as Tool Call Accuracy and Agent Goal Accuracy are vital because they verify that the system correctly interacts with external resources and consistently achieves its intended objectives.<br>In summary, focusing on retrieval (Context Precision/Recall), relevance (Response Relevancy), and generation accuracy (Faithfulness/Factual Correctness) provides a robust foundation for any RAG system, ensuring that outputs are both contextually rich and reliable.</p><h3>Advantages</h3><p>• <em>Structured Evaluation</em>: Breaks down pipeline performance into retrieval quality, generation accuracy, and overall efficiency, making it easy to pinpoint issues.<br>• <em>Enhanced Factual Consistency</em>: By aligning the retrieved information with generated content, it minimizes hallucinations and improves answer reliability.<br>• <em>Continuous Optimization</em>: Benchmarking allows teams to fine-tune both retrieval and generation components, balancing speed with quality.<br>• <em>Accelerated Development</em>: Clear, quantifiable metrics streamline iterative improvements, reducing development time and speeding up deployment.</p><h3>Next Steps</h3><p>· Extend the dataset to include more complex queries and domain-specific documents.</p><p>· Experiment with different retriever strategies and embeddings to improve Context Recall.</p><p>· Combine more advanced prompt-engineering or chain-of-thought approaches to enhance Faithfulness and Factual Correctness.</p><h3>Conclusion</h3><p>By combining Azure Open AI, LangChain, and the RAGAS framework, you can build robust RAG pipelines that not only deliver context-rich answers but are also thoroughly evaluated for reliability.</p><p>The metrics provided by RAGAS — Faithfulness, Context Recall, and Response relevancy and other metrics integrated within it like BLEU, ROUGE etc. — offer a holistic way to measure and refine the performance of your system. This ensures that your RAG deployment consistently produces trustworthy, consistent results for enterprise-grade applications.</p><p>With this foundation, you have a powerful blueprint to build, evaluate, and evolve a robust RAG solution tailored to your unique domain. By leveraging the proven capabilities of Azure OpenAI, Langchain’s user-friendly components, and RAGAS’s specialized metrics, you can confidently deploy a system that is both trustworthy and highly effective.</p><h3>References</h3><ul><li><a href="https://github.com/kaustubhrm/GenAI_LLM_Examples/blob/main/examples/ragas_evaluation_openai.ipynb">GenAI_LLM_Examples/examples/ragas_evaluation_openai.ipynb at main · kaustubhrm/GenAI_LLM_Examples</a></li><li><a href="https://github.com/kaustubhrm/GenAI_LLM_Examples/blob/main/examples/ragas_evaluation_ollama.ipynb">GenAI_LLM_Examples/examples/ragas_evaluation_ollama.ipynb at main · kaustubhrm/GenAI_LLM_Examples</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05e0517875f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>