Skip to main content

adk_guardrail/
error.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6use crate::Severity;
7
8/// The [`AdkError::code`](adk_core::AdkError) of a user message input guardrails block.
9pub const INPUT_BLOCKED_CODE: &str = "guardrail.input_blocked";
10
11/// The [`AdkError::code`](adk_core::AdkError) of a model turn or tool result output
12/// guardrails block.
13pub const OUTPUT_BLOCKED_CODE: &str = "guardrail.output_blocked";
14
15/// The event metadata key under which an agent records the low-severity failures of the
16/// output guardrails that screened the event's content, as a JSON array of
17/// [`GuardrailFailure`]s.
18pub const GUARDRAIL_WARNINGS_KEY: &str = "adk.guardrail.warnings";
19
20/// What a guardrail set was screening.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum GuardrailPhase {
24    /// A user message, before the agent or the session sees it.
25    Input,
26    /// What the agent produces: model text and results that end the turn.
27    Output,
28}
29
30impl fmt::Display for GuardrailPhase {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str(match self {
33            Self::Input => "input",
34            Self::Output => "output",
35        })
36    }
37}
38
39/// One guardrail's failing verdict.
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct GuardrailFailure {
42    /// Name of the guardrail that failed the content.
43    pub guardrail: String,
44    /// Why it failed the content.
45    pub reason: String,
46    /// How serious the failure is. [`Severity::Low`] does not block.
47    pub severity: Severity,
48}
49
50/// Errors produced by guardrail validation.
51#[derive(Debug, thiserror::Error)]
52pub enum GuardrailError {
53    /// A single guardrail check failed.
54    #[error("Guardrail '{name}' failed: {reason}")]
55    ValidationFailed { name: String, reason: String, severity: Severity },
56
57    /// Multiple guardrails failed in a single execution.
58    #[error("Multiple guardrails failed: {0:?}")]
59    MultipleFailures(Vec<GuardrailError>),
60
61    /// A guardrail set blocked content: at least one failure is above [`Severity::Low`].
62    ///
63    /// Converts to an [`AdkError`](adk_core::AdkError) with category `InvalidInput`, code
64    /// [`INPUT_BLOCKED_CODE`] or [`OUTPUT_BLOCKED_CODE`], and details metadata naming the
65    /// blocking `guardrail`, its `severity`, the `phase`, and every `failures` entry.
66    #[error("{phase} guardrails blocked content: {}", describe(.failures))]
67    Blocked {
68        /// What was being screened.
69        phase: GuardrailPhase,
70        /// Every failure the set reported, in the order the guardrails ran.
71        failures: Vec<GuardrailFailure>,
72    },
73
74    /// JSON schema validation error.
75    #[error("Schema validation error: {0}")]
76    Schema(String),
77
78    /// Invalid regex pattern in a guardrail configuration.
79    #[error("Regex error: {0}")]
80    Regex(#[from] regex::Error),
81
82    /// Unexpected internal error.
83    #[error("Internal error: {0}")]
84    Internal(String),
85}
86
87fn describe(failures: &[GuardrailFailure]) -> String {
88    failures
89        .iter()
90        .map(|failure| {
91            format!("{} ({:?}): {}", failure.guardrail, failure.severity, failure.reason)
92        })
93        .collect::<Vec<_>>()
94        .join("; ")
95}
96
97/// Convenience alias for guardrail operations.
98pub type Result<T> = std::result::Result<T, GuardrailError>;
99
100impl From<GuardrailError> for adk_core::AdkError {
101    fn from(err: GuardrailError) -> Self {
102        use adk_core::{ErrorCategory, ErrorComponent, ErrorDetails};
103        let (category, code) = match &err {
104            GuardrailError::ValidationFailed { .. } => {
105                (ErrorCategory::InvalidInput, "guardrail.validation_failed")
106            }
107            GuardrailError::MultipleFailures(_) => {
108                (ErrorCategory::InvalidInput, "guardrail.multiple_failures")
109            }
110            GuardrailError::Blocked { phase: GuardrailPhase::Input, .. } => {
111                (ErrorCategory::InvalidInput, INPUT_BLOCKED_CODE)
112            }
113            GuardrailError::Blocked { phase: GuardrailPhase::Output, .. } => {
114                (ErrorCategory::InvalidInput, OUTPUT_BLOCKED_CODE)
115            }
116            GuardrailError::Schema(_) => (ErrorCategory::InvalidInput, "guardrail.schema"),
117            GuardrailError::Regex(_) => (ErrorCategory::InvalidInput, "guardrail.regex"),
118            GuardrailError::Internal(_) => (ErrorCategory::Internal, "guardrail.internal"),
119        };
120        let mut details = ErrorDetails::default();
121        match &err {
122            GuardrailError::ValidationFailed { name, severity, .. } => {
123                details.metadata.insert("guardrail".to_string(), json!(name));
124                details.metadata.insert("severity".to_string(), json!(severity));
125            }
126            GuardrailError::Blocked { phase, failures } => {
127                // The blocking guardrail is the first whose failure is above `Low`.
128                let blocking = failures
129                    .iter()
130                    .find(|failure| failure.severity != Severity::Low)
131                    .or_else(|| failures.first());
132                if let Some(blocking) = blocking {
133                    details.metadata.insert("guardrail".to_string(), json!(blocking.guardrail));
134                    details.metadata.insert("severity".to_string(), json!(blocking.severity));
135                }
136                details.metadata.insert("phase".to_string(), json!(phase));
137                details.metadata.insert(
138                    "failures".to_string(),
139                    serde_json::to_value(failures).unwrap_or(Value::Null),
140                );
141            }
142            GuardrailError::MultipleFailures(_)
143            | GuardrailError::Schema(_)
144            | GuardrailError::Regex(_)
145            | GuardrailError::Internal(_) => {}
146        }
147        adk_core::AdkError::new(ErrorComponent::Guardrail, category, code, err.to_string())
148            .with_details(details)
149            .with_source(err)
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use adk_core::{AdkError, ErrorCategory, ErrorComponent};
157
158    #[test]
159    fn a_block_converts_to_a_structured_invalid_input_error() {
160        let err: AdkError = GuardrailError::Blocked {
161            phase: GuardrailPhase::Output,
162            failures: vec![
163                GuardrailFailure {
164                    guardrail: "tone".into(),
165                    reason: "informal".into(),
166                    severity: Severity::Low,
167                },
168                GuardrailFailure {
169                    guardrail: "blocked_keywords".into(),
170                    reason: "matched 1 pattern".into(),
171                    severity: Severity::High,
172                },
173            ],
174        }
175        .into();
176        assert_eq!(err.component, ErrorComponent::Guardrail);
177        assert_eq!(err.category, ErrorCategory::InvalidInput);
178        assert_eq!(err.code, OUTPUT_BLOCKED_CODE);
179        assert_eq!(err.http_status_code(), 400);
180        let metadata = &err.details.metadata;
181        assert_eq!(metadata["guardrail"], json!("blocked_keywords"));
182        assert_eq!(metadata["severity"], json!("High"));
183        assert_eq!(metadata["phase"], json!("output"));
184        assert_eq!(metadata["failures"].as_array().map(Vec::len), Some(2));
185        assert_eq!(
186            err.message,
187            "output guardrails blocked content: tone (Low): informal; blocked_keywords (High): \
188             matched 1 pattern"
189        );
190    }
191
192    #[test]
193    fn an_input_block_has_its_own_code() {
194        let err: AdkError = GuardrailError::Blocked {
195            phase: GuardrailPhase::Input,
196            failures: vec![GuardrailFailure {
197                guardrail: "harmful_content".into(),
198                reason: "matched".into(),
199                severity: Severity::Critical,
200            }],
201        }
202        .into();
203        assert_eq!(err.code, INPUT_BLOCKED_CODE);
204        assert_eq!(err.details.metadata["severity"], json!("Critical"));
205    }
206}