1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6use crate::Severity;
7
8pub const INPUT_BLOCKED_CODE: &str = "guardrail.input_blocked";
10
11pub const OUTPUT_BLOCKED_CODE: &str = "guardrail.output_blocked";
14
15pub const GUARDRAIL_WARNINGS_KEY: &str = "adk.guardrail.warnings";
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum GuardrailPhase {
24 Input,
26 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct GuardrailFailure {
42 pub guardrail: String,
44 pub reason: String,
46 pub severity: Severity,
48}
49
50#[derive(Debug, thiserror::Error)]
52pub enum GuardrailError {
53 #[error("Guardrail '{name}' failed: {reason}")]
55 ValidationFailed { name: String, reason: String, severity: Severity },
56
57 #[error("Multiple guardrails failed: {0:?}")]
59 MultipleFailures(Vec<GuardrailError>),
60
61 #[error("{phase} guardrails blocked content: {}", describe(.failures))]
67 Blocked {
68 phase: GuardrailPhase,
70 failures: Vec<GuardrailFailure>,
72 },
73
74 #[error("Schema validation error: {0}")]
76 Schema(String),
77
78 #[error("Regex error: {0}")]
80 Regex(#[from] regex::Error),
81
82 #[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
97pub 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 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}