adk_guardrail/traits.rs
1use adk_core::{CitationMetadata, Content, GroundingSource};
2use async_trait::async_trait;
3use serde::{Deserialize, Serialize};
4
5/// Severity level for guardrail failures
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
7pub enum Severity {
8 Low,
9 Medium,
10 High,
11 Critical,
12}
13
14/// Result of guardrail validation
15#[derive(Debug, Clone)]
16pub enum GuardrailResult {
17 /// Content passed validation
18 Pass,
19 /// Content failed validation
20 Fail { reason: String, severity: Severity },
21 /// Content was transformed (e.g., PII redacted)
22 Transform { new_content: Content, reason: String },
23}
24
25impl GuardrailResult {
26 pub fn pass() -> Self {
27 Self::Pass
28 }
29
30 pub fn fail(reason: impl Into<String>, severity: Severity) -> Self {
31 Self::Fail { reason: reason.into(), severity }
32 }
33
34 pub fn transform(new_content: Content, reason: impl Into<String>) -> Self {
35 Self::Transform { new_content, reason: reason.into() }
36 }
37
38 pub fn is_pass(&self) -> bool {
39 matches!(self, Self::Pass)
40 }
41
42 pub fn is_fail(&self) -> bool {
43 matches!(self, Self::Fail { .. })
44 }
45}
46
47/// What an agent knows about its final answer's grounding, for
48/// [`Guardrail::validate_output`].
49///
50/// # Example
51///
52/// ```rust
53/// use adk_core::GroundingSource;
54/// use adk_guardrail::OutputEvidence;
55///
56/// let sources = [GroundingSource::new("rag_search", "https://example.com/refunds")];
57/// let evidence = OutputEvidence::new(&sources, None);
58/// assert_eq!(evidence.sources.len(), 1);
59/// ```
60#[derive(Debug, Clone, Copy)]
61#[non_exhaustive]
62pub struct OutputEvidence<'a> {
63 /// The sources the agent's run recorded as retrieved, in the order recorded.
64 pub sources: &'a [GroundingSource],
65 /// The answer's citations: the provider's, and the answer's markdown links to a source in
66 /// `sources`.
67 pub citations: Option<&'a CitationMetadata>,
68}
69
70impl<'a> OutputEvidence<'a> {
71 /// Evidence of `sources` retrieved and `citations` made.
72 pub fn new(sources: &'a [GroundingSource], citations: Option<&'a CitationMetadata>) -> Self {
73 Self { sources, citations }
74 }
75}
76
77/// Core guardrail trait for input/output validation
78#[async_trait]
79pub trait Guardrail: Send + Sync {
80 /// Unique name for this guardrail
81 fn name(&self) -> &str;
82
83 /// Validate content and return result
84 async fn validate(&self, content: &Content) -> GuardrailResult;
85
86 /// Validates the text a model writes in a turn that also calls tools, or in a turn the
87 /// provider paused (a preamble).
88 ///
89 /// An agent's output guardrails screen this text before it reaches the client or the
90 /// session, as they screen the final response: a failure blocks the turn and a transform
91 /// rewrites the text. `content` holds only the turn's text parts. Defaults to
92 /// [`validate`](Self::validate); override it when a check describes the complete answer
93 /// rather than any text the user can see, as [`SchemaValidator`](crate::SchemaValidator)
94 /// does for the answer's JSON shape.
95 ///
96 /// # Example
97 ///
98 /// ```rust
99 /// use adk_core::{Content, Part};
100 /// use adk_guardrail::{Guardrail, GuardrailResult, Severity};
101 /// use async_trait::async_trait;
102 ///
103 /// /// Requires the final answer to cite a source; a preamble needs none.
104 /// struct CitesSource;
105 ///
106 /// #[async_trait]
107 /// impl Guardrail for CitesSource {
108 /// fn name(&self) -> &str {
109 /// "cites_source"
110 /// }
111 ///
112 /// async fn validate(&self, content: &Content) -> GuardrailResult {
113 /// let text: String = content.parts.iter().filter_map(Part::text).collect();
114 /// if text.contains("Source:") {
115 /// GuardrailResult::Pass
116 /// } else {
117 /// GuardrailResult::fail("the answer cites no source", Severity::Medium)
118 /// }
119 /// }
120 ///
121 /// async fn validate_preamble(&self, _content: &Content) -> GuardrailResult {
122 /// GuardrailResult::Pass
123 /// }
124 /// }
125 /// ```
126 async fn validate_preamble(&self, content: &Content) -> GuardrailResult {
127 self.validate(content).await
128 }
129
130 /// Validates an agent's final answer with what the agent knows about its grounding: the
131 /// sources its run retrieved and the answer's citations.
132 ///
133 /// An agent's output guardrails screen its final answer through this method. Defaults to
134 /// [`validate`](Self::validate); override it when a check needs the evidence, as
135 /// [`CitationRequired`](crate::CitationRequired) does.
136 ///
137 /// # Example
138 ///
139 /// ```rust
140 /// use adk_core::Content;
141 /// use adk_guardrail::{Guardrail, GuardrailResult, OutputEvidence, Severity};
142 /// use async_trait::async_trait;
143 ///
144 /// /// Fails an answer given while nothing was retrieved.
145 /// struct Grounded;
146 ///
147 /// #[async_trait]
148 /// impl Guardrail for Grounded {
149 /// fn name(&self) -> &str {
150 /// "grounded"
151 /// }
152 ///
153 /// async fn validate(&self, _content: &Content) -> GuardrailResult {
154 /// GuardrailResult::Pass
155 /// }
156 ///
157 /// async fn validate_output(
158 /// &self,
159 /// _content: &Content,
160 /// evidence: &OutputEvidence<'_>,
161 /// ) -> GuardrailResult {
162 /// if evidence.sources.is_empty() {
163 /// GuardrailResult::fail("nothing was retrieved", Severity::High)
164 /// } else {
165 /// GuardrailResult::Pass
166 /// }
167 /// }
168 /// }
169 /// ```
170 async fn validate_output(
171 &self,
172 content: &Content,
173 evidence: &OutputEvidence<'_>,
174 ) -> GuardrailResult {
175 let _ = evidence;
176 self.validate(content).await
177 }
178
179 /// Whether to run in parallel with other guardrails (default: true)
180 fn run_parallel(&self) -> bool {
181 true
182 }
183
184 /// Whether to fail fast on this guardrail's failure (default: true for High/Critical)
185 fn fail_fast(&self) -> bool {
186 true
187 }
188}