use adk_core::{CitationMetadata, Content, Event, GroundingSource, Result};
#[cfg(feature = "guardrails")]
use adk_core::Part;
#[cfg(feature = "guardrails")]
pub use adk_guardrail::{
CitationRequired, ContentFilter, ContentFilterConfig, GUARDRAIL_WARNINGS_KEY, Guardrail,
GuardrailError, GuardrailExecutor, GuardrailFailure, GuardrailPhase, GuardrailResult,
GuardrailSet, INPUT_BLOCKED_CODE, OUTPUT_BLOCKED_CODE, OutputEvidence, PiiRedactor, PiiType,
Severity, WhenNothingRetrieved,
};
#[cfg(feature = "guardrails")]
pub use adk_guardrail::SchemaValidator;
#[cfg(not(feature = "guardrails"))]
pub struct GuardrailSet;
#[cfg(not(feature = "guardrails"))]
impl GuardrailSet {
pub fn new() -> Self {
Self
}
pub fn is_empty(&self) -> bool {
true
}
}
#[cfg(not(feature = "guardrails"))]
impl Default for GuardrailSet {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Phase {
Input,
Output,
}
#[cfg(feature = "guardrails")]
impl From<Phase> for GuardrailPhase {
fn from(phase: Phase) -> Self {
match phase {
Phase::Input => Self::Input,
Phase::Output => Self::Output,
}
}
}
#[derive(Clone, Copy)]
#[cfg_attr(
not(feature = "guardrails"),
expect(dead_code, reason = "only output guardrails read the evidence")
)]
pub(crate) struct Grounding<'a> {
pub(crate) retrieved: &'a [GroundingSource],
pub(crate) citations: Option<&'a CitationMetadata>,
}
pub(crate) struct Screened {
pub(crate) content: Content,
pub(crate) warnings: Warnings,
}
impl Screened {
pub(crate) fn unscreened(content: Content) -> Self {
Self { content, warnings: Warnings::default() }
}
}
#[derive(Default)]
pub(crate) struct Warnings {
#[cfg(feature = "guardrails")]
failures: Vec<GuardrailFailure>,
}
impl Warnings {
pub(crate) fn extend(&mut self, other: Warnings) {
#[cfg(feature = "guardrails")]
self.failures.extend(other.failures);
#[cfg(not(feature = "guardrails"))]
let _ = other;
}
pub(crate) fn record_on(&self, event: &mut Event) {
#[cfg(feature = "guardrails")]
if !self.failures.is_empty() {
event.provider_metadata.insert(
GUARDRAIL_WARNINGS_KEY.to_string(),
serde_json::to_string(&self.failures).unwrap_or_default(),
);
}
#[cfg(not(feature = "guardrails"))]
let _ = event;
}
}
#[cfg(feature = "guardrails")]
pub(crate) async fn enforce_guardrails(
guardrails: &GuardrailSet,
content: &Content,
phase: Phase,
) -> Result<Screened> {
if guardrails.is_empty() {
return Ok(Screened::unscreened(content.clone()));
}
let screening = GuardrailExecutor::enforce(guardrails, content, phase.into(), false).await?;
Ok(Screened { content: screening.content, warnings: Warnings { failures: screening.warnings } })
}
#[cfg(all(feature = "guardrails", feature = "codeact"))]
pub(crate) async fn enforce_final_output(
guardrails: &GuardrailSet,
content: &Content,
grounding: Grounding<'_>,
) -> Result<Screened> {
if guardrails.is_empty() {
return Ok(Screened::unscreened(content.clone()));
}
let evidence = OutputEvidence::new(grounding.retrieved, grounding.citations);
let screening = GuardrailExecutor::enforce_output(guardrails, content, &evidence).await?;
Ok(Screened { content: screening.content, warnings: Warnings { failures: screening.warnings } })
}
#[cfg(all(not(feature = "guardrails"), feature = "codeact"))]
pub(crate) async fn enforce_final_output(
_guardrails: &GuardrailSet,
content: &Content,
_grounding: Grounding<'_>,
) -> Result<Screened> {
Ok(Screened::unscreened(content.clone()))
}
#[cfg(not(feature = "guardrails"))]
pub(crate) async fn enforce_guardrails(
_guardrails: &GuardrailSet,
content: &Content,
_phase: Phase,
) -> Result<Screened> {
Ok(Screened::unscreened(content.clone()))
}
#[cfg(feature = "guardrails")]
enum Slot {
Text(usize),
Native { part: usize, item: usize },
Other(usize),
}
#[cfg(feature = "guardrails")]
fn native_message_texts(payload: &serde_json::Value) -> Vec<(usize, String)> {
if payload.get("type").and_then(serde_json::Value::as_str) != Some("message")
|| payload.get("role").and_then(serde_json::Value::as_str) != Some("assistant")
{
return Vec::new();
}
payload
.get("content")
.and_then(serde_json::Value::as_array)
.map(|items| {
items
.iter()
.enumerate()
.filter_map(|(item, entry)| {
entry.get("text").and_then(serde_json::Value::as_str).map(|t| (item, t.into()))
})
.collect()
})
.unwrap_or_default()
}
#[cfg(feature = "guardrails")]
pub(crate) async fn screen_model_output(
guardrails: &GuardrailSet,
mut content: Content,
preamble: bool,
grounding: Grounding<'_>,
) -> Result<Screened> {
if guardrails.is_empty() {
return Ok(Screened::unscreened(content));
}
let mut slots = Vec::new();
let mut view = Vec::new();
for (index, part) in content.parts.iter().enumerate() {
let native = match part {
Part::ServerToolCall { server_tool_call } => native_message_texts(server_tool_call),
_ => Vec::new(),
};
if !native.is_empty() {
for (item, text) in native {
slots.push(Slot::Native { part: index, item });
view.push(Part::Text { text });
}
} else if let Part::Text { text } = part {
slots.push(Slot::Text(index));
view.push(Part::Text { text: text.clone() });
} else if !preamble {
slots.push(Slot::Other(index));
view.push(part.clone());
}
}
if preamble && view.is_empty() {
return Ok(Screened::unscreened(content));
}
let shown = Content { role: content.role.clone(), parts: view };
let screening = if preamble {
GuardrailExecutor::enforce(guardrails, &shown, GuardrailPhase::Output, true).await?
} else {
let evidence = OutputEvidence::new(grounding.retrieved, grounding.citations);
GuardrailExecutor::enforce_output(guardrails, &shown, &evidence).await?
};
let mut screened = screening.content.parts;
if screened.len() == slots.len() {
for (slot, part) in slots.iter().zip(screened) {
match *slot {
Slot::Text(index) | Slot::Other(index) => content.parts[index] = part,
Slot::Native { part: index, item } => {
let text = part.text().unwrap_or_default().to_string();
if let Part::ServerToolCall { server_tool_call } = &mut content.parts[index]
&& let Some(entry) = server_tool_call
.get_mut("content")
.and_then(|items| items.get_mut(item))
{
entry["text"] = serde_json::Value::String(text);
}
}
}
}
} else if !preamble {
content.parts = screened;
} else {
let joined: String =
screened.drain(..).filter_map(|part| part.text().map(str::to_string)).collect();
let mut first = Some(joined);
let mut emptied = Vec::new();
for slot in &slots {
let text = first.take().unwrap_or_default();
match *slot {
Slot::Text(index) => {
if text.is_empty() {
emptied.push(index);
}
content.parts[index] = Part::Text { text };
}
Slot::Native { part: index, item } => {
if let Part::ServerToolCall { server_tool_call } = &mut content.parts[index]
&& let Some(entry) = server_tool_call
.get_mut("content")
.and_then(|items| items.get_mut(item))
{
entry["text"] = serde_json::Value::String(text);
}
}
Slot::Other(_) => {}
}
}
let mut index = 0;
content.parts.retain(|_| {
let keep = !emptied.contains(&index);
index += 1;
keep
});
}
Ok(Screened { content, warnings: Warnings { failures: screening.warnings } })
}
#[cfg(not(feature = "guardrails"))]
pub(crate) async fn screen_model_output(
_guardrails: &GuardrailSet,
content: Content,
_preamble: bool,
_grounding: Grounding<'_>,
) -> Result<Screened> {
Ok(Screened::unscreened(content))
}
#[cfg(feature = "guardrails")]
pub use adk_guardrail::{
DeniedArgumentPattern, PathAllowList, ResultTextGuardrail, ToolCallDecision, ToolGuardrail,
ToolGuardrailResult, ToolGuardrailSet, ToolResultDecision, ToolResultGuardrailResult,
};
#[cfg(not(feature = "guardrails"))]
pub struct ToolGuardrailSet;
#[cfg(not(feature = "guardrails"))]
impl ToolGuardrailSet {
pub fn new() -> Self {
Self
}
pub fn is_empty(&self) -> bool {
true
}
}
#[cfg(not(feature = "guardrails"))]
impl Default for ToolGuardrailSet {
fn default() -> Self {
Self::new()
}
}
pub(crate) enum ToolScreening {
Allow(serde_json::Value),
#[cfg_attr(not(feature = "guardrails"), allow(dead_code))]
Deny(String),
}
#[cfg(feature = "guardrails")]
pub(crate) async fn screen_tool_call(
guardrails: &ToolGuardrailSet,
tool_name: &str,
args: &serde_json::Value,
) -> ToolScreening {
if guardrails.is_empty() {
return ToolScreening::Allow(args.clone());
}
match guardrails.evaluate(tool_name, args).await {
ToolCallDecision::Allow { args } => ToolScreening::Allow(args),
ToolCallDecision::Deny { guardrail, reason, severity } => ToolScreening::Deny(format!(
"Tool '{tool_name}' blocked by guardrail '{guardrail}' ({severity:?}): {reason}"
)),
}
}
#[cfg(not(feature = "guardrails"))]
pub(crate) async fn screen_tool_call(
_guardrails: &ToolGuardrailSet,
_tool_name: &str,
args: &serde_json::Value,
) -> ToolScreening {
ToolScreening::Allow(args.clone())
}
pub(crate) struct GuardrailScreen<'a>(pub(crate) &'a ToolGuardrailSet);
#[async_trait::async_trait]
impl adk_core::ToolCallScreen for GuardrailScreen<'_> {
async fn screen(
&self,
tool_name: &str,
args: &serde_json::Value,
) -> std::result::Result<serde_json::Value, String> {
match screen_tool_call(self.0, tool_name, args).await {
ToolScreening::Allow(args) => Ok(args),
ToolScreening::Deny(reason) => Err(reason),
}
}
}
#[cfg(feature = "guardrails")]
pub(crate) async fn screen_tool_result(
guardrails: &ToolGuardrailSet,
tool_name: &str,
args: &serde_json::Value,
executed: bool,
mut content: Content,
) -> (Content, Vec<String>) {
use adk_core::ToolResultScreen as _;
let mut withheld = Vec::new();
if guardrails.is_empty() {
return (content, withheld);
}
for part in &mut content.parts {
let previous = part.tool_result_status();
let Part::FunctionResponse { function_response, .. } = part else { continue };
match guardrails.screen_result(tool_name, args, &function_response.response).await {
Ok(result) => function_response.response = result,
Err(reason) => {
function_response.response = adk_core::result_blocked_response(tool_name, &reason);
function_response.inline_data.clear();
function_response.file_data.clear();
withheld.push(reason);
let status = adk_core::ToolResultStatus::when_withheld(previous, executed);
if previous != Some(status) {
part.set_tool_result_status(status, None);
}
}
}
}
(content, withheld)
}
#[cfg(not(feature = "guardrails"))]
pub(crate) async fn screen_tool_result(
_guardrails: &ToolGuardrailSet,
_tool_name: &str,
_args: &serde_json::Value,
_executed: bool,
content: Content,
) -> (Content, Vec<String>) {
(content, Vec::new())
}