<?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 Ravi Chamarthy on Medium]]></title>
        <description><![CDATA[Stories by Ravi Chamarthy on Medium]]></description>
        <link>https://medium.com/@ravi-chamarthy?source=rss-18a5c220ba3c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*ndT-uJJ3KRXxuGv0_3_OVw.jpeg</url>
            <title>Stories by Ravi Chamarthy on Medium</title>
            <link>https://medium.com/@ravi-chamarthy?source=rss-18a5c220ba3c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 14:17:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ravi-chamarthy/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[Your AI Agent Is Ready. But Is It Secure?]]></title>
            <link>https://ravi-chamarthy.medium.com/your-ai-agent-is-ready-but-is-it-secure-54e8b02c27e7?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/54e8b02c27e7</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[owasp]]></category>
            <category><![CDATA[watsonx]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 09:42:20 GMT</pubDate>
            <atom:updated>2026-10-26T09:42:20.860Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Assessing Security Risks from the OWASP Top 10 for Agentic Applications with IBM watsonx.governance</em></p><p>Co-authored by <a href="https://www.linkedin.com/in/neelima-reddy-gade/">NeelimaReddy Gade</a> , <a href="https://www.linkedin.com/in/manishbhide/">Manish Bhide</a> , <a href="https://www.linkedin.com/in/ravichamarthy/">Ravi Chamarthy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HRyzhcjCtCEpFLDoVHkgmQ.png" /><figcaption>Bob-watsonx.governance security scan</figcaption></figure><h3>The Challenge: Is Your AI Agent Secure?</h3><p>AI-powered development tools are changing how developers build applications. What previously required days of coding can now be accomplished in minutes with a well-crafted prompt.</p><p>With <strong>IBM Bob</strong>, developers can generate AI agents, implement business logic, integrate agent development frameworks, and accelerate their development workflows. But as AI-generated agents become increasingly capable, an important question emerges:</p><p><strong>Just because an AI agent meets your organization’s governance policies, does that mean it is secure?</strong></p><p><em>Not necessarily.</em></p><p>An AI agent might satisfy organizational requirements around fairness, transparency, and responsible AI while still containing serious security vulnerabilities.</p><p>For example, consider a loan approval agent that processes applicant information to determine eligibility. What if malicious instructions embedded in an applicant’s input manipulate the agent into using fabricated income or credit scores? Or what if failures in fairness checks do not prevent the agent from proceeding with loan approval decisions?</p><pre>response = llm.invoke([HumanMessage(content=applicant_input)])</pre><p>Here, untrusted applicant input is passed directly to the LLM without adequate safeguards, potentially allowing malicious instructions to influence the agent’s behavior. This could lead to <strong>Agent Goal Hijack (ASI01)</strong>, resulting in incorrect loan eligibility decisions.</p><p>This is where the <strong>OWASP Top 10 for Agentic Applications</strong> becomes particularly relevant. It highlights the most critical security risks associated with AI agents, including goal hijacking, tool misuse, unauthorized code execution, and privilege abuse.</p><h3>Understanding Agentic AI Security Risks</h3><p>Unlike traditional applications, AI agents can dynamically invoke tools, access information, and perform actions. This autonomy introduces security risks such as malicious instructions, unvalidated inputs, unauthorized access, and sensitive data exposure.</p><p>The <a href="https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/">OWASP Top 10 for Agentic Applications for 2026</a> provides a framework for understanding and addressing security risks associated with agentic applications.</p><p>For developers, the challenge is translating these security principles into practical checks against the code they are building.</p><p>Questions worth asking include:</p><ul><li>Can the agent execute code generated by an LLM without validation?</li><li>Are tool invocations protected by appropriate input validation?</li><li>Can the agent access resources or data beyond the requesting user’s permissions?</li><li>Are credentials and other sensitive information adequately protected?</li></ul><p>These are precisely the kinds of security concerns that need attention before deploying an agent into production.</p><h3>Introducing OWASP Security Assessment in IBM watsonx.governance</h3><p>A recent release of <strong>IBM watsonx.governance</strong> introduces security assessment capabilities aligned with the OWASP Top 10 for Agentic Applications, which provides an additional way to assess the security posture of discovered AI agents.</p><p>The workflow is particularly interesting when combined with IBM Bob and GitHub Enterprise.</p><p>Developers can generate agent code using Bob, push the code to a configured GitHub Enterprise repository, and then use watsonx.governance to discover the agent and initiate an OWASP security scan.</p><p>The assessment identifies potential security issues, categorizes findings, assigns severity levels, and provides supporting evidence and recommendations.</p><p>The resulting workflow looks like this:</p><p><strong>IBM Bob → GitHub Enterprise → watsonx.governance AI Discovery → OWASP Security Scan → Findings → Code Remediation → Rescan</strong></p><p>This connects agent development, governance visibility, and security assessment in a single iterative process.</p><h3>From Agent Discovery to Security Remediation</h3><p>The configuration and assessment process is straightforward.</p><h4>Configure GitHub Enterprise in watsonx.governance</h4><p>Configure a GitHub Enterprise connection in watsonx.governance by specifying the GitHub organization, repository, and Personal Access Token.</p><p>This enables watsonx.governance to discover AI agents from the configured repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFm420MuEqvnRT0LjDhZ_w.png" /><figcaption>GitHub Enterprise — Org/Repo configuration with watsonx.governance for scanning</figcaption></figure><h4>Configure Git Credentials for IBM Bob</h4><p>Configure Git authentication on the local development system so Bob can push generated code to GitHub Enterprise.</p><p>For example, using ~/.netrc:</p><pre># cat  ~/.netrc <br>machine github.ibm.com<br>login &lt;GIT_USER&gt;<br>password &lt;GIT_PERSONAL_ACCESS_TOKEN&gt;<br># echo &quot;Restrict access to the credentials file&quot;<br># chmod 600 ~/.netrc</pre><p>Ensure the credentials have the required repository permissions.</p><h4>Generate and Push Agent Code Using IBM Bob</h4><p>Provide the following prompt to IBM Bob:</p><pre>Create an agent using the LangGraph Agent Framework for a loan approval <br>scenario.Evaluate applicant eligibility based on income, credit score, <br>and existing liabilities whileensuring fair treatment regardless of gender.<br>Keep the implementation simple and contained in a single Python file named<br>techxchange_loan_approval_agent.py. <br>Make sure the agent name is &quot;Loan Processing Agent&quot;.<br>Also, push the generated Python file to:<br>https://github.ibm.com/&lt;MYORG&gt;/&lt;MYREPO&gt;/tree/master/&lt;MYFOLDER&gt;</pre><p>Bob generates the agent code and can push it to the specified GitHub Enterprise repository using the configured credentials.</p><h4>Discover the Agent and Trigger the OWASP Scan</h4><p>Navigate to <strong>AI Discovery</strong> in the watsonx.governance console, the agents discovered from the configured GitHub Enterprise repository appear in the asset inventory. Select the discovered agent, open its actions menu, and choose <strong>Run OWASP scan</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bDlLyzm-89vrh9-H37tJRg.png" /><figcaption><strong>AI Discovery showing the discovered agent and Run OWASP scan option</strong></figcaption></figure><h4>Review the OWASP Security Findings</h4><p>Once the scan completes, watsonx.governance displays the identified vulnerabilities along with their severity, evidence, impact, and recommended remediation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cp1L9dCMVNF763E2xA8ghQ.png" /><figcaption><strong>OWASP scan results showing the findings and severity levels</strong></figcaption></figure><p>In this example, the assessment identified <strong>2 security findings — 1 High and 1 Medium</strong>, covering two OWASP categories:</p><ul><li><strong>ASI01 — Agent Goal Hijack (High):</strong> Applicant-controlled instructions can manipulate the loan processing agent’s objective, potentially introducing fabricated applicant information into eligibility decisions.</li><li><strong>ASI08 — Cascading Failures (Medium):</strong> Failures detected during fairness audits do not prevent the agent from proceeding with final loan decisions, potentially resulting in unfair outcomes.</li></ul><h4>Remediate the Vulnerabilities Using IBM Bob</h4><p>The findings can be addressed manually or provided back to IBM Bob for code remediation.</p><p>For example:</p><pre>Review the following OWASP security finding identified by <br>IBM watsonx.governance.<br><br>Category: ASI01_Agent_Goal_Hijack<br>Severity: High<br>Finding:<br>Applicant-controlled instructions can hijack the loan parser objective and<br>feed fabricated profile data into eligibility decisions.<br>Evidence:<br>The parse_applicant function passes untrusted applicant text directly to <br>the LLM and uses the generated JSON output for downstream loan eligibility <br>decisions without validation.<br>Recommendation:<br>Treat applicant-provided text as untrusted data. Use structured LLM outputs<br>with strict schema validation and prevent embedded instructions from <br>influencing the agent&#39;s behavior. Fix the vulnerability while preserving the<br>existing loan approval functionality. Add appropriate input validation and<br>security tests.</pre><p>Once the changes are reviewed and tested, the updated code can be pushed to GitHub Enterprise. The OWASP scan can then be triggered again in watsonx.governance to verify whether the reported vulnerability has been addressed.</p><p>This creates a continuous security improvement workflow:</p><p><strong>Generate with Bob → Push to GitHub → Discover in watsonx.governance → Run OWASP Scan → Fix with Bob → Rescan</strong></p><h3>Conclusion</h3><p>AI-generated agents can introduce security vulnerabilities even when they implement the intended business functionality.</p><p>The OWASP Top 10 security assessment for Agentic Applications capability in <strong>IBM watsonx.governance</strong> helps developers identify such vulnerabilities in agents discovered from GitHub Enterprise repositories.</p><p>Combined with <strong>IBM Bob</strong>, this enables a practical workflow for generating agent code, identifying security risks, remediating vulnerabilities, and validating the updated implementation.</p><blockquote><strong>The goal is not just to generate code for AI agents faster, but to build them more securely.</strong></blockquote><h3><strong>References</strong></h3><ul><li><a href="https://www.ibm.com/new/announcements/new-in-ibm-watsonx-governance-govern-ai-agents-as-you-build-expand-accountability-and-streamline-compliance">New in IBM watsonx.governance: Govern AI agents as you build, expand accountability and streamline compliance</a></li><li><a href="https://medium.com/@ravi-chamarthy/govern-ai-agents-as-you-build-bringing-ibm-watsonx-governance-into-ibm-bob-a083fbbe1e9a">Govern AI Agents as You Build: Bringing IBM watsonx.governance into IBM Bob</a></li><li><a href="https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/">OWASP Top 10 for Agentic Applications — 2026</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54e8b02c27e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Govern AI Agents as You Build: Bringing IBM watsonx.governance into IBM Bob]]></title>
            <link>https://ravi-chamarthy.medium.com/govern-ai-agents-as-you-build-bringing-ibm-watsonx-governance-into-ibm-bob-a083fbbe1e9a?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a083fbbe1e9a</guid>
            <category><![CDATA[watsonx]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[ai-governance]]></category>
            <category><![CDATA[ibm-bob]]></category>
            <category><![CDATA[governance]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 19:53:04 GMT</pubDate>
            <atom:updated>2026-10-17T19:53:04.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Co-Authored with <a href="https://www.linkedin.com/in/puneet-udhayan/">Puneet Udhayan</a>, Shashidhar Y</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_1EyxK49e5LleGicM0XNg.png" /><figcaption>IBM Bob + watsonx.governance workflow</figcaption></figure><h3>Why AI Governance Matters in AI-Assisted Development?</h3><p>AI-powered development assistants are transforming how developers build applications and AI agents. With (AI-powered) software development partners like <strong>IBM Bob</strong>, developers can turn natural-language instructions into working code and AI agents within minutes. But faster development raises an important question:</p><p><strong><em>How do we ensure that AI-generated code aligns with an organization’s responsible AI policies?</em></strong></p><p>This is where the integration of <strong>IBM Bob with IBM watsonx.governance</strong> becomes valuable.</p><p>By connecting AI-assisted development with governance capabilities, organizations can introduce policy validation directly and as early as into the development workflow, helping developers identify potential policy violations and governance risks before applications move further toward deployment.</p><h3>Bringing Governance into the Development Workflow</h3><p>When a developer saves an agent-related file or completes an interaction with Bob, watsonx.governance can analyze the code, identify AI agents, capture relevant metadata, and assess potential policy violations and risks against organizational AI usage criteria.</p><p>Well, let’s take an example — consider a developer is using IBM Bob to build a loan approval agent with the following prompt:</p><blockquote>Create an agent using the LangGraph Agent Framework for a loan approval scenario. Evaluate applicant eligibility based on income, credit score, and existing liabilities while ensuring fair treatment regardless of gender. Keep the implementation simple and contained in a single Python file with file name as loan_approval_agent.py.</blockquote><p>The agent code is generated, but loan approval is a sensitive use case. At first glance, the prompt appears to address fairness. But does that automatically make the agent compliant with organizational AI policies?</p><p><strong><em>Not necessarily!</em></strong></p><p>Loan approval is a consequential decision-making use case, and many organizations require additional risk reviews for AI systems involved in determining access to financial services.</p><p><strong>And, this is where watsonx.governance enters the picture.</strong></p><p>Through the IBM Bob extension, an API call can be triggered to watsonx.governance to evaluate the generated code or its associated use-case information against organizational governance policies.</p><p>The resulting policy assessment helps developers understand whether their implementation meets the applicable policy criteria or requires further review.</p><h3>How the Integration Works.</h3><p>The integration can be understood through five key steps:</p><p><strong>Define organizational policies:</strong> Governance teams establish AI usage criteria in watsonx.governance, identifying use cases that require additional scrutiny, such as loan approvals, healthcare decisions, employment screening, and sensitive profiling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJ4vLwNeGyRuek35JbuIfw.png" /><figcaption>Sample AI Policy</figcaption></figure><p><strong>Generate code with IBM Bob:</strong> A developer provides a natural-language prompt, and Bob generates the corresponding agent implementation.</p><p><strong>Trigger governance validation:</strong> The Bob extension invokes an API to submit relevant code or use-case information for policy evaluation.</p><p><strong>Evaluate policy compliance:</strong> watsonx.governance evaluates the submitted information against the configured policy criteria.</p><p><strong>Surface the governance result:</strong> The developer receives a policy outcome, such as MET or NOT MET, along with relevant findings that can guide remediation or additional review.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHNpVF87_0kinSIq9SKCzg.png" /><figcaption>Illustrating Policy Met Scenario, with the generated code ran against the policy.</figcaption></figure><p><strong>Auto-Govern the Agent: </strong>Beyond policy assessment, the Bob extension triggers an automated governance workflow to create a <strong>Shadow Agent</strong>, perform similarity searches against existing agents, and apply auto-triaging rules. Based on the applicable governance criteria, the Shadow Agent can be promoted to a <strong>Governed Agent</strong>, enabling centralized oversight and lifecycle management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qP1g9Yw4c_L6DNma9Nl2Q.png" /><figcaption>Shadow Discovery of the Bob generated Agent</figcaption></figure><p>So, in short — this brings governance closer to the point of development without requiring developers to initiate a completely separate governance process. To better understand <strong>Policy MET and NOT MET</strong> outcomes, let’s look at a sample policy and how the evaluation results are determined.</p><h3>Sample Policy: High-Risk AI Use Case Assessment</h3><h4><strong>Sample Policy Objective</strong></h4><blockquote>Identify AI agents involved in sensitive or consequential decision-making that require additional governance review.</blockquote><blockquote>AI agents supporting credit or loan decisions, insurance eligibility, healthcare diagnosis, employment decisions, education assessments, profiling, surveillance, or other defined sensitive use cases must undergo additional risk review.</blockquote><h4>Scenario 1: Policy MET</h4><p>Imagine a developer creates an AI agent that explains general financial concepts and answers questions about loan terminology without assessing individual applicants or making eligibility recommendations.</p><p>The governance assessment identifies no applicable high-risk decision-making category.</p><p>The developer can continue development, subject to other applicable organizational policies.</p><h4>Scenario 2: Policy NOT MET</h4><p>Now consider our LangGraph loan approval agent.</p><p>The generated code evaluates an applicant’s income, credit score, and existing liabilities to determine loan eligibility.</p><p>The governance assessment identifies that the agent supports decisions affecting access to credit, which is explicitly included in the organization’s high-risk review categories.</p><p><strong>Illustrative result:</strong></p><p><strong>Policy:</strong> High-Risk AI Use Case Assessment<br><strong>Status:</strong> NOT MET<br><strong>Risk Category:</strong> Access to Essential Services — Credit and Loan Decisions<br><strong>Reason:</strong> The agent supports loan eligibility decisions and requires additional risk review.<br><strong>Recommended Action:</strong> Initiate governance review before deployment.</p><blockquote><strong>Important: A NOT MET result is not necessarily a code failure. It is a signal that the agent requires additional governance attention.</strong></blockquote><p>The developer and governance team can then assess fairness, explainability, human oversight, and other relevant requirements before approving the application for its intended use.</p><h3>Why This Integration Matters</h3><p>The significance of this integration goes beyond identifying policy violations.</p><p>It helps organizations shift from reactive governance toward <strong>governance embedded into AI development</strong>.</p><ul><li>For developers, it means earlier awareness of potential policy concerns without leaving their development environment.</li><li>For governance teams, it means greater visibility into AI agents being created across the organization, including agent metadata and identified risks.</li><li>For enterprises, it creates an opportunity to scale AI development while maintaining oversight and accountability.</li></ul><p>Most importantly, it encourages developers to think about responsible AI from the moment an agent is created, rather than treating governance as a final compliance checkpoint.</p><p><strong>The future of enterprise AI development isn’t just about building agents faster. It’s about building them responsibly, with governance integrated from the start.</strong></p><h3>References</h3><ul><li><a href="https://www.ibm.com/new/announcements/new-in-ibm-watsonx-governance-govern-ai-agents-as-you-build-expand-accountability-and-streamline-compliance">New in IBM watsonx.governance: Govern AI agents as you build, expand accountability and streamline compliance</a></li><li><a href="https://www.ibm.com/products/watsonx-governance">IBM watsonx.governance</a></li></ul><p><em>Build with IBM Bob. Govern with watsonx.governance. Innovate responsibly.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a083fbbe1e9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RBI Model Risk Management 2026: From Regulatory Expectations to Enterprise-Wide Governance with IBM…]]></title>
            <link>https://ravi-chamarthy.medium.com/rbi-model-risk-management-2026-from-regulatory-expectations-to-enterprise-wide-governance-with-ibm-f81a4ff801d8?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f81a4ff801d8</guid>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 00:50:07 GMT</pubDate>
            <atom:updated>2026-10-13T13:07:23.397Z</atom:updated>
            <content:encoded><![CDATA[<h3>RBI Model Risk Management 2026: From Regulatory Expectations to Enterprise-Wide Governance with IBM watsonx.governance</h3><p>Co-authored by <strong>Amisha Bhanushali, </strong><a href="https://www.linkedin.com/in/manishbhide"><strong>Manish Bhide</strong></a><strong>, and </strong><a href="https://www.linkedin.com/in/ravichamarthy"><strong>Ravi Chamarthy</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cu6oQ8iBfIvHTam4oyAmcw.png" /><figcaption>IBM watsonx.governance — MRM end-to-end.</figcaption></figure><p><em>Why visibility, controls, and accountability are becoming essential to managing model risk across financial institutions.</em></p><h3>India Markets — RBI Model Risk Management 2026: A New Era of Enterprise-Wide Model Governance</h3><p>As financial institutions increasingly rely on autonomous AI agents, Generative AI, and machine learning models managing model risk has become a critical enterprise responsibility.</p><p>The Reserve Bank of India’s (RBI) proposed Model Risk Management (MRM) framework signals a shift from fragmented, model-specific oversight toward a more structured, risk-based, and enterprise-wide governance approach.</p><p>The framework emphasizes several foundational expectations:</p><ul><li><strong>Enterprise governance:</strong> Board-approved MRM frameworks, clearly defined ownership, and oversight by senior management and risk committees.</li><li><strong>Model inventory and risk tiering:</strong> Comprehensive identification, classification, and risk-based management of models across the organization.</li><li><strong>Independent validation and continuous monitoring:</strong> Appropriate validation before and after deployment, ongoing performance monitoring, and escalation of breaches.</li><li><strong>AI and third-party governance:</strong> Safeguards for AI/ML models, explainability, human oversight, and governance of externally sourced models.</li><li><strong>Documentation and auditability:</strong> Traceable decisions, model changes, approvals, and evidence throughout the model lifecycle.</li></ul><p>The real challenge for financial institutions is not simply defining these policies. It is operationalizing them consistently across hundreds of models, multiple business units, and increasingly complex AI technologies.</p><p><strong>The fundamental shift is from managing individual models to managing model risk as an enterprise-wide discipline.</strong></p><h3>IBM watsonx.governance: Bringing Visibility, Controls, and Accountability Together</h3><p>Meeting evolving MRM expectations requires more than spreadsheets, disconnected approval processes, and periodic reviews. Financial institutions need a scalable governance operating model that connects people, processes, models, and risk information.</p><p>IBM watsonx.governance provides capabilities to support this operating model through three foundational pillars.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ryl1uLRIsZ9MH54oxTghg.png" /><figcaption>Visibility, Controls, and Accountability</figcaption></figure><h4>Visibility: Know What Exists and Understand the Risk</h4><p>Effective governance starts with understanding the enterprise’s model landscape.</p><p>IBM watsonx.governance enables centralized visibility into governed AI use cases, model inventories including and not limited to — agents, tools, MCPServers, LLMs, Knowledge bases — lifecycle information, associated risks, and monitoring outcomes. Through Governance Console dynamic dashboards, and governance records, organizations can build a more consistent view of traditional ML and generative AI assets, including those from third-party providers.</p><p>This helps answer a fundamental question: <em>What models are being used, where are they deployed, and what risks do they introduce?</em></p><h4>Controls: Turn Governance Policies into Action</h4><p>Visibility alone does not reduce model risk. Institutions need mechanisms to consistently apply governance requirements throughout the model lifecycle.</p><p>watsonx.governance supports configurable risk assessments, model validation workflows, approval processes, policy-driven monitoring, and exception management. AI-specific evaluation capabilities further help organizations assess dimensions such as fairness, drift, quality, and generative AI risks.</p><p>The objective is to move from governance policies documented on paper to <em>repeatable, measurable, and actionable controls.</em></p><h4>Accountability: Establish Ownership and Demonstrate Oversight</h4><p>Model risk management ultimately depends on clearly defined responsibilities and demonstrable oversight.</p><p>Through role-based workflows, lifecycle documentation, approval records, and governance reporting, watsonx.governance helps establish accountability among model owners, validators, risk teams, and governance stakeholders.</p><p><em>It also provides a foundation for management and Board-level reporting, helping institutions demonstrate not just that controls exist, but how governance activities are performed and evidenced.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQBhQMaliDKWEEWyDINcww.png" /><figcaption>watsonx.governance — Governance Console</figcaption></figure><blockquote>Together, <strong>Visibility, Controls, and Accountability</strong> create the foundation for an integrated model risk governance operating model.</blockquote><h3>Connecting RBI Expectations to watsonx.governance Capabilities</h3><p>The RBI’s proposed MRM expectations can be translated into practical governance capabilities supported by IBM watsonx.governance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBh4K0aoTIcF3EfRIXRy-A.png" /><figcaption>Matching RBI MRM Expectations and IBMwatsonx.governance capabilities</figcaption></figure><p>These capabilities can help institutions establish a more consistent governance framework spanning traditional models, machine learning, Generative AI, and AI agents, with appropriate integrations and configuration.</p><p>Importantly, technology is an enabler of regulatory alignment — not a substitute for independent validation, institutional accountability, or regulatory interpretation.</p><h3><strong>The Way Forward</strong></h3><p>RBI’s evolving MRM direction represents an opportunity for financial institutions to rethink how model risk is governed across the enterprise.</p><p>Rather than treating MRM as another compliance exercise, institutions can use this transition to establish a unified governance operating model built around visibility, controls, and accountability.</p><p>With IBM watsonx.governance, organizations have a platform foundation to move from fragmented model oversight toward more connected, scalable, and evidence-driven model risk management.</p><blockquote>The future of model risk management is not just about governing more models. It is about governing them with greater consistency, transparency, and accountability.</blockquote><h3>References</h3><ul><li><a href="https://chambers.com/articles/rbi-s-draft-guidance-on-regulatory-principles-for-model-risk-management">RBI&#39;s Draft Guidance on Regulatory Principles for Model Risk Management | Article | Chambers and Partners</a></li><li><a href="https://www.ibm.com/think/perspectives/ai-governance-to-assurance-what-we-shared-think-2026">From AI governance to AI assurance: What we shared at Think 2026 | IBM</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f81a4ff801d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Traces to Trust: Operationalizing LangFlow RAG Evaluations with LangFuse and IBM watsonx.govern]]></title>
            <link>https://ravi-chamarthy.medium.com/from-traces-to-trust-operationalizing-langflow-rag-evaluations-with-langfuse-and-ibm-watsonx-govern-a96df15b3f04?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96df15b3f04</guid>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[ibm-watson]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[governance]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 16:06:22 GMT</pubDate>
            <atom:updated>2025-10-27T08:41:11.843Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Traces to Trust: Operationalizing LangFlow RAG Evaluations with LangFuse and IBM watsonx.governance</h3><p>Co-Authored with <a href="https://medium.com/u/722df226dc5e">Pratap V</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeDybMNXbo_aZKC9cx4PlA.png" /><figcaption>Author Creative Imagination — Each branch represents traces with spans produced from LangFlow/LangFuse which are evaluated using IBM watsonx.governance</figcaption></figure><h3>What this article addresses..</h3><p>This article is an extension to the earlier post — <a href="https://medium.com/@ravi-chamarthy/evaluating-langflow-rag-flows-using-ibm-watsonx-governance-sdk-270649f965d4"><em>Evaluating LangFlow RAG Flows using IBM watsonx.governance SDK</em></a> — which demonstrated how LangFlow-based RAG applications can be evaluated using the IBM watsonx.governance SDK and its out-of-the-box quality metrics.</p><p>While the earlier work focused on evaluating RAG flows in a static setup, this article takes the concept further by operationalizing the evaluation loop with traceability, observability, and governed experimentation.</p><p>In this extended exploration:</p><ul><li>A LangFlow Agent is designed to respond to Banking FAQs.</li><li>LangFuse is integrated with LangFlow to enable full traceability of each flow execution.</li><li>The collected traces are processed to extract structured agent input, retreived context, and output.</li><li>IBM watsonx.governance Metrics Evaluator is employed to compute a combination of standard and custom metrics for both test and validation datasets.</li><li>The results are stored as experiment runs in IBM watsonx.governance Evaluation Studio, enabling governed comparison metrics between test and validation data runs.</li></ul><h3><strong>How this is addressed..</strong></h3><p>To establish a traceable and governed evaluation workflow, the solution combines LangFlow, LangFuse, and IBM watsonx.governance into a cohesive pipeline.</p><p>Each component contributes a critical capability — from data flow orchestration to observability and evaluation.</p><p>The overall process unfolds through the following stages:</p><h4>Integration with LangFuse for Tracing</h4><p>LangFlow executions are integrated with LangFuse to capture trace-level data for every interaction. Each trace records the input, retrieved context, generated output, and additional metadata such as execution time and latency. These traces enable complete observability into how the agent processes user requests.</p><p>To establish the integration, create an account in <a href="https://cloud.langfuse.com/">LangFuse</a>, followed by creation of an organization and a project, and then create new API Keys in the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLLywtMey1TEuvpxlbFsBg.png" /><figcaption>LangFuse — Org, Project, Credentials</figcaption></figure><p>Set the LangFuse credentials in the same terminal where LangFlow is running.</p><pre>% export LANGFUSE_SECRET_KEY=[Your LANGFUSE_SECRET_KEY]<br>% export LANGFUSE_PUBLIC_KEY=[Your LANGFUSE_PUBLIC_KEY]<br>% export LANGFUSE_HOST=&quot;https://cloud.langfuse.com&quot;<br>% pip install langfuse<br>% langflow run</pre><h4>LangFlow Agent Setup</h4><p>A LangFlow-based agent is designed to handle Banking FAQ–type queries. It dynamically determines whether to invoke the search_documents tool (to retrieve relevant information from Astra DB) or the calculator tool (for arithmetic responses, say to compute Mutual Funds returns YoY based on the invested amount). Retrieved context is combined with the input query to generate a final answer using the OpenAI GPT model.</p><p>As an In-Flow evaluations, like in the previous article <a href="https://medium.com/@ravi-chamarthy/evaluating-langflow-rag-flows-using-ibm-watsonx-governance-sdk-270649f965d4"><em>Evaluating LangFlow RAG Flows using IBM watsonx.governance SDK</em></a><em> </em>the flow is enriched to include a custom component to compute Relevance metrics on question and the Answer. Please refer to the said post for the code and the procedure on how to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnICdSMEM9QfQrrWXTe72A.png" /><figcaption>LangFlow Agent setup</figcaption></figure><h4>Conversing with Agent</h4><p>From the LangFlow Playground, send questions around Banking related products or ask around financial computations, for any other question the Agent will come back with “I do not know” answer as mentioned in its prompt instruction. The agent will make use of the respective tools — “search_documents” or “calculator” — to fetch the context built a prompt and run against the OpenAI GPT model, and serve back the response to the user. Behind all these, the traces for each integration is captured and logged to LangFuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MUq5KkL48BLB-cCp1JYBQ.png" /><figcaption>LangFlow Playground for communicating with the Agent</figcaption></figure><h4>LangFuse Traces</h4><p>Over the interactions with the Agent, one can observe the logged traces and their associated cost against underlying LLM from LangFuse dashboard, as in the below snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4lcsis2koIPI0QOT2rCCIw.png" /><figcaption>LangFuse Traces Dashboard</figcaption></figure><p>One can further drill down on individual traces from the LangFuse Tracing UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EqBzm3NCVD33G9-ntV1C5w.png" /><figcaption>Individual Traces UI</figcaption></figure><h4>Trace Extraction and Dataset Preparation</h4><p>A LangFuse utility is used to fetch traces from the last one hour and extract structured information containing input, context, and output. To facilitate supervised evaluation, a ground_truth field is added for each record.</p><pre>def extract_trace_fields(traces):<br>    from jsonpath_ng import parse<br>    jsonpath_input = parse(&#39;$.input.&quot;Chat Input (ChatInput-qHFrs)&quot;.input_value&#39;)<br>    jsonpath_output = parse(&#39;$.output.&quot;Agent (Agent-Zr1RM)&quot;.response.text&#39;)<br>    jsonpath_context_blocks = parse(&#39;$.output.&quot;Agent (Agent-Zr1RM)&quot;.response.data.content_blocks[*].contents[*]&#39;)<br>    <br>    results = []<br>    for trace in traces.data:<br>        trace_dict = trace.dict() if hasattr(trace, &quot;dict&quot;) else trace<br>    <br>        # Apply JSONPath queries<br>        user_input = [m.value for m in jsonpath_input.find(trace_dict)]<br>        agent_output = [m.value for m in jsonpath_output.find(trace_dict)]<br>    <br>        # Context: filter tool_use blocks named search_documents<br>        context_matches = [m.value for m in jsonpath_context_blocks.find(trace_dict)]<br>        context_texts = []<br>        for block in context_matches:<br>            if block.get(&quot;type&quot;) == &quot;tool_use&quot; and block.get(&quot;name&quot;) == &quot;search_documents&quot;:<br>                for out in block.get(&quot;output&quot;, []):<br>                    text = out.get(&quot;data&quot;, {}).get(&quot;text&quot;)<br>                    if text:<br>                        context_texts.append(text)<br>    <br>        results.append({<br>            &quot;id&quot;: trace_dict.get(&quot;id&quot;),<br>            &quot;input&quot;: user_input[0] if user_input else None,<br>            &quot;output&quot;: agent_output[0] if agent_output else None,<br>            &quot;context&quot;: &quot;\n\n&quot;.join(context_texts) if context_texts else None<br>        })<br>    return results</pre><p>Please refer to the <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langfuse-langflow-watsonx.gov-explorations.ipynb">notebook</a> for the complete code.</p><h4>Metric Computation using watsonx.governance Metrics Evaluator</h4><p>The IBM watsonx.governance Metrics Evaluator is used to compute a combination of out-of-the-box (only few are listed below and the comprehensive list can be found <a href="https://ibm.github.io/ibm-watsonx-gov/generated_apidoc/ibm_watsonx_gov.metrics.html">here</a>) and custom metrics for both datasets.</p><p>Out of the box Metrics:</p><ul><li>AnswerRelevanceMetric()</li><li>FaithfulnessMetric()</li><li>AnswerSimilarityMetric()</li><li>TextGradeLevelMetric()</li><li>TextReadingEaseMetric()</li></ul><p>Custom Metrics:</p><ul><li>ContextSufficiencyMetric()</li><li>ContextRelevanceMetric()</li><li>ContextPrecisionMetric()</li></ul><pre>class ContextSufficiencyMetric(BaseContextMetric):<br>    name: ClassVar[str] = &quot;context_sufficiency&quot;<br>    display_name: ClassVar[str] = &quot;Context Sufficiency&quot;<br>    metric_type: ClassVar[str] = &quot;sufficiency&quot;<br>    eval_fn: ClassVar[Callable[[str, str], float]] = staticmethod(evaluate_context_sufficiency)<br>    result_cls: ClassVar[Type[RecordMetricResult]] = ContextSufficiencyResult<br><br><br>class ContextRelevanceMetric(BaseContextMetric):<br>    name: ClassVar[str] = &quot;context_relevance&quot;<br>    display_name: ClassVar[str] = &quot;Context Relevance&quot;<br>    metric_type: ClassVar[str] = &quot;relevance&quot;<br>    eval_fn: ClassVar[Callable[[str, str], float]] = staticmethod(evaluate_context_relevance)<br>    result_cls: ClassVar[Type[RecordMetricResult]] = ContextRelevanceResult<br><br><br>class ContextPrecisionMetric(BaseContextMetric):<br>    name: ClassVar[str] = &quot;context_precision&quot;<br>    display_name: ClassVar[str] = &quot;Context Precision&quot;<br>    metric_type: ClassVar[str] = &quot;precision&quot;<br>    eval_fn: ClassVar[Callable[[str, str], float]] = staticmethod(evaluate_context_precision)<br>    result_cls: ClassVar[Type[RecordMetricResult]] = ContextPrecisionResult</pre><p>Please refer to the <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langfuse-langflow-watsonx.gov-explorations.ipynb">notebook</a> for the complete code around usage of Custom metrics.</p><pre>evaluation_results_1 = evaluator.evaluate(<br>    data=banking_rag_chatbot_qna_1,<br>    metrics=[<br>        ContextSufficiencyMetric(), ContextRelevanceMetric(), ContextPrecisionMetric(),<br>        AnswerRelevanceMetric(), FaithfulnessMetric(),<br>        AnswerSimilarityMetric(), TextGradeLevelMetric(), TextReadingEaseMetric()<br>    ]<br>)<br>evaluation_results_df_1 = evaluation_results_1.to_df()</pre><p>These metrics collectively measure contextual relevance, generated output quality, and factual alignment between the model output and the retrieved content.</p><h4>Experiment Tracking in IBM watsonx.governance Evaluation Studio</h4><p>The computed metrics are logged as two separate experiment runs — Test Run and Validation Run — using the Evaluation Studio APIs. An AI Evaluation is then created to compare these runs, enabling structured analysis of how prompt, model, or retrieval changes affect output quality.</p><p>Please refer to the <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langfuse-langflow-watsonx.gov-explorations.ipynb">notebook</a> for the complete code around setting up the same — the snapshot of the Agents Evaluation Studio is as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZdLkip6gVLMrCnbCSxN-w.png" /><figcaption>IBM watsonx.governance Agents Evaluation Studio</figcaption></figure><p>So, that’s about it — in summary this article demonstrates that if you are building LangFlow based agent and integrated it with LangFuse for tracing, then during development time, one can capture those traces and on them evaluate the various quality and custom metrics using IBM watsonx.governance SDK — Metrics Evaluator and use Agents Evaluation Studio for comparison against agents metrics, or data sets or experiment runs.</p><h3><strong>Key Takeaways</strong></h3><p>The combined setup establishes a governed evaluation loop, where every LangFlow execution is observable (via LangFuse), measurable (via watsonx.governance), and comparable (via Evaluation Studio).<br> This ensures that model improvements or prompt iterations are based on quantitative, reproducible evidence rather than subjective judgment.</p><h3>Resources</h3><ul><li>Refer <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langfuse-langflow-watsonx.gov-explorations.ipynb">here</a> for the notebook used to compute the metrics and Evaluation Studio integration.</li><li>Refer <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langflow_custom_component.py">here</a> for the custom python component code.</li><li>Refer <a href="https://medium.com/trusted-ai/experiment-tracking-in-watsonx-governance-compare-and-optimize-agentic-ai-variants-with-confidence-646dfcb9523f">here</a> for more on Evaluation Studio capabilities.</li><li>Refer <a href="https://medium.com/trusted-ai/in-the-loop-and-offline-evals-with-watsonx-governance-26b043f89b7c">here</a> for more on Evals with watsonx.governance.</li><li>Refer <a href="https://ibm.github.io/ibm-watsonx-gov/generated_apidoc/ibm_watsonx_gov.metrics.html">here</a> for all the comprehensive list of evals from IBM watsonx.governance SDK.</li></ul><p>Happy Tracing and Happy Evaluations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96df15b3f04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Quality in LangFlow RAG Applications using IBM watsonx.governance]]></title>
            <link>https://ravi-chamarthy.medium.com/evaluating-langflow-rag-flows-using-ibm-watsonx-governance-sdk-270649f965d4?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/270649f965d4</guid>
            <category><![CDATA[watsonx]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[ibm-watson]]></category>
            <category><![CDATA[langflow]]></category>
            <category><![CDATA[watsonx-governance]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Fri, 19 Sep 2025 14:11:50 GMT</pubDate>
            <atom:updated>2025-09-21T08:33:25.815Z</atom:updated>
            <content:encoded><![CDATA[<p>(Co-Authored by <a href="https://www.linkedin.com/in/ravichamarthy/">Ravi Chamarthy</a> and <a href="https://www.linkedin.com/in/manishbhide/">Manish Bhide</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzHzv3r7dS96Gcwd4QeJjw.png" /><figcaption>Author Creative Imagination — LangFlow connects the wires, and watsonx.governance ensures the flow stays balanced and trustworthy.</figcaption></figure><p>Retrieval-Augmented Generation (RAG) has quickly become one of the most effective ways to build domain-specific agentic chatbots and knowledge assistants. With tools like LangFlow, it becomes remarkably easy to design and deploy these RAG pipelines through an intuitive visual interface. At the same time, validating the quality and reliability of the generated answers is essential. This is where IBM watsonx.governance Evaluation Studio plays a vital role. In this article, we’ll explore how to integrate LangFlow and the IBM watsonx.governance SDK to not only build a RAG flow using DataStax LangFlow but also evaluate its performance with IBM watsonx.governance AI quality metrics.</p><blockquote>IBM watsonx.governance is a platform for <strong>Responsible AI</strong> that ensures LLM and Agent outputs are transparent, reliable, and auditable. It offers experiment tracking, rich evaluation metrics, and an AI Evaluation Studio to compare outputs across runs for agents, prompts, and foundation models.</blockquote><p>and..</p><blockquote>LangFlow is an open-source visual framework that lets developers quickly build LLM-powered applications using a drag-and-drop interface. It simplifies the design of RAG pipelines by enabling easy orchestration of retrievers, embeddings, vector stores, and language models, while also supporting extensions through custom Python components — among various other supporting features like agentic flows, etc.</blockquote><h3>Building a Banking FAQs Chatbot with LangFlow</h3><p>For this article, the Vector RAG example flow in LangFlow is used, with a needed modifications for evaluation.</p><ol><li>Bank FAQs Data Ingestion — Loaded a dataset of Banking FAQs into DataStax AstraDB, where the text was vectorized and indexed for retrieval.</li><li>Flow Design</li></ol><ul><li>The user query comes from the Chat Input component.</li><li>Retrieved documents from AstraDB are parsed and injected into the prompt along with the user query.</li><li>The OpenAI GPT model generates the final answer.</li></ul><p>3. LangFlow Components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZQXS4o5IjGYT9A0WK4vMPg.png" /><figcaption>Vector Store RAG — LangFlow</figcaption></figure><p>4. Dual Branch Component Execution</p><ul><li><strong>Branch 1</strong> — The standard chatbot output, where the generated answer is returned to the user and executed within the LangFlow Playground. The next section explains how quality evaluations are applied to the LLM-generated output, from a notebook and then pushed to Evaluation Studio for comparison.</li><li><strong>Branch 2 </strong>— Metrics evaluation path, where Faithfulness, Context Relevance, and Answer Relevance among other metrics are computed using the question, retrieved context, and generated answer. This is done using a Custom Python Component which internally uses IBM watsonx.governance SDK MetricsEvaluator. More on this in the latter section.</li></ul><h3>Evaluation Studio — Perform Quality Evaluation Experiments on the output of LangFlow RAG Flows</h3><p>Building the chatbot is only half the story. To ensure quality, the workflow is extended to compute evaluation metrics using IBM watsonx.governance Metrics Evaluation and thereby track the experiments using IBM watsonx.governance Evaluation Studio.</p><h4>Test &amp; Validation Datasets — Generate LangFlow RAG Flow Responses</h4><ul><li>Using the LangFlow API route ran questions from test data and collect generated answers. Alongside, the ground-truth answers for these test sets are also provided.</li><li>Likewise, the generated answers are collected for the validation data set.</li></ul><h4>Metrics Computation — watsonx.governance Metrics Evaluators</h4><ul><li>Using IBM watsonx.governance SDK, calculated the built-in metrics,</li><li>Answer Relevance (between generated answer and asked question).</li><li>Answer Similarity (between generated and ground truth answers).</li><li>Text Readability (to assess fluency and clarity).</li><li>Metrics evaluation can be easily extended to capture custom metrics as well.</li></ul><pre># Evaluator and its configuration<br>evaluator = MetricsEvaluator(<br>    api_client = APIClient(credentials=credentials),<br>    configuration = GenAIConfiguration(<br>        input_fields=[&quot;question&quot;],<br>        context_fields=[],<br>        output_fields=[&quot;langflow_generated_answer&quot;],<br>        reference_fields=[&quot;ground_truth&quot;]),<br>)<br># Evaluator the said metrics<br>evaluation_results_1 = evaluator.evaluate(<br>    data=banking_rag_chatbot_qna_1,<br>    metrics=[<br>        AnswerRelevanceMetric(), AnswerSimilarityMetric(),<br>        TextGradeLevelMetric(), TextReadingEaseMetric(),<br>    ]<br>)<br>testdata_results_df_1 = evaluation_results_1.to_df()<br>run_1_metric_results = construct_run_metrics(testdata_results_df_1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMjFSuPwH3jU-_nbLIKHQA.png" /><figcaption>Metrics Evaluation Results</figcaption></figure><h4>Experiment Run Comparisons — watsonx.governance Evaluation Studio</h4><ul><li>Using the watsonx.governance SDK, create:</li><li>AI Experiments — to organize test and validation runs.</li><li>Experiment Runs — each run captured metrics for a dataset (test or validation).</li><li>AI Evaluations — aggregated results pushed to Evaluation Studio, where different runs can be compared visually.</li></ul><pre># Creating AI Experiment asset<br>name = &quot;LangFlow based Banking ChatBot AI Experiment&quot;<br>description = &quot;Evaluation of a LangFlow based RAG-based chatbot for common banking queries, using manually curated test cases across account services, loans, cards, digital banking, and UPI. Each case includes the user question, retrieved context, model answer, and human-verified ground truth for quality benchmarking.&quot;<br><br>ai_experiment_client = AIExperimentsClient(api_client=api_client, project_id=WATSONX_PROJECT_ID)<br>ai_experiment = AIExperiment(name=name, <br>                             description=description,<br>                             component_type=&quot;agent&quot;,<br>                             component_name=&quot;LangFlow based Banking Chatbot Agent&quot;)<br><br>ai_experiment_asset = ai_experiment_client.create(ai_experiment)<br><br># associating experiment runs with the metrics<br>ai_experiment_client.update(<br>    ai_experiment_id=ai_experiment_id,<br>    experiment_run_details=AIExperimentRun(run_id=str(uuid.uuid4()),<br>                            run_name=&quot;LangFlow based ChatBot Test Data Metrics Evaluation&quot;, nodes=[], duration=10<br>                        ),<br>    evaluation_results=run_1_metric_results<br>)</pre><h4>Evaluation Studio — Experiment tracking and comparison of metrics</h4><p>Using <strong>Evaluation Studio</strong>, we can easily compare metrics across different runs of the LangFlow-based Banking ChatBot experiment. The side-by-side view highlights variations in answer quality between test and validation datasets. Color-coded indicators make it simple to spot strengths and weaknesses. This enables practitioners to quickly assess performance, track improvements, and make data-driven decisions on model quality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZfolqH4awkNuN1X-w5DYA.png" /><figcaption>watsonx.governance Evaluation Studio — comparison of evaluated metrics</figcaption></figure><h3>LangFlow — Evaluations from Custom Python Component</h3><p>While LangFlow provides built-in components for building RAG flows, went<strong> a step further</strong> and directly integrate <strong>IBM watsonx.governance metrics</strong> into the flow. For this, a <strong>Custom Python Component</strong> is created that receives the <strong>context, question, and answer</strong> from the other flow components — specifically from Chat Input, AstraDB output, and LLM Output components — and computes a set of evaluation metrics.</p><p>The custom component leverages the ibm_watsonx_gov SDK to calculate metrics such as:</p><ul><li><strong>Answer Relevance</strong> — how well the generated answer addresses the user’s question.</li><li><strong>Faithfulness</strong> — whether the answer is grounded in the retrieved context from AstraDB.</li><li><strong>Context Relevance</strong> — the degree of relevance between the retrieved context and the question.</li><li><strong>Text Grade Level &amp; Reading Ease</strong> — readability measures to ensure responses are easy to understand.</li><li>And one can compute a whole set of various metrics as listed <a href="https://ibm.github.io/ibm-watsonx-gov/generated_apidoc/ibm_watsonx_gov.metrics.html">here</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*CJsEhqq0XcSmQBXoYoY-aw.png" /><figcaption>Check Relevance Metrics — Custom Python Component</figcaption></figure><p>The screenshot above shows the <strong>“</strong>Check Relevance Metrics<strong>”</strong> custom component inside Vector RAG LangFlow. Behind the scenes, as in the below code snippet, the component initializes credentials for <strong>I</strong>BM watsonx.governance, constructs a MetricsEvaluator, and runs evaluations on the inputs. The results are returned as structured data that can be viewed directly in the LangFlow flow or exported for further analysis.</p><pre><br>class CustomComponent(Component):<br>    # Input and Outputs .. please refer to the actual code from the <br>    # References section<br><br>    # Main function to compute metrics<br>    def build_output(self) -&gt; Data:<br>        # ...<br><br>        # Initialize evaluator with credentials and configuration<br>        evaluator = MetricsEvaluator(<br>            api_client=APIClient(credentials=credentials),<br>            configuration=GenAIConfiguration(<br>                input_fields=[&quot;question&quot;],   # user query<br>                context_fields=[&quot;context&quot;],  # retrieved context<br>                output_fields=[&quot;answer&quot;],    # LLM generated response<br>                reference_fields=[]          # (optional) ground truth references<br>                ),<br>        )        <br>        <br>        # Build a dataframe with single row: {question, context, answer}<br>        input_df = pd.DataFrame([{&quot;question&quot;: self.input_value, &quot;context&quot;: self.context, &quot;answer&quot;: self.answer}])<br><br>        # Run evaluation using selected metrics<br>        evaluation_results = evaluator.evaluate(<br>            data=input_df,<br>            metrics=[<br>                AnswerRelevanceMetric(), FaithfulnessMetric(), ContextRelevanceMetric(),<br>                TextGradeLevelMetric(), TextReadingEaseMetric(),<br>                ],<br>        )        <br>        <br>        # Convert results to a DataFrame, then to JSON<br>        evaluation_results_df = evaluation_results.to_df()<br>        json_obj = evaluation_results_df.to_dict(orient=&quot;records&quot;)[0]<br>        <br>        # Wrap results into a LangFlow Data object for output<br>        data = Data(data=json_obj)<br>        self.status = data<br>        return data</pre><p>Following the output of one such sample exeuction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uX2h-pVAHAqaP5D5hf97TA.png" /><figcaption>Custom Python Component Results</figcaption></figure><h3>Key Takeaways</h3><p>This integration ensures that every chatbot response is automatically evaluated, enabling ChatBot developers to monitor quality metrics seamlessly as part of their RAG workflow. It bridges LangFlow’s orchestration power with watsonx.governance’s evaluation capabilities, creating a more robust and measurable AI pipeline. The Banking FAQs chatbot use case demonstrates how test/validation evaluations can be pushed to <strong>Evaluation Studio</strong> for side-by-side comparison</p><h3>Resources</h3><ul><li>Refer <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langflow-explorations.ipynb">here</a> for the notebook used to compute the metrics and Evaluation Studio integration.</li><li>Refer <a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/langflow_custom_component.py">here</a> for the custom python component code.</li><li>Refer <a href="https://medium.com/trusted-ai/experiment-tracking-in-watsonx-governance-compare-and-optimize-agentic-ai-variants-with-confidence-646dfcb9523f">here</a> for more on Evaluation Studio capabilities.</li><li>Refer <a href="https://medium.com/trusted-ai/in-the-loop-and-offline-evals-with-watsonx-governance-26b043f89b7c">here</a> for more on Evals with watsonx.governance.</li><li>Refer <a href="https://ibm.github.io/ibm-watsonx-gov/generated_apidoc/ibm_watsonx_gov.metrics.html">here</a> for all the comprehensive list of evals from IBM watsonx.governance SDK.</li></ul><p>Happy LangFlows and Evaluations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270649f965d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IBM watsonx.governance in Action: Evaluating DeepSeek R1-Powered RAG Apps]]></title>
            <link>https://ravi-chamarthy.medium.com/ibm-watsonx-governance-in-action-evaluating-deepseek-r1-powered-rag-apps-d07c41ccf004?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d07c41ccf004</guid>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[watsonx]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[large-language-models]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 18:22:12 GMT</pubDate>
            <atom:updated>2025-01-31T18:22:12.778Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Setting the context</strong></h3><p>With the excitement surrounding the recent release of the DeepSeek R1 model, many LLM application developers are eager to explore its capabilities. A key question arises — does the DeepSeek model generate faithful responses based on the provided context, or does it produce hallucinated answers? Additionally, how relevant are the generated responses by the model to the questions asked?</p><p>This is where <strong>IBM watsonx.governance</strong> comes into play. It enables the evaluation of RAG-based applications powered by DeepSeek R1 by measuring key quality metrics such as <strong>faithfulness, answer relevancy, and similarity</strong> — comparing model-generated outputs against ground truth data or even answers generated from other large language models. By leveraging watsonx.governance, developers can gain deeper insights into model performance and ensure the reliability of their applications, including any Proof of Concepts they plan to build.</p><h3><strong>Model Installation — Local</strong></h3><p>On a <strong>RHEL VM</strong> (I used an <strong>8-core, 16GB memory</strong> instance with multiple other applications running), install <strong>Ollama</strong> as the <strong>root user</strong> using the following command:</p><pre># curl -fsSL https://ollama.com/install.sh | sh</pre><p>If <strong>Jupyter Notebooks</strong> are running under a <strong>non-root user</strong> (which is typically the case), <strong>download and run </strong>the <strong>DeepSeek R1 model</strong> as below using the non-root user.</p><p>(Initially, I experimented with the <strong>14B model</strong>, but given the resource constraints of my VM, I opted for the bare <strong>1.5B model</strong> instead.)</p><pre># ollama run deepseek-r1:1.5b</pre><h3><strong>Model generation</strong></h3><p>There are multiple ways to connect to the model via <strong>Ollama</strong>. In this case, I chose to use <strong>LangChain</strong> to interact with the <strong>DeepSeek R1 model</strong>. The main reason for this choice is that LangChain provides <strong>Chain-of-Thought (CoT) reasoning</strong> in its output.</p><pre>from langchain_community.llms import Ollama<br>llm = Ollama(model=&quot;deepseek-r1:1.5b&quot;)</pre><p>As you may have already noticed by now, the DeepSeek model’s response includes <strong>CoT reasoning</strong> enclosed within &lt;think&gt; and &lt;/think&gt; tags. Below is a utility function to extract the model’s reply while <strong>excluding</strong> the content within these tags.</p><pre>def extract_model_reply(model_response):<br>    output = model_response.generations[0][0].text<br>    import re<br>    model_reply = re.sub(r&#39;^.*?&lt;/think&gt;\s*&#39;, &#39;&#39;, output, flags=re.DOTALL)<br>    print(model_reply)<br>    return model_reply</pre><p>Below is the <strong>prompt</strong>, parameterized with the <strong>RAG $context</strong> and the $<strong>question</strong> to be asked.</p><pre>from string import Template<br>prompt_template = Template(&quot;&quot;&quot;<br>You are a helpful AI assistant. Use ONLY the following context to answer the question. If unsure, say &quot;I don&#39;t know&quot;. Keep answers under 2 sentences.<br><br>Context: $context<br><br>Question: $question<br><br>Answer:<br>&quot;&quot;&quot;)</pre><p>For a sample dataset containing relevant contexts and corresponding questions, construct a prompt and invoke the model to generate responses. Then, use the utility function to extract the actual model output.</p><pre># accumulate the prompt response for each query<br>results = []<br>for relevant_context, question in zip(relevant_contexts, question_texts):<br>    context = construct_context(relevant_context)<br>    prompt_str = prompt_template.substitute(context=context, question=question)<br>    model_response = llm.generate([prompt_str])<br>    model_reply = extract_model_reply(model_response)<br>    results.append(model_reply)</pre><p>Below is one such sample output from DeepSeek R1 1.5B model.</p><pre>generations=[[GenerationChunk(text=&#39;<br><br>&lt;think&gt;\nOkay, I need to figure out how to answer the question &quot;What is the difference between copayment and coinsurance?&quot; <br>based on the provided context. <br><br>Let me go through each term one by one.\n\n<br>First, a copayment refers to a fixed amount you pay for covered services, like $20 for a doctor visit. <br>It\&#39;s a set amount that doesn\&#39;t change regardless of how much your costs are beyond the deductible.\n\n<br>On the other hand, coinsurance is a percentage of costs you must pay before your insurance covers the rest. <br>For example, if the deductible is 10%, and you spend $150 for an office visit, you\&#39;d pay $15 (10% of $150) in coinsurance.\n\n<br>So, the key difference is that copayment is a flat fee, while coinsurance adds on a percentage based on costs exceeding a certain threshold. <br>This makes me understand how each term works and helps prevent miscommunication about payment structures.\n&lt;/think&gt;\n\n<br><br>The copayment is a fixed amount paid for covered services (e.g., $20), while the coinsurance is a percentage of costs paid before the deductible, such as 10% on an office visit costing $150.&#39;, <br><br>generation_info={&#39;model&#39;: &#39;deepseek-r1:1.5b&#39;, &#39;created_at&#39;: &#39;2025-01-30T13:03:52.62955432Z&#39;, &#39;response&#39;: &#39;&#39;, &#39;done&#39;: True, &#39;done_reason&#39;: &#39;stop&#39;, <br>&#39;context&#39;: [151644, ….,13], &#39;total_duration&#39;: 22509413057, &#39;load_duration&#39;: 2381354546, &#39;prompt_eval_count&#39;: 432, &#39;prompt_eval_duration&#39;: 7470000000, <br>&#39;eval_count&#39;: 250, &#39;eval_duration&#39;: 12655000000})]] llm_output=None run=[RunInfo(run_id=UUID(&#39;f8795416-5415-47fe-b196-cdc7dde43cae&#39;))]</pre><p>Here is a Pandas DataFrame containing the question, DeepSeek R1 response, reference answer (e.g., from another LLM), and the RAG context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1SN91z9U9m_A786aOAp6Q.png" /><figcaption>DeepSeek R1 Response</figcaption></figure><h3>Evaluation of RAG metrics using IBM watsonx.governance</h3><p>Using the combination of Question, Contexts, DeepSeek R1 model generated answer, and with the reference answer, let’s evaluate a host of various metrics:</p><ul><li>Faithfulness: Measures how well the generated text aligns with the context. Did the model stay on topic based on what it found?</li><li>Answer Relevance: Captures how relevant the final response is to the original prompt.</li><li>Context Relevance: Captures how valid are the retrieved contexts against the questions.</li><li>Unanswered Requests: Questions that could not be answered by the model.</li><li>Answer Similarity: Given a ground truth answer, evaluate the semantic similarity with the model generated answer.</li><li>Content Analysis Metrics</li><li>Coverage: This metric quantifies the extent to which the answer is derivative of the context, where it measures the percentage of summary words within the source text.</li><li>Density: The density measure is used to assess how well the overall sequence of words in the generated answer aligns with being a series of direct extractions from the source text.</li><li>Compression: The metric calculates the ratio of the number of words in the content to the number of words in the generated answer.</li><li>Novelty: The Novelty / Abstractness metric measures how many new n-grams are present in the generated answer as compared to the references.</li><li>Redundancy: The redundancy metric measures the percentage of n-grams in the answer which are (unnecessarily!) repeated.</li></ul><pre>from ibm_metrics_plugin.metrics.llm.utils.constants import LLMTextMetricGroup, LLMCommonMetrics, LLMQAMetrics, LLMRAGMetrics, RetrievalQualityMetric<br><br># Edit below values based on the input data<br>context_columns = [&quot;contexts&quot;]<br>question_column = &quot;question&quot;<br>answer_column = &quot;d3r1_result&quot;<br>reference_column = &quot;reference_answer&quot;<br><br>config_json = {<br>            &quot;configuration&quot;: {<br>                &quot;record_level&quot;: True,<br>                &quot;context_columns&quot;: context_columns,<br>                &quot;question_column&quot;: question_column,<br>                 LLMTextMetricGroup.RAG.value: {<br>                        LLMCommonMetrics.FAITHFULNESS.value: {},<br>                        LLMCommonMetrics.ANSWER_RELEVANCE.value: {},<br>                        LLMQAMetrics.UNSUCCESSFUL_REQUESTS.value: {},<br>                        LLMCommonMetrics.CONTENT_ANALYSIS.value: {},<br>                        LLMRAGMetrics.RETRIEVAL_QUALITY.value: {<br>                            RetrievalQualityMetric.CONTEXT_RELEVANCE.value: {<br>                            &quot;ngrams&quot;: 5<br>                            },<br>                            RetrievalQualityMetric.RETRIEVAL_PRECISION.value: {},<br>                            RetrievalQualityMetric.AVERAGE_PRECISION.value: {},<br>                            RetrievalQualityMetric.RECIPROCAL_RANK.value: {},<br>                            RetrievalQualityMetric.HIT_RATE.value: {},<br>                            RetrievalQualityMetric.NDCG.value: {}<br>                        }<br>                }<br>            }<br>        }</pre><p>Call the watsonx.governance SDK to evaluate the metrics, by passing the model input and output and the reference answers.</p><pre>df_input = pd.DataFrame(llm_data, columns=context_columns+[question_column])<br>df_output = pd.DataFrame(llm_data, columns=[answer_column])<br>df_reference = pd.DataFrame(llm_data, columns=[reference_column])<br><br>import json<br>metrics_result = client.llm_metrics.compute_metrics(config_json, <br>                                                    sources=df_input, <br>                                                    predictions=df_output,<br>                                                    references=df_reference,<br>                                                    # background_mode=False<br>                                                   )</pre><p>Here are the evaluation results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AeyjayZP-9gSdfOIVYM3A.png" /><figcaption>Evaluation Results</figcaption></figure><p>As observed, faithfulness is strong for some context-answer combinations but falls short in others, even when human oversight is involved. Similarly, while most generated answers appear relevant to the corresponding questions, some do not, despite expectations.</p><h3>Notes</h3><p>This article does not draw conclusions about the model’s overall performance, as it also depends on the dataset used. Instead, it focuses on demonstrating the mechanism for using <strong>IBM watsonx.governance</strong> to evaluate responses generated by the <strong>DeepSeek R1 model</strong>.</p><p>As most LLM application developers are still in the exploration phase of the <strong>DeepSeek R1 model</strong>, with many implementations being part of a <strong>Proof of Concept (PoC)</strong>, this article focuses solely on evaluating metrics using the <strong>SDK approach</strong>.</p><p>Additionally, <strong>IBM watsonx.governance</strong> can be leveraged for <strong>continuous monitoring</strong> of prompts across any <strong>Large Language Model (LLM).</strong></p><h3>References</h3><ul><li><a href="https://www.ibm.com/products/watsonx-governance">IBM watsonx.goverenance</a></li><li><a href="https://client-docs.aiopenscale.cloud.ibm.com/html/index.html">IBM watsonx.goverenance monitoring toolkit</a></li><li><a href="https://github.com/IBM/watson-openscale-samples/tree/main/IBM%20Cloud/WML/notebooks/watsonx">Sample notebooks</a></li><li><a href="https://ollama.com/library/deepseek-r1">Ollama DeepSeek Installation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d07c41ccf004" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating faithfulness of an Agentic RAG System using IBM watsonx.governance]]></title>
            <link>https://ravi-chamarthy.medium.com/evaluating-faithfulness-of-an-agentic-rag-system-using-ibm-watsonx-governance-0532e4b4b468?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0532e4b4b468</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[watsonx]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Mon, 06 Jan 2025 09:12:02 GMT</pubDate>
            <atom:updated>2025-01-06T09:12:02.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APf7LUsDj9gchAsKcuyf5g.png" /><figcaption>Agentic AI System — conceptual representation — Agents interacting with external systems.</figcaption></figure><h3><strong>The Understanding — Agentic AI and Agentic RAG.</strong></h3><p><em>Imagine a system similar to a Tour Operator, proficient in handling essential travel services like booking flights, hotels, and currency exchange.</em></p><p>This system acts as an <strong><em>Agent</em></strong> orchestrating multiple <strong><em>Tools </em></strong>(flight booking, hotel booking etc), representing a foundational AI capability that exhibit autonomous decision-making and goal-oriented behaviour. That’s Agentic AI.</p><p>For example, via., the Tour Operator’s ChatBot a customer might ask, <em>“I want to spend a week in the English countryside. Can you suggest some places along with hotel details?”</em>. To handle this query, the Agent leverages Large Language Model (LLM) say <em>Granite</em> or <em>OpenAI GPT</em> model or the likes, which acts as the reasoning engine behind the process, combined with tools for retrieving precise information. Here’s how it works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lyqA9Q1aE0l--ZRAdaaE-A.png" /><figcaption>Agentic AI — Plan, Execute, Reflect, Repeat.</figcaption></figure><ol><li><strong>Plan:</strong> The LLM interprets the query and formulates an initial plan to retrieve the required information (e.g., places and hotels).</li><li><strong>Reason and Execute:</strong> The Agent uses the LLM to orchestrate the execution by calling specific tools, such as a <em>Places Retriever</em> and a <em>Hotels Retriever</em>, to fetch relevant information.</li><li><strong>Reflect:</strong> The LLM evaluates whether the response fully answers the question. If not, refine the Plan and repeat.</li></ol><p>For this query, the LLM Agent might first list places like the <em>Cotswolds</em> and <em>Yorkshire Dales</em>. Realizing this doesn’t address the hotel aspect, it then re-plans to get hotel details using a different tool and fetches hotels like <em>North End House</em> in the <em>Cotswolds</em> and <em>The Old Farmhouse</em> in <em>Yorkshire Dales</em>. The final response integrates both places and hotels, fully addressing the query.</p><p>Now, if a user extends the query to include travel insurance, the system can incorporate an <em>Insurance Provider Tool</em> without a complete redesign, demonstrating its modular and scalable design.</p><h3><strong>The Problem — Is the Agentic RAG System faithful in providing the answers?</strong></h3><p>Continuing with the example above, how can we verify that the <em>Places</em> included in the final answer are indeed sourced from the <em>Places Retriever</em>, and similarly, that the Hotel names come from the <em>Hotels Retriever</em>?</p><p>This brings us to the importance of measuring faithfulness — ensuring the generated answer aligns accurately with the information retrieved from the Agentic Tools — and checking for any hallucinations or inaccuracies.</p><p>And this is where <strong>IBM watsonx.governance</strong> comes into play:</p><ul><li><strong>Measure Faithfulness</strong>: Evaluate whether the generated answer aligns accurately with the context retrieved from the Agentic Tool(s).</li><li><strong>Assess Tool Context Relevance</strong>: Determine how relevant the retrieved context from the Agentic Tool(s) is to the user’s question.</li><li><strong>Evaluate Answer Relevance</strong>: Ensure the generated answer is pertinent and directly addresses the user’s question.</li></ul><p>In this post, we will focus on understanding how to measure the above three key RAG metrics of an Agentic System: <strong>Faithfulness</strong>, <strong>Tool Context Relevance</strong>, and <strong>Answer Relevance</strong>.</p><p>While there are other important aspects of quality evaluation for an Agentic RAG system — such as ensuring the right tool is called for a given question or assessing the accuracy of the information passed to the tool — these will be explored in an near future. For now, our focus will remain on these core RAG metrics.</p><blockquote>In the following sections, we will develop a simple Agentic RAG System, capture its outputs, and leverage <strong>IBM watsonx.governance</strong> to evaluate key RAG metrics such as Faithfulness, Tool Context Relevance, and Answer Relevance.</blockquote><h3>The Setup — Building an Agentic RAG system.</h3><p>Although this post initially began with the tour operator example and ideally would have liked to continue with the same dataset, finding suitable data for this scenario proved challenging. Additionally, generating high-quality synthetic data for this purpose is time-intensive. Therefore, this post will proceed with a different example to illustrate the concepts.</p><p>So, imagine a team of LLM Application Developers building a chatbot designed to answer questions about AI governance topics. One of the data sources for this chatbot comes from the FAQs of IBM’s own watsonx suite of products — <a href="https://www.ibm.com/docs/en/watsonx/saas?topic=overview-faq">IBM watsonx FAQs</a>.</p><p>If the LLM Application Developers were to build a traditional RAG system, then the steps would be like this:</p><ol><li>Split, index, and load the documents into the vector store.</li><li>Query the vector store with the user’s question to retrieve the top-k chunks/contexts.</li><li>Use these contexts and the user’s question to create a system prompt and run it through an LLM.</li><li>Finally, retrieve the answer.</li></ol><p>Now, let’s say users of this chatbot begin asking questions about the recently released EU AI Act. The challenge with a traditional RAG system is its lack of adaptability. Such systems may struggle to adjust to changing information sources or evolving user needs. However, Agentic RAG, with its modular architecture, adapts easily by adding new tools to its flexible framework.</p><p>In this case, for the chatbot to answer questions about the EU AI Act, the summary of the EU AI Act is available here — <a href="https://artificialintelligenceact.eu/high-level-summary/">EU AI Act Summary</a>.</p><p>Not to deviate a lot from the traditional RAG system, the next step is to load the data from the above web resources to, say, a vector store and create a Retriever out of it — as shown in the code snippet below:</p><pre>gov_faq_urls = [<br>    &#39;https://www.ibm.com/docs/en/watsonx/saas?topic=overview-faq&#39;<br>]<br><br>ai_act_urls = [<br>    &#39;https://artificialintelligenceact.eu/high-level-summary/&#39;<br>]<br><br>def get_retriever(urls, collection_name):<br>    docs = [WebBaseLoader(url).load() for url in urls]<br>    docs_list = [item for sublist in docs for item in sublist]<br>    text_splitter = get_text_splitter()<br>    doc_splits = text_splitter.split_documents(docs_list)<br>    vectorstore = Chroma.from_documents(<br>        documents=doc_splits,<br>        collection_name=collection_name,<br>        embedding=get_embeddings(),<br>    )<br>    retriever = vectorstore.as_retriever()<br>    return retriever<br><br>gov_faqs_retriever = get_retriever(urls=gov_faq_urls, collection_name=&#39;gov_faqs&#39;)<br>ai_act_retriever = get_retriever(urls=ai_act_urls, collection_name=&#39;ai_act&#39;)</pre><p>To proceed, the next step is to wrap each retriever into Agentic tool-based functions using LangChain. The <strong><em>docstring</em></strong> for each tool function should be sufficiently descriptive, as the Agent will rely on this description to determine which tool to call. Below is an example implementation:</p><pre>from langchain.tools import tool<br>ai_act_context = &quot;&quot;<br>gov_faqs_context = &quot;&quot;<br><br>@tool<br>def get_Gov_FAQs_Context(question: str):<br>    &quot;&quot;&quot;Get context from watsonx.ai, watsonx.governance, OpenScale related Frequently asked questions.&quot;&quot;&quot;<br>    global gov_faqs_context<br>    gov_faqs_context = gov_faqs_retriever.invoke(question)<br>    return gov_faqs_context<br><br>@tool<br>def get_AI_Act_Summary_Context(question: str):<br>    &quot;&quot;&quot;Get context from High-level summary of the AI Act.&quot;&quot;&quot;<br>    global ai_act_context<br>    ai_act_context = ai_act_retriever.invoke(question)<br>    return ai_act_context<br><br>tools = [get_AI_Act_Summary_Context, get_Gov_FAQs_Context]</pre><p>Using the concept of <a href="https://api.python.langchain.com/en/latest/agents/langchain.agents.structured_chat.base.create_structured_chat_agent.html#langchain-agents-structured-chat-base-create-structured-chat-agent">Structured Chat Prompts</a> from langchain, let’s create a System Prompt and Human Prompt as follows. These prompts are taken from the <a href="https://ibm.github.io/ibm-generative-ai/v2.3.0/rst_source/examples.extensions.langchain.langchain_agent.html">IBM Generative AI toolkit</a>, which, are also mentioned in the langchain documentation.</p><pre>system_prompt = &quot;&quot;&quot;Respond to the human as helpfully and accurately as possible. You have access to the following tools: {tools}<br>Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).<br>Valid &quot;action&quot; values: &quot;Final Answer&quot; or {tool_names}<br>Provide only ONE action per $JSON_BLOB, as shown:&quot;<br>```<br>{{<br>  &quot;action&quot;: $TOOL_NAME,<br>  &quot;action_input&quot;: $INPUT<br>}}<br>```<br>Follow this format:<br>Question: input question to answer<br>Thought: consider previous and subsequent steps<br>Action:<br>```<br>$JSON_BLOB<br>```<br>Observation: action result<br>... (repeat Thought/Action/Observation N times)<br>Thought: I know what to respond<br>Action:<br>```<br>{{<br>  &quot;action&quot;: &quot;Final Answer&quot;,<br>  &quot;action_input&quot;: &quot;Final response to human&quot;<br>}}<br>Begin! Reminder to ALWAYS respond with a valid json blob of a single action.<br>Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation&quot;&quot;&quot;<br><br><br>human_prompt = &quot;&quot;&quot;{input}<br>{agent_scratchpad}<br>(reminder to always respond in a JSON blob)&quot;&quot;&quot;<br><br></pre><p>Using both system prompt and human prompt strings, create a langchain prompt.</p><pre>from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder<br>from langchain.prompts import PromptTemplate<br>prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, system_prompt),<br>        MessagesPlaceholder(&quot;chat_history&quot;, optional=True),<br>        (&quot;human&quot;, human_prompt),<br>    ]<br>)</pre><p>For LLM to be used by the Agent, let’s use Granite model from IBM watsonx.ai.</p><pre>from langchain_ibm import WatsonxEmbeddings, WatsonxLLM<br>llm = WatsonxLLM(<br>    model_id=&quot;ibm/granite-3-8b-instruct&quot;, <br>    url=credentials.get(&quot;url&quot;),<br>    apikey=credentials.get(&quot;apikey&quot;),<br>    project_id=project_id,<br>    params={<br>        GenParams.DECODING_METHOD: &quot;greedy&quot;,<br>        GenParams.TEMPERATURE: 0,<br>        GenParams.MIN_NEW_TOKENS: 5,<br>        GenParams.MAX_NEW_TOKENS: 250,<br>        GenParams.STOP_SEQUENCES: [&quot;Human:&quot;, &quot;Observation&quot;],<br>    },<br>)</pre><p>And now we can set up the chain with above objects. The <strong><em>AgentExecutor</em></strong> class, which takes chain and the tools, is used to execute the agent.</p><pre>chain = (<br>    RunnablePassthrough.assign(<br>        agent_scratchpad=lambda x: format_log_to_str(x[&quot;intermediate_steps&quot;]),<br>        chat_history=lambda x: memory.chat_memory.messages,<br>    )<br>    | prompt<br>    | llm<br>    | JSONAgentOutputParser()<br>)<br><br>agent_executor = AgentExecutor(<br>    agent=chain, tools=tools, handle_parsing_errors=True, verbose=True, memory=memory<br>)</pre><p>Let’s run one such question <em>“What are considered as Prohibited AI systems?” </em>which ideally is against the EU AI Act content.</p><pre>response = agent_executor.invoke(<br>    {&quot;input&quot;: &quot;What are considered as Prohibited AI systems?&quot;}<br>)</pre><p>The output will be something like this:</p><pre>Entering new AgentExecutor chain...<br><br>```<br>{<br>  &quot;action&quot;: &quot;get_AI_Act_Summary_Context&quot;,<br>  &quot;action_input&quot;: {<br>    &quot;question&quot;: &quot;What are considered as Prohibited AI systems?&quot;<br>  }<br>}<br>```<br><br>Observation[Document(metadata={&#39;language&#39;: &#39;en-US&#39;, &#39;source&#39;: &#39;https://artificialintelligenceact.eu/high-level-summary/&#39;, &#39;title&#39;: &#39;High-level summary of the AI Act ...GPAI models must:&#39;)]<br><br>Action:<br>```<br>{<br>  &quot;action&quot;: &quot;Final Answer&quot;,<br>  &quot;action_input&quot;: &quot;Prohibited AI systems, as per the EU Artificial Intelligence Act, are AI systems that are used as a safety component or a product covered by EU laws in Annex I and required to undergo a third-party conformity assessment under those Annex I laws. They also include AI systems under Annex III use cases, except if the AI system performs a narrow procedural task, improves the result of a previously completed human activity, detects decision-making patterns or deviations from prior decision-making patterns and is not meant to replace or influence the previously completed human assessment without proper human review, or performs a preparatory task to an assessment relevant for the purpose of the use cases listed in Annex III. Additionally, AI systems that profile individuals, i.e., automated processing of personal data to assess various aspects of a person’s life, are always considered high-risk. Providers whose AI system falls under the use cases in Annex III but believes it is not high-risk must document such an assessment before placing it on the market or putting it into service.&quot;<br>}<br>```</pre><p>The AgentExecutor identifies that it needs to call the “<strong><em>get_AI_Act_Summary_Context</em></strong>” tool based on the question and the tool’s <strong><em>docstring</em></strong>. It then invokes the corresponding EU AI Act retriever to obtain the context for the given question. The Agent uses this retrieved context, along with the system prompt and human prompt combination, to generate the final answer, by calling the configured Granite LLM. Store this context in a variable, as it will be used to calculate the RAG metrics.</p><p>Continue handling similar questions with the Agent.</p><p>Let’s ask one more question, for which the answer is not found in any of the retriever context.</p><pre>response = agent_executor.invoke(<br>    {&quot;input&quot;: &quot;How to monitor custom metrics with Watson OpenScale?&quot;}<br>)</pre><p>The output will be something like this:</p><pre>```<br>{<br>  &quot;action&quot;: &quot;Final Answer&quot;,<br>  &quot;action_input&quot;: &quot;To monitor custom metrics with Watson OpenScale, you can use the Watson OpenScale API to collect and analyze data on your AI models&#39; performance. This includes metrics such as accuracy, fairness, and explainability. You can also set up alerts to notify you when certain thresholds are met. For more detailed information, refer to the Watson OpenScale documentation.&quot;<br>}<br>```</pre><p>Looks like the above answer is not completely correct (or to say partially correct) for the question asked, but still the Agent is providing some answer related to custom metrics. Clearly Hallucinating! <em>And this is what we need to detect using IBM watsonx.governance.</em></p><p>Upon asking for some more questions, we capture each tool’s context and also the answer in a data frame. As shown in the screen-shot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUZqIoGRj32ptiQc0GlA5A.png" /><figcaption>More questions, more answers</figcaption></figure><p>The notebook demonstrating such Agentic RAG system using langchain is shared in the references section of this post.</p><blockquote>This post demonstrates the use of two tools, where the output of each tool is treated as the RAG context. In practice, there may be scenarios where the Agent invokes multiple matching tools to answer a single user request. This demo can certainly be extended to handle multi-tool invocations for a given user request, and constructing the RAG context using the output of each tool execution. And to complicate things, and to be more real, there can be scenarios where there are multi-agents with multi-tools invocations. However, for simplicity of this post, we will focus on restricting the execution to a single tool for each user request.</blockquote><h3>The Monitoring Configuration — IBM watsonx.governance.</h3><p>In summary till now, for the given set of questions, we have utilised different Agentic Tools to capture their respective outputs, which are considered as the RAG context. Combining this context with the system prompt and human prompt, we generate the final answer. The result can be represented as a structured dataset: <em>[{ question, contexts, generated answer }].</em></p><p>Using <strong>IBM watsonx.governance</strong>, evaluation and monitoring of LLM applications can be performed at various stages:</p><h4><strong>Application Design Phase</strong></h4><p>As soon as the LLM application developer creates a prompt or Agentic tool(s) and wants to validate the application, they can test the prompts or tools using test data.</p><p>To facilitate this, the developer can leverage the <strong>IBM watsonx.governance Python SDK APIs</strong> and <a href="https://github.com/IBM/watson-openscale-samples/blob/main/WatsonX.Governance/Cloud/GenAI/samples/RAG%20metrics%20computation%20with%20llm%20and%20IBM%20watsonx.gov.ipynb">sample notebooks</a> to validate the designed prompts effectively.</p><h4><strong>Application Development Phase</strong></h4><p>When the developer identifies the need to validate the prompt using validation data, two approaches can be taken:</p><p><strong>Prompt Not Yet Inferred:</strong></p><ol><li>Subscribe the prompt with watsonx.governance, specifying a preferred LLM from watsonx.ai.</li><li>watsonx.governance performs inferencing to generate outputs.</li><li>Using the prompt inputs and outputs, the platform evaluates various LLM quality metrics, including RAG metrics.</li></ol><p><strong>Prompt Already Inferred:</strong></p><ol><li>Subscribe the prompt as a <strong>Detached Prompt Template</strong> in watsonx.governance.</li><li>Upload data containing the prompt inputs and their corresponding pre-inferred outputs.</li><li>watsonx.governance evaluates the uploaded data against various metrics.</li></ol><h4><strong>Pre-Production and Production Phases</strong></h4><ol><li>In the pre-production phase, evaluate prompts comprehensively to ensure readiness for deployment.</li><li>Once in production, implement <strong>continuous monitoring</strong> to maintain quality and detect potential issues.</li></ol><p>For the demonstration in this post, we will evaluate the <strong>RAG metrics</strong> using the <strong>Detached Prompt Template</strong> approach, as we have already captured the structured dataset: [{ question, contexts, generated answer }]. And then there are two ways to evaluate:</p><ul><li><strong>Option 1:</strong> Upload the dataset via the watsonx.governance UI.</li><li><strong>Option 2:</strong> Use the <strong>Python SDK APIs</strong> in a notebook.</li></ul><p>In this case the <strong>notebook route, </strong>as in Option 2 is used, to showcase the APIs. This approach may interest developers who want to automate the evaluation process as part of their application workflows.</p><h4>Creation of the Detached Prompt Template</h4><p>Utilize the watsonx.governance SDK API to create the Detached Prompt Template, providing details such as the Model ID (in this case, the Granite3 8B model) representing the Agent LLM, the task (RAG in this instance) associated with the prompt, the prompt template, its variables, and other relevant details.</p><pre>from ibm_aigov_facts_client import DetachedPromptTemplate, PromptTemplate<br>pta_details = facts_client.assets.create_detached_prompt(<br>    model_id=&quot;ibm/granite-3-8b-instruct&quot;,<br>    task_id=&quot;retrieval_augmented_generation&quot;,<br>    name=&quot;Agentic RAG Testing&quot;,<br>    description=&quot;Agentic RAG Testing&quot;,<br>    prompt_details=PromptTemplate(<br>        input=&quot;$system_prompt_human_prompt&quot;,<br>        prompt_variables={&quot;context&quot;: &quot;&quot;, &quot;query&quot;: &quot;&quot;},<br>        input_prefix=&quot;&quot;,<br>        output_prefix=&quot;&quot;,<br>    ),<br>    detached_information=DetachedPromptTemplate(<br>        prompt_id=&quot;detached_prompt&quot;,<br>        model_id=&quot;ibm/granite-3-8b-instruct&quot;,<br>        model_provider=&quot;IBM&quot;,<br>        model_name=&quot;granite-3-8b-instruct&quot;,<br>        model_url=&quot;$model_url&quot;,<br>        prompt_url=&quot;$prompt_url&quot;,<br>        prompt_additional_info={&quot;IBM Cloud Region&quot;: &quot;us-east1&quot;}<br>))<br>project_pta_id = pta_details.to_dict()[&quot;asset_id&quot;]</pre><p>To evaluate RAG metrics in IBM Cloud SaaS, we will use the <strong>LLM-as-a-Judge</strong> approach. This requires configuring an LLM as an Evaluator within <strong>watsonx.governance</strong>. You can accomplish this through the <strong>UI</strong> or by using the following <strong>code snippet</strong>.</p><p>The Judge Evaluator can be a model from <strong>watsonx.ai</strong> or any other LLM. For this demonstration, the <strong>MIXTRAL_8X7B_INSTRUCT_V01</strong> model is used as the Judge Evaluator.</p><pre>from ibm_watsonx_ai.foundation_models.utils.enums import ModelTypes<br><br>gen_ai_evaluator = wos_client.integrated_systems.add(<br>    name=&quot;RAG Metrics Evaluator&quot;,<br>    description=&quot;RAG Metrics Evaluator&quot;,<br>    type=&quot;generative_ai_evaluator&quot;,<br>    parameters={&quot;evaluator_type&quot;: &quot;watsonx.ai&quot;, &quot;model_id&quot;: ModelTypes.MIXTRAL_8X7B_INSTRUCT_V01.value},<br>    credentials={<br>        &quot;wml_location&quot;: &quot;cloud&quot;,<br>        &quot;apikey&quot;: CLOUD_API_KEY,<br>    },<br>)<br><br># get evaluator integrated system ID<br>result = gen_ai_evaluator.result._to_dict()<br>evaluator_id = result[&quot;metadata&quot;][&quot;id&quot;]<br>evaluator_id</pre><p>Configure the RAG and other metrics, like HAP, PII detection on input and output, to evaluate either using API or using UI.</p><pre>response = wos_client.monitor_instances.mrm.execute_prompt_setup(<br>    prompt_template_asset_id=project_pta_id, <br>    project_id=project_id,<br>    label_column=&quot;reference&quot;,<br>    context_fields = [&quot;context&quot;],     <br>    question_field = &quot;query&quot;,     <br>    operational_space_id=&quot;development&quot;, <br>    problem_type=&quot;retrieval_augmented_generation&quot;,<br>    input_data_type=&quot;unstructured_text&quot;, <br>    supporting_monitors={<br>    &quot;generative_ai_quality&quot;: {<br>        &quot;parameters&quot;: {<br>            &quot;generative_ai_evaluator&quot;: { # global LLM as judge configuration<br>               &quot;enabled&quot;: True,<br>               &quot;evaluator_id&quot;: evaluator_id,<br>            },<br>            &quot;min_sample_size&quot;: 2,<br>            &quot;metrics_configuration&quot;: {<br>                &quot;faithfulness&quot;: {},<br>                &quot;answer_relevance&quot;: {},<br>                &quot;unsuccessful_requests&quot;: {},<br>                &quot;hap_input_score&quot;: {},<br>                &quot;hap_score&quot;: {},<br>                &quot;pii&quot;: {},<br>                &quot;pii_input&quot;: {},<br>                &quot;retrieval_quality&quot;: {},<br>                &quot;answer_similarity&quot;: {},<br>            },<br>        }<br>    }<br>}, <br>    background_mode=False<br>)<br><br>result = response.result<br>result.to_dict()</pre><h3>RAG Metrics Evaluation</h3><p>Trigger Prompt Setup, followed by evaluating the prompt.</p><pre>response = wos_client.monitor_instances.mrm.get_prompt_setup(<br>    prompt_template_asset_id=project_pta_id,<br>    project_id=project_id<br>)<br>#...<br>response  = wos_client.monitor_instances.mrm.evaluate_risk(<br>    monitor_instance_id=mrm_monitor_instance_id,<br>    test_data_set_name=test_data_set_name, <br>    test_data_path=test_data_path,<br>    content_type=content_type,<br>    body=body,<br>    project_id=project_id,<br>    includes_model_output=True,<br>    background_mode=False<br>)</pre><p>And then visualise the results or use APIs to retrieve the evaluated metrics. Using API is as follows:</p><pre>wos_client.monitor_instances.show_metrics(monitor_instance_id=genaiquality_monitor_id, project_id=project_id)</pre><p>Using UI, navigate to the Detached Prompt Prompt Template asset in the project in dataplatform.cloud.ibm.com:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jA5Y8-F-ZRwOvl-pUa2EMA.png" /><figcaption>RAG Metrics in the Model Risk Management Dashboard</figcaption></figure><p>Notice that the overall Faithfulness is bit low 0.65 as an average for 4 records, let’s check why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzG2nPc50qqAuri1GktHKQ.png" /><figcaption>Time Series view of metrics</figcaption></figure><p>Drill down further to examine the faithfulness for each record. Recall that there was one question about custom metrics where no relevant context was retrieved, yet the LLM used by the Agent still generated an answer. For this record, the Faithfulness score is 0.2 — and we could detect this successfully!</p><p>And, in contrast, the other records have a reasonably good Faithfulness score of 0.8. A higher faithfulness score, closer to 1, indicates better performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*0TbifORrAkOn-uYyDDPP7A.png" /><figcaption>Record that is contributing to the Faithfulness issue.</figcaption></figure><p>To demonstrate further, using <strong>IBM watsonx.governance</strong>, you can perform a root-cause analysis of the violated metrics against their thresholds. For instance, you can analyze how many records out of 100 have violated thresholds for metrics like Faithfulness, Answer Relevance, or Unanswered Questions. Additionally, you can identify the records that have violations across all three metrics, or a combination of them. This is illustrated in the screenshot below.</p><p>For Faithfulness, you can pinpoint which part of the context is contributing to the answer, including the source attributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0M-7GHtOEPaFZ5ddVcSOg.png" /><figcaption>Root Cause Metrics for RAG Metrics</figcaption></figure><p>And that wraps up the demonstration!</p><h3>The Summary</h3><ul><li>Began with an explanation of Agentic AI and Agentic RAG.</li><li>Built an Agentic RAG application using LangChain, featuring a single Agent with multiple tools.</li><li>Executed a few questions, capturing the output of each tool as the context, resulting in a collection of <em>[ {question, contexts, answers} ]</em>.</li><li>Created a Detached Prompt Template by combining the system prompt and human prompt.</li><li>Used the Mistral model as the RAG LLM-as-a-Judge Evaluator to assess RAG metrics.</li><li>Logged and evaluated the metrics.</li><li>Visualized the metrics using the IBM watsonx.governance UI.</li></ul><h3>References</h3><ul><li><a href="https://www.ibm.com/products/watsonx-governance">IBM watsonx.goverenance</a></li><li><a href="https://www.ibm.com/docs/en/watsonx/saas?topic=models-evaluation-studio">IBM watsonx.governance Evaluation Studio documentation</a></li><li><a href="https://client-docs.aiopenscale.cloud.ibm.com/html/index.html">IBM watsonx.goverenance monitoring toolkit</a></li><li><a href="https://github.com/IBM/watson-openscale-samples/tree/main/WatsonX.Governance">Sample notebooks</a></li><li><a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/watsonx.gov%20-%20Agentic%20RAG%20Monitoring.ipynb">Notebook used in this post</a></li></ul><p>Hope this helps!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0532e4b4b468" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IBM watsonx.governance Evaluation Studio for Advanced Prompt Assessment]]></title>
            <link>https://ravi-chamarthy.medium.com/ibm-watsonx-governance-evaluation-studio-for-advanced-prompt-assessment-d18c41fb06ca?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d18c41fb06ca</guid>
            <category><![CDATA[watsonx]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[ibm]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 09:45:31 GMT</pubDate>
            <atom:updated>2024-12-26T14:14:51.100Z</atom:updated>
            <content:encoded><![CDATA[<p>(Co-Authored by <a href="https://www.linkedin.com/in/ravichamarthy/">Ravi Chamarthy</a>, <a href="https://www.linkedin.com/in/arunkumarks/">Arunkumar K Suryanarayanan</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmYmJ_3ZhcdUPr5eM3SlXA.png" /><figcaption>IBM watsonx.governance Evaluation Studio</figcaption></figure><h3>The problem statement: Evaluating multiple LLMs and Prompts for Quality Chatbot Responses.</h3><p>Consider a scenario where a bank is building a chatbot powered by a Large Language Model using Retrieval-Augmented Generation, enabling the bank users to ask questions about banking products. Let’s say a team of LLM application developers is tasked with the development of this chatbot. The typical steps to develop the RAG powered chatbot are as follows:</p><ol><li>Split, index, and load the documents into the vector store.</li><li>Query the vector store with the user’s question to retrieve the top-k chunks/contexts.</li><li>Use these contexts and the user’s question to construct a system prompt and run it against an LLM.</li><li>Finally, retrieve the answer.</li></ol><p>Something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oG_09G5IHFG6V_zF3lQytA.png" /><figcaption>Typical RAG Pipeline</figcaption></figure><p>In this process, LLM application developers typically face the following challenges:</p><ul><li><strong>Selecting the LLM:</strong> Among different LLMs, determine which one provides responses that result in better RAG metrics, such as Faithfulness, Answer Relevance, and Context Relevance.</li><li><strong>Defining the system prompt:</strong> Does including varied and multiple N-shot examples result in better relevance scores and no hallucinated answers compared to using only a few N-shot examples?</li><li><strong>Tuning the prompt parameters:</strong> For instance, does a prompt temperature value of 0.6 produce better answer relevance scores and fewer hallucinations compared to a temperature value of 0.9?</li></ul><p>You can imagine various combinations for evaluating which LLM to use, what prompt string to employ, and which prompt parameters to set.</p><p>The obvious question is: How can LLM application developers streamline the LLM selection process, perform these evaluations, and effectively compare the quality metrics?</p><h3>The Solution: IBM watsonx.governance Evaluation Studio.</h3><p>IBM watsonx.governance Evaluation Studio enables LLM application developers to evaluate and compare generative AI assets using quality metrics and customizable criteria tailored to specific application needs. Developers can assess the performance of multiple assets simultaneously and compare results to identify the best LLM, prompt, or prompt parameters for their LLM-powered application.</p><p>By using Evaluation Studio, developers can accelerate the AI development process. The platform automates the evaluation of multiple AI assets for different tasks (like Summarisation, Content Generation, RAG, Text Classification, Entity Extraction, Question and Answering), removing the need to review each prompt template individually. Instead, a single AI evaluation experiment can be configured to test multiple prompt templates at once, saving valuable development time.</p><h3>The Evaluation Procedure: IBM watsonx.governance Evaluation Studio.</h3><p>Among the various combinations mentioned above, let’s consider a scenario where the LLM application developers have designed the following system prompt. They now want to validate it by testing the prompt against three different LLMs using validation data.</p><pre>Context: {context}<br><br>Answer the following question using only information from the above context.<br>Answer in a complete sentence. If there is no good answer in the context, <br>say &quot;I don&#39;t know&quot;.<br><br>Question: {question}<br><br>Answer:</pre><p>Login to <a href="https://dataplatform.cloud.ibm.com/">https://dataplatform.cloud.ibm.com/</a> and navigate to the project of your choice. Using IBM watsonx.ai Prompt Lab, in a wx context project, create 3 Prompt Template assets, each using a different LLM — as shown below.</p><blockquote>Please note that, in practice, the system prompt would include much more sophisticated and detailed instructions with N-shot examples. However, for the purpose of this post, we are using a highly simplified prompt for demonstration.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XBeyFxys-f-wH_NkwaQLLQ.png" /><figcaption>Prompt Template Assets with different LLMs</figcaption></figure><p>You don’t need to evaluate each Prompt Template Asset individually as we would be evaluating all the Prompts at one go as part of the Evaluation Studio process, but the choice is yours.</p><p>The next step is to create an Evaluation Asset using the following steps:</p><ul><li>In the project, click on “New asset”</li><li>Select “Evaluate and compare prompts”</li><li>Provide a name and an optional description for the experiment.</li><li>Select the task type for the prompt, which in this case is RAG.</li><li>Clicking “Next” will display the available RAG-based prompt templates from the current project.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im-dtIU_UTNvM-SQH6aSrA.png" /><figcaption>Listing of the prompt template assets for the Evaluation Experiment.</figcaption></figure><ul><li>Clicking “Next” again will bring you to a screen where you can configure the metric dimensions: “Generative AI Quality” and “Model Health.”</li><li>For “Generative AI Quality”, click “Configure” to select the metrics for evaluation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r32jD2UHC9OmTVzAdZsymw.png" /><figcaption>Configure the Generative AI Quality Dimension.</figcaption></figure><ul><li>Select all metrics except “Data safety” metrics (for this demonstration, we are not checking for HAP and PII content in the validation data, as we know it doesn’t contain any, so no need to check it again).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fr4gxE8dX9hQsUcixVgJ0Q.png" /><figcaption>Dimensions selection for evaluation.</figcaption></figure><ul><li>To evaluate Answer Quality and Retrieval Quality metrics, configure an LLM-as-a-Judge model to assess Faithfulness, Context Relevance, and Answer Relevance metrics. We are using Mistral AI as the Judge Evaluator for the RAG metrics evaluation. Click on “Save”</li><li>Click again on “Save”, after changing any metric thresholds, as needed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaBc8VdvBTLfUWv9ObnYCg.png" /><figcaption>Configure Evaluations</figcaption></figure><ul><li>If you go back to the beginning of this section, the system prompt contains two variables: context and question. In the follow-up screen, select these two prompt variables.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypsUmCWrC71jzEQc4N39UA.png" /><figcaption>RAG specific settings</figcaption></figure><ul><li>Clicking “Next” will provide a screen for test/validation data selection. In the context of RAG, the test/validation file should contain the columns for Question, Context, and Reference Answer. The Reference Answer column is optional and is needed when one would like to compute reference based metrics like ROUGE, BLEU, etc.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qNe3UYWyAaQEWqrj3tqag.png" /><figcaption>Test/Validation data selection for running the Evaluation Experiment.</figcaption></figure><ul><li>Select the data asset file from the Project Assets.</li><li>In the follow-up screen, select the appropriate mappings: choose the column from the data asset that corresponds to the context, the column from the CSV that corresponds to the reference answer (for computing reference-based quality metrics such as ROUGE, BLEU, etc.), and the column for the question.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVmMqUfGBZDKUry8IhkDxw.png" /><figcaption>Data mapping</figcaption></figure><ul><li>Review the configuration selections and click on “Run evaluation”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2D1sQ1aTezPPiHO9icGr5Q.png" /><figcaption>Review and Run evaluation</figcaption></figure><ul><li>The evaluation will be triggered, and you will see the evaluation progress screen, as shown below.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJXzcmWo3t57-iWNQ-8x4Q.png" /><figcaption>Evaluation Progress</figcaption></figure><p>This concludes the evaluation configuration and triggering. In the next section, we will review the evaluation output.</p><h3>The Evaluation Results: IBM watsonx.governance Evaluation Studio.</h3><p>Once the evaluation job is completed, the Evaluation/Metrics comparison screen will be displayed, showing the computed metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQrCTHAWefKHuf28DDcY2g.png" /><figcaption>Evaluation Output</figcaption></figure><p>The Metrics comparison screen will display the metrics for the selected metrics group, with each bar in the chart representing the respective selected LLM. For example, the red-colored bar corresponds to the Granite model. You can observe that the Mistral model performs better for the Faithfulness and Answer Relevance metrics for the selected Prompts.</p><p>You can change the Metrics group using the dropdown, as shown in the screenshot below, to view the computed metrics for the selected prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgQltSN_BgyLPwaD-PC0uw.png" /><figcaption>Viewing metrics for different metric groups</figcaption></figure><p>You can pin a prompt to view the difference in metric values across different prompts, as shown in the screenshot below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaK7dqk-ZjmXCO2mkRY1kw.png" /><figcaption>Pin and compare</figcaption></figure><p>Click on the icon beside the Metrics Group selection to view the “Custom Ranking” option. This allows the LLM application developer to apply weight factors to a set of metrics and see how the computed score fares across the selected prompts. For example, in the screenshot below, the Faithfulness metric is assigned a weight factor of 1, and the Answer Relevance metric is assigned a weight factor of 0.8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g5nI1NOEUcoxMzbx127IMw.png" /><figcaption>Custom ranking configuration</figcaption></figure><p>When you click “Apply,” the Metrics comparison screen is updated with the selected metrics, and the prompts are ranked based on the custom ranking score. As you can see, Mistral performs better according to the custom ranking score (again this is only based on the demo/synthetic data, and not based on actual customer data) for the selected Prompts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w17C8l0F9oj1CpGZY8RHJQ.png" /><figcaption>Custom ranking results</figcaption></figure><p>Well, I can go on with the features, but will pause here..</p><p>In summary, IBM watsonx.governance Evaluation Studio enables developers to configure a single evaluation experiment to test and compare multiple prompt templates across varied LLMs simultaneously, streamlining the process, reducing manual effort, and boosting development efficiency.</p><blockquote>Give it a try today at cloud.ibm.com by provisioning watsonx.governance!</blockquote><h3>References</h3><ul><li><a href="https://www.ibm.com/products/watsonx-governance">IBM watsonx.goverenance</a></li><li><a href="https://www.ibm.com/docs/en/watsonx/saas?topic=models-evaluation-studio">IBM watsonx.governance Evaluation Studio documentation</a></li></ul><p><em>Happy Evaluating! — IBM watsonx.governance — Streamlining Generative AI evaluations for smarter decisions!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d18c41fb06ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Responsible AI: Monitoring Azure Databricks Deployments with IBM watsonx.governance]]></title>
            <link>https://ravi-chamarthy.medium.com/ensuring-responsible-ai-monitoring-azure-databricks-deployments-with-ibm-watsonx-governance-62143e49c732?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/62143e49c732</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[watsonx]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 17:04:03 GMT</pubDate>
            <atom:updated>2024-07-02T17:04:03.291Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNsKHHg2Dcm0rY2FZW6lxA.jpeg" /><figcaption>Abstraction to represent Databricks and monitoring</figcaption></figure><p>Greetings!</p><h3>Bridging Azure Databricks and IBM watsonx.governance</h3><p>Built on Apache Spark, Azure Databricks allows users to collaboratively work on data tasks throughout the entire project lifecycle — from data ingestion and engineering to machine learning model development and deployment. By harnessing the power of the Azure cloud, Databricks unlocks valuable data insights and provides machine learning model development and deployment capabilities.</p><p>However, managing and monitoring deployed models is crucial for any AI-based project. This is where IBM Watsonx.governance comes in. It provides a comprehensive solution for governing both traditional predictive AI/Machine Learning models and the emerging realm of Large Language Model (LLM) prompt deployments. This allows organizations to proactively monitor model performance, mitigate risks, and ensure responsible AI practices throughout the deployment lifecycle.</p><p>Ensuring the continued effectiveness and quality of deployed AI models is a critical challenge.</p><p>This article explores how IBM Watsonx.governance empowers effective monitoring of predictive AI/ML models deployed in Azure Databricks.</p><h3>The Use Case</h3><p>Let’s keep it simple.</p><p>Imagine we have information about someone’s “age”, “gender”, “Body Mass Index”, “family size”, and “smoking” habits.</p><p>Using this information, we will build a model to predict the person health insurance amount.</p><p>Classic example of a regression problem.</p><p>Data is from <a href="https://www.kaggle.com/datasets/mirichoi0218/insurance">https://www.kaggle.com/datasets/mirichoi0218/insurance</a></p><h3>Azure Databricks — Model Development and Deployment ..</h3><p>In this post, Microsoft Azure is used as the cloud provider for Databricks. However, you can also use other providers like AWS or Vertex AI to host Databricks workspaces.</p><h4>Azure Databricks workspace</h4><p>Login to <a href="https://portal.azure.com/">https://portal.azure.com</a> and create Azure Databricks workspace. I earlier tried with Trial tier, but something or the other did not work (may be just a timing thing) and hence I used Premium tier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*obU4vmd81Aku636EiTnxrw.png" /><figcaption>Azure Databricks workspace</figcaption></figure><h4>Azure Databricks Cluster</h4><p>Once the workspace is created, launch it, and proceed to create a compute ML cluster. As part of this article, we used 10.4 LTS (Long Term Support) ML runtime and bare minimum Worker and Driver type and minimum and maximum workers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O54AYGgQQRBrOMNxjn7C3A.png" /><figcaption>Azure Databricks Cluster</figcaption></figure><h4>Load training data to Databricks Catalog</h4><p>Load the <a href="https://github.com/ravichamarthy/azure-databricks/blob/main/insurance.csv">Insurance amount training data</a>, to the default schema in the catalog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8XtC9K3C--rv7S8kjBlKow.png" /><figcaption>Load data to catalog</figcaption></figure><h4>AutoML experiment</h4><p>Start an AutoML experiment by selecting the cluster, and the training dataset, select prediction column and the metric to evaluate the AutoML experiments. Thereby run the experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YG2d1fRHGRj6f9jvFH4wfw.png" /><figcaption>Configure an AutoML experiment</figcaption></figure><h4>Experiment Results</h4><p>Check the experiment results and select the model with better R2 score for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9VTlID1lQbZrM9AHhxgZHA.png" /><figcaption>Experiment Results</figcaption></figure><h4>Model deployment</h4><p>Select the model with better R2 score for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L1E8YZ0_yjMsixlSvNPTjg.png" /><figcaption>Select best model for deployment</figcaption></figure><h4>Model endpoint</h4><p>For the selected model, create an endpoint — basically deploy the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oL7dEfDSx6npvEl0BHt4Vg.png" /><figcaption>Create an endpoint for the model deployment</figcaption></figure><h4>Query endpoint — sample invocation</h4><p>Do a sample evaluation/invocation of the model deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OrONldRujJoOB92xbE7lOg.png" /><figcaption>Quick evaluation</figcaption></figure><h3>IBM watsonx.governance monitoring</h3><h4>Wrapping Azure Databricks invocations as Python Function</h4><p>Currently, we have created and deployed a model in Azure Databricks. The next step is to use IBM watsonx.governance to configure and monitor this model deployment. To facilitate monitoring, we encapsulate the Azure Databricks invocation endpoint in a REST API, which can also be deployed as a Python Function in IBM Watson Machine Learning.</p><p>Here is the code snippet that wraps the Azure Databricks model invocation endpoint as a python function:</p><pre>def azure_databricks_scoring_wrapper():<br><br>    AZURE_DATABRICKS_TOKEN = &#39;#AZURE_DATABRICKS_TOKEN&#39; #generate a token in Azure Databricks console, with desired validity.<br>    invocations_url = &#39;#invocations_url&#39;<br>    <br>    import os<br>    import requests<br>    import numpy as np<br>    import pandas as pd<br>    import json<br>    <br>    #entry point scoring method for this python function    <br>    def score(scoring_payload):<br>        <br>        headers = {}<br>        headers[&quot;Content-Type&quot;] = &quot;application/json&quot;<br>        headers[&quot;Accept&quot;] = &quot;application/json&quot;<br>        headers[&quot;Authorization&quot;] = &quot;Bearer {}&quot;.format(AZURE_DATABRICKS_TOKEN)        <br>        <br>        input_fields = scoring_payload[&#39;input_data&#39;][0][&#39;fields&#39;]<br>        input_values = scoring_payload[&#39;input_data&#39;][0][&#39;values&#39;]<br><br>        # construct the scoring payload for ADB Model Deployment<br>        adb_scoring_payload = {<br>            &quot;dataframe_split&quot;: {<br>                &quot;columns&quot;: input_fields,<br>                &quot;data&quot;: input_values<br>            }<br>        }<br>        <br>        # get the response<br>        response = requests.post(invocations_url, headers=headers, json = adb_scoring_payload, verify=False)<br>        response_json = response.json()<br><br>        # construct the response to what WML Python Function should send back.<br>        transformed_response = {<br>            &#39;predictions&#39;: [{<br>                &#39;values&#39;: [[round(value, 4)] for value in response_json[&#39;predictions&#39;]],<br>                &#39;fields&#39;: [&#39;prediction&#39;]<br>            }]<br>        }        <br>        return transformed_response<br>    return score</pre><h4>Monitoring Evaluations</h4><p>The next steps are as follows:</p><ol><li>Deploy the azure_databricks_scoring_wrapperto WML and obtain a scoring endpoint.</li><li>Use the IBM watsonx.governance UI to configure this endpoint for monitoring.</li></ol><p>Alternatively, as a Developer Persona, you can use IBM watsonx.governance APIs to configure the monitors and perform evaluations by following these steps:</p><ol><li>In watsonx.governance, create a Service Provider for WML where the azure_databricks_scoring_wrapper Python function is deployed.</li><li>Subscribe the WML Python Function deployment to IBM watsonx.governance for monitoring.</li><li>Score the model and log the data.</li><li>Configure all monitors, including Drift V2, Fairness (to ensure that Females and Males receive similar insurance amounts regardless of gender as a model training feature), Explain (both local transaction-level and global explanations to understand the features contributing to predictions), and Quality monitoring.</li><li>Perform evaluations using both the API and the UI.</li><li>Check the results.</li></ol><p>End to end notebook can be found <a href="https://github.com/ravichamarthy/azure-databricks/blob/main/Azure%20Databricks%20Model%20Monitoring.ipynb">here</a>.</p><h4>Evaluation Results</h4><p>You can use IBM watsonx.governance UI to check the evaluated results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_dBHVprZpBm92_Vcjlb5A.png" /><figcaption>Monitoring results.</figcaption></figure><h3>Conclusion</h3><p>This post details the steps for creating and deploying a model in Azure Databricks, wrapping the Azure Databricks invocations endpoint as a WML Python function deployment, and configure IBM watsonx.governance for various monitors to finally evaluate them.</p><p>References</p><ul><li><a href="https://www.ibm.com/products/watsonx-governance">IBM watsonx.goverenance</a></li><li><a href="https://github.com/ravichamarthy/azure-databricks/blob/main/Azure%20Databricks%20Model%20Monitoring.ipynb">Notebook used for setting up IBM watsonx.governance monitoring</a></li></ul><p>Happy Monitoring!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62143e49c732" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring RAG Application Quality with IBM watsonx.governance]]></title>
            <link>https://ravi-chamarthy.medium.com/monitoring-rag-application-quality-with-ibm-watsonx-governance-b2dbd7668816?source=rss-18a5c220ba3c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2dbd7668816</guid>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[hallucinations]]></category>
            <category><![CDATA[ibm]]></category>
            <category><![CDATA[faithfulness]]></category>
            <category><![CDATA[watsonx]]></category>
            <dc:creator><![CDATA[Ravi Chamarthy]]></dc:creator>
            <pubDate>Sat, 22 Jun 2024 15:54:04 GMT</pubDate>
            <atom:updated>2024-06-25T14:19:13.658Z</atom:updated>
            <content:encoded><![CDATA[<p>(Co-Authored by <a href="https://medium.com/@ravi-chamarthy">Ravi Chamarthy</a>, <a href="https://medium.com/@pratapkishorevarma">Pratap Kishore Varma</a>, <a href="https://medium.com/@engineer.passion">Prateek Goyal</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65Co5DG30kIMnTX66Y_ENg.png" /><figcaption>RAG Pattern</figcaption></figure><p>Greetings!</p><h3>The Context — IBM watsonx.governance 2.0.</h3><p>Among its many notable features, IBM watsonx.governance 2.0 includes two new key functionalities: assessing the quality of prompts generated against <strong><em>any</em></strong> Large Language Models, and evaluating the quality of RAG-powered applications.</p><p>This post explain these two aspects.</p><p>To set the context, let’s consider a use case where a bank wants to build a chat-bot to answer user questions about various banking products, such as <em>“What is the annual interest rate for a savings account?”</em> or <em>“How to enable two-factor authentication for the account?”</em>, etc.</p><p>Building such an application in a cost-effective manner with proper governance is one aspect, and equally important to evaluate in development phase and continuously monitor are:</p><ul><li><strong><em>Faithfulness detection</em></strong> — ensuring the chat-bot provides accurate answers based on the given context, rather than fabricating or hallucination responses.</li><li><strong><em>Relevance detection</em></strong> — ensuring the chat-bot generates answers pertinent to the questions and that the application retrieves contexts relevant to the questions rather than irrelevant ones.</li></ul><p>And that’s exactly this post will delve into — How IBM watsonx.governance can measure the faithfulness and relevance of answers obtained from a Conversational AI system, such as a chat-bot powered by any Large Language Model and Retrieval-Augmented Generation (RAG) Pattern.</p><h3>The Background — RAG Pattern.</h3><p>Before delving into the product capabilities, here’s a quick overview of the RAG pattern.</p><p>Using the example of a banking-related chat-bot, a typical RAG system is set up as follows:</p><ul><li>Banking related data is divided into documents, which are further broken down into smaller chunks. Embeddings are generated for these chunks and stored in a vector database such as Milvus, Chroma DB, etc.</li></ul><pre>text_splitter = RecursiveCharacterTextSplitter(chunk_size= chunk_size, chunk_overlap=chunk_overlap)<br>docs = text_splitter.split_documents(data)<br><br>embeddings = HuggingFaceEmbeddings(model_name=&quot;all-MiniLM-L6-v2&quot;)<br><br>doc_db = Chroma.from_documents(docs, embedding=embeddings)</pre><ul><li>For a given question, such as “<em>What is the annual interest rate for a savings account</em>?”, the system retrieves the relevant contexts from the vector store. For instance, the relevant contexts might be found on pages 5, 10, and 20 of the vector store.</li></ul><pre>query1 = &#39;From the list of beneficiaries, I am not able to see the name of beneficiary I have added earlier.&#39;<br>query2 = &#39;If a transaction is not credited to the beneficiary account, does the remitter get back the money?&#39;<br>question_texts = [query1, query2]<br><br># Retrieve relevant context for each question<br>relevant_contexts = []<br><br>for question_text in question_texts:<br>    relevant_chunks = doc_db.similarity_search_with_score(query=question_text, k=1)<br>    relevant_contexts.append(relevant_chunks)</pre><ul><li>A prompt is then constructed using the combination of these contexts and the original question, formatted like this:</li></ul><pre>Context: {}<br><br>Answer the following question using only information from the above context. <br><br>Answer in a complete sentence. If there is no good answer in the context, <br>say &quot;I don&#39;t know&quot;.<br><br>Question: {}<br><br>Answer:</pre><ul><li>This prompt is run against a Large Language Model (LLM), which could be any LLM, such as those from IBM watsonx.ai, AWS Bedrock, Azure OpenAI, Google Vertex AI, etc.</li></ul><p>This post uses Azure OpenAI GPT35 Turbo model for running the RAG prompts.</p><pre>import os<br>import openai<br><br>openai.api_type = &quot;azure&quot;<br>openai.api_base = &quot;https://azure-openai-xxxxx.openai.azure.com/&quot;<br>openai.api_version = &quot;2023-09-15-preview&quot;<br>openai.api_key = &#39;#openai.api_key&#39;<br><br>def get_completion(prompt_text):<br>    response = openai.Completion.create(<br>        engine = &quot;azure-openai-deployment-001&quot;,<br>        prompt=prompt_text,<br>        temperature=0.1,<br>        max_tokens=100,<br>        top_p=0.5,<br>        frequency_penalty=0,<br>        presence_penalty=0,<br>        stop=&#39;\n&#39;<br>    )<br>    return response.choices[0].text<br><br>results = []<br><br>for prompt_text in prompt_texts:<br>    model_response = get_completion(prompt_text=prompt_text)<br>    results.append(model_response)</pre><ul><li>Finally, the system generates the answer.</li></ul><pre>results<br><br>[&quot;Please use &#39;raise a query&#39; option available in support section in the app. You could also track your query from time to time. You can now browse our &#39;Discover our features&#39; videos available in support section of our app for a demo of various features available in our app. &quot;,<br> &quot;Yes. If the beneficiary&#39;s bank is unable to credit the beneficiary&#39;s account for any reason, the former will return the money to the remitting bank within 2 hours. Once the amount is received by the remitting bank, it is credited to the remitter&#39;s account by the branch concerned.&quot;]</pre><p>Export the results to a CSV file for evaluating using IBM watsonx.governance</p><pre>final_payload = []<br>for question, relevant_context, answer, reference_answer in zip(question_texts, relevant_contexts, results, reference_answers):<br>    record_payload = []<br><br>    context = construct_context(relevant_context)<br>    record_payload.append(context)<br>    record_payload.append(question)<br>    record_payload.append(answer)<br>    record_payload.append(reference_answer)<br>    final_payload.append(record_payload)<br><br>import pandas as pd<br>llm_data = pd.DataFrame(final_payload, columns=[&#39;context&#39;, &#39;question&#39;, &#39;generated_text&#39;, &#39;reference_answer&#39;])<br><br>test_data_path = &quot;banking_faq_data.csv&quot;<br>llm_data.to_csv(test_data_path, index=False)</pre><p>At this stage, we have the combination of:</p><ul><li>The question</li><li>The retrieved contexts</li><li>The generated answer</li></ul><p>Using these elements, IBM watsonx.governance can be utilized to measure the RAG Triad metrics: Context Relevance, Faithfulness, and Answer Relevance.</p><ul><li><strong><em>Context Relevance:</em></strong> This measures whether the retrieved contexts are pertinent to the question. <strong><em>(will be released shortly)</em></strong></li><li><strong><em>Faithfulness</em></strong>: This assesses whether the model is deriving the answer from the provided context or if it is being creative and providing its own answer, which could lead to hallucinations.</li><li><strong><em>Answer Relevance</em></strong>: This evaluates whether the obtained answer is relevant to the question.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzcKSjsim69lR-DBTD2lNg.png" /><figcaption>RAG Ecosystem Metrics</figcaption></figure><p>Here is a quick description of additional metrics:</p><ul><li><strong>Answer Similarity Metric:</strong> This metric assesses the overall semantic similarity between the generated response and the ideal answer. <strong><em>(will be released shortly)</em></strong></li><li><strong>Answer Coverage Metrics:</strong> These include various measures:</li><li><strong>Coverage:</strong> Evaluates how much of the answer is a derivative of the context. <strong><em>(available as part of watsonx.governance monitoring SDK)</em></strong></li><li><strong>Density:</strong> Measures how closely the answer follows the source text. <strong><em>(available as part of watsonx.governance monitoring SDK)</em></strong></li><li><strong>Compression:</strong> Assesses the conciseness of the generated summary compared to the source. <strong><em>(available as part of watsonx.governance monitoring SDK)</em></strong></li><li><strong>Novelty:</strong> Evaluates the presence of new n-grams in the answer compared to the references. <strong><em>(available as part of watsonx.governance monitoring SDK)</em></strong></li><li><strong>Redundancy:</strong> Detects repetitive information within the answer. <strong><em>(available as part of watsonx.governance monitoring SDK)</em></strong></li><li><strong>Keyword Inclusions:</strong> Checks for the presence of important keywords from the context in the answer and calculates the F1 Score for matching keywords between the context and the answer. <strong><em>(available as part of watsonx.governance monitoring SDK)</em></strong></li><li><strong>Unanswered Questions:</strong> Identifies questions that the model could not answer. <strong><em>(available as part of watsonx.governance monitoring SDK and also runtime support.)</em></strong></li></ul><blockquote>As a quick recap, this post has covered the RAG pattern and evaluated some questions to retrieve relevant contexts and answers.</blockquote><blockquote>Now, let’s shift focus to how IBM watsonx.governance can be used to evaluate such RAG/LLM — powered applications.</blockquote><h3>IBM watsonx.governance — workflow</h3><p>IBM watsonx.governance offers comprehensive governance capabilities for LLM — powered applications, beyond just computing metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFlODQTPVVNMsNSCky5MGg.png" /><figcaption>IBM watsonx.governance — workflow</figcaption></figure><p>During the design phase, LLM application developers can use the IBM watsonx.governance monitoring toolkit to evaluate the RAG Triad Metrics on the RAG prompts output. This helps refine the retrieval of relevant contexts from the vector database and adjust the prompt generation parameters as needed. Detailed instructions are available in this <a href="https://github.com/IBM/watson-openscale-samples/blob/main/WatsonX.Governance/OnPrem/GenAI/2.0/samples/RAG_metrics_computation_with_IBM_watsonx.governance.ipynb">notebook</a>.</p><p>Once the prompt is designed by LLM application developers, it can be further developed and tested in a project and tracked as part of an AI use case. If the metric values are satisfactory during testing, the prompt can be validated by LLM application validators in a pre-production or validation environment, known as the Validation Space.</p><p>After validation, the prompt can be promoted to a production space for continuous monitoring. As users ask questions, the combination of questions, contexts, and answers are payload logged with IBM watsonx.governance.</p><p>At every phase, IBM watsonx.governance provides capabilities to track the prompt as part of the AI use cases.</p><p>This post focuses on creating, configuring, and evaluating prompts in a Development Project using IBM watsonx.governance, emphasizing API integration. The same functionalities are also available via the IBM watsonx.governance UI.</p><h3>Detached Prompt Template Asset Creation</h3><p>For a given prompt template with prompt input and prompt variables, and using the LLM details, we create a “detached” prompt template asset.</p><blockquote>In this context, “detached” refers to the use of an external LLM model, such as Azure OpenAI GPT-3.5 Turbo, instead of an using an existing model from IBM watsonx.ai. Since the monitoring and evaluation are performed on the logged data for a given prompt template, and not directly scoring the prompt template itself, this setup is termed as a “detached prompt template asset.”</blockquote><pre>task_id = &quot;retrieval_augmented_generation&quot;<br>name = &quot;Banking FAQ External prompt (Azure OpenAI GPT35)&quot;<br><br>from ibm_aigov_facts_client import DetachedPromptTemplate, PromptTemplate<br>detached_information = DetachedPromptTemplate(<br>    prompt_id=&quot;banking_faq_prompt&quot;,<br>    model_id=&quot;gpt-35-turbo&quot;,<br>    model_provider=&quot;Azure OpenAI GPT35&quot;,<br>    model_name=name, ...<br>)<br><br># define parameters for PromptTemplate<br>prompt_variables = {&quot;context&quot;: &quot;&quot;, &quot;question&quot;: &quot;&quot;}<br>input = &quot;&quot;&quot;Context: {context}<br>        Answer the following question using only information from the above context. <br>        Answer in a complete sentence. If there is no good answer in the context, say &quot;I don&#39;t know&quot;.<br>        Question: {question}<br>        Answer:&quot;&quot;&quot;<br><br>prompt_template = PromptTemplate(<br>    input=input,<br>    prompt_variables=prompt_variables, ...<br>)<br><br>pta_details = facts_client.assets.create_detached_prompt(<br>    task_id=task_id,<br>    prompt_details=prompt_template,<br>    detached_information=detached_information, ...<br>)<br>project_pta_id = pta_details.to_dict()[&quot;asset_id&quot;]</pre><h3>Detached Prompt Template Asset Setup</h3><p>For a given detached prompt template asset, setup the monitoring by configuring the RAG related metrics, as described in the below code snippet. As you can notice, we are configuring Faithfulness, Answer Relevance, and other LLM Quality Metrics like ROUGE, BLEU, etc metrics.</p><pre>monitors = {<br>    &quot;generative_ai_quality&quot;: {<br>        &quot;parameters&quot;: {<br>            &quot;min_sample_size&quot;: 10,<br>            &quot;metrics_configuration&quot;: {<br>                &quot;faithfulness&quot;: {},<br>                &quot;answer_relevance&quot;: {},<br>                &quot;rouge_score&quot;: {},<br>                &quot;exact_match&quot;: {},<br>                &quot;bleu&quot;: {},<br>                &quot;unsuccessful_requests&quot;: {}<br>            }<br>        }<br>    }<br>}<br><br>response = wos_client.monitor_instances.mrm.execute_prompt_setup(<br>    prompt_template_asset_id=project_pta_id, <br>    project_id=PROJECT_ID,<br>    supporting_monitors=monitors, ...<br>)</pre><h3>Detached Prompt Template Asset Evaluation</h3><p>Now, we proceed with evaluating the prompt template asset for RAG metrics using the test data that we have gathered in the previous steps.</p><p>As a quick recap, the test data comprise of: questions, their contexts, and the answers. Also includes ground truth answer, if any.</p><p>Evaluation happens using home grown models specifically built for checking faithfulness and relevancy metrics.</p><pre>response  = wos_client.monitor_instances.mrm.evaluate_risk(<br>    test_data_path=test_data_path, ...<br>)</pre><h3>Evaluation Results and Fact Sheets</h3><p>Once the evaluation is completed, you can then view the results in the IBM watsonx.governance console or can fetch the results via., the API</p><p>Evaluation results in the notebook:</p><p>If you zoom in the screen, then you can notice that the Faithfulness score seems to be good, above 70%, but answer relevance score is very less, and this is where the LLM Application developer can go back and fine tune the RAG prompt and/or fix the retrieval of the contexts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*um_Yj0kVW5Ah6hy4jcNqBg.png" /></figure><p>Evaluation results in the IBM watsonx.governance console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MgNwoWqUOCBMKn7bqMkuAQ.png" /><figcaption>Evaluation results IBM watsonx.governance console</figcaption></figure><p>Fact Sheets for the corresponding Prompt Template Asset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F08nGpyllViVv_EziEOd0A.png" /><figcaption>AI Fact Sheet</figcaption></figure><p>Likewise, the AI Use Case Lifecycle tracking:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2jm09SeFiKtVHxfjB9mv5A.png" /></figure><h3>Conclusion</h3><p>This post describes the RAG pattern in general and using IBM watsonx.governance, this post describes how to evaluate the RAG related metrics using the combination of Questions, their contexts and answers — which is generated using an external LLM.</p><h3>References</h3><ul><li><a href="https://www.ibm.com/products/watsonx-governance">IBM watsonx.goverenance</a></li><li><a href="https://client-docs.aiopenscale.cloud.ibm.com/html/index.html">IBM watsonx.goverenance monitoring toolkit</a></li><li><a href="https://github.com/IBM/watson-openscale-samples/tree/main/WatsonX.Governance">Sample notebooks</a></li><li><a href="https://github.com/ravichamarthy/watsonx-explorations/blob/main/Azure%20OpenAI%20GPT35%20Model%20-%20RAG%20Monitoring.ipynb">Notebook used in this post</a></li></ul><p><em>Happy Governing! — IBM watsonx.governance — Making AI conversations more ‘faithful’!!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2dbd7668816" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>