1use std::collections::HashSet;
59use std::sync::Arc;
60
61use futures::StreamExt;
62use serde::{Deserialize, Serialize};
63use serde_json::{Value, json};
64
65use crate::{
66 AdkError, Content, ErrorCategory, ErrorComponent, GenerateContentConfig, Llm, LlmRequest,
67 ModelCallScope, Part, Result,
68};
69
70#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[non_exhaustive]
80pub struct ChoiceOption {
81 pub name: String,
83 pub description: String,
85}
86
87impl ChoiceOption {
88 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
90 Self { name: name.into(), description: description.into() }
91 }
92}
93
94pub trait Choice: Sized {
130 fn options() -> Vec<ChoiceOption>;
132
133 fn from_option(name: &str) -> Option<Self>;
135}
136
137#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct Decision<T> {
152 pub choice: T,
154 pub option: String,
156 pub rationale: String,
158 pub confidence: f64,
160}
161
162impl<T> Decision<T> {
163 pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Decision<U> {
165 Decision {
166 choice: f(self.choice),
167 option: self.option,
168 rationale: self.rationale,
169 confidence: self.confidence,
170 }
171 }
172}
173
174pub async fn decide<T: Choice>(model: Arc<dyn Llm>, input: &str) -> Result<Decision<T>> {
184 Decider::new(model).decide(input).await
185}
186
187#[derive(Clone)]
214pub struct Decider {
215 model: Arc<dyn Llm>,
216 instruction: Option<String>,
217 scope: Option<ModelCallScope>,
218 max_output_tokens: Option<i32>,
219}
220
221impl std::fmt::Debug for Decider {
222 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223 f.debug_struct("Decider")
224 .field("model", &self.model.name())
225 .field("instruction", &self.instruction)
226 .field("scoped", &self.scope.is_some())
227 .finish_non_exhaustive()
228 }
229}
230
231const INVALID_CHOICE: &str = "decision.invalid_choice";
233
234impl Decider {
235 pub fn new(model: Arc<dyn Llm>) -> Self {
237 Self { model, instruction: None, scope: None, max_output_tokens: None }
238 }
239
240 #[must_use]
243 pub fn with_instruction(mut self, instruction: impl Into<String>) -> Self {
244 self.instruction = Some(instruction.into());
245 self
246 }
247
248 #[must_use]
250 pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
251 self.scope = Some(scope);
252 self
253 }
254
255 #[must_use]
258 pub fn with_max_output_tokens(mut self, tokens: i32) -> Self {
259 self.max_output_tokens = Some(tokens);
260 self
261 }
262
263 pub async fn decide<T: Choice>(&self, input: &str) -> Result<Decision<T>> {
270 let decision = self.decide_among(&T::options(), input).await?;
271 let Some(choice) = T::from_option(&decision.option) else {
272 return Err(invalid_options(format!(
273 "option `{}` is one of the type's options but from_option does not map it",
274 decision.option
275 )));
276 };
277 Ok(decision.map(|_| choice))
278 }
279
280 pub async fn decide_among(
288 &self,
289 options: &[ChoiceOption],
290 input: &str,
291 ) -> Result<Decision<String>> {
292 validate(options)?;
293 let mut listed = String::new();
294 for option in options {
295 listed.push_str(&format!("- `{}`: {}\n", option.name, option.description));
296 }
297 let instruction =
298 self.instruction.as_deref().unwrap_or("Decide which option fits the input best.");
299 let prompt = format!(
300 "{instruction}\n\nOptions:\n{listed}\n<input>\n{input}\n</input>\n\nReply with only a \
301 JSON object: {{\"choice\": \"<the name of one option>\", \"rationale\": \"<why, \
302 in one or two sentences>\", \"confidence\": <a number from 0 to 1>}}."
303 );
304 let config = GenerateContentConfig {
305 response_schema: Some(decision_schema(options)),
306 max_output_tokens: self.max_output_tokens,
307 ..Default::default()
308 };
309 let request =
310 LlmRequest::new(self.model.name(), vec![Content::new("user").with_text(prompt)])
311 .with_config(config);
312 let mut stream = match &self.scope {
313 Some(scope) => scope.generate(self.model.as_ref(), request, false).await?,
314 None => crate::generate_metered(self.model.as_ref(), request, false).await?,
315 };
316 let mut reply = String::new();
317 while let Some(response) = stream.next().await {
318 let response = response?;
319 if response.partial {
320 continue;
321 }
322 if let Some(content) = &response.content {
323 reply.extend(content.parts.iter().filter_map(Part::text));
324 }
325 }
326 let decision = read_decision(&reply, options)?;
327 tracing::debug!(
328 decision.option = %decision.option,
329 decision.confidence = decision.confidence,
330 "decision made"
331 );
332 Ok(decision)
333 }
334}
335
336fn invalid_options(message: String) -> AdkError {
337 AdkError::new(
338 ErrorComponent::Agent,
339 ErrorCategory::InvalidInput,
340 "decision.invalid_options",
341 message,
342 )
343}
344
345fn validate(options: &[ChoiceOption]) -> Result<()> {
346 if options.is_empty() {
347 return Err(invalid_options("a decision needs at least one option".to_string()));
348 }
349 let mut seen = HashSet::new();
350 for option in options {
351 if option.name.trim().is_empty() {
352 return Err(invalid_options("an option of a decision has an empty name".to_string()));
353 }
354 if !seen.insert(option.name.as_str()) {
355 return Err(invalid_options(format!(
356 "the options of a decision repeat the name `{}`; give each a distinct name",
357 option.name
358 )));
359 }
360 }
361 Ok(())
362}
363
364fn decision_schema(options: &[ChoiceOption]) -> Value {
367 let names: Vec<&str> = options.iter().map(|option| option.name.as_str()).collect();
368 json!({
369 "type": "object",
370 "properties": {
371 "choice": {"type": "string", "enum": names},
372 "rationale": {"type": "string"},
373 "confidence": {"type": "number"}
374 },
375 "required": ["choice", "rationale", "confidence"],
376 "additionalProperties": false
377 })
378}
379
380fn match_option<'a>(answer: &str, options: &'a [ChoiceOption]) -> Option<&'a ChoiceOption> {
383 let cleaned = answer.trim().trim_matches(|c: char| matches!(c, '`' | '"' | '\'' | '.')).trim();
384 options
385 .iter()
386 .find(|option| option.name == cleaned)
387 .or_else(|| options.iter().find(|option| option.name.eq_ignore_ascii_case(cleaned)))
388}
389
390fn json_object(text: &str) -> Option<serde_json::Map<String, Value>> {
393 let trimmed = text.trim();
394 if let Ok(Value::Object(object)) = serde_json::from_str(trimmed) {
395 return Some(object);
396 }
397 let start = trimmed.find('{')?;
398 let mut depth = 0usize;
399 let mut in_string = false;
400 let mut escaped = false;
401 for (offset, ch) in trimmed[start..].char_indices() {
402 match ch {
403 _ if escaped => escaped = false,
404 '\\' if in_string => escaped = true,
405 '"' => in_string = !in_string,
406 '{' if !in_string => depth += 1,
407 '}' if !in_string => {
408 depth -= 1;
409 if depth == 0 {
410 let candidate = &trimmed[start..start + offset + 1];
411 return match serde_json::from_str(candidate) {
412 Ok(Value::Object(object)) => Some(object),
413 _ => None,
414 };
415 }
416 }
417 _ => {}
418 }
419 }
420 None
421}
422
423fn read_decision(reply: &str, options: &[ChoiceOption]) -> Result<Decision<String>> {
425 let names = || options.iter().map(|option| option.name.as_str()).collect::<Vec<_>>().join(", ");
426 let (answer, rationale, confidence) = match json_object(reply) {
427 Some(object) => (
428 object.get("choice").and_then(Value::as_str).unwrap_or_default().to_string(),
429 object.get("rationale").and_then(Value::as_str).unwrap_or_default().trim().to_string(),
430 object
431 .get("confidence")
432 .and_then(Value::as_f64)
433 .filter(|confidence| confidence.is_finite())
434 .map_or(0.0, |confidence| confidence.clamp(0.0, 1.0)),
435 ),
436 None => (reply.to_string(), String::new(), 0.0),
438 };
439 let option = match_option(&answer, options).ok_or_else(|| {
440 AdkError::new(
441 ErrorComponent::Model,
442 ErrorCategory::Internal,
443 INVALID_CHOICE,
444 format!(
445 "the model's decision names no option (expected one of: {}); its reply: {}",
446 names(),
447 truncate(reply, 300)
448 ),
449 )
450 })?;
451 Ok(Decision { choice: option.name.clone(), option: option.name.clone(), rationale, confidence })
452}
453
454fn truncate(text: &str, max: usize) -> &str {
455 if text.len() <= max {
456 return text;
457 }
458 let mut end = max;
459 while !text.is_char_boundary(end) {
460 end -= 1;
461 }
462 &text[..end]
463}
464
465#[cfg(test)]
466mod tests {
467 use super::*;
468
469 fn options() -> Vec<ChoiceOption> {
470 vec![
471 ChoiceOption::new("billing", "Invoices and refunds"),
472 ChoiceOption::new("technical", "Errors and outages"),
473 ]
474 }
475
476 #[test]
477 fn a_json_reply_is_read_and_its_confidence_clamped() {
478 let decision = read_decision(
479 "```json\n{\"choice\": \"Billing\", \"rationale\": \"double charge\", \"confidence\": 1.4}\n```",
480 &options(),
481 )
482 .unwrap();
483 assert_eq!(
484 decision,
485 Decision {
486 choice: "billing".to_string(),
487 option: "billing".to_string(),
488 rationale: "double charge".to_string(),
489 confidence: 1.0,
490 }
491 );
492 }
493
494 #[test]
495 fn a_bare_option_name_is_a_decision_without_rationale() {
496 let decision = read_decision(" `technical`. ", &options()).unwrap();
497 assert_eq!((decision.option.as_str(), decision.confidence), ("technical", 0.0));
498 }
499
500 #[test]
501 fn a_reply_that_names_no_option_is_refused() {
502 for reply in [
503 "{\"choice\": \"sales\", \"rationale\": \"\", \"confidence\": 0.9}",
504 "probably billing?",
505 ] {
506 let error = read_decision(reply, &options()).unwrap_err();
507 assert_eq!(error.code, INVALID_CHOICE, "{reply}");
508 assert!(error.message.contains("billing, technical"), "{error}");
509 }
510 }
511
512 #[test]
513 fn options_must_be_distinct_and_named() {
514 assert!(validate(&options()).is_ok());
515 assert!(validate(&[]).is_err());
516 let repeated = [ChoiceOption::new("a", "x"), ChoiceOption::new("a", "y")];
517 assert_eq!(validate(&repeated).unwrap_err().code, "decision.invalid_options");
518 assert!(validate(&[ChoiceOption::new(" ", "x")]).is_err());
519 }
520
521 #[test]
522 fn the_schema_enumerates_the_options_without_bounds() {
523 let schema = decision_schema(&options());
524 assert_eq!(schema["properties"]["choice"]["enum"], json!(["billing", "technical"]));
525 assert_eq!(schema["additionalProperties"], json!(false));
526 let text = schema.to_string();
527 assert!(!text.contains("minimum") && !text.contains("maximum"), "{text}");
528 }
529}