1use std::collections::{BTreeMap, BTreeSet};
7use std::sync::Arc;
8
9use serde::Deserialize;
10use serde_json::json;
11use switchyard_protocol::{
12 BooleanEstimate, Category, ContentBlock, DecisionKind, DecisionQuestion, DecisionRequest,
13 DecisionResponse, DecisionValue, LlmRequest, LlmResponse, Request, Response, Role, StopReason,
14 WireFormat, text_response,
15};
16
17use crate::{Algorithm, Driver, LibsyError, OutcomeMetadata, Result, RoutingOutcome};
18
19#[derive(Clone, Debug, Deserialize)]
21#[serde(deny_unknown_fields)]
22pub struct SelectionRule {
23 pub enabled: bool,
25 pub system_instruction: String,
27 pub catalog_prefix: String,
30 pub task_prefix: String,
32 pub task_suffix: String,
34 pub question: String,
36 #[serde(default)]
38 pub stop_words: BTreeSet<String>,
39 #[serde(default = "default_question_prefix")]
41 pub question_prefix: String,
42 pub shortlist: usize,
44 pub top_k: usize,
46}
47
48fn default_question_prefix() -> String {
49 "q".into()
50}
51
52pub struct DecisionSelect {
54 rule: SelectionRule,
55}
56
57struct Candidate {
58 name: String,
59 description: String,
60}
61
62impl DecisionSelect {
63 pub fn new(rule: SelectionRule) -> Result<Self> {
65 if [
66 &rule.system_instruction,
67 &rule.catalog_prefix,
68 &rule.task_prefix,
69 &rule.task_suffix,
70 &rule.question,
71 ]
72 .iter()
73 .any(|value| value.trim().is_empty())
74 || !(1..=512).contains(&rule.shortlist)
75 || !(1..=rule.shortlist).contains(&rule.top_k)
76 {
77 return Err(LibsyError::AlgorithmError {
78 message:
79 "selection requires nonempty prompt fields and 1 <= top_k <= shortlist <= 512"
80 .into(),
81 });
82 }
83 Ok(Self { rule })
84 }
85
86 fn extract<'a>(&self, request: &'a LlmRequest) -> Option<(&'a str, Vec<Candidate>)> {
87 let fields = &request.extensions.fields;
89 if fields.contains_key("previous_response_id")
90 || fields.contains_key("conversation")
91 || (request
92 .preservation
93 .requests
94 .contains_key(&WireFormat::OpenAiResponses.into())
95 && fields.get("store").and_then(serde_json::Value::as_bool) != Some(false))
96 {
97 return None;
98 }
99 let [system] = request.instructions.as_slice() else {
100 return None;
101 };
102 if system.role != Role::System
103 || plain_text(&system.content)? != self.rule.system_instruction
104 || !request.tools.is_empty()
105 || request.tool_choice.is_some()
106 || request.output.response_format.is_some()
107 || request.output.max_output_tokens.is_some()
108 || fields
109 .get("n")
110 .and_then(|n| n.as_u64())
111 .is_some_and(|n| n != 1)
112 || fields.get("logprobs").and_then(|v| v.as_bool()) == Some(true)
113 || ["stop", "stop_sequences", "modalities", "audio"]
114 .iter()
115 .any(|key| fields.get(*key).is_some_and(|v| !v.is_null()))
116 || request.is_compaction
117 {
118 return None;
119 }
120 let [first, .., last] = request.messages.as_slice() else {
121 return None;
122 };
123 if first.role != Role::User || last.role != Role::User {
124 return None;
125 }
126 let task = plain_text(&last.content)?
127 .strip_prefix(&self.rule.task_prefix)?
128 .strip_suffix(&self.rule.task_suffix)?;
129 let catalog = plain_text(&first.content)?.strip_prefix(&self.rule.catalog_prefix)?;
130 if task.trim().is_empty() || catalog.len() > 256 * 1024 {
131 return None;
132 }
133 let groups: yaml_serde::Mapping = yaml_serde::from_str(catalog).ok()?;
134 let mut options = Vec::new();
135 let mut names = BTreeSet::new();
136 let mut push = |name: String, description: &str| -> Option<()> {
137 if name.trim().is_empty() || name.contains(['\n', '\r']) || !names.insert(name.clone())
138 {
139 return None;
140 }
141 options.push(Candidate {
142 name,
143 description: description.into(),
144 });
145 Some(())
146 };
147 for (key, value) in &groups {
148 let key = key.as_str()?;
149 if let Some(description) = value.as_str() {
150 push(key.to_owned(), description)?;
151 } else {
152 for (name, description) in value.as_mapping()? {
153 push(format!("{key}.{}", name.as_str()?), description.as_str()?)?;
154 }
155 }
156 }
157 (!options.is_empty()).then_some((task, options))
158 }
159}
160
161fn plain_text(content: &[ContentBlock]) -> Option<&str> {
162 match content {
163 [ContentBlock::Text { text }] => Some(text),
164 _ => None,
165 }
166}
167
168fn words(text: &str) -> impl Iterator<Item = String> + '_ {
169 text.split(|c: char| !c.is_alphanumeric())
170 .filter(|word| !word.is_empty())
171 .map(str::to_lowercase)
172}
173
174fn shortlist(
176 task: &str,
177 options: &mut Vec<Candidate>,
178 limit: usize,
179 stop_words: &BTreeSet<String>,
180) {
181 if options.len() <= limit {
182 return;
183 }
184 let mut seen = BTreeSet::new();
186 let query: Vec<_> = words(task)
187 .filter(|w| !stop_words.contains(w) && seen.insert(w.clone()))
188 .collect();
189 let mut document_counts = BTreeMap::new();
190 let documents: Vec<_> = options
191 .drain(..)
192 .map(|option| {
193 let mut counts = BTreeMap::new();
194 let mut length = 0;
195 for word in words(&option.name)
196 .chain(words(&option.description))
197 .filter(|w| !stop_words.contains(w))
198 {
199 length += 1;
200 if seen.contains(&word) {
201 *counts.entry(word).or_insert(0u32) += 1;
202 }
203 }
204 for word in counts.keys() {
205 *document_counts.entry(word.clone()).or_insert(0u32) += 1;
206 }
207 (option, length, counts)
208 })
209 .collect();
210 let n = documents.len() as f64;
211 let average = documents.iter().map(|(_, length, _)| length).sum::<usize>() as f64 / n;
212 let mut ranked: Vec<_> = documents
213 .into_iter()
214 .map(|(option, length, counts)| {
215 let score: f64 = query
216 .iter()
217 .filter_map(|word| {
218 let count = f64::from(*counts.get(word)?);
219 let norm = 1.5 * (0.25 + 0.75 * length as f64 / average);
220 let df = f64::from(document_counts[word]);
221 let idf = (1.0 + (n - df + 0.5) / (df + 0.5)).ln();
222 Some(idf * count * 2.5 / (count + norm))
223 })
224 .sum();
225 (option, score)
226 })
227 .collect();
228 ranked.sort_by(|a, b| b.1.total_cmp(&a.1));
229 options.extend(ranked.into_iter().take(limit).map(|(option, _)| option));
230}
231
232fn select_names(
233 response: &DecisionResponse,
234 prefix: &str,
235 options: &[Candidate],
236 limit: usize,
237) -> Option<String> {
238 if options.len() != response.answers.len() {
239 return None;
240 }
241 let mut scores = Vec::with_capacity(options.len());
242 for (i, option) in options.iter().enumerate() {
243 let answer = response.answers.get(&format!("{prefix}{i}"))?;
244 let DecisionValue::Boolean(BooleanEstimate::ProbabilityTrue(p)) = answer.value else {
245 return None;
246 };
247 if !(0.0..=1.0).contains(&p.0) {
248 return None;
249 }
250 scores.push((option.name.as_str(), p.0));
251 }
252 scores.sort_by(|a, b| b.1.total_cmp(&a.1));
253 Some(
254 scores
255 .into_iter()
256 .take(limit)
257 .map(|(name, _)| name)
258 .collect::<Vec<_>>()
259 .join("\n"),
260 )
261}
262
263#[async_trait::async_trait]
264impl Algorithm for DecisionSelect {
265 fn name(&self) -> &str {
266 "decision_select"
267 }
268
269 async fn route(self: Arc<Self>, driver: Driver, request: Request) -> Result<RoutingOutcome> {
270 let target = driver
271 .models_for(&Category::Any)
272 .first()
273 .ok_or(LibsyError::NoTargets)?;
274 let fallback = |request, reason| {
275 let mut outcome = RoutingOutcome::route_to(target.clone(), Vec::new(), request);
276 outcome.metadata = Some(OutcomeMetadata::new(
277 self.name().into(),
278 Some(json!({"reason":reason})),
279 ));
280 Ok(outcome)
281 };
282 if !self.rule.enabled {
283 return fallback(request, "disabled");
284 }
285 let Some((task, mut options)) = self.extract(&request.llm_request) else {
286 return fallback(request, "unmatched");
287 };
288 let catalog_size = options.len();
289 shortlist(
290 task,
291 &mut options,
292 self.rule.shortlist,
293 &self.rule.stop_words,
294 );
295 let prefix = &self.rule.question_prefix;
296 let questions = options.iter().enumerate().map(|(i, option)| (
297 format!("{prefix}{i}"),
298 DecisionQuestion {
299 instructions: json!(format!("{}\nConsider one option only: {} ({})\nDoes this option belong to the answer?", self.rule.question, option.name, option.description)),
300 kind: DecisionKind::Boolean { true_description: None, false_description: None },
301 },
302 )).collect();
303 let model = driver
304 .models_for(&Category::Judge)
305 .first()
306 .ok_or(LibsyError::NoTargets)?;
307 let decision = DecisionRequest {
308 model: None,
309 input: json!(task),
310 questions,
311 };
312 let response = match driver.call_decision(decision, model.clone()).await {
313 Ok(response) => response,
314 Err(LibsyError::ClientCall { .. } | LibsyError::InvalidDecision { .. }) => {
315 return fallback(request, "decision_failed");
316 }
317 Err(error) => return Err(error),
318 };
319 let Some(names) = select_names(&response, prefix, &options, self.rule.top_k) else {
320 return fallback(request, "invalid_selection");
321 };
322 let mut answer = text_response(Some(driver.provider_model(model).to_string()), names);
323 answer.id = response.id;
324 answer.usage = response.usage;
325 answer.outputs[0].stop_reason = Some(StopReason::EndTurn);
326 let llm_response = if request.llm_request.stream {
327 LlmResponse::Stream(answer.into_stream())
328 } else {
329 LlmResponse::Agg(answer)
330 };
331 let mut response = Response {
332 llm_response,
333 metadata: request.metadata.clone(),
334 upstream_headers: Default::default(),
335 };
336 response.set_served_model(model);
337 let mut outcome = RoutingOutcome::answered(model.clone(), request, response);
338 outcome.metadata = Some(OutcomeMetadata::new(
339 self.name().into(),
340 Some(json!({
341 "reason": "decision_answer", "catalog_size": catalog_size, "scored": options.len(),
342 "returned": self.rule.top_k.min(options.len())
343 })),
344 ));
345 Ok(outcome)
346 }
347}
348
349#[cfg(test)]
350mod tests {
351 use super::*;
352
353 #[test]
354 fn stop_words_apply_to_query_and_document_lengths() {
355 let mut options = [
356 ("second", "the the the song"),
357 ("first", "song"),
358 ("other", "the the the"),
359 ]
360 .into_iter()
361 .map(|(name, description)| Candidate {
362 name: name.into(),
363 description: description.into(),
364 })
365 .collect();
366 shortlist("the song", &mut options, 2, &BTreeSet::from(["the".into()]));
367 assert_eq!(options[0].name, "second");
368 assert_eq!(options[1].name, "first");
369 }
370
371 #[test]
372 fn shortlist_scores_task_terms_before_applying_the_limit() {
373 let mut options = [
374 ("music.play", "play a track"),
375 ("wallet.approve", "approve a payment request"),
376 ("wallet.reject", "reject a payment request"),
377 ]
378 .into_iter()
379 .map(|(name, description)| Candidate {
380 name: name.into(),
381 description: description.into(),
382 })
383 .collect();
384 shortlist(
385 "approve a payment request",
386 &mut options,
387 2,
388 &BTreeSet::new(),
389 );
390 assert_eq!(
391 options
392 .iter()
393 .map(|option| option.name.as_str())
394 .collect::<Vec<_>>(),
395 ["wallet.approve", "wallet.reject"]
396 );
397 shortlist("unrelated", &mut options, 1, &BTreeSet::new());
398 assert_eq!(options[0].name, "wallet.approve");
399 }
400}