strands/vended_interventions/hitl/
classifier.rs1use std::fmt;
4use std::future::Future;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use serde::Deserialize;
9use serde_json::json;
10
11use crate::agent::{Agent, InvocationContext, InvokeOptions};
12use crate::error::BoxError;
13use crate::hooks::BeforeToolCallEvent;
14use crate::models::Model;
15use crate::types::JsonSchema;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20pub struct ClassifierResult {
21 pub requires_human_in_the_loop: bool,
23 pub reason: Option<String>,
25}
26
27impl ClassifierResult {
28 #[must_use]
30 pub fn new(requires_human_in_the_loop: bool) -> Self {
31 Self {
32 requires_human_in_the_loop,
33 reason: None,
34 }
35 }
36
37 #[must_use]
39 pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
40 self.reason = Some(reason.into());
41 self
42 }
43}
44
45#[async_trait]
61pub trait HumanInTheLoopClassifier: Send + Sync + 'static {
62 async fn classify(&self, event: &BeforeToolCallEvent) -> Result<ClassifierResult, BoxError>;
68}
69
70#[async_trait]
71impl<F, Fut> HumanInTheLoopClassifier for F
72where
73 F: Fn(&BeforeToolCallEvent) -> Fut + Send + Sync + 'static,
74 Fut: Future<Output = Result<ClassifierResult, BoxError>> + Send + 'static,
75{
76 async fn classify(&self, event: &BeforeToolCallEvent) -> Result<ClassifierResult, BoxError> {
77 self(event).await
78 }
79}
80
81#[derive(Clone, Default, bon::Builder)]
83pub struct LlmClassifierConfig {
84 #[builder(into)]
86 pub system_prompt: Option<String>,
87 pub model: Option<Arc<dyn Model>>,
90}
91
92impl fmt::Debug for LlmClassifierConfig {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 f.debug_struct("LlmClassifierConfig")
95 .field("system_prompt", &self.system_prompt)
96 .field("model", &self.model.as_ref().map(|model| model.model_id()))
97 .finish()
98 }
99}
100
101#[derive(Clone)]
104#[non_exhaustive]
105pub enum ClassifierConfig {
106 Llm(LlmClassifierConfig),
108 Custom(Arc<dyn HumanInTheLoopClassifier>),
110}
111
112impl ClassifierConfig {
113 #[must_use]
115 pub fn llm() -> Self {
116 Self::Llm(LlmClassifierConfig::default())
117 }
118
119 pub fn custom(classifier: impl HumanInTheLoopClassifier) -> Self {
121 Self::Custom(Arc::new(classifier))
122 }
123
124 pub(crate) fn resolve(self) -> Arc<dyn HumanInTheLoopClassifier> {
125 match self {
126 Self::Llm(config) => Arc::new(LlmRiskClassifier::new(config)),
127 Self::Custom(classifier) => classifier,
128 }
129 }
130}
131
132impl From<LlmClassifierConfig> for ClassifierConfig {
133 fn from(config: LlmClassifierConfig) -> Self {
134 Self::Llm(config)
135 }
136}
137
138impl<C: HumanInTheLoopClassifier> From<C> for ClassifierConfig {
141 fn from(classifier: C) -> Self {
142 Self::Custom(Arc::new(classifier))
143 }
144}
145
146impl fmt::Debug for ClassifierConfig {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 match self {
149 Self::Llm(config) => f.debug_tuple("Llm").field(config).finish(),
150 Self::Custom(_) => f.write_str("Custom(..)"),
151 }
152 }
153}
154
155const RISK_CRITERIA: &str = "## When to require approval
156
157Require approval when the tool call:
158- Is destructive or irreversible (deleting data, dropping tables, revoking access)
159- Modifies important state in production or shared environments
160- Accesses or transmits sensitive data (credentials, PII, financial records)
161- Communicates externally (sending emails, posting messages, making payments)
162- Has a large blast radius (affecting many records, users, or systems)
163
164## When approval is NOT needed
165
166Do not require approval when the tool call:
167- Is read-only AND does not access sensitive data (listing non-sensitive files, querying public data, searching)
168- Operates on local or temporary resources
169- Has easily reversible effects
170- Is scoped to a single non-critical resource
171
172Note: even read-only operations that access credentials, secrets, PII, or financial data still require approval.";
173
174pub(crate) fn default_system_prompt() -> String {
175 format!(
176 "You are a risk evaluator for an AI agent's tool calls. Your job is to decide whether each tool call requires human approval before executing.
177
178{RISK_CRITERIA}
179
180## Instructions
181
182Evaluate the tool name and its input arguments. Consider what could go wrong if this specific call executes with these specific arguments. When uncertain, require approval.
183
184Keep your reason under 10 words \u{2014} it is shown to a human in a CLI prompt."
185 )
186}
187
188fn risk_decision_schema() -> JsonSchema {
189 json!({
190 "type": "object",
191 "properties": {
192 "requiresApproval": {
193 "type": "boolean",
194 "description": "Whether this tool call requires human approval before executing"
195 },
196 "reason": {
197 "type": "string",
198 "description": "Brief reason (under 10 words) why approval is or is not required"
199 }
200 },
201 "required": ["requiresApproval", "reason"],
202 "additionalProperties": false
203 })
204}
205
206#[derive(Deserialize)]
207#[serde(rename_all = "camelCase")]
208struct RiskDecision {
209 requires_approval: bool,
210 reason: String,
211}
212
213pub(crate) fn format_tool_call(event: &BeforeToolCallEvent) -> String {
215 let input = serde_json::to_string_pretty(&event.tool_use().input).unwrap_or_default();
216 format!("Tool: {}\nInput: {input}", event.tool_use().name)
217}
218
219struct LlmRiskClassifier {
222 system_prompt: String,
223 model: Option<Arc<dyn Model>>,
224}
225
226impl LlmRiskClassifier {
227 fn new(config: LlmClassifierConfig) -> Self {
228 Self {
229 system_prompt: config.system_prompt.unwrap_or_else(default_system_prompt),
230 model: config.model,
231 }
232 }
233}
234
235#[async_trait]
236impl HumanInTheLoopClassifier for LlmRiskClassifier {
237 async fn classify(&self, event: &BeforeToolCallEvent) -> Result<ClassifierResult, BoxError> {
238 let model = self.model.clone().unwrap_or_else(|| event.agent().aux_model().clone());
239 let mut inner = Agent::builder()
240 .model(model)
241 .system_prompt(self.system_prompt.clone())
242 .structured_output_schema_json(risk_decision_schema())
243 .printer(false)
244 .build()?;
245 let prompt = format!(
246 "Should this tool call require human approval?\n\n{}",
247 format_tool_call(event)
248 );
249 let options = InvokeOptions {
250 invocation_context: InvocationContext::auxiliary(event.invocation_context()),
251 ..Default::default()
252 };
253 let result = inner.invoke_with(prompt, options).await?;
254 let decision: RiskDecision = result.structured_output()?;
255 Ok(ClassifierResult::new(decision.requires_approval).with_reason(decision.reason))
256 }
257}