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::Driver;
5use crate::{LibsyError, Result};
6use async_trait::async_trait;
7use switchyard_protocol::{Request, Response};
8
9/// One classifier's recommendation of a routing `target`, with a `[0.0, 1.0]` confidence.
10#[derive(Debug, Clone, PartialEq)]
11pub struct Score {
12    /// `[0.0, 1.0]` confidence in `target`.
13    pub confidence: f64,
14    /// The target (model / tier) being recommended.
15    pub target: String,
16}
17
18/// A classifier's verdict for a request: a set of target [`Score`]s, flagged by how
19/// confident the classifier is that they are decisive.
20pub enum Classification {
21    /// Definite recommendations; [`argmax`](Self::argmax) always yields the top target.
22    Scores(Vec<Score>),
23    /// Recommendations the classifier considers ambiguous; [`argmax`](Self::argmax) yields
24    /// nothing unless the caller opts to ignore ambiguity.
25    Ambiguous(Vec<Score>),
26}
27
28impl Classification {
29    /// The top-scoring [`Score`], or `None` when the classifier abstained (an empty set).
30    ///
31    /// An [`Ambiguous`](Self::Ambiguous) classification also yields `None` unless
32    /// `ignore_ambiguous` is set, in which case it falls back to the plain argmax.
33    /// Errors if any confidence is `NaN` (an unorderable score the caller should surface).
34    pub fn argmax(&self, ignore_ambiguous: bool) -> Result<Option<Score>> {
35        match self {
36            Classification::Scores(scores) => argmax(scores),
37            Classification::Ambiguous(scores) => {
38                if ignore_ambiguous {
39                    argmax(scores)
40                } else {
41                    Ok(None)
42                }
43            }
44        }
45    }
46}
47
48/// The highest-confidence score, or `None` when the set is empty (the classifier abstained).
49/// Ties keep the first. Errors on a `NaN` confidence,
50/// which has no defined ordering.
51fn argmax(scores: &[Score]) -> Result<Option<Score>> {
52    let mut best: Option<&Score> = None;
53    for score in scores.iter() {
54        if score.confidence.is_nan() {
55            return Err(LibsyError::AlgorithmError {
56                message: format!(
57                    "classifier returned NaN confidence for target {:?}",
58                    score.target
59                ),
60            });
61        }
62        match best {
63            Some(cur_best) if score.confidence > cur_best.confidence => best = Some(score),
64            None => best = Some(score),
65            _ => {}
66        }
67    }
68    Ok(best.cloned())
69}
70
71/// Scores targets from the current request and the composition's state.
72#[async_trait]
73pub trait Classifier<S = ()>: Send + Sync {
74    /// Stable tier represented by `selected_model`, when this classifier defines one.
75    fn routing_tier(&self, _selected_model: &str) -> Option<&'static str> {
76        None
77    }
78
79    /// Score the classifier's targets given the current state and request.
80    ///
81    /// When present, `driver` lets a classifier offload model calls. It is `None`
82    /// when the classifier is evaluated outside an algorithm run.
83    ///
84    /// `request` is borrowed mutably so a classifier may rewrite it in place — inject a
85    /// system prompt, drop tools, compact history. The edit is not scoped to this call:
86    /// later classifiers in the cascade score the rewritten request, and it is the
87    /// rewritten request that is finally sent to the selected model. Most classifiers
88    /// only read it.
89    async fn score(
90        &self,
91        state: &mut S,
92        request: &mut Request,
93        driver: Option<&Driver>,
94    ) -> Result<(Classification, Option<Response>)>;
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use switchyard_protocol::text_request;
101
102    /// Terse `Score` builder for the assertions below.
103    fn score(target: &str, confidence: f64) -> Score {
104        Score {
105            target: target.to_string(),
106            confidence,
107        }
108    }
109
110    #[test]
111    fn argmax_picks_the_highest_confidence_score() -> Result<()> {
112        let scores = vec![score("weak", 0.2), score("strong", 0.9), score("mid", 0.5)];
113        let best = Classification::Scores(scores).argmax(false)?;
114        assert_eq!(best, Some(score("strong", 0.9)));
115        Ok(())
116    }
117
118    #[test]
119    fn argmax_breaks_ties_by_cascade_order() -> Result<()> {
120        // Equal confidence: the earlier target in cascade order wins the tie.
121        let scores = vec![score("first", 0.7), score("second", 0.7)];
122        let best = Classification::Scores(scores).argmax(false)?;
123        assert_eq!(best.map(|s| s.target), Some("first".to_string()));
124        Ok(())
125    }
126
127    #[test]
128    fn argmax_on_an_empty_set_abstains() -> Result<()> {
129        // No scores means the classifier abstained — no choice to make.
130        assert_eq!(Classification::Scores(vec![]).argmax(false)?, None);
131        assert_eq!(Classification::Ambiguous(vec![]).argmax(true)?, None);
132        Ok(())
133    }
134
135    #[test]
136    fn argmax_errors_on_nan_confidence() {
137        // A NaN confidence has no defined ordering — surface it rather than guess.
138        let scores = vec![score("weak", 0.3), score("strong", f64::NAN)];
139        assert!(matches!(
140            Classification::Scores(scores).argmax(false),
141            Err(LibsyError::AlgorithmError { message })
142                if message == "classifier returned NaN confidence for target \"strong\""
143        ));
144        // A lone NaN errors too, even with nothing to compare it against.
145        assert!(matches!(
146            Classification::Scores(vec![score("only", f64::NAN)]).argmax(false),
147            Err(LibsyError::AlgorithmError { message })
148                if message == "classifier returned NaN confidence for target \"only\""
149        ));
150    }
151
152    #[test]
153    fn ambiguous_without_ignore_makes_no_choice() -> Result<()> {
154        // Ambiguous means "don't pick" unless the caller opts to ignore ambiguity.
155        let scores = vec![score("strong", 0.9)];
156        assert_eq!(Classification::Ambiguous(scores).argmax(false)?, None);
157        Ok(())
158    }
159
160    #[test]
161    fn ambiguous_with_ignore_falls_back_to_argmax() -> Result<()> {
162        let scores = vec![score("weak", 0.3), score("strong", 0.8)];
163        let best = Classification::Ambiguous(scores).argmax(true)?;
164        assert_eq!(best, Some(score("strong", 0.8)));
165        Ok(())
166    }
167
168    #[test]
169    fn scores_variant_ignores_the_ambiguous_flag() -> Result<()> {
170        // A definitive classification always yields its argmax, regardless of the flag.
171        let scores = vec![score("a", 0.4), score("b", 0.6)];
172        let with_ignore = Classification::Scores(scores.clone()).argmax(true)?;
173        let without_ignore = Classification::Scores(scores).argmax(false)?;
174        assert_eq!(with_ignore, without_ignore);
175        assert_eq!(with_ignore, Some(score("b", 0.6)));
176        Ok(())
177    }
178
179    /// Scores the request's requested model at full confidence and records that it ran.
180    struct RecordingClassifier;
181
182    #[async_trait]
183    impl Classifier<bool> for RecordingClassifier {
184        async fn score(
185            &self,
186            state: &mut bool,
187            request: &mut Request,
188            _driver: Option<&Driver>,
189        ) -> Result<(Classification, Option<Response>)> {
190            *state = true;
191            let target = request.requested_model().unwrap_or("auto").to_string();
192            Ok((
193                Classification::Scores(vec![Score {
194                    target,
195                    confidence: 1.0,
196                }]),
197                None,
198            ))
199        }
200    }
201
202    #[tokio::test]
203    async fn classifier_reads_request_and_mutates_state() -> Result<()> {
204        let mut state = false;
205        let mut request = Request {
206            llm_request: text_request(Some("strong".to_string()), "hi"),
207            raw_request: None,
208            metadata: None,
209        };
210        // A `None` driver is valid: the classifier scored without offloading a model call.
211        let (classification, _) = RecordingClassifier
212            .score(&mut state, &mut request, None)
213            .await?;
214        assert_eq!(
215            classification.argmax(false)?.map(|s| s.target),
216            Some("strong".to_string())
217        );
218        assert!(state);
219        Ok(())
220    }
221
222    /// Rewrites the request's model, then scores the rewritten value.
223    struct RewritingClassifier;
224
225    #[async_trait]
226    impl Classifier for RewritingClassifier {
227        async fn score(
228            &self,
229            _state: &mut (),
230            request: &mut Request,
231            _driver: Option<&Driver>,
232        ) -> Result<(Classification, Option<Response>)> {
233            request.llm_request.model = Some("rewritten".to_string());
234            Ok((
235                Classification::Scores(vec![Score {
236                    target: "rewritten".to_string(),
237                    confidence: 1.0,
238                }]),
239                None,
240            ))
241        }
242    }
243
244    #[tokio::test]
245    async fn classifier_rewrites_the_request_in_place() -> Result<()> {
246        let mut state = ();
247        let mut request = Request {
248            llm_request: text_request(Some("auto".to_string()), "hi"),
249            raw_request: None,
250            metadata: None,
251        };
252
253        RewritingClassifier
254            .score(&mut state, &mut request, None)
255            .await?;
256
257        // The rewrite outlives the call: later classifiers in the cascade score this value,
258        // and it is what reaches the model.
259        assert_eq!(request.requested_model(), Some("rewritten"));
260        Ok(())
261    }
262}