guardrails

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	SeverityCritical = "critical"
	SeverityHigh     = "high"
	SeverityMedium   = "medium"
	SeverityLow      = "low"
)

Severity 常量定义

View Source
const (
	ErrCodeInjectionDetected = "INJECTION_DETECTED"
	ErrCodePIIDetected       = "PII_DETECTED"
	ErrCodeMaxLengthExceeded = "MAX_LENGTH_EXCEEDED"
	ErrCodeBlockedKeyword    = "BLOCKED_KEYWORD"
	ErrCodeContentBlocked    = "CONTENT_BLOCKED"
	ErrCodeValidationFailed  = "VALIDATION_FAILED"
)

Error 错误代码常量

Variables

This section is empty.

Functions

This section is empty.

Types

type AIPattern

type AIPattern struct {
	Name        string         `json:"name"`
	Type        string         `json:"type"` // domain, content, api
	Pattern     *regexp.Regexp `json:"-"`
	PatternStr  string         `json:"pattern"`
	Severity    string         `json:"severity"`
	Description string         `json:"description"`
}

AIPattern是检测AI服务的一种模式.

type AuditEventType

type AuditEventType string

AuditEventType 审计事件类型

const (
	// AuditEventValidationFailed 验证失败事件
	AuditEventValidationFailed AuditEventType = "validation_failed"
	// AuditEventContentFiltered 内容过滤事件
	AuditEventContentFiltered AuditEventType = "content_filtered"
	// AuditEventPIIDetected PII 检测事件
	AuditEventPIIDetected AuditEventType = "pii_detected"
	// AuditEventInjectionDetected 注入检测事件
	AuditEventInjectionDetected AuditEventType = "injection_detected"
)

type AuditLogEntry

type AuditLogEntry struct {
	// Timestamp 时间戳
	Timestamp time.Time `json:"timestamp"`
	// EventType 事件类型
	EventType AuditEventType `json:"event_type"`
	// ValidatorName 验证器名称
	ValidatorName string `json:"validator_name"`
	// ContentHash 内容哈希(用于追踪,不存储原始内容)
	ContentHash string `json:"content_hash"`
	// Errors 验证错误列表
	Errors []ValidationError `json:"errors,omitempty"`
	// Metadata 附加元数据
	Metadata map[string]any `json:"metadata,omitempty"`
}

AuditLogEntry 审计日志条目 Requirements 2.5: 记录所有验证失败事件用于审计

type AuditLogFilter

type AuditLogFilter struct {
	// StartTime 开始时间
	StartTime *time.Time
	// EndTime 结束时间
	EndTime *time.Time
	// EventTypes 事件类型过滤
	EventTypes []AuditEventType
	// ValidatorNames 验证器名称过滤
	ValidatorNames []string
	// Limit 返回数量限制
	Limit int
	// Offset 偏移量
	Offset int
}

AuditLogFilter 审计日志查询过滤器

type AuditLogger

type AuditLogger interface {
	// Log 记录审计日志
	Log(ctx context.Context, entry *AuditLogEntry) error
	// Query 查询审计日志
	Query(ctx context.Context, filter *AuditLogFilter) ([]*AuditLogEntry, error)
	// Count 统计审计日志数量
	Count(ctx context.Context, filter *AuditLogFilter) (int, error)
}

AuditLogger 护栏层审计日志记录器接口。

注意:项目中存在三个 AuditLogger 接口,各自服务不同领域,无法统一:

  • llm.AuditLogger — 框架级,记录 AuditEvent(通用事件)
  • llm/tools.AuditLogger — 工具层,记录 *AuditEntry(工具调用/权限/成本),含 LogAsync/Close
  • agent/guardrails.AuditLogger(本接口) — 护栏层,记录 *AuditLogEntry(验证失败/PII/注入),含 Count

三者的事件类型、过滤器结构和方法签名均不同,统一会导致接口膨胀。

type ChainMode

type ChainMode string

ChainMode 验证器链执行模式

const (
	// ChainModeFailFast 快速失败模式:遇到第一个错误立即停止
	ChainModeFailFast ChainMode = "fail_fast"
	// ChainModeCollectAll 收集全部模式:执行所有验证器并收集所有结果
	ChainModeCollectAll ChainMode = "collect_all"
	// ChainModeParallel 并行模式:并行执行所有验证器并收集结果
	ChainModeParallel ChainMode = "parallel"
)

type ContentFilter

type ContentFilter struct {
	// contains filtered or unexported fields
}

ContentFilter 内容过滤器 用于过滤输出中的有害内容 Requirements 2.2: 拦截有害内容

func NewContentFilter

func NewContentFilter(config *ContentFilterConfig) (*ContentFilter, error)

NewContentFilter 创建内容过滤器

func (*ContentFilter) AddPattern

func (f *ContentFilter) AddPattern(pattern string) error

AddPattern 添加禁止模式

func (*ContentFilter) Detect

func (f *ContentFilter) Detect(content string) []ContentMatch

Detect 检测内容中是否包含禁止模式

func (*ContentFilter) Filter

func (f *ContentFilter) Filter(ctx context.Context, content string) (string, error)

Filter 执行内容过滤 实现 Filter 接口

func (*ContentFilter) GetPatterns

func (f *ContentFilter) GetPatterns() []string

GetPatterns 返回所有禁止模式

func (*ContentFilter) Name

func (f *ContentFilter) Name() string

Name 返回过滤器名称

func (*ContentFilter) RemovePattern

func (f *ContentFilter) RemovePattern(pattern string) bool

RemovePattern 移除禁止模式

func (*ContentFilter) SetReplacement

func (f *ContentFilter) SetReplacement(replacement string)

SetReplacement 设置替换文本

type ContentFilterConfig

type ContentFilterConfig struct {
	// BlockedPatterns 禁止的正则模式
	BlockedPatterns []string
	// Replacement 替换文本
	Replacement string
	// CaseSensitive 是否区分大小写
	CaseSensitive bool
}

ContentFilterConfig 内容过滤器配置

func DefaultContentFilterConfig

func DefaultContentFilterConfig() *ContentFilterConfig

DefaultContentFilterConfig 返回默认配置

type ContentFilterValidator

type ContentFilterValidator struct {
	// contains filtered or unexported fields
}

ContentFilterValidator 内容过滤验证器 将 ContentFilter 包装为 Validator 接口

func NewContentFilterValidator

func NewContentFilterValidator(filter *ContentFilter, priority int) *ContentFilterValidator

NewContentFilterValidator 创建内容过滤验证器

func (*ContentFilterValidator) Name

func (v *ContentFilterValidator) Name() string

Name 返回验证器名称

func (*ContentFilterValidator) Priority

func (v *ContentFilterValidator) Priority() int

Priority 返回优先级

func (*ContentFilterValidator) Validate

func (v *ContentFilterValidator) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行内容过滤验证

type ContentMatch

type ContentMatch struct {
	Pattern  string `json:"pattern"`
	Value    string `json:"value"`
	Position int    `json:"position"`
	Length   int    `json:"length"`
}

ContentMatch 内容匹配结果

type Detection

type Detection struct {
	ID          string         `json:"id"`
	PatternName string         `json:"pattern_name"`
	Type        string         `json:"type"`
	Source      string         `json:"source"`
	Evidence    string         `json:"evidence"`
	Severity    string         `json:"severity"`
	Timestamp   time.Time      `json:"timestamp"`
	UserID      string         `json:"user_id,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
}

检测代表检测到的阴影AI用法.

type FailureAction

type FailureAction string

FailureAction 失败处理动作

const (
	// FailureActionReject 拒绝请求
	FailureActionReject FailureAction = "reject"
	// FailureActionWarn 发出警告但继续处理
	FailureActionWarn FailureAction = "warn"
	// FailureActionRetry 重试请求
	FailureActionRetry FailureAction = "retry"
)

type Filter

type Filter interface {
	// Filter 执行过滤,返回过滤后的内容
	Filter(ctx context.Context, content string) (string, error)
	// Name 返回过滤器名称
	Name() string
}

Filter 过滤器接口 用于过滤和转换内容

type FilterRegistry

type FilterRegistry struct {
	// contains filtered or unexported fields
}

FilterRegistry 过滤器注册表

func NewFilterRegistry

func NewFilterRegistry() *FilterRegistry

NewFilterRegistry 创建过滤器注册表

func (*FilterRegistry) Get

func (r *FilterRegistry) Get(name string) (Filter, bool)

Get 获取过滤器

func (*FilterRegistry) List

func (r *FilterRegistry) List() []Filter

List 列出所有过滤器

func (*FilterRegistry) Register

func (r *FilterRegistry) Register(f Filter)

Register 注册过滤器

func (*FilterRegistry) Unregister

func (r *FilterRegistry) Unregister(name string)

Unregister 注销过滤器

type GuardrailsConfig

type GuardrailsConfig struct {
	InputValidators  []Validator `json:"-"`
	OutputValidators []Validator `json:"-"`
	OutputFilters    []Filter    `json:"-"`

	// 内置验证器配置
	MaxInputLength      int      `json:"max_input_length"`
	BlockedKeywords     []string `json:"blocked_keywords"`
	PIIDetectionEnabled bool     `json:"pii_detection_enabled"`
	InjectionDetection  bool     `json:"injection_detection"`

	// 失败处理
	OnInputFailure  FailureAction `json:"on_input_failure"`
	OnOutputFailure FailureAction `json:"on_output_failure"`
	MaxRetries      int           `json:"max_retries"`
}

GuardrailsConfig 护栏配置

func DefaultConfig

func DefaultConfig() *GuardrailsConfig

DefaultConfig 返回默认配置

type InjectionDetector

type InjectionDetector struct {
	// contains filtered or unexported fields
}

InjectionDetector 提示注入检测器 实现 Validator 接口,用于检测和防止提示注入攻击

func NewInjectionDetector

func NewInjectionDetector(config *InjectionDetectorConfig) *InjectionDetector

NewInjectionDetector 创建注入检测器

func (*InjectionDetector) Detect

func (d *InjectionDetector) Detect(content string) []InjectionMatch

Detect 检测内容中的所有注入模式

func (*InjectionDetector) IsolateWithDelimiters

func (d *InjectionDetector) IsolateWithDelimiters(content string) string

IsolateWithDelimiters 使用分隔符隔离用户输入 返回被安全分隔符包围的内容

func (*InjectionDetector) IsolateWithRole

func (d *InjectionDetector) IsolateWithRole(content string) string

IsolateWithRole 使用角色标记隔离用户输入 返回带有明确角色标记的内容

func (*InjectionDetector) Name

func (d *InjectionDetector) Name() string

Name 返回验证器名称

func (*InjectionDetector) Priority

func (d *InjectionDetector) Priority() int

Priority 返回优先级

func (*InjectionDetector) Validate

func (d *InjectionDetector) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行注入检测验证 实现 Validator 接口

type InjectionDetectorConfig

type InjectionDetectorConfig struct {
	// CaseSensitive 是否区分大小写
	CaseSensitive bool
	// UseDelimiters 是否使用分隔符隔离
	UseDelimiters bool
	// CustomPatterns 自定义注入模式
	CustomPatterns []string
	// Priority 验证器优先级
	Priority int
	// EnabledLanguages 启用的语言检测,为空则启用所有
	EnabledLanguages []string
}

InjectionDetectorConfig 注入检测器配置

func DefaultInjectionDetectorConfig

func DefaultInjectionDetectorConfig() *InjectionDetectorConfig

DefaultInjectionDetectorConfig 返回默认配置

type InjectionMatch

type InjectionMatch struct {
	Pattern     string `json:"pattern"`
	Description string `json:"description"`
	Severity    string `json:"severity"`
	Position    int    `json:"position"`
	Length      int    `json:"length"`
	MatchedText string `json:"matched_text"`
}

InjectionMatch 注入匹配结果

type InjectionPattern

type InjectionPattern struct {
	Pattern     *regexp.Regexp
	Description string
	Severity    string
	Language    string // "en", "zh", "universal"
}

InjectionPattern 注入模式类型

type KeywordAction

type KeywordAction string

KeywordAction 关键词处理动作

const (
	// KeywordActionReject 拒绝处理
	KeywordActionReject KeywordAction = "reject"
	// KeywordActionWarn 警告处理
	KeywordActionWarn KeywordAction = "warn"
	// KeywordActionFilter 过滤处理(替换关键词)
	KeywordActionFilter KeywordAction = "filter"
)

type KeywordMatch

type KeywordMatch struct {
	Keyword  string `json:"keyword"`
	Severity string `json:"severity"`
	Position int    `json:"position"`
	Length   int    `json:"length"`
}

KeywordMatch 关键词匹配结果

type KeywordSeverity

type KeywordSeverity struct {
	Keyword  string
	Severity string
}

KeywordSeverity 关键词严重级别配置

type KeywordValidator

type KeywordValidator struct {
	// contains filtered or unexported fields
}

KeywordValidator 关键词验证器 实现 Validator 接口,用于检测禁止的关键词 Requirements 1.4: 当用户输入包含禁止的关键词时,根据配置的严重级别进行处理

func NewKeywordValidator

func NewKeywordValidator(config *KeywordValidatorConfig) *KeywordValidator

NewKeywordValidator 创建关键词验证器

func (*KeywordValidator) AddKeyword

func (v *KeywordValidator) AddKeyword(keyword string, severity string)

AddKeyword 添加禁止关键词

func (*KeywordValidator) Detect

func (v *KeywordValidator) Detect(content string) []KeywordMatch

Detect 检测内容中的所有禁止关键词

func (*KeywordValidator) Filter

func (v *KeywordValidator) Filter(content string) string

Filter 过滤内容中的禁止关键词

func (*KeywordValidator) GetAction

func (v *KeywordValidator) GetAction() KeywordAction

GetAction 返回配置的处理动作

func (*KeywordValidator) GetBlockedKeywords

func (v *KeywordValidator) GetBlockedKeywords() []string

GetBlockedKeywords 返回禁止关键词列表

func (*KeywordValidator) Name

func (v *KeywordValidator) Name() string

Name 返回验证器名称

func (*KeywordValidator) Priority

func (v *KeywordValidator) Priority() int

Priority 返回优先级

func (*KeywordValidator) RemoveKeyword

func (v *KeywordValidator) RemoveKeyword(keyword string)

RemoveKeyword 移除禁止关键词

func (*KeywordValidator) Validate

func (v *KeywordValidator) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行关键词验证 实现 Validator 接口

type KeywordValidatorConfig

type KeywordValidatorConfig struct {
	// BlockedKeywords 禁止的关键词列表
	BlockedKeywords []string
	// KeywordSeverities 关键词严重级别映射(可选,未配置的使用默认级别)
	KeywordSeverities map[string]string
	// DefaultSeverity 默认严重级别
	DefaultSeverity string
	// Action 处理动作
	Action KeywordAction
	// CaseSensitive 是否区分大小写
	CaseSensitive bool
	// Replacement 过滤模式下的替换文本
	Replacement string
	// Priority 验证器优先级
	Priority int
}

KeywordValidatorConfig 关键词验证器配置

func DefaultKeywordValidatorConfig

func DefaultKeywordValidatorConfig() *KeywordValidatorConfig

DefaultKeywordValidatorConfig 返回默认配置

type LengthAction

type LengthAction string

LengthAction 长度超限处理动作

const (
	// LengthActionTruncate 截断处理
	LengthActionTruncate LengthAction = "truncate"
	// LengthActionReject 拒绝处理
	LengthActionReject LengthAction = "reject"
)

type LengthValidator

type LengthValidator struct {
	// contains filtered or unexported fields
}

LengthValidator 长度验证器 实现 Validator 接口,用于验证输入长度 Requirements 1.3: 当用户输入超过配置的最大长度时,截断或拒绝该输入

func NewLengthValidator

func NewLengthValidator(config *LengthValidatorConfig) *LengthValidator

NewLengthValidator 创建长度验证器

func (*LengthValidator) GetAction

func (v *LengthValidator) GetAction() LengthAction

GetAction 返回配置的处理动作

func (*LengthValidator) GetMaxLength

func (v *LengthValidator) GetMaxLength() int

GetMaxLength 返回配置的最大长度

func (*LengthValidator) Name

func (v *LengthValidator) Name() string

Name 返回验证器名称

func (*LengthValidator) Priority

func (v *LengthValidator) Priority() int

Priority 返回优先级

func (*LengthValidator) Truncate

func (v *LengthValidator) Truncate(content string) string

Truncate 截断内容至最大长度

func (*LengthValidator) Validate

func (v *LengthValidator) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行长度验证 实现 Validator 接口

type LengthValidatorConfig

type LengthValidatorConfig struct {
	// MaxLength 最大长度(字符数)
	MaxLength int
	// Action 超限处理动作
	Action LengthAction
	// Priority 验证器优先级
	Priority int
}

LengthValidatorConfig 长度验证器配置

func DefaultLengthValidatorConfig

func DefaultLengthValidatorConfig() *LengthValidatorConfig

DefaultLengthValidatorConfig 返回默认配置

type MemoryAuditLogger

type MemoryAuditLogger struct {
	// contains filtered or unexported fields
}

MemoryAuditLogger 内存审计日志记录器 用于测试和开发环境

func NewMemoryAuditLogger

func NewMemoryAuditLogger(maxSize int) *MemoryAuditLogger

NewMemoryAuditLogger 创建内存审计日志记录器

func (*MemoryAuditLogger) Clear

func (l *MemoryAuditLogger) Clear()

Clear 清空所有日志条目

func (*MemoryAuditLogger) Count

func (l *MemoryAuditLogger) Count(ctx context.Context, filter *AuditLogFilter) (int, error)

Count 统计审计日志数量

func (*MemoryAuditLogger) GetEntries

func (l *MemoryAuditLogger) GetEntries() []*AuditLogEntry

GetEntries 获取所有日志条目(用于测试)

func (*MemoryAuditLogger) Log

func (l *MemoryAuditLogger) Log(ctx context.Context, entry *AuditLogEntry) error

Log 记录审计日志

func (*MemoryAuditLogger) Query

func (l *MemoryAuditLogger) Query(ctx context.Context, filter *AuditLogFilter) ([]*AuditLogEntry, error)

Query 查询审计日志

type OutputValidator

type OutputValidator struct {
	// contains filtered or unexported fields
}

OutputValidator 输出验证器 用于验证 Agent 输出的安全性和合规性 Requirements 2.1: 检测并脱敏敏感信息 Requirements 2.2: 拦截有害内容并返回安全替代响应 Requirements 2.3: 验证输出格式 Requirements 2.5: 记录所有验证失败事件用于审计

func NewOutputValidator

func NewOutputValidator(config *OutputValidatorConfig) *OutputValidator

NewOutputValidator 创建输出验证器

func (*OutputValidator) AddFilter

func (v *OutputValidator) AddFilter(filter Filter)

AddFilter 添加过滤器

func (*OutputValidator) AddValidator

func (v *OutputValidator) AddValidator(validator Validator)

AddValidator 添加验证器

func (*OutputValidator) GetAuditLogger

func (v *OutputValidator) GetAuditLogger() AuditLogger

GetAuditLogger 获取审计日志记录器

func (*OutputValidator) Name

func (v *OutputValidator) Name() string

Name 返回验证器名称

func (*OutputValidator) Priority

func (v *OutputValidator) Priority() int

Priority 返回优先级

func (*OutputValidator) SetSafeReplacement

func (v *OutputValidator) SetSafeReplacement(replacement string)

SetSafeReplacement 设置安全替代响应

func (*OutputValidator) Validate

func (v *OutputValidator) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行输出验证 实现 Validator 接口

func (*OutputValidator) ValidateAndFilter

func (v *OutputValidator) ValidateAndFilter(ctx context.Context, content string) (string, *ValidationResult, error)

ValidateAndFilter 验证并过滤输出内容 返回过滤后的内容和验证结果

type OutputValidatorConfig

type OutputValidatorConfig struct {
	// Validators 输出验证器列表
	Validators []Validator
	// Filters 输出过滤器列表
	Filters []Filter
	// SafeReplacement 有害内容的安全替代响应
	SafeReplacement string
	// EnableAuditLog 是否启用审计日志
	EnableAuditLog bool
	// AuditLogger 审计日志记录器
	AuditLogger AuditLogger
	// Priority 验证器优先级
	Priority int
}

OutputValidatorConfig 输出验证器配置

func DefaultOutputValidatorConfig

func DefaultOutputValidatorConfig() *OutputValidatorConfig

DefaultOutputValidatorConfig 返回默认配置

type PIIAction

type PIIAction string

PIIAction PII 处理动作

const (
	// PIIActionMask 脱敏处理
	PIIActionMask PIIAction = "mask"
	// PIIActionReject 拒绝处理
	PIIActionReject PIIAction = "reject"
	// PIIActionWarn 警告处理
	PIIActionWarn PIIAction = "warn"
)

type PIIDetector

type PIIDetector struct {
	// contains filtered or unexported fields
}

PIIDetector PII 检测器 实现 Validator 接口,用于检测和处理个人身份信息

func NewPIIDetector

func NewPIIDetector(config *PIIDetectorConfig) *PIIDetector

NewPIIDetector 创建 PII 检测器

func (*PIIDetector) Detect

func (d *PIIDetector) Detect(content string) []PIIMatch

Detect 检测内容中的所有 PII

func (*PIIDetector) Filter

func (d *PIIDetector) Filter(ctx context.Context, content string) (string, error)

Filter 实现 Filter 接口,对内容进行脱敏过滤

func (*PIIDetector) GetAction

func (d *PIIDetector) GetAction() PIIAction

GetAction 返回当前配置的处理动作

func (*PIIDetector) Mask

func (d *PIIDetector) Mask(content string) string

Mask 对内容中的 PII 进行脱敏处理

func (*PIIDetector) Name

func (d *PIIDetector) Name() string

Name 返回验证器名称

func (*PIIDetector) Priority

func (d *PIIDetector) Priority() int

Priority 返回优先级

func (*PIIDetector) SetAction

func (d *PIIDetector) SetAction(action PIIAction)

SetAction 设置处理动作

func (*PIIDetector) Validate

func (d *PIIDetector) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行 PII 检测验证 实现 Validator 接口

type PIIDetectorConfig

type PIIDetectorConfig struct {
	// Action 处理动作
	Action PIIAction
	// EnabledTypes 启用的 PII 类型,为空则启用所有类型
	EnabledTypes []PIIType
	// CustomPatterns 自定义正则模式
	CustomPatterns map[PIIType]*regexp.Regexp
	// Priority 验证器优先级
	Priority int
}

PIIDetectorConfig PII 检测器配置

func DefaultPIIDetectorConfig

func DefaultPIIDetectorConfig() *PIIDetectorConfig

DefaultPIIDetectorConfig 返回默认配置

type PIIMatch

type PIIMatch struct {
	Type     PIIType `json:"type"`
	Value    string  `json:"value"`
	Masked   string  `json:"masked"`
	Position int     `json:"position"`
	Length   int     `json:"length"`
}

PIIMatch PII 匹配结果

type PIIType

type PIIType string

PIIType PII 类型

const (
	// PIITypePhone 手机号
	PIITypePhone PIIType = "phone"
	// PIITypeEmail 邮箱
	PIITypeEmail PIIType = "email"
	// PIITypeIDCard 身份证号
	PIITypeIDCard PIIType = "id_card"
	// PIITypeBankCard 银行卡号
	PIITypeBankCard PIIType = "bank_card"
	// PIITypeAddress 地址
	PIITypeAddress PIIType = "address"
)

type ShadowAIConfig

type ShadowAIConfig struct {
	EnableNetworkMonitor bool          `json:"enable_network_monitor"`
	EnableContentScan    bool          `json:"enable_content_scan"`
	ScanInterval         time.Duration `json:"scan_interval"`
	AlertThreshold       int           `json:"alert_threshold"`
	WhitelistedDomains   []string      `json:"whitelisted_domains"`
	WhitelistedApps      []string      `json:"whitelisted_apps"`
}

ShadowAIConfig配置了阴影AI检测.

func DefaultShadowAIConfig

func DefaultShadowAIConfig() ShadowAIConfig

默认 ShadowAIConfig 返回默认配置 。

type ShadowAIDetector

type ShadowAIDetector struct {
	// contains filtered or unexported fields
}

ShadowAI探测器检测出未经授权的AI用法.

func NewShadowAIDetector

func NewShadowAIDetector(config ShadowAIConfig, logger *zap.Logger) *ShadowAIDetector

NewShadowAI探测器制造出一个新的阴影AI探测器.

func (*ShadowAIDetector) AddPattern

func (d *ShadowAIDetector) AddPattern(name, patternType, patternStr, severity, description string) error

添加Pattern 添加自定义检测模式 。

func (*ShadowAIDetector) CheckDomain

func (d *ShadowAIDetector) CheckDomain(domain string) *Detection

检查域名检查是否为AI服务.

func (*ShadowAIDetector) GetDetections

func (d *ShadowAIDetector) GetDetections(limit int) []Detection

Get Detections 返回最近的检测。

func (*ShadowAIDetector) GetStats

func (d *ShadowAIDetector) GetStats() ShadowAIStats

GetStats 返回检测统计.

func (*ShadowAIDetector) ScanContent

func (d *ShadowAIDetector) ScanContent(ctx context.Context, content, source, userID string) []Detection

ScanContent为阴影AI指标扫描内容.

type ShadowAIStats

type ShadowAIStats struct {
	TotalDetections int            `json:"total_detections"`
	BySeverity      map[string]int `json:"by_severity"`
	ByPattern       map[string]int `json:"by_pattern"`
}

ShadowAIStats包含检测统计数据.

type TripwireError

type TripwireError struct {
	ValidatorName string
	Result        *ValidationResult
}

TripwireError 表示 Tripwire 被触发的错误。 当验证器返回 Tripwire=true 时,整个 Agent 执行链应立即中断。

func (*TripwireError) Error

func (e *TripwireError) Error() string

Error 实现 error 接口

type ValidationError

type ValidationError struct {
	Code     string `json:"code"`
	Message  string `json:"message"`
	Severity string `json:"severity"` // critical, high, medium, low
	Field    string `json:"field,omitempty"`
}

ValidationError 验证错误

type ValidationResult

type ValidationResult struct {
	Valid    bool              `json:"valid"`
	Tripwire bool              `json:"tripwire,omitempty"` // 触发即中断整个 Agent 执行链
	Errors   []ValidationError `json:"errors,omitempty"`
	Warnings []string          `json:"warnings,omitempty"`
	Metadata map[string]any    `json:"metadata,omitempty"`
}

ValidationResult 验证结果

func NewValidationResult

func NewValidationResult() *ValidationResult

NewValidationResult 创建一个有效的验证结果

func (*ValidationResult) AddError

func (r *ValidationResult) AddError(err ValidationError)

AddError 添加验证错误并将结果标记为无效

func (*ValidationResult) AddWarning

func (r *ValidationResult) AddWarning(warning string)

AddWarning 添加警告信息

func (*ValidationResult) Merge

func (r *ValidationResult) Merge(other *ValidationResult)

Merge 合并另一个验证结果

type Validator

type Validator interface {
	// Validate 执行验证,返回验证结果
	Validate(ctx context.Context, content string) (*ValidationResult, error)
	// Name 返回验证器名称
	Name() string
	// Priority 返回优先级(数字越小优先级越高)
	Priority() int
}

Validator 验证器接口 用于验证输入或输出内容的安全性和合规性

type ValidatorChain

type ValidatorChain struct {
	// contains filtered or unexported fields
}

ValidatorChain 验证器链 按优先级顺序执行多个验证器并聚合结果 Requirements 1.5: 按优先级顺序执行所有规则 Requirements 1.6: 返回包含失败原因的详细错误信息

func NewValidatorChain

func NewValidatorChain(config *ValidatorChainConfig) *ValidatorChain

NewValidatorChain 创建验证器链

func (*ValidatorChain) Add

func (c *ValidatorChain) Add(validators ...Validator)

Add 添加验证器到链中

func (*ValidatorChain) Clear

func (c *ValidatorChain) Clear()

Clear 清空所有验证器

func (*ValidatorChain) GetMode

func (c *ValidatorChain) GetMode() ChainMode

GetMode 获取当前执行模式

func (*ValidatorChain) Len

func (c *ValidatorChain) Len() int

Len 返回验证器数量

func (*ValidatorChain) Name

func (c *ValidatorChain) Name() string

Name 返回验证器链名称

func (*ValidatorChain) Priority

func (c *ValidatorChain) Priority() int

Priority 返回验证器链优先级(作为整体的优先级)

func (*ValidatorChain) Remove

func (c *ValidatorChain) Remove(name string) bool

Remove 从链中移除指定名称的验证器

func (*ValidatorChain) SetMode

func (c *ValidatorChain) SetMode(mode ChainMode)

SetMode 设置执行模式

func (*ValidatorChain) Validate

func (c *ValidatorChain) Validate(ctx context.Context, content string) (*ValidationResult, error)

Validate 执行验证器链 按优先级顺序执行所有验证器,聚合验证结果 实现 Validator 接口

func (*ValidatorChain) ValidateWithCallback

func (c *ValidatorChain) ValidateWithCallback(
	ctx context.Context,
	content string,
	callback func(validator Validator, result *ValidationResult) bool,
) (*ValidationResult, error)

ValidateWithCallback 执行验证器链,支持回调 callback 在每个验证器执行后被调用,返回 false 可中断执行

func (*ValidatorChain) Validators

func (c *ValidatorChain) Validators() []Validator

Validators 返回按优先级排序的验证器列表

type ValidatorChainConfig

type ValidatorChainConfig struct {
	// Mode 执行模式
	Mode ChainMode
}

ValidatorChainConfig 验证器链配置

func DefaultValidatorChainConfig

func DefaultValidatorChainConfig() *ValidatorChainConfig

DefaultValidatorChainConfig 返回默认配置

type ValidatorRegistry

type ValidatorRegistry struct {
	// contains filtered or unexported fields
}

ValidatorRegistry 验证器注册表 支持自定义验证规则的注册和扩展 (Requirements 1.7)

func NewValidatorRegistry

func NewValidatorRegistry() *ValidatorRegistry

NewValidatorRegistry 创建验证器注册表

func (*ValidatorRegistry) Get

func (r *ValidatorRegistry) Get(name string) (Validator, bool)

Get 获取验证器

func (*ValidatorRegistry) List

func (r *ValidatorRegistry) List() []Validator

List 列出所有验证器

func (*ValidatorRegistry) Register

func (r *ValidatorRegistry) Register(v Validator)

Register 注册验证器

func (*ValidatorRegistry) Unregister

func (r *ValidatorRegistry) Unregister(name string)

Unregister 注销验证器

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL