-
Notifications
You must be signed in to change notification settings - Fork 4
feat(guardrail): add regex #105
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,18 @@ | ||
| pub mod bedrock; | ||
| pub mod regex; | ||
|
|
||
| pub use bedrock::{BedrockGuardrailMeta, BedrockGuardrailRuntime}; | ||
| pub use self::{ | ||
| bedrock::{BedrockGuardrailMeta, BedrockGuardrailRuntime}, | ||
| regex::{RegexGuardrailMeta, RegexGuardrailRuntime}, | ||
| }; | ||
|
|
||
| pub mod identifiers { | ||
| use super::bedrock; | ||
| use super::{bedrock, regex}; | ||
|
|
||
| pub const BEDROCK: &str = bedrock::IDENTIFIER; | ||
| pub const REGEX: &str = regex::IDENTIFIER; | ||
| } | ||
|
|
||
| pub mod configs { | ||
| pub use super::bedrock::BedrockGuardrailConfig; | ||
| pub use super::{bedrock::BedrockGuardrailConfig, regex::RegexGuardrailConfig}; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,240 @@ | ||
| use std::convert::Infallible; | ||
|
|
||
| use async_trait::async_trait; | ||
| use regex::Regex; | ||
| use serde::{Deserialize, Deserializer, Serialize, de}; | ||
| use utoipa::ToSchema; | ||
|
|
||
| use crate::traits::{ | ||
| GuardrailCheckPayload, GuardrailContentPart, GuardrailMessage, GuardrailMessageContent, | ||
| GuardrailMeta, GuardrailOutcome, GuardrailRuntime, | ||
| }; | ||
|
|
||
| pub const IDENTIFIER: &str = "regex"; | ||
|
|
||
| #[derive(Debug, Clone, Serialize, ToSchema)] | ||
| pub struct RegexGuardrailConfig { | ||
| pub pattern: String, | ||
|
|
||
| #[serde(skip_serializing_if = "Option::is_none")] | ||
| pub block_reason: Option<String>, | ||
|
|
||
| #[serde(skip)] | ||
| #[schema(ignore)] | ||
| compiled_pattern: Regex, | ||
| } | ||
|
|
||
| impl RegexGuardrailConfig { | ||
| pub fn new( | ||
| pattern: impl Into<String>, | ||
| block_reason: Option<String>, | ||
| ) -> Result<Self, regex::Error> { | ||
| let pattern = pattern.into(); | ||
| let compiled_pattern = Regex::new(&pattern)?; | ||
|
|
||
| Ok(Self { | ||
| pattern, | ||
| block_reason, | ||
| compiled_pattern, | ||
| }) | ||
| } | ||
|
|
||
| pub fn compiled_pattern(&self) -> &Regex { | ||
| &self.compiled_pattern | ||
| } | ||
| } | ||
|
|
||
| impl<'de> Deserialize<'de> for RegexGuardrailConfig { | ||
| fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> | ||
| where | ||
| D: Deserializer<'de>, | ||
| { | ||
| #[derive(Deserialize)] | ||
| struct RawRegexGuardrailConfig { | ||
| pattern: String, | ||
| #[serde(default)] | ||
| block_reason: Option<String>, | ||
| } | ||
|
|
||
| let raw = RawRegexGuardrailConfig::deserialize(deserializer)?; | ||
|
|
||
| Self::new(raw.pattern, raw.block_reason) | ||
| .map_err(|error| de::Error::custom(format!("invalid regex guardrail pattern: {error}"))) | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Copy, Default)] | ||
| pub struct RegexGuardrailMeta; | ||
|
|
||
| impl GuardrailMeta for RegexGuardrailMeta { | ||
| fn name(&self) -> &'static str { | ||
| IDENTIFIER | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug, Clone, Copy, Default)] | ||
| pub struct RegexGuardrailRuntime; | ||
|
|
||
| impl RegexGuardrailRuntime { | ||
| pub fn new() -> Self { | ||
| Self | ||
| } | ||
| } | ||
|
|
||
| impl GuardrailMeta for RegexGuardrailRuntime { | ||
| fn name(&self) -> &'static str { | ||
| IDENTIFIER | ||
| } | ||
| } | ||
|
|
||
| #[async_trait] | ||
| impl GuardrailRuntime<RegexGuardrailConfig> for RegexGuardrailRuntime { | ||
| type Error = Infallible; | ||
|
|
||
| async fn check( | ||
| &self, | ||
| payload: &GuardrailCheckPayload, | ||
| config: &RegexGuardrailConfig, | ||
| ) -> Result<GuardrailOutcome, Self::Error> { | ||
| if payload_matches(config.compiled_pattern(), payload) { | ||
| return Ok(GuardrailOutcome::Block { | ||
| reason: config | ||
| .block_reason | ||
| .clone() | ||
| .unwrap_or_else(|| "regex guardrail blocked".into()), | ||
| }); | ||
| } | ||
|
|
||
| Ok(GuardrailOutcome::Allow) | ||
| } | ||
| } | ||
|
|
||
| fn payload_matches(pattern: &Regex, payload: &GuardrailCheckPayload) -> bool { | ||
| let messages = match payload { | ||
| GuardrailCheckPayload::Input(payload) => &payload.messages, | ||
| GuardrailCheckPayload::Output(payload) => &payload.messages, | ||
| }; | ||
|
|
||
| messages | ||
| .iter() | ||
| .any(|message| message_matches(pattern, message)) | ||
| } | ||
|
|
||
| fn message_matches(pattern: &Regex, message: &GuardrailMessage) -> bool { | ||
| match &message.content { | ||
| Some(GuardrailMessageContent::Text(text)) => pattern.is_match(text), | ||
| Some(GuardrailMessageContent::Parts(parts)) => parts.iter().any(|part| match part { | ||
| GuardrailContentPart::Text { text } => pattern.is_match(text), | ||
| GuardrailContentPart::ImageUrl { .. } => false, | ||
| }), | ||
| None => false, | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use serde_json::json; | ||
|
|
||
| use super::{RegexGuardrailConfig, RegexGuardrailRuntime}; | ||
| use crate::traits::{ | ||
| GuardrailCheckPayload, GuardrailContentPart, GuardrailImageUrl, GuardrailMessage, | ||
| GuardrailMessageContent, GuardrailOutcome, GuardrailRole, GuardrailRuntime, | ||
| InputGuardrailPayload, | ||
| }; | ||
|
|
||
| fn config(pattern: &str) -> RegexGuardrailConfig { | ||
| RegexGuardrailConfig::new(pattern, Some("matched blocked content".into())).unwrap() | ||
| } | ||
|
|
||
| fn runtime() -> RegexGuardrailRuntime { | ||
| RegexGuardrailRuntime::new() | ||
| } | ||
|
|
||
| fn input_payload(content: GuardrailMessageContent) -> GuardrailCheckPayload { | ||
| GuardrailCheckPayload::Input(InputGuardrailPayload { | ||
| messages: vec![GuardrailMessage { | ||
| role: GuardrailRole::User, | ||
| content: Some(content), | ||
| name: None, | ||
| tool_calls: None, | ||
| tool_call_id: None, | ||
| }], | ||
| }) | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn blocks_when_plain_text_matches_pattern() { | ||
| let outcome = runtime() | ||
| .check( | ||
| &input_payload(GuardrailMessageContent::Text( | ||
| "my secret token is 12345".into(), | ||
| )), | ||
| &config(r"secret token"), | ||
| ) | ||
| .await | ||
| .unwrap(); | ||
|
|
||
| assert_eq!( | ||
| outcome, | ||
| GuardrailOutcome::Block { | ||
| reason: "matched blocked content".into(), | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn allows_when_no_message_text_matches_pattern() { | ||
| let outcome = runtime() | ||
| .check( | ||
| &input_payload(GuardrailMessageContent::Text("hello world".into())), | ||
| &config(r"secret token"), | ||
| ) | ||
| .await | ||
| .unwrap(); | ||
|
|
||
| assert_eq!(outcome, GuardrailOutcome::Allow); | ||
| } | ||
|
|
||
| #[tokio::test] | ||
| async fn matches_text_parts_and_ignores_non_text_parts() { | ||
| let outcome = runtime() | ||
| .check( | ||
| &input_payload(GuardrailMessageContent::Parts(vec![ | ||
| GuardrailContentPart::ImageUrl { | ||
| image_url: GuardrailImageUrl { | ||
| url: "https://example.com/cat.png".into(), | ||
| detail: Some("high".into()), | ||
| }, | ||
| }, | ||
| GuardrailContentPart::Text { | ||
| text: "contains credit card 4111111111111111".into(), | ||
| }, | ||
| ])), | ||
| &config(r"\b\d{16}\b"), | ||
| ) | ||
| .await | ||
| .unwrap(); | ||
|
|
||
| assert_eq!( | ||
| outcome, | ||
| GuardrailOutcome::Block { | ||
| reason: "matched blocked content".into(), | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| #[test] | ||
| fn deserialize_rejects_invalid_patterns() { | ||
| let error = serde_json::from_value::<RegexGuardrailConfig>(json!({ | ||
| "pattern": "[", | ||
| "block_reason": "matched blocked content" | ||
| })) | ||
| .unwrap_err(); | ||
|
|
||
| assert!( | ||
| error | ||
| .to_string() | ||
| .contains("invalid regex guardrail pattern") | ||
| ); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.