Skip to main content

adk_core/
decision.rs

1//! Typed decisions: a model picks one of a fixed set of options and states why and how sure
2//! it is.
3//!
4//! | Item | Use |
5//! |---|---|
6//! | [`Choice`] | a type whose values a model can decide, such as an enum of routes |
7//! | [`decide`] | one decision of type `T` with a model, in the current [`ModelCallScope`] |
8//! | [`Decider`] | the same with an instruction, an explicit scope or an output cap; [`Decider::decide_among`] decides among options known only at run time |
9//! | [`Decision`] | the choice, the option's name, the model's rationale and its confidence |
10//!
11//! The request carries a JSON response schema whose `choice` is an `enum` of the option names,
12//! so a provider with structured outputs (Anthropic `output_config.format`, OpenAI `strict`
13//! JSON schema, Gemini `responseSchema`) constrains the reply to a valid option. No tool is
14//! declared and no `tool_choice` is forced, which models that reject forced tool use accept.
15//! A provider without structured outputs is asked for the same JSON in the prompt, and the
16//! reply is validated: a choice that names no option is an error, never a guess.
17//!
18//! Every call goes through a [`ModelCallScope`], so it counts against the run's budget and
19//! spend ledger and is refused before it reaches the provider when a limit is reached.
20//!
21//! # Example
22//!
23//! ```rust,no_run
24//! use std::sync::Arc;
25//!
26//! use adk_core::{Choice, ChoiceOption, Llm, decide};
27//!
28//! #[derive(Debug, PartialEq)]
29//! enum Route {
30//!     Billing,
31//!     Technical,
32//! }
33//!
34//! impl Choice for Route {
35//!     fn options() -> Vec<ChoiceOption> {
36//!         vec![
37//!             ChoiceOption::new("billing", "Invoices, refunds and payment problems"),
38//!             ChoiceOption::new("technical", "Errors, outages and how-to questions"),
39//!         ]
40//!     }
41//!
42//!     fn from_option(name: &str) -> Option<Self> {
43//!         match name {
44//!             "billing" => Some(Self::Billing),
45//!             "technical" => Some(Self::Technical),
46//!             _ => None,
47//!         }
48//!     }
49//! }
50//!
51//! async fn route(model: Arc<dyn Llm>) -> adk_core::Result<()> {
52//!     let decision = decide::<Route>(model, "I was charged twice this month").await?;
53//!     println!("{:?} ({:.2}): {}", decision.choice, decision.confidence, decision.rationale);
54//!     Ok(())
55//! }
56//! ```
57
58use 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/// One option of a decision: the name the model answers with and what it means.
71///
72/// # Example
73///
74/// ```rust
75/// let option = adk_core::ChoiceOption::new("billing", "Invoices, refunds and payment problems");
76/// assert_eq!(option.name, "billing");
77/// ```
78#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
79#[non_exhaustive]
80pub struct ChoiceOption {
81    /// The name the model answers with.
82    pub name: String,
83    /// What choosing it means, shown to the model.
84    pub description: String,
85}
86
87impl ChoiceOption {
88    /// An option named `name`, described by `description`.
89    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
90        Self { name: name.into(), description: description.into() }
91    }
92}
93
94/// A type whose values a model can decide among: a fixed set of named options.
95///
96/// Implement it for an enum of routes, labels or next actions, or derive it with
97/// `#[derive(Choice)]` from `adk-rust-macros`, then call [`decide`]. Option names must be
98/// distinct and non-empty; [`from_option`](Self::from_option) maps each name back to its value.
99///
100/// # Example
101///
102/// ```rust
103/// use adk_core::{Choice, ChoiceOption};
104///
105/// enum Next {
106///     Answer,
107///     Escalate,
108/// }
109///
110/// impl Choice for Next {
111///     fn options() -> Vec<ChoiceOption> {
112///         vec![
113///             ChoiceOption::new("answer", "The question can be answered from the docs"),
114///             ChoiceOption::new("escalate", "A person must decide"),
115///         ]
116///     }
117///
118///     fn from_option(name: &str) -> Option<Self> {
119///         match name {
120///             "answer" => Some(Self::Answer),
121///             "escalate" => Some(Self::Escalate),
122///             _ => None,
123///         }
124///     }
125/// }
126///
127/// assert!(matches!(Next::from_option("escalate"), Some(Next::Escalate)));
128/// ```
129pub trait Choice: Sized {
130    /// The options, in the order the model sees them.
131    fn options() -> Vec<ChoiceOption>;
132
133    /// The value of the option named `name`, or `None` when no option has that name.
134    fn from_option(name: &str) -> Option<Self>;
135}
136
137/// What a model decided: the choice, the name of the option it picked, why, and how sure it
138/// is.
139///
140/// # Example
141///
142/// ```rust
143/// let decision: adk_core::Decision<String> = serde_json::from_value(serde_json::json!({
144///     "choice": "billing", "option": "billing", "rationale": "a double charge", "confidence": 0.9
145/// }))?;
146/// assert_eq!(decision.option, "billing");
147/// # Ok::<(), serde_json::Error>(())
148/// ```
149#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct Decision<T> {
152    /// The value decided.
153    pub choice: T,
154    /// The name of the option picked.
155    pub option: String,
156    /// The model's reason, in its words; empty when it gave none.
157    pub rationale: String,
158    /// The model's confidence from 0.0 to 1.0; 0.0 when it stated none.
159    pub confidence: f64,
160}
161
162impl<T> Decision<T> {
163    /// The same decision with its choice mapped by `f`.
164    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
174/// Decides one [`Choice`] with `model` about `input`, in the current [`ModelCallScope`].
175///
176/// # Errors
177///
178/// See [`Decider::decide_among`].
179///
180/// # Example
181///
182/// See the [module documentation](self).
183pub async fn decide<T: Choice>(model: Arc<dyn Llm>, input: &str) -> Result<Decision<T>> {
184    Decider::new(model).decide(input).await
185}
186
187/// Makes typed decisions with a model: an instruction, an optional explicit
188/// [`ModelCallScope`], and an output cap.
189///
190/// Without [`with_scope`](Self::with_scope) a call is metered against the scope current
191/// when it runs ([`ModelCallScope::within`]), as `LlmAgent` tools and workflow agents set
192/// it, and runs unmetered outside one.
193///
194/// # Example
195///
196/// ```rust,no_run
197/// use std::sync::Arc;
198///
199/// use adk_core::{ChoiceOption, Decider, Llm};
200///
201/// async fn triage(model: Arc<dyn Llm>, ticket: &str) -> adk_core::Result<String> {
202///     let options = [
203///         ChoiceOption::new("urgent", "Production is down or data is at risk"),
204///         ChoiceOption::new("normal", "Everything else"),
205///     ];
206///     let decision = Decider::new(model)
207///         .with_instruction("Triage the support ticket.")
208///         .decide_among(&options, ticket)
209///         .await?;
210///     Ok(decision.choice)
211/// }
212/// ```
213#[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
231/// The decision code of a reply that names no option.
232const INVALID_CHOICE: &str = "decision.invalid_choice";
233
234impl Decider {
235    /// A decider that asks `model`.
236    pub fn new(model: Arc<dyn Llm>) -> Self {
237        Self { model, instruction: None, scope: None, max_output_tokens: None }
238    }
239
240    /// What to decide and how, shown to the model before the options; by default "Decide
241    /// which option fits the input best."
242    #[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    /// Meters every call against `scope`, whether or not another scope is current.
249    #[must_use]
250    pub fn with_scope(mut self, scope: ModelCallScope) -> Self {
251        self.scope = Some(scope);
252        self
253    }
254
255    /// Caps the reply; by default the provider's limit applies, which leaves room for models
256    /// that count thinking against it.
257    #[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    /// Decides one value of `T` about `input`.
264    ///
265    /// # Errors
266    ///
267    /// See [`decide_among`](Self::decide_among); also `decision.invalid_options` when
268    /// [`Choice::from_option`] does not map one of `T`'s own option names.
269    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    /// Decides one of `options` about `input`; the decision's choice is the option's name.
281    ///
282    /// # Errors
283    ///
284    /// Returns `decision.invalid_options` when `options` is empty or repeats or leaves out a
285    /// name, `decision.invalid_choice` when the reply names no option, and the model's error
286    /// when the call fails or is refused, such as an exhausted run budget.
287    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
364/// The response schema of a decision, in the subset every provider's structured output
365/// accepts: no numeric bounds, every property required, closed objects.
366fn 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
380/// The option `answer` names: exactly, else ignoring case and the quotes, backticks and
381/// trailing period a model may wrap a name in.
382fn 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
390/// The first JSON object in `text`: the whole text, a fenced block, or the first balanced
391/// braces in prose.
392fn 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
423/// Reads the decision in `reply`: its JSON object, or a reply that is only an option's name.
424fn 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        // A provider that ignores the schema may answer with the bare name.
437        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}