autoagents-guardrails 0.3.7

Agent Framework for Building Autonomous Agents
Documentation
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use std::sync::Arc;

use autoagents_llm::{LLMProvider, error::LLMError};

use crate::{
    guard::{GuardContext, GuardDecision, GuardedInput, GuardedOutput, InputGuard, OutputGuard},
    layer::GuardrailsLayer,
    policy::{EnforcementPolicy, GuardPhase, guard_failure_to_llm_error, violation_to_llm_error},
    provider::GuardedProvider,
    sanitizers::{
        SharedInputSanitizer, SharedOutputSanitizer, default_input_sanitizer,
        default_output_sanitizer,
    },
};

struct InputGuardEntry {
    guard: Arc<dyn InputGuard>,
    policy_override: Option<EnforcementPolicy>,
}

struct OutputGuardEntry {
    guard: Arc<dyn OutputGuard>,
    policy_override: Option<EnforcementPolicy>,
}

/// User-facing guardrails handle.
#[derive(Clone)]
pub struct Guardrails {
    pub(crate) engine: Arc<GuardrailsEngine>,
}

impl Guardrails {
    /// Create guardrails directly from input/output guard lists with default
    /// [`EnforcementPolicy::Block`] behavior.
    pub fn new(
        input_guards: Vec<Arc<dyn InputGuard>>,
        output_guards: Vec<Arc<dyn OutputGuard>>,
    ) -> Self {
        let input_guards = input_guards
            .into_iter()
            .map(|guard| InputGuardEntry {
                guard,
                policy_override: None,
            })
            .collect();
        let output_guards = output_guards
            .into_iter()
            .map(|guard| OutputGuardEntry {
                guard,
                policy_override: None,
            })
            .collect();

        Self {
            engine: Arc::new(GuardrailsEngine {
                input_guards,
                output_guards,
                policy: EnforcementPolicy::Block,
                input_sanitizer: default_input_sanitizer(),
                output_sanitizer: default_output_sanitizer(),
            }),
        }
    }

    /// Start building a guardrails configuration.
    pub fn builder() -> GuardrailsBuilder {
        GuardrailsBuilder::default()
    }

    /// Create an `LLMLayer` for use with `PipelineBuilder`.
    pub fn layer(&self) -> GuardrailsLayer {
        GuardrailsLayer::new(self.engine.clone())
    }

    /// Wrap a provider directly without a pipeline.
    pub fn wrap(&self, inner: Arc<dyn LLMProvider>) -> Arc<dyn LLMProvider> {
        Arc::new(GuardedProvider::new(inner, self.engine.clone()))
    }
}

/// Builder for [`Guardrails`].
pub struct GuardrailsBuilder {
    input_guards: Vec<InputGuardEntry>,
    output_guards: Vec<OutputGuardEntry>,
    policy: EnforcementPolicy,
    input_sanitizer: SharedInputSanitizer,
    output_sanitizer: SharedOutputSanitizer,
}

impl Default for GuardrailsBuilder {
    fn default() -> Self {
        Self {
            input_guards: Vec::new(),
            output_guards: Vec::new(),
            policy: EnforcementPolicy::default(),
            input_sanitizer: default_input_sanitizer(),
            output_sanitizer: default_output_sanitizer(),
        }
    }
}

impl GuardrailsBuilder {
    pub fn input_guard<G: InputGuard>(mut self, guard: G) -> Self {
        self.input_guards.push(InputGuardEntry {
            guard: Arc::new(guard),
            policy_override: None,
        });
        self
    }

    pub fn output_guard<G: OutputGuard>(mut self, guard: G) -> Self {
        self.output_guards.push(OutputGuardEntry {
            guard: Arc::new(guard),
            policy_override: None,
        });
        self
    }

    pub fn input_guard_arc(mut self, guard: Arc<dyn InputGuard>) -> Self {
        self.input_guards.push(InputGuardEntry {
            guard,
            policy_override: None,
        });
        self
    }

    pub fn output_guard_arc(mut self, guard: Arc<dyn OutputGuard>) -> Self {
        self.output_guards.push(OutputGuardEntry {
            guard,
            policy_override: None,
        });
        self
    }

    /// Add an input guard with a per-guard policy override.
    pub fn input_guard_with_policy<G: InputGuard>(
        mut self,
        guard: G,
        policy: EnforcementPolicy,
    ) -> Self {
        self.input_guards.push(InputGuardEntry {
            guard: Arc::new(guard),
            policy_override: Some(policy),
        });
        self
    }

    /// Add an output guard with a per-guard policy override.
    pub fn output_guard_with_policy<G: OutputGuard>(
        mut self,
        guard: G,
        policy: EnforcementPolicy,
    ) -> Self {
        self.output_guards.push(OutputGuardEntry {
            guard: Arc::new(guard),
            policy_override: Some(policy),
        });
        self
    }

    /// Add an input guard Arc with a per-guard policy override.
    pub fn input_guard_arc_with_policy(
        mut self,
        guard: Arc<dyn InputGuard>,
        policy: EnforcementPolicy,
    ) -> Self {
        self.input_guards.push(InputGuardEntry {
            guard,
            policy_override: Some(policy),
        });
        self
    }

    /// Add an output guard Arc with a per-guard policy override.
    pub fn output_guard_arc_with_policy(
        mut self,
        guard: Arc<dyn OutputGuard>,
        policy: EnforcementPolicy,
    ) -> Self {
        self.output_guards.push(OutputGuardEntry {
            guard,
            policy_override: Some(policy),
        });
        self
    }

    pub fn enforcement_policy(mut self, policy: EnforcementPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Set custom input sanitizer logic used when policy is
    /// [`EnforcementPolicy::Sanitize`].
    pub fn input_sanitizer<F>(mut self, sanitizer: F) -> Self
    where
        F: Fn(&mut GuardedInput, &crate::guard::GuardViolation, &GuardContext)
            + Send
            + Sync
            + 'static,
    {
        self.input_sanitizer = Arc::new(sanitizer);
        self
    }

    /// Set custom output sanitizer logic used when policy is
    /// [`EnforcementPolicy::Sanitize`].
    pub fn output_sanitizer<F>(mut self, sanitizer: F) -> Self
    where
        F: Fn(&mut GuardedOutput, &crate::guard::GuardViolation, &GuardContext)
            + Send
            + Sync
            + 'static,
    {
        self.output_sanitizer = Arc::new(sanitizer);
        self
    }

    /// Set input sanitizer using a pre-built shared sanitizer handle.
    pub fn input_sanitizer_arc(mut self, sanitizer: SharedInputSanitizer) -> Self {
        self.input_sanitizer = sanitizer;
        self
    }

    /// Set output sanitizer using a pre-built shared sanitizer handle.
    pub fn output_sanitizer_arc(mut self, sanitizer: SharedOutputSanitizer) -> Self {
        self.output_sanitizer = sanitizer;
        self
    }

    pub fn build(self) -> Guardrails {
        Guardrails {
            engine: Arc::new(GuardrailsEngine {
                input_guards: self.input_guards,
                output_guards: self.output_guards,
                policy: self.policy,
                input_sanitizer: self.input_sanitizer,
                output_sanitizer: self.output_sanitizer,
            }),
        }
    }
}

pub(crate) struct GuardrailsEngine {
    input_guards: Vec<InputGuardEntry>,
    output_guards: Vec<OutputGuardEntry>,
    policy: EnforcementPolicy,
    input_sanitizer: SharedInputSanitizer,
    output_sanitizer: SharedOutputSanitizer,
}

impl GuardrailsEngine {
    pub(crate) fn has_input_guards(&self) -> bool {
        !self.input_guards.is_empty()
    }

    pub(crate) fn has_output_guards(&self) -> bool {
        !self.output_guards.is_empty()
    }

    pub(crate) async fn evaluate_input(
        &self,
        input: &mut GuardedInput,
        context: &GuardContext,
    ) -> Result<(), LLMError> {
        for entry in &self.input_guards {
            let decision = entry
                .guard
                .inspect(input, context)
                .await
                .map_err(|err| guard_failure_to_llm_error(entry.guard.name(), &err.message))?;
            self.apply_input_decision(
                decision,
                input,
                entry.guard.name(),
                entry.policy_override.unwrap_or(self.policy),
                context,
            )?;
        }
        Ok(())
    }

    pub(crate) async fn evaluate_output(
        &self,
        output: &mut GuardedOutput,
        context: &GuardContext,
    ) -> Result<(), LLMError> {
        for entry in &self.output_guards {
            let decision = entry
                .guard
                .inspect(output, context)
                .await
                .map_err(|err| guard_failure_to_llm_error(entry.guard.name(), &err.message))?;
            self.apply_output_decision(
                decision,
                output,
                entry.guard.name(),
                entry.policy_override.unwrap_or(self.policy),
                context,
            )?;
        }
        Ok(())
    }

    fn apply_input_decision(
        &self,
        decision: GuardDecision,
        input: &mut GuardedInput,
        guard_name: &str,
        policy: EnforcementPolicy,
        context: &GuardContext,
    ) -> Result<(), LLMError> {
        match decision {
            GuardDecision::Pass => Ok(()),
            GuardDecision::Modify { violation } => {
                if let Some(violation) = violation {
                    self.handle_input_violation(input, guard_name, policy, context, &violation)
                } else {
                    Ok(())
                }
            }
            GuardDecision::Reject(violation) => {
                self.handle_input_violation(input, guard_name, policy, context, &violation)
            }
        }
    }

    fn apply_output_decision(
        &self,
        decision: GuardDecision,
        output: &mut GuardedOutput,
        guard_name: &str,
        policy: EnforcementPolicy,
        context: &GuardContext,
    ) -> Result<(), LLMError> {
        match decision {
            GuardDecision::Pass => Ok(()),
            GuardDecision::Modify { violation } => {
                if let Some(violation) = violation {
                    self.handle_output_violation(output, guard_name, policy, context, &violation)
                } else {
                    Ok(())
                }
            }
            GuardDecision::Reject(violation) => {
                self.handle_output_violation(output, guard_name, policy, context, &violation)
            }
        }
    }

    fn handle_input_violation(
        &self,
        input: &mut GuardedInput,
        guard_name: &str,
        policy: EnforcementPolicy,
        context: &GuardContext,
        violation: &crate::guard::GuardViolation,
    ) -> Result<(), LLMError> {
        match policy {
            EnforcementPolicy::Block => Err(violation_to_llm_error(
                GuardPhase::Input,
                guard_name,
                violation,
            )),
            EnforcementPolicy::Sanitize => {
                (self.input_sanitizer)(input, violation, context);
                log::warn!(
                    "guardrail input violation sanitized: request_id={}, op={}, guard={}, rule={}, category={}, severity={}, message={}",
                    context.request_id,
                    context.operation,
                    guard_name,
                    violation.rule_id,
                    violation.category,
                    violation.severity,
                    violation.message,
                );
                Ok(())
            }
            EnforcementPolicy::Audit => {
                log::warn!(
                    "guardrail input violation audited: request_id={}, op={}, guard={}, rule={}, category={}, severity={}, message={}",
                    context.request_id,
                    context.operation,
                    guard_name,
                    violation.rule_id,
                    violation.category,
                    violation.severity,
                    violation.message,
                );
                Ok(())
            }
        }
    }

    fn handle_output_violation(
        &self,
        output: &mut GuardedOutput,
        guard_name: &str,
        policy: EnforcementPolicy,
        context: &GuardContext,
        violation: &crate::guard::GuardViolation,
    ) -> Result<(), LLMError> {
        match policy {
            EnforcementPolicy::Block => Err(violation_to_llm_error(
                GuardPhase::Output,
                guard_name,
                violation,
            )),
            EnforcementPolicy::Sanitize => {
                (self.output_sanitizer)(output, violation, context);
                log::warn!(
                    "guardrail output violation sanitized: request_id={}, op={}, guard={}, rule={}, category={}, severity={}, message={}",
                    context.request_id,
                    context.operation,
                    guard_name,
                    violation.rule_id,
                    violation.category,
                    violation.severity,
                    violation.message,
                );
                Ok(())
            }
            EnforcementPolicy::Audit => {
                log::warn!(
                    "guardrail output violation audited: request_id={}, op={}, guard={}, rule={}, category={}, severity={}, message={}",
                    context.request_id,
                    context.operation,
                    guard_name,
                    violation.rule_id,
                    violation.category,
                    violation.severity,
                    violation.message,
                );
                Ok(())
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use async_trait::async_trait;

    use crate::{
        guard::{
            DEFAULT_REDACTED_TEXT, GuardContext, GuardDecision, GuardError, GuardOperation,
            GuardViolation, GuardedInput, GuardedOutput, InputGuard, OutputGuard,
        },
        policy::{EnforcementPolicy, GuardCategory, GuardSeverity},
    };

    use super::Guardrails;

    struct RejectInputGuard;

    #[async_trait]
    impl InputGuard for RejectInputGuard {
        fn name(&self) -> &'static str {
            "reject-input"
        }

        async fn inspect(
            &self,
            _input: &mut GuardedInput,
            _context: &GuardContext,
        ) -> Result<GuardDecision, GuardError> {
            Ok(GuardDecision::Reject(GuardViolation::new(
                "reject",
                GuardCategory::Custom("test".to_string()),
                GuardSeverity::High,
                "blocked",
            )))
        }
    }

    struct RejectOutputGuard;

    #[async_trait]
    impl OutputGuard for RejectOutputGuard {
        fn name(&self) -> &'static str {
            "reject-output"
        }

        async fn inspect(
            &self,
            _output: &mut GuardedOutput,
            _context: &GuardContext,
        ) -> Result<GuardDecision, GuardError> {
            Ok(GuardDecision::Reject(GuardViolation::new(
                "reject",
                GuardCategory::Custom("test".to_string()),
                GuardSeverity::High,
                "blocked",
            )))
        }
    }

    #[tokio::test]
    async fn block_policy_fails_input_violations() {
        let guardrails = Guardrails::builder()
            .input_guard(RejectInputGuard)
            .enforcement_policy(EnforcementPolicy::Block)
            .build();

        let mut input = GuardedInput::WebSearch(crate::guard::WebSearchGuardInput {
            input: "hello".to_string(),
        });
        let context = GuardContext::new(GuardOperation::ChatWithWebSearch);

        let result = guardrails.engine.evaluate_input(&mut input, &context).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn sanitize_policy_rewrites_output() {
        let guardrails = Guardrails::builder()
            .output_guard(RejectOutputGuard)
            .enforcement_policy(EnforcementPolicy::Sanitize)
            .build();

        let mut output = GuardedOutput::Completion(crate::guard::CompletionGuardOutput {
            text: "unsafe".to_string(),
        });
        let context = GuardContext::new(GuardOperation::Complete);

        guardrails
            .engine
            .evaluate_output(&mut output, &context)
            .await
            .unwrap();

        match output {
            GuardedOutput::Completion(value) => {
                assert_eq!(value.text, DEFAULT_REDACTED_TEXT);
            }
            _ => panic!("unexpected output variant"),
        }
    }

    #[tokio::test]
    async fn audit_policy_allows_violations() {
        let guardrails = Guardrails::builder()
            .input_guard(RejectInputGuard)
            .enforcement_policy(EnforcementPolicy::Audit)
            .build();

        let mut input = GuardedInput::WebSearch(crate::guard::WebSearchGuardInput {
            input: "hello".to_string(),
        });
        let context = GuardContext::new(GuardOperation::ChatWithWebSearch);

        guardrails
            .engine
            .evaluate_input(&mut input, &context)
            .await
            .unwrap();

        match input {
            GuardedInput::WebSearch(value) => assert_eq!(value.input, "hello"),
            _ => panic!("unexpected input variant"),
        }
    }

    #[tokio::test]
    async fn custom_sanitizers_are_applied() {
        let guardrails = Guardrails::builder()
            .input_guard(RejectInputGuard)
            .output_guard(RejectOutputGuard)
            .enforcement_policy(EnforcementPolicy::Sanitize)
            .input_sanitizer(|input, _violation, _context| {
                if let GuardedInput::WebSearch(web) = input {
                    web.input = "custom-input".to_string();
                }
            })
            .output_sanitizer(|output, _violation, _context| {
                if let GuardedOutput::Completion(completion) = output {
                    completion.text = "custom-output".to_string();
                }
            })
            .build();

        let mut input = GuardedInput::WebSearch(crate::guard::WebSearchGuardInput {
            input: "hello".to_string(),
        });
        let input_context = GuardContext::new(GuardOperation::ChatWithWebSearch);
        guardrails
            .engine
            .evaluate_input(&mut input, &input_context)
            .await
            .unwrap();

        match input {
            GuardedInput::WebSearch(web) => assert_eq!(web.input, "custom-input"),
            _ => panic!("unexpected input variant"),
        }

        let mut output = GuardedOutput::Completion(crate::guard::CompletionGuardOutput {
            text: "unsafe".to_string(),
        });
        let output_context = GuardContext::new(GuardOperation::Complete);
        guardrails
            .engine
            .evaluate_output(&mut output, &output_context)
            .await
            .unwrap();

        match output {
            GuardedOutput::Completion(completion) => assert_eq!(completion.text, "custom-output"),
            _ => panic!("unexpected output variant"),
        }
    }

    #[tokio::test]
    async fn per_guard_policy_override_can_block_when_global_is_audit() {
        let guardrails = Guardrails::builder()
            .enforcement_policy(EnforcementPolicy::Audit)
            .output_guard_with_policy(RejectOutputGuard, EnforcementPolicy::Block)
            .build();

        let mut output = GuardedOutput::Completion(crate::guard::CompletionGuardOutput {
            text: "unsafe".to_string(),
        });
        let context = GuardContext::new(GuardOperation::Complete);

        let result = guardrails
            .engine
            .evaluate_output(&mut output, &context)
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn per_guard_policy_override_can_sanitize_when_global_is_block() {
        let guardrails = Guardrails::builder()
            .enforcement_policy(EnforcementPolicy::Block)
            .input_guard_with_policy(RejectInputGuard, EnforcementPolicy::Sanitize)
            .build();

        let mut input = GuardedInput::WebSearch(crate::guard::WebSearchGuardInput {
            input: "hello".to_string(),
        });
        let context = GuardContext::new(GuardOperation::ChatWithWebSearch);

        guardrails
            .engine
            .evaluate_input(&mut input, &context)
            .await
            .unwrap();

        match input {
            GuardedInput::WebSearch(web) => assert_eq!(web.input, DEFAULT_REDACTED_TEXT),
            _ => panic!("unexpected input variant"),
        }
    }
}