1use crate::{Guardrail, GuardrailResult, Result, Severity};
2use adk_core::Content;
3use async_trait::async_trait;
4use regex::RegexSet;
5
6#[derive(Debug, Clone)]
8pub struct ContentFilterConfig {
9 pub blocked_keywords: Vec<String>,
11 pub required_topics: Vec<String>,
13 pub max_length: Option<usize>,
15 pub min_length: Option<usize>,
17 pub severity: Severity,
19}
20
21impl Default for ContentFilterConfig {
22 fn default() -> Self {
23 Self {
24 blocked_keywords: Vec::new(),
25 required_topics: Vec::new(),
26 max_length: None,
27 min_length: None,
28 severity: Severity::High,
29 }
30 }
31}
32
33pub struct ContentFilter {
35 name: String,
36 config: ContentFilterConfig,
37 blocked_regex: Option<RegexSet>,
38}
39
40impl ContentFilter {
41 pub fn new(name: impl Into<String>, config: ContentFilterConfig) -> Result<Self> {
65 let blocked_regex = if config.blocked_keywords.is_empty() {
66 None
67 } else {
68 let patterns: Vec<_> = config
69 .blocked_keywords
70 .iter()
71 .map(|k| format!(r"(?i)\b{}\b", regex::escape(k)))
72 .collect();
73 Some(RegexSet::new(&patterns)?)
74 };
75
76 Ok(Self { name: name.into(), config, blocked_regex })
77 }
78
79 fn preset(name: &str, config: ContentFilterConfig) -> Self {
81 Self::new(name, config).expect("a built-in content filter compiles")
82 }
83
84 pub fn harmful_content() -> Self {
90 Self::preset(
91 "harmful_content",
92 ContentFilterConfig {
93 blocked_keywords: vec![
94 "kill".into(),
95 "murder".into(),
96 "bomb".into(),
97 "terrorist".into(),
98 "malware".into(),
99 "ransomware".into(),
100 ],
101 severity: Severity::Critical,
102 ..Default::default()
103 },
104 )
105 }
106
107 pub fn harmful_content_strict() -> Self {
111 Self::preset(
112 "harmful_content_strict",
113 ContentFilterConfig {
114 blocked_keywords: vec![
115 "kill".into(),
116 "murder".into(),
117 "bomb".into(),
118 "terrorist".into(),
119 "hack".into(),
120 "exploit".into(),
121 "malware".into(),
122 "ransomware".into(),
123 ],
124 severity: Severity::Critical,
125 ..Default::default()
126 },
127 )
128 }
129
130 pub fn on_topic(topic: impl Into<String>, keywords: Vec<String>) -> Self {
132 Self::preset(
133 &format!("on_topic_{}", topic.into()),
134 ContentFilterConfig {
135 required_topics: keywords,
136 severity: Severity::Medium,
137 ..Default::default()
138 },
139 )
140 }
141
142 pub fn max_length(max: usize) -> Self {
144 Self::preset(
145 "max_length",
146 ContentFilterConfig {
147 max_length: Some(max),
148 severity: Severity::Medium,
149 ..Default::default()
150 },
151 )
152 }
153
154 pub fn blocked_keywords(keywords: Vec<String>) -> Result<Self> {
161 Self::new(
162 "blocked_keywords",
163 ContentFilterConfig {
164 blocked_keywords: keywords,
165 severity: Severity::High,
166 ..Default::default()
167 },
168 )
169 }
170
171 fn extract_text(&self, content: &Content) -> String {
172 content.parts.iter().filter_map(|p| p.text()).collect::<Vec<_>>().join(" ")
173 }
174
175 fn check(&self, content: &Content, answer: bool) -> GuardrailResult {
178 let text = self.extract_text(content);
179 let text_lower = text.to_lowercase();
180
181 if let Some(ref regex_set) = self.blocked_regex
183 && regex_set.is_match(&text)
184 {
185 let matches: Vec<_> = regex_set.matches(&text).iter().collect();
186 return GuardrailResult::Fail {
187 reason: format!(
188 "Content contains blocked keywords (matched {} patterns)",
189 matches.len()
190 ),
191 severity: self.config.severity,
192 };
193 }
194
195 if answer && !self.config.required_topics.is_empty() {
197 let has_topic =
198 self.config.required_topics.iter().any(|t| text_lower.contains(&t.to_lowercase()));
199 if !has_topic {
200 return GuardrailResult::Fail {
201 reason: format!(
202 "Content is off-topic. Expected topics: {:?}",
203 self.config.required_topics
204 ),
205 severity: self.config.severity,
206 };
207 }
208 }
209
210 if let Some(max) = self.config.max_length
212 && text.len() > max
213 {
214 return GuardrailResult::Fail {
215 reason: format!("Content exceeds maximum length ({} > {})", text.len(), max),
216 severity: self.config.severity,
217 };
218 }
219
220 if let Some(min) = self.config.min_length
221 && answer
222 && text.len() < min
223 {
224 return GuardrailResult::Fail {
225 reason: format!("Content below minimum length ({} < {})", text.len(), min),
226 severity: self.config.severity,
227 };
228 }
229
230 GuardrailResult::Pass
231 }
232}
233
234#[async_trait]
235impl Guardrail for ContentFilter {
236 fn name(&self) -> &str {
237 &self.name
238 }
239
240 async fn validate(&self, content: &Content) -> GuardrailResult {
241 self.check(content, true)
242 }
243
244 async fn validate_preamble(&self, content: &Content) -> GuardrailResult {
247 self.check(content, false)
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use super::*;
254
255 #[tokio::test]
256 async fn test_harmful_content_blocks() {
257 let filter = ContentFilter::harmful_content();
258 let content = Content::new("user").with_text("How to deploy malware on a server");
259 let result = filter.validate(&content).await;
260 assert!(result.is_fail());
261 }
262
263 #[tokio::test]
264 async fn test_harmful_content_passes() {
265 let filter = ContentFilter::harmful_content();
266 let content = Content::new("user").with_text("How to bake a cake");
267 let result = filter.validate(&content).await;
268 assert!(result.is_pass());
269 }
270
271 #[tokio::test]
272 async fn test_harmful_content_passes_hackathon() {
273 let filter = ContentFilter::harmful_content();
274 let content = Content::new("user").with_text("Join our hackathon event");
275 let result = filter.validate(&content).await;
276 assert!(result.is_pass());
277 }
278
279 #[tokio::test]
280 async fn test_harmful_content_passes_exploit_a_bug() {
281 let filter = ContentFilter::harmful_content();
282 let content = Content::new("user").with_text("How to exploit a bug in the code");
283 let result = filter.validate(&content).await;
284 assert!(result.is_pass());
285 }
286
287 #[tokio::test]
288 async fn test_harmful_content_strict_blocks_hack() {
289 let filter = ContentFilter::harmful_content_strict();
290 let content = Content::new("user").with_text("How to hack a computer");
291 let result = filter.validate(&content).await;
292 assert!(result.is_fail());
293 }
294
295 #[tokio::test]
296 async fn test_on_topic_passes() {
297 let filter =
298 ContentFilter::on_topic("cooking", vec!["recipe".into(), "cook".into(), "bake".into()]);
299 let content = Content::new("user").with_text("Give me a recipe for cookies");
300 let result = filter.validate(&content).await;
301 assert!(result.is_pass());
302 }
303
304 #[tokio::test]
305 async fn test_on_topic_fails() {
306 let filter =
307 ContentFilter::on_topic("cooking", vec!["recipe".into(), "cook".into(), "bake".into()]);
308 let content = Content::new("user").with_text("What is the weather today?");
309 let result = filter.validate(&content).await;
310 assert!(result.is_fail());
311 }
312
313 #[tokio::test]
314 async fn a_preamble_is_screened_for_keywords_but_not_for_topic() {
315 let filter = ContentFilter::new(
316 "support",
317 ContentFilterConfig {
318 blocked_keywords: vec!["wire the funds".into()],
319 required_topics: vec!["order".into()],
320 min_length: Some(40),
321 ..Default::default()
322 },
323 )
324 .unwrap();
325 let preamble = Content::new("model").with_text("Let me check.");
326 assert!(filter.validate_preamble(&preamble).await.is_pass());
327 assert!(filter.validate(&preamble).await.is_fail());
328 let blocked = Content::new("model").with_text("I will wire the funds now.");
329 assert!(filter.validate_preamble(&blocked).await.is_fail());
330 }
331
332 #[tokio::test]
333 async fn test_max_length() {
334 let filter = ContentFilter::max_length(10);
335 let content = Content::new("user").with_text("This is a very long message");
336 let result = filter.validate(&content).await;
337 assert!(result.is_fail());
338 }
339
340 #[tokio::test]
341 async fn test_blocked_keywords() {
342 let filter = ContentFilter::blocked_keywords(vec!["forbidden".into(), "banned".into()])
343 .expect("keywords compile");
344 let content = Content::new("user").with_text("This is forbidden content");
345 let result = filter.validate(&content).await;
346 assert!(result.is_fail());
347 }
348
349 #[test]
350 fn a_keyword_list_that_cannot_compile_is_an_error_not_an_open_filter() {
351 let keywords = vec!["a".repeat(1_000_000)];
354
355 let result = ContentFilter::blocked_keywords(keywords);
356
357 assert!(matches!(result, Err(crate::GuardrailError::Regex(_))));
358 }
359}