惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Apple Machine Learning Research
Apple Machine Learning Research
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
G
Google Developers Blog
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
酷 壳 – CoolShell
酷 壳 – CoolShell
T
Threat Research - Cisco Blogs
A
Arctic Wolf
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
The Cloudflare Blog
博客园 - 【当耐特】
AWS News Blog
AWS News Blog
U
Unit 42
V
Vulnerabilities – Threatpost
P
Privacy International News Feed
T
Tor Project blog
Microsoft Security Blog
Microsoft Security Blog
宝玉的分享
宝玉的分享
Google DeepMind News
Google DeepMind News
爱范儿
爱范儿
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Recorded Future
Recorded Future
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
C
CXSECURITY Database RSS Feed - CXSecurity.com
T
Threatpost
Latest news
Latest news
GbyAI
GbyAI
S
SegmentFault 最新的问题
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
Hacker News: Ask HN
Hacker News: Ask HN
美团技术团队
N
News | PayPal Newsroom
J
Java Code Geeks
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Hacker News
The Hacker News
The GitHub Blog
The GitHub Blog
V
V2EX
N
News and Events Feed by Topic
T
Troy Hunt's Blog
Security Latest
Security Latest
博客园 - 叶小钗
P
Palo Alto Networks Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Composable Output Guardrails: Filter Agent Responses Before They Reach Users
Mukunda Rao · 2026-05-26 · via DEV Community

The model returned a response that contained a phone number. Someone's real phone number, lifted from the training data. It went straight to the user.

The model returned a response that started with "As an AI language model, I..." — a generic hedge that made the product look unpolished.

The model returned a response with an HTML injection attempt embedded in user-provided text that it had reflected back verbatim.

All of these are output problems. agent-guard-rails is a composable pipeline of output filters that catch them before responses reach users.


The Shape of the Fix

from agent_guard_rails import GuardRails, RuleResult

rails = GuardRails([
    "strip_ai_preamble",          # remove "As an AI..." opener
    "no_pii",                     # flag SSN, cards, phones
    "no_html_injection",          # strip <script>, <img>, HTML tags
    "max_length:2000",            # cap response length
    "no_empty",                   # flag empty responses
])

llm_response = call_llm(prompt)
result: RuleResult = rails.apply(llm_response.content)

if result.blocked:
    return fallback_response(result.rule_name)

# Safe to send
return result.cleaned_text

Enter fullscreen mode Exit fullscreen mode

Each rule either passes (with optional cleaning) or blocks. The first blocking rule stops the pipeline. result.cleaned_text has any cleaning applied by passing rules.


What It Does NOT Do

agent-guard-rails does not use an LLM to evaluate the response. All rules are regex and string-operation based. For semantic guardrails (is this response harmful?), you need a separate classifier.

It does not guarantee safety. Rules catch known patterns. Novel jailbreak outputs or novel PII formats may not be caught. Defense in depth applies here: guardrails are one layer, not the only layer.

It does not block at the request level. It filters responses. For request-level filtering (blocking certain user inputs), you need a separate pre-call filter.


Inside the Library

Rules are composed in a pipeline. Each rule is a function (text: str) -> RuleResult where RuleResult has passed, blocked, cleaned_text, and rule_name.

Built-in rules:

BUILTIN_RULES = {
    "strip_ai_preamble": strip_ai_preamble_rule,
    "no_pii": no_pii_rule,
    "no_html_injection": no_html_injection_rule,
    "no_empty": no_empty_rule,
    "no_repetition": no_repetition_rule,  # detect looping/stuck output
}

# Parameterized rules use "rule_name:param" syntax
def parse_rule(spec: str) -> Callable:
    if ":" in spec:
        name, param = spec.split(":", 1)
        if name == "max_length":
            return max_length_rule(int(param))
        if name == "forbidden_pattern":
            return forbidden_pattern_rule(param)
    return BUILTIN_RULES[spec]

Enter fullscreen mode Exit fullscreen mode

Custom rules: pass callables in the rule list. GuardRails(["no_pii", my_custom_rule]) where my_custom_rule(text) -> RuleResult.

strip_ai_preamble: removes "As an AI language model,", "I'm an AI assistant,", "As a large language model," and similar openers. These make products look unpolished and add no value.

no_html_injection: removes <script>, <iframe>, <img src=...>, and javascript: URIs. Does not strip all HTML (some responses legitimately use markdown-style HTML). Targets injection patterns specifically.

no_repetition: flags output where the same sentence appears 3+ times consecutively. This catches stuck-generation loops where the model starts repeating itself.


When to Use It

Use it for any user-facing agent response. Customer support bots, document Q&A, coding assistants. Anywhere a response goes directly from the LLM to a user without intermediate editing.

The preamble rule is low-risk and high-value. Strip it everywhere. "As an AI language model" adds nothing and signals a lack of product polish.

The PII rule requires thought: do you want to block responses with PII (return a fallback) or clean them (strip the PII from the text)? The blocking approach is safer for compliance. The cleaning approach is better for user experience. Configure per use case.

Skip it for intermediate LLM calls (tool planning, internal reasoning steps). Guardrails are for the final response, not internal agent state.


Install

pip install git+https://github.com/MukundaKatta/agent-guard-rails

Enter fullscreen mode Exit fullscreen mode

from agent_guard_rails import GuardRails, RuleResult

def make_rails_for_context(channel: str) -> GuardRails:
    base_rules = [
        "strip_ai_preamble",
        "no_empty",
        "no_repetition",
        "max_length:3000",
    ]

    if channel == "web":
        base_rules.append("no_html_injection")

    if channel in ("public", "web", "mobile"):
        base_rules.append("no_pii")

    return GuardRails(base_rules)

web_rails = make_rails_for_context("web")

def respond_to_user(user_message: str, channel: str = "web") -> str:
    llm_text = call_llm(user_message)
    result = web_rails.apply(llm_text)

    if result.blocked:
        logger.warning("response_blocked", rule=result.rule_name, channel=channel)
        return "I couldn't generate a complete response. Please try again."

    return result.cleaned_text

Enter fullscreen mode Exit fullscreen mode


Sibling Libraries

Library What it solves
llm-output-validator Rule-based validation of structured output shape
llm-pii-redact Reversible PII redaction with restore support
tool-secret-scrubber Redact API keys from tool output
prompt-shield Pattern-based prompt-injection detection on inputs
agentvet Validate tool call arguments before execution

The combined pipeline: prompt-shield on user inputs (block injection attempts), agentvet on tool calls (validate args), agent-guard-rails on LLM outputs (clean and filter responses).


What's Next

Configurable action per rule: right now rules either block or clean. A warn action that logs but passes would be useful for auditing without blocking production traffic. This would make it easier to tune rules on real traffic before enabling blocking.

Rule composition operators: GuardRails(["no_pii AND no_html_injection", "max_length:2000"]) where AND means both must fail to block. Right now every rule failure blocks independently.

Telemetry integration: emit a structured event every time a rule fires with rule name, input length, and outcome. Feed this into your observability stack to understand how often guardrails trigger in production.


Built as part of the agent-stack family: composable Python primitives for production LLM agents.