Skip to main content

Module 25.5: Responsible AI (RAI) & Safety Plugins

Responsible AI Safety Gateway & Guardrails (Light) Responsible AI Safety Gateway & Guardrails (Dark)

Theory​

🧭 Building on Module 25 (From Node Callbacks to App Plugins): In Module 25, you mastered ADK's six lifecycle callbacks (before_agent, after_agent, before_model, after_model, before_tool, after_tool) attached to a single Agent. In multi-agent enterprise systems, copy-pasting safety callbacks onto every sub-agent is error-proneβ€”one forgotten specialist creates a compliance gap! By packaging those exact lifecycle hooks (plus stream-level hooks like on_event_callback) into a BasePlugin registered once on App(plugins=[...]), ADK enforces Responsible AI (RAI) policies across every agent, sub-agent, and workflow node automatically.

In enterprise environments, you cannot rely solely on a model's internal prompt alignment; you need a programmatic, deterministic Defense-in-Depth Guardrail System that governs what your entire application is allowed to process and output.

The Four Guardrail Layers of Enterprise AI​

Enterprise agent applications deploy multi-layered guardrails:

  1. Input Guardrail (Layer 1): Intercepts inbound prompts before the LLM reasons (before_model_callback), blocking prompt injections, jailbreak templates, and unauthorized system override attempts.
  2. Tool Execution Policy (Layer 2): Intercepts tool calls (before_tool_callback / on_tool_error_callback), verifying that tool arguments remain within permissible business boundaries.
  3. Core Agent Reasoner (Layer 3): Foundational LLM reasoning guided by system instructions and safety settings.
  4. Output Guardrail (Layer 4): Intercepts generated responses (on_event_callback), inspecting final text for PII (credit cards, SSNs, API keys) or harmful content, enforcing strict Fail-Closed data redaction.

The "Fail-Closed" vs "Fail-Open" Paradigm​

Fail-Closed Safety Interception Pipeline (Light) Fail-Closed Safety Interception Pipeline (Dark) Figure: Real-time fail-closed safety interception pipeline intercepting violations before response delivery.

  • Fail-Open (Dangerous): If a guardrail fails or times out, the unverified LLM output is delivered to the user.
  • Fail-Closed (Enterprise Standard): If a guardrail detects a violation, times out, or encounters an internal evaluation error, the unverified output is withheld and replaced with a deterministic, sanitized response while logging an audit event.

Implementing Multi-Layered Safety with ADK Plugins​

ADK 2.0 plugins are ideal for safety because they operate outside the LLM reasoning loop with full access to Event and LlmRequest objects:

import re
from google.adk.plugins import BasePlugin
from google.adk.events import Event

class PIIGuardrailPlugin(BasePlugin):
"""Fail-Closed output guardrail: redacts financial identifiers."""
def __init__(self, name: str = 'pii_guardrail'):
super().__init__(name)
self.cc_pattern = re.compile(r"\b\d{4}-\d{4}-\d{4}-\d{4}\b")

async def on_event_callback(self, *, event: Event, **kwargs):
if event.is_final_response() and event.content and event.content.parts:
response_text = event.content.parts[0].text

# Check for PII pattern
if response_text and self.cc_pattern.search(response_text):
# πŸ›‘οΈ THE INTERVENTION: Replace output with safe warning
event.content.parts[0].text = (
"πŸ›‘ [SECURITY BLOCK] This response was withheld because it contained "
"sensitive financial information (PII)."
)
print(f"πŸ›‘ [SAFETY AUDIT] Blocked PII in invocation: {getattr(event, 'invocation_id', 'unknown')}")

# Register once on App -- wraps root_agent and every downstream sub-agent!
from google.adk.apps import App

app = App(
name="enterprise_app",
root_agent=root_agent,
plugins=[PIIGuardrailPlugin()],
)

Why use a Plugin for Responsible AI?​

  1. Centralized Enterprise Governance: A single compliance plugin can be attached across an entire fleet of agents without modifying their individual instructions.
  2. Deterministic Security: Unlike probabilistic system prompts that can be bypassed via sophisticated prompt injection, programmatic Python plugins run deterministically.
  3. Auditability & Compliance: Safety plugins can stream intervention logs to BigQuery or Cloud Logging for regulatory compliance (GDPR, HIPAA, PCI-DSS).
🎯 Knowledge CheckSelect Best Answer

Why is the 'Fail-Closed' architectural pattern considered mandatory for enterprise Responsible AI (RAI) guardrails?

Key Takeaways​

  • RAI is a core production requirement: Enterprise AI systems require defense-in-depth across input, tool, and output stages.
  • Fail-Closed Guarantee: Unsafe or unverified messages are blocked deterministically before reaching the user.
  • Separation of Concerns: Safety rules live in modular plugins rather than cluttering core agent instructions.
  • Audit Lineage: Every safety intervention records telemetry for compliance and threat analysis.
πŸ“–

25.5: RAI Safety & Moderation(Theory & Overview)

Part 4: Production Readiness β€’ Module 25.5

Overall Course Progress:
0%(0/98)
Next Step: Challenge Lab πŸ§ͺ β†’