Skip to main content

switchyard_libsy/algorithms/llm_class/
decision.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Compare two candidates by the chance that the capable candidate alone succeeds.
5
6use std::collections::{BTreeMap, HashSet};
7
8use async_trait::async_trait;
9use serde_json::{Value, json};
10use switchyard_protocol::{
11    Category, ChoiceOption, DecisionKind, DecisionQuestion, DecisionRequest, DecisionValue,
12    ModelId, Request, Response,
13};
14
15use crate::algorithms::llm_class::TaskInput;
16use crate::algorithms::util::llm_judge::{libsy_error_reason, report_fail_open};
17use crate::algorithms::util::robustness::safe_error_summary;
18use crate::{Classification, Classifier, Driver, LibsyError, Result, Score, State};
19
20/// Evidence and policy for a relative-advantage decision judge.
21///
22/// Candidate labels keep model names out of the generated context. Evidence must use
23/// the same labels, with unknown outcomes left unknown. Only the first runtime
24/// capable and efficient targets are compared; extra candidates do not add routes.
25#[derive(Clone, Debug)]
26pub struct DecisionJudgeConfig {
27    /// Route capable only when its advantage score is strictly above this cutoff.
28    /// This score is not a calibrated solve probability. Choose a cutoff from evaluations.
29    pub cutoff: f64,
30    /// Replaces the packaged structured instructions; must keep the meaning of
31    /// `advantage` (capable succeeds and efficient fails) and `no_advantage`.
32    pub instructions: Option<Value>,
33    /// Maps anonymous labels used in evidence (e.g. `"a"`) to runtime model IDs.
34    /// Every compared target needs a unique label; extra candidates provide context.
35    pub candidates: BTreeMap<String, ModelId>,
36    /// JSON passed unchanged to the judge, such as candidate descriptions, reference
37    /// cases, outcome/cost summaries, and selection notes. The judge interprets it
38    /// using the instructions; the router neither reads its fields nor derives statistics.
39    pub evidence: Value,
40}
41
42impl DecisionJudgeConfig {
43    pub(super) fn validate(&self) -> Result<()> {
44        if !(0.0..=1.0).contains(&self.cutoff) {
45            return Err(LibsyError::AlgorithmError {
46                message: "decision cutoff must be between 0 and 1".into(),
47            });
48        }
49        if self.candidates.values().collect::<HashSet<_>>().len() != self.candidates.len() {
50            return Err(LibsyError::AlgorithmError {
51                message: "decision candidates must map to distinct targets".into(),
52            });
53        }
54        Ok(())
55    }
56
57    fn candidate(&self, model: &ModelId) -> Result<&str> {
58        self.candidates
59            .iter()
60            .find(|(_, target)| *target == model)
61            .map(|(id, _)| id.as_str())
62            .ok_or_else(|| LibsyError::AlgorithmError {
63                message: format!("decision candidate is missing for target {model}"),
64            })
65    }
66}
67
68pub(super) struct DecisionClassifier {
69    config: DecisionJudgeConfig,
70    input: TaskInput,
71    fail_open: bool,
72    question: DecisionQuestion,
73}
74
75impl DecisionClassifier {
76    pub(super) fn new(
77        mut config: DecisionJudgeConfig,
78        input: TaskInput,
79        fail_open: bool,
80    ) -> Result<Self> {
81        let instructions = match config.instructions.take() {
82            Some(instructions) => instructions,
83            None => serde_json::from_str(include_str!(
84                "../../prompts/capability-classifier/relative_advantage.json"
85            ))
86            .map_err(|error| LibsyError::external("loading decision judge instructions", error))?,
87        };
88        let question = DecisionQuestion {
89            instructions,
90            kind: DecisionKind::Choice {
91                options: [
92                    ("advantage", "The capable candidate succeeds AND the efficient candidate fails."),
93                    ("no_advantage", "The efficient candidate succeeds OR the capable candidate fails, including shared failure."),
94                ]
95                .into_iter()
96                .map(|(id, description)| ChoiceOption {
97                    id: id.into(),
98                    description: Some(json!(description)),
99                })
100                .collect(),
101            },
102        };
103        Ok(Self {
104            config,
105            input,
106            fail_open,
107            question,
108        })
109    }
110}
111
112#[async_trait]
113impl Classifier for DecisionClassifier {
114    fn max_pool_targets(&self) -> Option<usize> {
115        Some(2)
116    }
117
118    async fn score(
119        &self,
120        _state: &mut State,
121        request: &mut Request,
122        driver: &Driver,
123    ) -> Result<(Classification, Option<Response>)> {
124        let judge = driver.first_model_for(&Category::Judge)?;
125        let capable = driver.first_model_for(&Category::Capable)?;
126        let efficient = driver.first_model_for(&Category::Efficient)?;
127        let decision = DecisionRequest {
128            model: None,
129            context: json!({
130                "task": self.input.messages(request),
131                "session": request.metadata.as_ref().and_then(|m| m.session_id.as_deref()),
132                "candidates": self.config.candidates.keys().collect::<Vec<_>>(),
133                "comparison": {
134                    "capable": self.config.candidate(capable)?,
135                    "efficient": self.config.candidate(efficient)?,
136                },
137                "evidence": self.config.evidence,
138            }),
139            questions: BTreeMap::from([("route".into(), self.question.clone())]),
140        };
141        let response = match driver.call_decision(decision, judge.clone()).await {
142            Ok(response) => response,
143            Err(error) if self.fail_open => {
144                return Ok(unavailable(
145                    driver,
146                    judge,
147                    safe_error_summary(&error),
148                    libsy_error_reason(&error),
149                ));
150            }
151            Err(error) => return Err(error),
152        };
153        // The provider's selected option can differ from the application's cutoff.
154        // Only the requested event's score is used; confidence is a separate signal.
155        let advantage = response
156            .answers
157            .get("route")
158            .and_then(|answer| match &answer.value {
159                DecisionValue::Choice {
160                    probabilities: Some(probabilities),
161                    ..
162                } => probabilities.get("advantage").map(|p| p.0),
163                _ => None,
164            })
165            .filter(|p| (0.0..=1.0).contains(p));
166        let Some(advantage) = advantage else {
167            return Ok(unavailable(
168                driver,
169                judge,
170                "missing or invalid advantage score".into(),
171                "invalid_verdict",
172            ));
173        };
174        let (target, category) = if advantage > self.config.cutoff {
175            (capable, Category::Capable)
176        } else {
177            (efficient, Category::Efficient)
178        };
179        driver.set_evidence(json!({
180            "source": "decision_classifier",
181            "verdict": "relative_advantage",
182            "score": advantage,
183            "threshold": self.config.cutoff,
184        }));
185        Ok((
186            Classification::Scores(vec![Score {
187                target: target.clone(),
188                confidence: 1.0,
189                category: Some(category),
190            }]),
191            None,
192        ))
193    }
194}
195
196fn unavailable(
197    driver: &Driver,
198    judge: &ModelId,
199    error: String,
200    reason: &'static str,
201) -> (Classification, Option<Response>) {
202    report_fail_open(judge.as_str(), error, reason);
203    driver.set_evidence_if_empty(json!({"source": "fail_open", "reason_code": reason}));
204    (Classification::Ambiguous(vec![]), None)
205}