switchyard_libsy/algorithms/llm_class/
decision.rs1use 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::{ClassifierInput, 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#[derive(Clone, Debug)]
26pub struct DecisionJudgeConfig {
27 pub cutoff: f64,
30 pub instructions: Option<Value>,
33 pub candidates: BTreeMap<String, ModelId>,
36 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<State> for DecisionClassifier {
114 async fn score(
115 &self,
116 _state: &mut State,
117 request: &mut Request,
118 driver: &Driver,
119 ) -> Result<(Classification, Option<Response>)> {
120 self.input.validate_request(request)?;
121 let judge = driver.first_model_for(&Category::Judge)?;
122 let capable = driver.first_model_for(&Category::Capable)?;
123 let efficient = driver.first_model_for(&Category::Efficient)?;
124 let decision = DecisionRequest {
125 model: None,
126 context: json!({
127 "task": self.input.messages(request),
128 "candidates": self.config.candidates.keys().collect::<Vec<_>>(),
129 "comparison": {
130 "capable": self.config.candidate(capable)?,
131 "efficient": self.config.candidate(efficient)?,
132 },
133 "evidence": self.config.evidence,
134 }),
135 questions: BTreeMap::from([("route".into(), self.question.clone())]),
136 };
137 let response = match driver.call_decision(decision, judge.clone()).await {
138 Ok(response) => response,
139 Err(error) if self.fail_open => {
140 return Ok(unavailable(
141 driver,
142 judge,
143 safe_error_summary(&error),
144 libsy_error_reason(&error),
145 ));
146 }
147 Err(error) => return Err(error),
148 };
149 let advantage = response
152 .answers
153 .get("route")
154 .and_then(|answer| match &answer.value {
155 DecisionValue::Choice {
156 probabilities: Some(probabilities),
157 ..
158 } => probabilities.get("advantage").map(|p| p.0),
159 _ => None,
160 })
161 .filter(|p| (0.0..=1.0).contains(p));
162 let Some(advantage) = advantage else {
163 return Ok(unavailable(
164 driver,
165 judge,
166 "missing or invalid advantage score".into(),
167 "invalid_verdict",
168 ));
169 };
170 let (target, category) = if advantage > self.config.cutoff {
171 (capable, Category::Capable)
172 } else {
173 (efficient, Category::Efficient)
174 };
175 driver.set_evidence(json!({
176 "source": "decision_classifier",
177 "verdict": "relative_advantage",
178 "score": advantage,
179 "threshold": self.config.cutoff,
180 }));
181 Ok((
182 Classification::Scores(vec![Score {
183 target: target.clone(),
184 confidence: 1.0,
185 category: Some(category),
186 }]),
187 None,
188 ))
189 }
190}
191
192fn unavailable(
193 driver: &Driver,
194 judge: &ModelId,
195 error: String,
196 reason: &'static str,
197) -> (Classification, Option<Response>) {
198 report_fail_open(judge.as_str(), error, reason);
199 driver.set_evidence_if_empty(json!({"source": "fail_open", "reason_code": reason}));
200 (Classification::Ambiguous(vec![]), None)
201}