Skip to main content

switchyard_libsy/core/
classifier.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::core::algorithm::{AnswerSummary, Driver};
5use crate::core::state::State;
6use crate::{LibsyError, Result};
7use async_trait::async_trait;
8use switchyard_protocol::{Category, ModelId, Request, Response};
9
10/// One classifier's recommendation of a routing `target`, with a `[0.0, 1.0]` confidence.
11#[derive(Debug, Clone, PartialEq)]
12pub struct Score {
13    /// `[0.0, 1.0]` confidence in `target`.
14    pub confidence: f64,
15    /// The target (model / tier) being recommended.
16    pub target: ModelId,
17    /// The category `target` was drawn from, when the classifier picked one. The rest of
18    /// that category is what the turn falls through on failure. A decision made without
19    /// a category leaves this `None`.
20    pub category: Option<Category>,
21}
22
23/// A classifier's verdict for a request: a set of target [`Score`]s, flagged by how
24/// confident the classifier is that they are decisive.
25pub enum Classification {
26    /// Definite recommendations; [`argmax`](Self::argmax) always yields the top target.
27    Scores(Vec<Score>),
28    /// Recommendations the classifier considers ambiguous; [`argmax`](Self::argmax) yields
29    /// nothing unless the caller opts to ignore ambiguity.
30    Ambiguous(Vec<Score>),
31}
32
33impl Classification {
34    /// The top-scoring [`Score`], or `None` when the classifier abstained (an empty set).
35    ///
36    /// An [`Ambiguous`](Self::Ambiguous) classification also yields `None` unless
37    /// `ignore_ambiguous` is set, in which case it falls back to the plain argmax.
38    /// Errors if any confidence is non-finite or outside `[0, 1]`, including ambiguous verdicts.
39    pub fn argmax(&self, ignore_ambiguous: bool) -> Result<Option<Score>> {
40        let scores = match self {
41            Self::Scores(scores) | Self::Ambiguous(scores) => scores,
42        };
43        let best = argmax(scores)?;
44        Ok(if matches!(self, Self::Ambiguous(_)) && !ignore_ambiguous {
45            None
46        } else {
47            best
48        })
49    }
50}
51
52/// The highest-confidence score, or `None` when the set is empty (the classifier abstained).
53/// Ties keep the first. Confidence must be finite and within `[0, 1]`.
54fn argmax(scores: &[Score]) -> Result<Option<Score>> {
55    let mut best: Option<&Score> = None;
56    for score in scores.iter() {
57        if score.confidence.is_nan() {
58            return Err(LibsyError::AlgorithmError {
59                message: format!(
60                    "classifier returned NaN confidence for target {:?}",
61                    score.target
62                ),
63            });
64        }
65        if !score.confidence.is_finite() || !(0.0..=1.0).contains(&score.confidence) {
66            return Err(LibsyError::AlgorithmError {
67                message: format!(
68                    "classifier confidence for target {:?} must be finite and between 0 and 1, got {}",
69                    score.target, score.confidence
70                ),
71            });
72        }
73        match best {
74            Some(cur_best) if score.confidence > cur_best.confidence => best = Some(score),
75            None => best = Some(score),
76            _ => {}
77        }
78    }
79    Ok(best.cloned())
80}
81
82/// Optional scalar output for classifiers that use a configured target pool.
83pub enum ClassifierOutput {
84    /// An existing target-based verdict, passed through unchanged.
85    Decision(Classification),
86    /// A position on the configured score line.
87    Position {
88        /// Finite value in `[0, 1]`.
89        value: f64,
90        /// Confidence in this recommendation.
91        confidence: f64,
92        /// Continue to the next classifier when true.
93        ambiguous: bool,
94    },
95}
96
97impl ClassifierOutput {
98    /// Resolve a clear position once; preserve target decisions and abstention.
99    pub fn resolve(&self, driver: &Driver) -> Result<Option<Score>> {
100        match self {
101            Self::Decision(decision) => decision.argmax(false),
102            Self::Position {
103                value,
104                confidence,
105                ambiguous,
106            } => {
107                super::pool::validate_value(*value)?;
108                super::pool::validate_value(*confidence)?;
109                let pool = driver.pool().ok_or_else(|| LibsyError::AlgorithmError {
110                    message: "a scalar classifier output requires a target pool; configure a pool or return a target decision".into(),
111                })?;
112                if *ambiguous {
113                    return Ok(None);
114                }
115                Ok(Some(Score {
116                    target: pool.resolve(*value)?.clone(),
117                    confidence: *confidence,
118                    category: None,
119                }))
120            }
121        }
122    }
123}
124
125/// Scores targets from the current request and the composition's state.
126#[async_trait]
127pub trait Classifier: Send + Sync {
128    /// Maximum score-pool size this model-selection classifier supports, if limited.
129    /// Custom classifiers with binary policies should return `Some(2)`.
130    fn max_pool_targets(&self) -> Option<usize> {
131        None
132    }
133
134    /// Optionally emit a scalar position. Existing classifiers keep their target decisions.
135    async fn classify(
136        &self,
137        state: &mut State,
138        request: &mut Request,
139        driver: &Driver,
140    ) -> Result<(ClassifierOutput, Option<Response>)> {
141        let (decision, response) = self.score(state, request, driver).await?;
142        Ok((ClassifierOutput::Decision(decision), response))
143    }
144
145    /// Score the classifier's targets given the current state and request.
146    ///
147    /// `driver` lets a classifier inspect runtime models and offload model calls.
148    ///
149    /// `request` is borrowed mutably so a classifier may rewrite it in place — inject a
150    /// system prompt, drop tools, compact history. The edit is not scoped to this call:
151    /// later classifiers in the cascade score the rewritten request, and it is the
152    /// rewritten request that is finally sent to the selected model. Most classifiers
153    /// only read it.
154    async fn score(
155        &self,
156        state: &mut State,
157        request: &mut Request,
158        driver: &Driver,
159    ) -> Result<(Classification, Option<Response>)>;
160
161    /// Whether a stateful composition should request served-answer reports.
162    fn tracks_answers(&self) -> bool {
163        false
164    }
165
166    /// Folds the answer the host served for this session into the composition's state.
167    fn observe_answer(&self, _state: &mut State, _answer: AnswerSummary) {}
168}
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173    use crate::core::testing::empty_driver;
174    use switchyard_protocol::text_request;
175
176    #[test]
177    fn invalid_confidence_is_rejected_even_when_ambiguous() {
178        for confidence in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.1, 1.1] {
179            for decision in [
180                Classification::Scores(vec![score("strong", confidence)]),
181                Classification::Ambiguous(vec![score("strong", confidence)]),
182            ] {
183                assert!(
184                    decision.argmax(false).is_err(),
185                    "accepted confidence {confidence}"
186                );
187            }
188        }
189    }
190
191    #[test]
192    fn scalar_outputs_require_a_pool_and_validate_both_numbers() -> Result<()> {
193        let output = |value, confidence, ambiguous| ClassifierOutput::Position {
194            value,
195            confidence,
196            ambiguous,
197        };
198        assert!(output(0.5, 1.0, false).resolve(&empty_driver()).is_err());
199        assert!(output(0.5, 1.0, true).resolve(&empty_driver()).is_err());
200        let models =
201            crate::RuntimeModels::new([(Category::Any, vec!["a".into(), "b".into()])].into())
202                .with_pool(crate::TargetPool::new(
203                    vec!["a".into(), "b".into()],
204                    vec![],
205                )?)?;
206        let (driver, _) = Driver::new("test", std::sync::Arc::new(models));
207        assert_eq!(output(0.5, 1.0, true).resolve(&driver)?, None);
208        assert_eq!(
209            output(1.0, 1.0, false).resolve(&driver)?.unwrap().target,
210            "b"
211        );
212        for value in [f64::NAN, f64::INFINITY, -0.1, 1.1] {
213            for ambiguous in [false, true] {
214                assert!(output(value, 1.0, ambiguous).resolve(&driver).is_err());
215                assert!(output(0.5, value, ambiguous).resolve(&driver).is_err());
216            }
217        }
218        Ok(())
219    }
220
221    /// Terse `Score` builder for the assertions below.
222    fn score(target: &str, confidence: f64) -> Score {
223        Score {
224            target: ModelId::from(target),
225            confidence,
226            category: None,
227        }
228    }
229
230    #[test]
231    fn argmax_picks_the_highest_confidence_score() -> Result<()> {
232        let scores = vec![score("weak", 0.2), score("strong", 0.9), score("mid", 0.5)];
233        let best = Classification::Scores(scores).argmax(false)?;
234        assert_eq!(best, Some(score("strong", 0.9)));
235        Ok(())
236    }
237
238    #[test]
239    fn argmax_breaks_ties_by_cascade_order() -> Result<()> {
240        // Equal confidence: the earlier target in cascade order wins the tie.
241        let scores = vec![score("first", 0.7), score("second", 0.7)];
242        let best = Classification::Scores(scores).argmax(false)?;
243        assert_eq!(best.map(|s| s.target), Some(ModelId::from("first")));
244        Ok(())
245    }
246
247    #[test]
248    fn argmax_on_an_empty_set_abstains() -> Result<()> {
249        // No scores means the classifier abstained — no choice to make.
250        assert_eq!(Classification::Scores(vec![]).argmax(false)?, None);
251        assert_eq!(Classification::Ambiguous(vec![]).argmax(true)?, None);
252        Ok(())
253    }
254
255    #[test]
256    fn argmax_errors_on_nan_confidence() {
257        // A NaN confidence has no defined ordering — surface it rather than guess.
258        let scores = vec![score("weak", 0.3), score("strong", f64::NAN)];
259        assert!(matches!(
260            Classification::Scores(scores).argmax(false),
261            Err(LibsyError::AlgorithmError { message })
262                if message == "classifier returned NaN confidence for target \"strong\""
263        ));
264        // A lone NaN errors too, even with nothing to compare it against.
265        assert!(matches!(
266            Classification::Scores(vec![score("only", f64::NAN)]).argmax(false),
267            Err(LibsyError::AlgorithmError { message })
268                if message == "classifier returned NaN confidence for target \"only\""
269        ));
270    }
271
272    #[test]
273    fn ambiguous_without_ignore_makes_no_choice() -> Result<()> {
274        // Ambiguous means "don't pick" unless the caller opts to ignore ambiguity.
275        let scores = vec![score("strong", 0.9)];
276        assert_eq!(Classification::Ambiguous(scores).argmax(false)?, None);
277        Ok(())
278    }
279
280    #[test]
281    fn ambiguous_with_ignore_falls_back_to_argmax() -> Result<()> {
282        let scores = vec![score("weak", 0.3), score("strong", 0.8)];
283        let best = Classification::Ambiguous(scores).argmax(true)?;
284        assert_eq!(best, Some(score("strong", 0.8)));
285        Ok(())
286    }
287
288    #[test]
289    fn scores_variant_ignores_the_ambiguous_flag() -> Result<()> {
290        // A definitive classification always yields its argmax, regardless of the flag.
291        let scores = vec![score("a", 0.4), score("b", 0.6)];
292        let with_ignore = Classification::Scores(scores.clone()).argmax(true)?;
293        let without_ignore = Classification::Scores(scores).argmax(false)?;
294        assert_eq!(with_ignore, without_ignore);
295        assert_eq!(with_ignore, Some(score("b", 0.6)));
296        Ok(())
297    }
298
299    /// Scores the request's requested model at full confidence and records that it ran.
300    struct RecordingClassifier;
301
302    #[async_trait]
303    impl Classifier for RecordingClassifier {
304        async fn score(
305            &self,
306            state: &mut State,
307            request: &mut Request,
308            _driver: &Driver,
309        ) -> Result<(Classification, Option<Response>)> {
310            state
311                .extra
312                .insert("ran".to_string(), crate::core::state::StateValue::Count(1));
313            let target = request.model_id().unwrap_or(ModelId::from("auto"));
314            Ok((
315                Classification::Scores(vec![Score {
316                    target,
317                    confidence: 1.0,
318                    category: None,
319                }]),
320                None,
321            ))
322        }
323    }
324
325    #[tokio::test]
326    async fn classifier_reads_request_and_mutates_state() -> Result<()> {
327        let mut state = State::default();
328        let mut request = Request {
329            llm_request: text_request(Some("strong".to_string()), "hi"),
330            raw_request: None,
331            metadata: None,
332        };
333        let (classification, _) = RecordingClassifier
334            .score(&mut state, &mut request, &empty_driver())
335            .await?;
336        assert_eq!(
337            classification.argmax(false)?.map(|s| s.target),
338            Some(ModelId::from("strong"))
339        );
340        assert_eq!(
341            state.extra.get("ran"),
342            Some(&crate::core::state::StateValue::Count(1))
343        );
344        Ok(())
345    }
346
347    /// Rewrites the request's model, then scores the rewritten value.
348    struct RewritingClassifier;
349
350    #[async_trait]
351    impl Classifier for RewritingClassifier {
352        async fn score(
353            &self,
354            _state: &mut State,
355            request: &mut Request,
356            _driver: &Driver,
357        ) -> Result<(Classification, Option<Response>)> {
358            request.llm_request.model = Some("rewritten".to_string());
359            Ok((
360                Classification::Scores(vec![Score {
361                    target: ModelId::from("rewritten"),
362                    confidence: 1.0,
363                    category: None,
364                }]),
365                None,
366            ))
367        }
368    }
369
370    #[tokio::test]
371    async fn classifier_rewrites_the_request_in_place() -> Result<()> {
372        let mut state = State::default();
373        let mut request = Request {
374            llm_request: text_request(Some("auto".to_string()), "hi"),
375            raw_request: None,
376            metadata: None,
377        };
378
379        RewritingClassifier
380            .score(&mut state, &mut request, &empty_driver())
381            .await?;
382
383        // The rewrite outlives the call: later classifiers in the cascade score this value,
384        // and it is what reaches the model.
385        assert_eq!(request.model_id().as_deref(), Some("rewritten"));
386        Ok(())
387    }
388}