use std::collections::HashSet;
use std::sync::Arc;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::{
AdkError, Content, ErrorCategory, ErrorComponent, GenerateContentConfig, Llm, LlmRequest,
ModelCallScope, Part, Result,
};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ChoiceOption {
pub name: String,
pub description: String,
}
impl ChoiceOption {
pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
Self { name: name.into(), description: description.into() }
}
}
pub trait Choice: Sized {
fn options() -> Vec<ChoiceOption>;
fn from_option(name: &str) -> Option<Self>;
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Decision<T> {
pub choice: T,
pub option: String,
pub rationale: String,
pub confidence: f64,
}
impl<T> Decision<T> {
pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Decision<U> {
Decision {
choice: f(self.choice),
option: self.option,
rationale: self.rationale,
confidence: self.confidence,
}
}
}
pub async fn decide<T: Choice>(model: Arc<dyn Llm>, input: &str) -> Result<Decision<T>> {
Decider::new(model).decide(input).await
}
#[derive(Clone)]
pub struct Decider {
model: Arc<dyn Llm>,
instruction: Option<String>,
scope: Option<ModelCallScope>,
max_output_tokens: Option<i32>,
}
impl std::fmt::Debug for Decider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Decider")
.field("model", &self.model.name())
.field("instruction", &self.instruction)
.field("scoped", &self.scope.is_some())
.finish_non_exhaustive()
}
}
const INVALID_CHOICE: &str = "decision.invalid_choice";
impl Decider {
pub fn new(model: Arc<dyn Llm>) -> Self {
Self { model, instruction: None, scope: None, max_output_tokens: None }
}
#[must_use]
pub fn with_instruction(mut self, instruction: impl Into<String>) -> Self {
self.instruction = Some(instruction.into());
self
}
#[must_use]
pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
self.scope = Some(scope);
self
}
#[must_use]
pub fn with_max_output_tokens(mut self, tokens: i32) -> Self {
self.max_output_tokens = Some(tokens);
self
}
pub async fn decide<T: Choice>(&self, input: &str) -> Result<Decision<T>> {
let decision = self.decide_among(&T::options(), input).await?;
let Some(choice) = T::from_option(&decision.option) else {
return Err(invalid_options(format!(
"option `{}` is one of the type's options but from_option does not map it",
decision.option
)));
};
Ok(decision.map(|_| choice))
}
pub async fn decide_among(
&self,
options: &[ChoiceOption],
input: &str,
) -> Result<Decision<String>> {
validate(options)?;
let mut listed = String::new();
for option in options {
listed.push_str(&format!("- `{}`: {}\n", option.name, option.description));
}
let instruction =
self.instruction.as_deref().unwrap_or("Decide which option fits the input best.");
let prompt = format!(
"{instruction}\n\nOptions:\n{listed}\n<input>\n{input}\n</input>\n\nReply with only a \
JSON object: {{\"choice\": \"<the name of one option>\", \"rationale\": \"<why, \
in one or two sentences>\", \"confidence\": <a number from 0 to 1>}}."
);
let config = GenerateContentConfig {
response_schema: Some(decision_schema(options)),
max_output_tokens: self.max_output_tokens,
..Default::default()
};
let request =
LlmRequest::new(self.model.name(), vec![Content::new("user").with_text(prompt)])
.with_config(config);
let mut stream = match &self.scope {
Some(scope) => scope.generate(self.model.as_ref(), request, false).await?,
None => crate::generate_metered(self.model.as_ref(), request, false).await?,
};
let mut reply = String::new();
while let Some(response) = stream.next().await {
let response = response?;
if response.partial {
continue;
}
if let Some(content) = &response.content {
reply.extend(content.parts.iter().filter_map(Part::text));
}
}
let decision = read_decision(&reply, options)?;
tracing::debug!(
decision.option = %decision.option,
decision.confidence = decision.confidence,
"decision made"
);
Ok(decision)
}
}
fn invalid_options(message: String) -> AdkError {
AdkError::new(
ErrorComponent::Agent,
ErrorCategory::InvalidInput,
"decision.invalid_options",
message,
)
}
fn validate(options: &[ChoiceOption]) -> Result<()> {
if options.is_empty() {
return Err(invalid_options("a decision needs at least one option".to_string()));
}
let mut seen = HashSet::new();
for option in options {
if option.name.trim().is_empty() {
return Err(invalid_options("an option of a decision has an empty name".to_string()));
}
if !seen.insert(option.name.as_str()) {
return Err(invalid_options(format!(
"the options of a decision repeat the name `{}`; give each a distinct name",
option.name
)));
}
}
Ok(())
}
fn decision_schema(options: &[ChoiceOption]) -> Value {
let names: Vec<&str> = options.iter().map(|option| option.name.as_str()).collect();
json!({
"type": "object",
"properties": {
"choice": {"type": "string", "enum": names},
"rationale": {"type": "string"},
"confidence": {"type": "number"}
},
"required": ["choice", "rationale", "confidence"],
"additionalProperties": false
})
}
fn match_option<'a>(answer: &str, options: &'a [ChoiceOption]) -> Option<&'a ChoiceOption> {
let cleaned = answer.trim().trim_matches(|c: char| matches!(c, '`' | '"' | '\'' | '.')).trim();
options
.iter()
.find(|option| option.name == cleaned)
.or_else(|| options.iter().find(|option| option.name.eq_ignore_ascii_case(cleaned)))
}
fn json_object(text: &str) -> Option<serde_json::Map<String, Value>> {
let trimmed = text.trim();
if let Ok(Value::Object(object)) = serde_json::from_str(trimmed) {
return Some(object);
}
let start = trimmed.find('{')?;
let mut depth = 0usize;
let mut in_string = false;
let mut escaped = false;
for (offset, ch) in trimmed[start..].char_indices() {
match ch {
_ if escaped => escaped = false,
'\\' if in_string => escaped = true,
'"' => in_string = !in_string,
'{' if !in_string => depth += 1,
'}' if !in_string => {
depth -= 1;
if depth == 0 {
let candidate = &trimmed[start..start + offset + 1];
return match serde_json::from_str(candidate) {
Ok(Value::Object(object)) => Some(object),
_ => None,
};
}
}
_ => {}
}
}
None
}
fn read_decision(reply: &str, options: &[ChoiceOption]) -> Result<Decision<String>> {
let names = || options.iter().map(|option| option.name.as_str()).collect::<Vec<_>>().join(", ");
let (answer, rationale, confidence) = match json_object(reply) {
Some(object) => (
object.get("choice").and_then(Value::as_str).unwrap_or_default().to_string(),
object.get("rationale").and_then(Value::as_str).unwrap_or_default().trim().to_string(),
object
.get("confidence")
.and_then(Value::as_f64)
.filter(|confidence| confidence.is_finite())
.map_or(0.0, |confidence| confidence.clamp(0.0, 1.0)),
),
None => (reply.to_string(), String::new(), 0.0),
};
let option = match_option(&answer, options).ok_or_else(|| {
AdkError::new(
ErrorComponent::Model,
ErrorCategory::Internal,
INVALID_CHOICE,
format!(
"the model's decision names no option (expected one of: {}); its reply: {}",
names(),
truncate(reply, 300)
),
)
})?;
Ok(Decision { choice: option.name.clone(), option: option.name.clone(), rationale, confidence })
}
fn truncate(text: &str, max: usize) -> &str {
if text.len() <= max {
return text;
}
let mut end = max;
while !text.is_char_boundary(end) {
end -= 1;
}
&text[..end]
}
#[cfg(test)]
mod tests {
use super::*;
fn options() -> Vec<ChoiceOption> {
vec![
ChoiceOption::new("billing", "Invoices and refunds"),
ChoiceOption::new("technical", "Errors and outages"),
]
}
#[test]
fn a_json_reply_is_read_and_its_confidence_clamped() {
let decision = read_decision(
"```json\n{\"choice\": \"Billing\", \"rationale\": \"double charge\", \"confidence\": 1.4}\n```",
&options(),
)
.unwrap();
assert_eq!(
decision,
Decision {
choice: "billing".to_string(),
option: "billing".to_string(),
rationale: "double charge".to_string(),
confidence: 1.0,
}
);
}
#[test]
fn a_bare_option_name_is_a_decision_without_rationale() {
let decision = read_decision(" `technical`. ", &options()).unwrap();
assert_eq!((decision.option.as_str(), decision.confidence), ("technical", 0.0));
}
#[test]
fn a_reply_that_names_no_option_is_refused() {
for reply in [
"{\"choice\": \"sales\", \"rationale\": \"\", \"confidence\": 0.9}",
"probably billing?",
] {
let error = read_decision(reply, &options()).unwrap_err();
assert_eq!(error.code, INVALID_CHOICE, "{reply}");
assert!(error.message.contains("billing, technical"), "{error}");
}
}
#[test]
fn options_must_be_distinct_and_named() {
assert!(validate(&options()).is_ok());
assert!(validate(&[]).is_err());
let repeated = [ChoiceOption::new("a", "x"), ChoiceOption::new("a", "y")];
assert_eq!(validate(&repeated).unwrap_err().code, "decision.invalid_options");
assert!(validate(&[ChoiceOption::new(" ", "x")]).is_err());
}
#[test]
fn the_schema_enumerates_the_options_without_bounds() {
let schema = decision_schema(&options());
assert_eq!(schema["properties"]["choice"]["enum"], json!(["billing", "technical"]));
assert_eq!(schema["additionalProperties"], json!(false));
let text = schema.to_string();
assert!(!text.contains("minimum") && !text.contains("maximum"), "{text}");
}
}