iyulab/FluxGuard
GitHub: iyulab/FluxGuard
FluxGuard 是一个默认安全的 .NET LLM 应用 Guardrails 库,通过正则、本地 ML 和可选的 LLM 裁判三层机制防护提示词注入、PII 泄漏及有害内容。
Stars: 2 | Forks: 0
# FluxGuard
默认安全 — LLM 应用的 Guardrails。
[](https://www.nuget.org/packages/FluxGuard)
[](https://dotnet.microsoft.com/)
[](LICENSE)
## 理念
FluxGuard 是一个 guardrail 库,旨在**加速安全的 LLM 应用开发**。
### 核心原则
1. **默认安全**
- 安装后即刻开始保护
- 所有核心 guard 默认开启
- 没有不安全的默认设置
2. **最少样板代码**
- 从一行代码开始
- 开箱即用,无需复杂配置
- 即使选项众多,也有合理的默认值
3. **完全可定制**
- 在每个决策点进行拦截
- 通过 hook 系统修改行为
- 完全覆盖默认策略
4. **本地优先**
- 95%+ 的请求在本地以 <20ms 的延迟处理
- 无需外部服务即可工作
- Remote 是可选的扩展功能
5. **优雅降级**
- Guard 失败不会阻止请求(默认)
- Remote 超时会回退到本地结果
- 所有失败行为均可被覆盖
## 安装
```
# 这在大多数情况下是您所需要的
dotnet add package FluxGuard
# 用于高级分析(LLM Judge, Semantic Cache)
dotnet add package FluxGuard.Remote
# 用于框架集成(ASP.NET Core, Microsoft.Extensions.AI)
dotnet add package FluxGuard.SDK
```
## 快速开始
```
// Start with one line - all core guards are enabled
var guard = new FluxGuard();
var inputCheck = guard.CheckInput(userMessage);
if (inputCheck.Blocked)
{
return inputCheck.BlockedResponse;
}
var response = await llm.CompleteAsync(userMessage);
var outputCheck = guard.CheckOutput(response);
return outputCheck.SanitizedContent ?? response;
```
**仅此一项即可提供:**
- Prompt 注入检测 ✅
- 阻断 Jailbreak 尝试 ✅
- 防御编码绕过攻击 ✅
- 防止 PII 暴露/泄漏 ✅
- 过滤有害内容 ✅
- 速率限制 ✅
## 架构
```
┌─────────────────────────────────────────────────────────────┐
│ FluxGuard (Core) │
├─────────────────────────────────────────────────────────────┤
│ │
│ INPUT ──▶ [L1: Regex] ──▶ [L2: Local ML] ──▶ DECISION │
│ <1ms 5-20ms │
│ │
│ OUTPUT ◀── [L1: Regex] ◀── [L2: Local ML] ◀── LLM │
│ │
└─────────────────────────────────────────────────────────────┘
│
▼ (Optional: FluxGuard.Remote)
┌─────────────────────────────────────────────────────────────┐
│ FluxGuard.Remote │
├─────────────────────────────────────────────────────────────┤
│ [L3: LLM Judge] ──▶ Semantic Analysis ──▶ Final Decision │
│ 50-200ms (on escalation) │
└─────────────────────────────────────────────────────────────┘
```
## Guard 层
| 层级 | 位置 | 延迟 | 默认 |
|-------|----------|---------|---------|
| **L1** | 本地 | <1ms | ✅ 开启 |
| **L2** | 本地 | 5-20ms | ✅ 开启 |
| **L3** | Remote | 50-200ms | ❌ 关闭(选择性开启) |
## 默认 Guard(全部开启)
### 输入 Guard
| Guard | 描述 | 层级 |
|-------|-------------|-------|
| `PromptInjection` | 指令覆盖检测 | L1+L2 |
| `Jailbreak` | 阻断 DAN、AIM 角色攻击 | L1 |
| `EncodingBypass` | Base64、Unicode 绕过检测 | L1 |
| `PIIExposure` | 输入中的 PII 检测 | L1 |
| `RateLimit` | 请求频率限制 | L1 |
| `ContentPolicy` | 自定义策略规则 | L1 |
### 输出 Guard
| Guard | 描述 | 层级 |
|-------|-------------|-------|
| `Toxicity` | 有害内容过滤 | L2 |
| `PIILeakage` | 响应中的 PII 脱敏 | L1 |
| `FormatCompliance` | JSON schema、长度验证 | L1 |
| `Refusal` | 模型拒绝响应检测 | L1 |
| `Hallucination` | 幻觉检测(基于上下文) | L2+**L3** |
## 配置
### Builder 模式
```
var guard = new FluxGuardBuilder()
.WithInputGuards(opt =>
{
// All guards are ON by default - turn OFF if needed
opt.EnableRateLimit = false;
opt.RateLimit.RequestsPerMinute = 120;
})
.WithOutputGuards(opt =>
{
opt.MaxOutputLength = 8192;
opt.PIIMaskingPattern = "[REDACTED]";
})
.Build();
```
### 预设
```
// Standard (default) - L1 + L2, all local guards enabled
var guard = new FluxGuard();
var guard = new FluxGuard(GuardPreset.Standard);
// Strict - Standard + stricter thresholds
var guard = new FluxGuard(GuardPreset.Strict);
// Minimal - L1 only, minimum latency
var guard = new FluxGuard(GuardPreset.Minimal);
```
### 依赖注入
```
// Default registration - Standard preset
services.AddFluxGuard();
// Custom configuration
services.AddFluxGuard(opt =>
{
opt.FailMode = FailMode.Open; // default
opt.LogLevel = GuardLogLevel.Warning; // log blocks/errors only
});
```
## Remote Guard(可选)
仅在需要高级分析时添加。
```
dotnet add package FluxGuard.Remote
```
```
// OpenAI — model must be set explicitly (no default since 0.11.0)
var guard = new FluxGuardBuilder()
.WithRemoteGuard("your-openai-api-key")
.WithModel("gpt-4o-mini")
.WithTimeout(200) // Use L2 result on timeout
.Build();
// Bring your own ITextCompletionService
var guard = new FluxGuardBuilder()
.WithRemoteGuard("your-openai-api-key")
.WithModel("gpt-4o-mini")
.WithCompletionService(myCompletionService)
.Build();
// DI (ASP.NET Core) — register remote separately
services.AddFluxGuard();
services.AddFluxGuardRemote("your-openai-api-key", opt =>
{
opt.Judge.Model = "gpt-4o-mini";
opt.TimeoutMs = 200;
});
```
**Remote 提供:**
- LLM-as-Judge 高级分析
- 语义缓存
- 幻觉检测(L3)
- 多模型集成
## SDK 集成
用于 ASP.NET Core 和 Microsoft.Extensions.AI 集成。
```
dotnet add package FluxGuard.SDK
```
### ASP.NET Core 中间件
```
// Program.cs
builder.Services.AddFluxGuard();
builder.Services.AddFluxGuardMiddleware();
app.UseFluxGuard();
```
### Microsoft.Extensions.AI
```
var chatClient = new ChatClientBuilder()
.UseFluxGuard()
.Use(new OpenAIChatClient(...))
.Build();
```
## Hook 与定制
在每个决策点进行拦截。
```
var guard = new FluxGuardBuilder()
.WithHooks(hooks =>
{
// Before/after checks
hooks.OnBeforeCheck = async ctx => { /* logging, modification */ };
hooks.OnAfterCheck = async (ctx, result) => { /* audit, notifications */ };
// Result-specific hooks
hooks.OnBlocked = async (ctx, result) =>
{
await alertService.NotifyAsync(result);
};
hooks.OnPassed = async (ctx, result) => { /* statistics */ };
// Escalation (when using Remote)
hooks.OnBeforeEscalation = async ctx => { /* pre-L3 processing */ };
hooks.OnEscalationTimeout = async ctx => { /* fallback logic */ };
// Custom decision - override default result
hooks.OnCustomDecision = async (ctx, result) =>
{
// Return null to use default result
// Return GuardDecision to override
if (ctx.User.IsAdmin)
return GuardDecision.Pass("Admin bypass");
return null;
};
})
.Build();
```
### 失败模式
```
services.AddFluxGuard(opt =>
{
// Behavior on guard execution error
opt.FailMode = FailMode.Open; // Pass (default, availability priority)
opt.FailMode = FailMode.Closed; // Block (security priority)
// Or fine-grained control with hooks
opt.OnGuardError = async (ctx, ex) =>
{
logger.LogError(ex, "Guard error");
return FailDecision.Pass; // or Block, Retry
};
});
```
## 国际化
内置对主要语言的 PII 模式和有害内容检测支持。
**支持的语言:**
- 英语、韩语、日语、中文(简体/繁体)
- 西班牙语、葡萄牙语、法语、德语
- 阿拉伯语、印地语、俄语
```
var guard = new FluxGuardBuilder()
.WithLanguages(Languages.Korean | Languages.English) // Default: All
.Build();
```
## 自定义规则
```
// Add input rule
guard.AddInputRule(new PatternRule
{
Name = "CompetitorBlock",
Pattern = @"\b(competitor1|competitor2)\b",
Action = GuardAction.Flag,
Severity = Severity.Medium
});
// Add output rule
guard.AddOutputRule(new ContentRule
{
Name = "InternalCodeFilter",
Keywords = ["INTERNAL:", "DEBUG:", "TODO:"],
Action = GuardAction.Remove
});
```
## 日志与指标
```
var guard = new FluxGuardBuilder()
.WithLogging(opt =>
{
opt.LogLevel = GuardLogLevel.Warning; // Default: blocks/errors only
opt.LogDestination = LogDestination.Console;
})
.WithMetrics(opt =>
{
opt.EnablePrometheus = true;
opt.MetricsPrefix = "fluxguard";
})
.Build();
// Get statistics
var stats = guard.GetStats();
Console.WriteLine($"Total: {stats.TotalChecks}");
Console.WriteLine($"Blocked: {stats.BlockedCount} ({stats.BlockRate:P1})");
Console.WriteLine($"Avg Latency: {stats.AvgLatencyMs:F1}ms");
```
## 配置文件
```
{
"FluxGuard": {
"Preset": "Standard",
"FailMode": "Open",
"LogLevel": "Warning",
"Input": {
"EnablePromptInjection": true,
"EnableJailbreak": true,
"EnableEncodingBypass": true,
"EnablePII": true,
"EnableRateLimit": true,
"MaxInputLength": 8192,
"RateLimit": {
"RequestsPerMinute": 60,
"RequestsPerHour": 500
}
},
"Output": {
"EnableToxicity": true,
"EnablePII": true,
"EnableFormatCompliance": true,
"MaxOutputLength": 4096
},
"Remote": {
"Enabled": false,
"EscalationThreshold": 0.7,
"TimeoutMs": 200
}
}
}
```
## 性能
| 预设 | 延迟 | 吞吐量 |
|--------|---------|------------|
| Minimal (L1) | <1ms | 100K+ req/s |
| Standard (L1+L2) | 5-20ms | 5K req/s |
| + Remote (L3) | 50-200ms | 500 req/s |
## 包
| 包 | 描述 | 依赖 |
|---------|-------------|--------------|
| `FluxGuard` | 核心 guardrails (L1+L2) | ONNX Runtime |
| `FluxGuard.Remote` | 远程分析 (L3) | FluxGuard, HTTP |
| `FluxGuard.SDK` | 框架集成 | FluxGuard, ASP.NET Core, MEAI |
## 许可证
MIT 许可证 - 详情请参阅 [LICENSE](LICENSE)。
标签:AI安全, Chat Copilot, Clair, IPv6支持, Naabu, Petitpotam, 内容安全, 多人体追踪, 提示注入防御, 数据脱敏, 源代码安全, 自定义请求头