-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathguardrails.go
More file actions
414 lines (348 loc) · 11.6 KB
/
Copy pathguardrails.go
File metadata and controls
414 lines (348 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
package sdk
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// GuardrailManager manages safety guardrails for AI operations.
type GuardrailManager struct {
logger logger.Logger
metrics metrics.Metrics
// Enabled guardrails
enablePII bool
enableToxicity bool
enablePromptInjection bool
enableContentFilter bool
// Configuration
piiPatterns []*regexp.Regexp
toxicWords map[string]bool
injectionPatterns []*regexp.Regexp
blockedContentPattern []*regexp.Regexp
maxInputLength int
maxOutputLength int
// Custom validators
customValidators []func(context.Context, string) error
}
// GuardrailOptions configures the guardrail manager.
type GuardrailOptions struct {
EnablePII bool
EnableToxicity bool
EnablePromptInjection bool
EnableContentFilter bool
MaxInputLength int
MaxOutputLength int
CustomPIIPatterns []string
CustomToxicWords []string
CustomBlockedPatterns []string
}
// GuardrailViolation represents a detected safety violation.
type GuardrailViolation struct {
Type string
Description string
Severity string // "low", "medium", "high", "critical"
Location string // "input" or "output"
Offending string // The offending text (may be redacted)
}
// NewGuardrailManager creates a new guardrail manager.
func NewGuardrailManager(
logger logger.Logger,
metrics metrics.Metrics,
opts *GuardrailOptions,
) *GuardrailManager {
gm := &GuardrailManager{
logger: logger,
metrics: metrics,
enablePII: true,
enableToxicity: true,
enablePromptInjection: true,
enableContentFilter: true,
maxInputLength: 100000, // 100k chars
maxOutputLength: 50000, // 50k chars
toxicWords: make(map[string]bool),
piiPatterns: make([]*regexp.Regexp, 0),
injectionPatterns: make([]*regexp.Regexp, 0),
blockedContentPattern: make([]*regexp.Regexp, 0),
customValidators: make([]func(context.Context, string) error, 0),
}
if opts != nil {
gm.enablePII = opts.EnablePII
gm.enableToxicity = opts.EnableToxicity
gm.enablePromptInjection = opts.EnablePromptInjection
gm.enableContentFilter = opts.EnableContentFilter
if opts.MaxInputLength > 0 {
gm.maxInputLength = opts.MaxInputLength
}
if opts.MaxOutputLength > 0 {
gm.maxOutputLength = opts.MaxOutputLength
}
// Add custom PII patterns
for _, pattern := range opts.CustomPIIPatterns {
if re, err := regexp.Compile(pattern); err == nil {
gm.piiPatterns = append(gm.piiPatterns, re)
}
}
// Add custom toxic words
for _, word := range opts.CustomToxicWords {
gm.toxicWords[strings.ToLower(word)] = true
}
// Add custom blocked patterns
for _, pattern := range opts.CustomBlockedPatterns {
if re, err := regexp.Compile(pattern); err == nil {
gm.blockedContentPattern = append(gm.blockedContentPattern, re)
}
}
}
// Initialize default patterns
gm.initializeDefaultPatterns()
return gm
}
// initializeDefaultPatterns sets up default detection patterns.
func (gm *GuardrailManager) initializeDefaultPatterns() {
// PII Patterns
piiPatterns := []string{
// Email addresses
`\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b`,
// Phone numbers (US format)
`\b\d{3}[-.]?\d{3}[-.]?\d{4}\b`,
// SSN
`\b\d{3}-\d{2}-\d{4}\b`,
// Credit card numbers (simple pattern)
`\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b`,
// IP addresses
`\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b`,
}
for _, pattern := range piiPatterns {
if re, err := regexp.Compile(pattern); err == nil {
gm.piiPatterns = append(gm.piiPatterns, re)
}
}
// Prompt injection patterns
injectionPatterns := []string{
`(?i)ignore\s+(previous|above|all)\s+(instructions?|prompts?)`,
`(?i)disregard\s+(previous|above|all)`,
`(?i)forget\s+(everything|all|previous)`,
`(?i)new\s+instructions?:`,
`(?i)system\s*:\s*`,
`(?i)\[INST\]|\[/INST\]`, // Common injection markers
`(?i)<\|im_start\|>`, // ChatML markers
}
for _, pattern := range injectionPatterns {
if re, err := regexp.Compile(pattern); err == nil {
gm.injectionPatterns = append(gm.injectionPatterns, re)
}
}
// Default toxic words (simplified list - in production, use a comprehensive database)
toxicWords := []string{
"offensive1", "offensive2", "hate", // Placeholder - add actual words
}
for _, word := range toxicWords {
gm.toxicWords[strings.ToLower(word)] = true
}
}
// ValidateInput validates input text against all enabled guardrails.
func (gm *GuardrailManager) ValidateInput(ctx context.Context, input string) ([]GuardrailViolation, error) {
violations := make([]GuardrailViolation, 0)
if gm.logger != nil {
gm.logger.Debug("Validating input",
F("length", len(input)),
F("pii_enabled", gm.enablePII),
F("toxicity_enabled", gm.enableToxicity),
F("injection_enabled", gm.enablePromptInjection),
)
}
// Check input length
if len(input) > gm.maxInputLength {
violations = append(violations, GuardrailViolation{
Type: "input_length",
Description: fmt.Sprintf("Input exceeds maximum length of %d characters", gm.maxInputLength),
Severity: "high",
Location: "input",
})
}
// Check for PII
if gm.enablePII {
piiViolations := gm.detectPII(input, "input")
violations = append(violations, piiViolations...)
}
// Check for toxicity
if gm.enableToxicity {
toxicViolations := gm.detectToxicity(input, "input")
violations = append(violations, toxicViolations...)
}
// Check for prompt injection
if gm.enablePromptInjection {
injectionViolations := gm.detectPromptInjection(input, "input")
violations = append(violations, injectionViolations...)
}
// Check for blocked content
if gm.enableContentFilter {
contentViolations := gm.detectBlockedContent(input, "input")
violations = append(violations, contentViolations...)
}
// Run custom validators
for i, validator := range gm.customValidators {
if err := validator(ctx, input); err != nil {
violations = append(violations, GuardrailViolation{
Type: fmt.Sprintf("custom_%d", i),
Description: err.Error(),
Severity: "medium",
Location: "input",
})
}
}
// Record metrics
if gm.metrics != nil {
gm.metrics.Counter("ai-sdk.guardrails.input_checks", metrics.WithLabel("type", "input")).Inc()
if len(violations) > 0 {
gm.metrics.Counter("ai-sdk.guardrails.input_violations", metrics.WithLabel("count", strconv.Itoa(len(violations)))).Inc()
}
}
return violations, nil
}
// ValidateOutput validates output text against all enabled guardrails.
func (gm *GuardrailManager) ValidateOutput(ctx context.Context, output string) ([]GuardrailViolation, error) {
violations := make([]GuardrailViolation, 0)
// Check output length
if len(output) > gm.maxOutputLength {
violations = append(violations, GuardrailViolation{
Type: "output_length",
Description: fmt.Sprintf("Output exceeds maximum length of %d characters", gm.maxOutputLength),
Severity: "medium",
Location: "output",
})
}
// Check for PII in output
if gm.enablePII {
piiViolations := gm.detectPII(output, "output")
violations = append(violations, piiViolations...)
}
// Check for toxicity in output
if gm.enableToxicity {
toxicViolations := gm.detectToxicity(output, "output")
violations = append(violations, toxicViolations...)
}
// Check for blocked content in output
if gm.enableContentFilter {
contentViolations := gm.detectBlockedContent(output, "output")
violations = append(violations, contentViolations...)
}
// Record metrics
if gm.metrics != nil {
gm.metrics.Counter("ai-sdk.guardrails.output_checks", metrics.WithLabel("type", "output")).Inc()
if len(violations) > 0 {
gm.metrics.Counter("ai-sdk.guardrails.output_violations", metrics.WithLabel("count", strconv.Itoa(len(violations)))).Inc()
}
}
return violations, nil
}
// detectPII detects personally identifiable information.
func (gm *GuardrailManager) detectPII(text, location string) []GuardrailViolation {
violations := make([]GuardrailViolation, 0)
for _, pattern := range gm.piiPatterns {
if matches := pattern.FindAllString(text, -1); len(matches) > 0 {
// Redact the actual PII in the violation
redacted := "[REDACTED]"
violations = append(violations, GuardrailViolation{
Type: "pii",
Description: fmt.Sprintf("Detected potential PII (%d instances)", len(matches)),
Severity: "critical",
Location: location,
Offending: redacted,
})
}
}
return violations
}
// detectToxicity detects toxic or harmful content.
func (gm *GuardrailManager) detectToxicity(text, location string) []GuardrailViolation {
violations := make([]GuardrailViolation, 0)
words := strings.Fields(strings.ToLower(text))
toxicFound := make([]string, 0)
for _, word := range words {
// Remove punctuation
cleaned := strings.Trim(word, ".,!?;:")
if gm.toxicWords[cleaned] {
toxicFound = append(toxicFound, "[REDACTED]")
}
}
if len(toxicFound) > 0 {
violations = append(violations, GuardrailViolation{
Type: "toxicity",
Description: fmt.Sprintf("Detected toxic content (%d instances)", len(toxicFound)),
Severity: "high",
Location: location,
Offending: "[REDACTED]",
})
}
return violations
}
// detectPromptInjection detects prompt injection attempts.
func (gm *GuardrailManager) detectPromptInjection(text, location string) []GuardrailViolation {
violations := make([]GuardrailViolation, 0)
for _, pattern := range gm.injectionPatterns {
if match := pattern.FindString(text); match != "" {
violations = append(violations, GuardrailViolation{
Type: "prompt_injection",
Description: "Detected potential prompt injection attempt",
Severity: "critical",
Location: location,
Offending: match,
})
}
}
return violations
}
// detectBlockedContent detects blocked content patterns.
func (gm *GuardrailManager) detectBlockedContent(text, location string) []GuardrailViolation {
violations := make([]GuardrailViolation, 0)
for _, pattern := range gm.blockedContentPattern {
if match := pattern.FindString(text); match != "" {
violations = append(violations, GuardrailViolation{
Type: "blocked_content",
Description: "Content matches blocked pattern",
Severity: "high",
Location: location,
Offending: "[REDACTED]",
})
}
}
return violations
}
// RedactPII removes PII from text.
func (gm *GuardrailManager) RedactPII(text string) string {
result := text
for _, pattern := range gm.piiPatterns {
result = pattern.ReplaceAllString(result, "[REDACTED]")
}
return result
}
// AddCustomValidator adds a custom validation function.
func (gm *GuardrailManager) AddCustomValidator(validator func(context.Context, string) error) {
gm.customValidators = append(gm.customValidators, validator)
}
// ShouldBlock returns true if violations warrant blocking the operation.
func ShouldBlock(violations []GuardrailViolation) bool {
for _, v := range violations {
if v.Severity == "critical" || v.Severity == "high" {
return true
}
}
return false
}
// FormatViolations formats violations into a human-readable string.
func FormatViolations(violations []GuardrailViolation) string {
if len(violations) == 0 {
return "No violations detected"
}
var builder strings.Builder
builder.WriteString(fmt.Sprintf("Found %d violation(s):\n", len(violations)))
for i, v := range violations {
builder.WriteString(fmt.Sprintf("%d. [%s] %s - %s (Severity: %s, Location: %s)\n",
i+1, v.Type, v.Description, v.Offending, v.Severity, v.Location))
}
return builder.String()
}