Skip to main content

gemini_adk_rs/flow/
decided.rs

1//! The `decided` guard atom: a guard on what a decision model concluded about
2//! the conversation, rather than on a state key something else wrote.
3//!
4//! A question is declared once (see [`crate::decision::Decisions`]); a guard
5//! names it and what it expects:
6//!
7//! | JSON | Holds when |
8//! |---|---|
9//! | `{"decided": "confirmed"}` | a boolean was answered yes, a choice picked an option, a score was given |
10//! | `{"decided": {"confirmed": false}}` | a boolean was answered no, or a choice picked "none of these" |
11//! | `{"decided": {"next_step": "book"}}` | a choice picked `book` |
12//! | `{"decided": {"frustration": {"at_least": 2}}}` | a score of 2 or more |
13//! | `{"decided": {"frustration": {"at_most": 1}}}` | a score of 1 or less |
14//!
15//! The runtime asks the questions the flow can act on at each decision point
16//! (the caller's turn ends, or the model calls a tool) and records each answer
17//! under `decision:{id}` with the caller turn it was about. An answer counts
18//! only for that turn: a yes given three turns ago does not satisfy a guard
19//! now, so nothing has to be latched or cleared. An unsure answer satisfies
20//! no expectation.
21
22use serde::{Deserialize, Deserializer, Serialize, Serializer};
23use serde_json::{Value, json};
24
25use crate::state::State;
26
27/// Prefix of the state keys answers are recorded under.
28pub const DECISION_PREFIX: &str = "decision:";
29/// The state key holding the caller turn answers are currently about.
30pub const DECISION_TURN_KEY: &str = "decision:turn";
31
32/// The state key an answer to `question` is recorded under.
33pub fn decision_key(question: &str) -> String {
34    format!("{DECISION_PREFIX}{question}")
35}
36
37/// What a `decided` guard expects of an answer.
38#[derive(Clone, Debug, PartialEq)]
39pub enum Expect {
40    /// A boolean answered yes, a choice that picked an option, or any score.
41    Yes,
42    /// A boolean answered no, or a choice that picked "none of these".
43    No,
44    /// A choice that picked this option.
45    Is(String),
46    /// A score of at least this.
47    AtLeast(f64),
48    /// A score of at most this.
49    AtMost(f64),
50}
51
52/// A guard on a decision: the question's id and what is expected.
53#[derive(Clone, Debug, PartialEq)]
54pub struct Decided {
55    /// The question's id in the decision bank.
56    pub question: String,
57    /// What the answer must be.
58    pub expect: Expect,
59}
60
61/// How an answer came out.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum Outcome {
65    /// A boolean answered yes.
66    Yes,
67    /// A boolean answered no.
68    No,
69    /// A choice picked an option.
70    Chosen,
71    /// A choice picked "none of these".
72    None,
73    /// A score was given.
74    Scored,
75    /// Not sure enough to decide, refused, or the model could not be asked.
76    Unsure,
77}
78
79/// An answer as recorded in state under [`decision_key`].
80#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
81pub struct DecisionRecord {
82    /// How it came out.
83    pub outcome: Outcome,
84    /// The chosen option's key (choice), or the score.
85    #[serde(default, skip_serializing_if = "Value::is_null")]
86    pub value: Value,
87    /// `P(true)` for a boolean, the certainty for a choice or score.
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub confidence: Option<f64>,
90    /// The caller turn the answer is about (see [`DECISION_TURN_KEY`]).
91    pub turn: String,
92}
93
94impl DecisionRecord {
95    /// The record for `question` in `state`, if it is about the current
96    /// caller turn.
97    pub fn current(state: &State, question: &str) -> Option<Self> {
98        let record: Self = state.get(&decision_key(question))?;
99        let turn: String = state.get(DECISION_TURN_KEY)?;
100        (record.turn == turn).then_some(record)
101    }
102}
103
104impl Decided {
105    /// Whether the current answer meets the expectation.
106    pub fn holds(&self, state: &State) -> bool {
107        let Some(record) = DecisionRecord::current(state, &self.question) else {
108            return false;
109        };
110        match (&self.expect, record.outcome) {
111            (Expect::Yes, Outcome::Yes | Outcome::Chosen | Outcome::Scored) => true,
112            (Expect::No, Outcome::No | Outcome::None) => true,
113            (Expect::Is(option), Outcome::Chosen) => record.value.as_str() == Some(option),
114            (Expect::AtLeast(x), Outcome::Scored) => record.value.as_f64().is_some_and(|s| s >= *x),
115            (Expect::AtMost(x), Outcome::Scored) => record.value.as_f64().is_some_and(|s| s <= *x),
116            _ => false,
117        }
118    }
119
120    /// The guard as a prose clause, for a refusal the model reads.
121    pub fn describe(&self) -> String {
122        let q = &self.question;
123        match &self.expect {
124            Expect::Yes => format!("the caller's latest words must settle '{q}'"),
125            Expect::No => format!("the caller's latest words must rule out '{q}'"),
126            Expect::Is(o) => format!("the caller's latest words must settle '{q}' as '{o}'"),
127            Expect::AtLeast(x) => format!("'{q}' must be at least {x}"),
128            Expect::AtMost(x) => format!("'{q}' must be at most {x}"),
129        }
130    }
131
132    fn to_value(&self) -> Value {
133        let expect = match &self.expect {
134            Expect::Yes => return Value::String(self.question.clone()),
135            Expect::No => json!(false),
136            Expect::Is(o) => json!(o),
137            Expect::AtLeast(x) => json!({ "at_least": x }),
138            Expect::AtMost(x) => json!({ "at_most": x }),
139        };
140        json!({ self.question.clone(): expect })
141    }
142
143    fn from_value(value: Value) -> Result<Self, String> {
144        match value {
145            Value::String(question) => Ok(Self {
146                question,
147                expect: Expect::Yes,
148            }),
149            Value::Object(map) => {
150                let mut entries = map.iter();
151                let (Some((question, expect)), None) = (entries.next(), entries.next()) else {
152                    return Err(format!(
153                        "decided takes a question id, or one {{question: expectation}} entry, not {}",
154                        Value::Object(map)
155                    ));
156                };
157                let question = question.clone();
158                let expect = match expect {
159                    Value::Bool(true) => Expect::Yes,
160                    Value::Bool(false) => Expect::No,
161                    Value::String(o) => Expect::Is(o.clone()),
162                    Value::Object(bound) => match (
163                        bound.get("at_least").and_then(Value::as_f64),
164                        bound.get("at_most").and_then(Value::as_f64),
165                    ) {
166                        (Some(x), None) if bound.len() == 1 => Expect::AtLeast(x),
167                        (None, Some(x)) if bound.len() == 1 => Expect::AtMost(x),
168                        _ => {
169                            return Err(format!(
170                                "decided '{question}': a score bound is {{\"at_least\": n}} or {{\"at_most\": n}}"
171                            ));
172                        }
173                    },
174                    other => {
175                        return Err(format!(
176                            "decided '{question}': expected true, false, an option or a score bound, not {other}"
177                        ));
178                    }
179                };
180                Ok(Self { question, expect })
181            }
182            other => Err(format!(
183                "decided takes a question id, or one {{question: expectation}} entry, not {other}"
184            )),
185        }
186    }
187}
188
189impl Serialize for Decided {
190    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
191        self.to_value().serialize(s)
192    }
193}
194
195impl<'de> Deserialize<'de> for Decided {
196    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
197        Self::from_value(Value::deserialize(d)?).map_err(serde::de::Error::custom)
198    }
199}
200
201impl schemars::JsonSchema for Decided {
202    fn schema_name() -> String {
203        "Decided".to_string()
204    }
205    fn json_schema(generator: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
206        #[derive(schemars::JsonSchema)]
207        #[serde(untagged)]
208        #[allow(
209            dead_code,
210            reason = "variants exist only to derive the JSON schema; never constructed"
211        )]
212        enum Bound {
213            AtLeast { at_least: f64 },
214            AtMost { at_most: f64 },
215        }
216        #[derive(schemars::JsonSchema)]
217        #[serde(untagged)]
218        #[allow(
219            dead_code,
220            reason = "variants exist only to derive the JSON schema; never constructed"
221        )]
222        enum Expectation {
223            /// `true` (yes) or `false` (no).
224            Boolean(bool),
225            /// A choice's option.
226            Option(String),
227            /// A score bound.
228            Score(Bound),
229        }
230        /// A question id (yes, picked, or scored), or one
231        /// `{question: expectation}` entry.
232        #[derive(schemars::JsonSchema)]
233        #[serde(untagged)]
234        #[allow(
235            dead_code,
236            reason = "variants exist only to derive the JSON schema; never constructed"
237        )]
238        enum DecidedSchema {
239            Question(String),
240            Expecting(std::collections::BTreeMap<String, Expectation>),
241        }
242        DecidedSchema::json_schema(generator)
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    fn record(state: &State, question: &str, outcome: Outcome, value: Value, turn: &str) {
251        let _ = state.set(
252            decision_key(question),
253            serde_json::to_value(DecisionRecord {
254                outcome,
255                value,
256                confidence: None,
257                turn: turn.into(),
258            })
259            .unwrap(),
260        );
261    }
262
263    #[test]
264    fn json_forms_round_trip() {
265        for (json, expect) in [
266            (json!("confirmed"), Expect::Yes),
267            (json!({ "confirmed": true }), Expect::Yes),
268            (json!({ "confirmed": false }), Expect::No),
269            (json!({ "next": "book" }), Expect::Is("book".into())),
270            (json!({ "anger": { "at_least": 2 } }), Expect::AtLeast(2.0)),
271            (json!({ "anger": { "at_most": 1 } }), Expect::AtMost(1.0)),
272        ] {
273            let d: Decided = serde_json::from_value(json.clone()).unwrap();
274            assert_eq!(d.expect, expect, "{json}");
275            let back: Decided = serde_json::from_value(serde_json::to_value(&d).unwrap()).unwrap();
276            assert_eq!(back, d);
277        }
278        assert!(serde_json::from_value::<Decided>(json!({ "a": 1, "b": 2 })).is_err());
279        assert!(serde_json::from_value::<Decided>(json!({ "a": { "over": 2 } })).is_err());
280        assert!(serde_json::from_value::<Decided>(json!(3)).is_err());
281    }
282
283    #[test]
284    fn an_answer_counts_only_for_its_turn() {
285        let state = State::new();
286        let yes = Decided {
287            question: "confirmed".into(),
288            expect: Expect::Yes,
289        };
290        assert!(!yes.holds(&state), "never asked");
291        let _ = state.set(DECISION_TURN_KEY, "t1");
292        record(&state, "confirmed", Outcome::Yes, Value::Null, "t1");
293        assert!(yes.holds(&state));
294        let _ = state.set(DECISION_TURN_KEY, "t2");
295        assert!(
296            !yes.holds(&state),
297            "a yes from an earlier turn is not a yes now"
298        );
299    }
300
301    #[test]
302    fn expectations_match_outcomes() {
303        let state = State::new();
304        let _ = state.set(DECISION_TURN_KEY, "t");
305        let d = |q: &str, expect| Decided {
306            question: q.into(),
307            expect,
308        };
309        record(&state, "ok", Outcome::No, Value::Null, "t");
310        assert!(d("ok", Expect::No).holds(&state));
311        assert!(!d("ok", Expect::Yes).holds(&state));
312
313        record(&state, "pick", Outcome::Chosen, json!("book"), "t");
314        assert!(d("pick", Expect::Yes).holds(&state));
315        assert!(d("pick", Expect::Is("book".into())).holds(&state));
316        assert!(!d("pick", Expect::Is("stay".into())).holds(&state));
317
318        record(&state, "none", Outcome::None, Value::Null, "t");
319        assert!(d("none", Expect::No).holds(&state));
320        assert!(!d("none", Expect::Yes).holds(&state));
321
322        record(&state, "anger", Outcome::Scored, json!(2.4), "t");
323        assert!(d("anger", Expect::AtLeast(2.0)).holds(&state));
324        assert!(!d("anger", Expect::AtMost(2.0)).holds(&state));
325
326        record(&state, "unsure", Outcome::Unsure, Value::Null, "t");
327        for e in [Expect::Yes, Expect::No] {
328            assert!(!d("unsure", e).holds(&state), "unsure satisfies nothing");
329        }
330    }
331}