Skip to content

Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.

Rust

feat(libsy): add direct decision selection to llm_classifier (#1195)

alexn-ac365ce830bfa8
diff --git a/crates/libsy/src/algorithms/llm_class.rs b/crates/libsy/src/algorithms/llm_class.rs
index d9921d244..c4ebe9cd5 100644
--- a/crates/libsy/src/algorithms/llm_class.rs
+++ b/crates/libsy/src/algorithms/llm_class.rs
@@ -12,8 +12,8 @@ use serde_json::Value;
use switchyard_protocol::{Category, ContentBlock, Message, Role};
mod decision;
-use decision::DecisionClassifier;
-pub use decision::DecisionJudgeConfig;
+use decision::{DecisionClassifier, DirectClassifier};
+pub use decision::{DecisionJudgeConfig, DirectClassifierConfig};
use super::escalation;
use super::fall_through::FallThrough;
@@ -639,7 +639,7 @@ fn affinity_router(
Some(Arc::new(router))
}
-/// Routes requests through a capability, escalation, or custom classifier mode.
+/// Routes requests through a capability, escalation, custom, or direct classifier mode.
pub struct LlmTaskClassifier {
route: FallThrough,
/// Classifier used when this router is embedded in another cascade.
@@ -704,6 +704,13 @@ pub enum LlmClassifierConfig {
/// Custom classifier settings.
config: CustomClassifierConfig,
},
+ /// Routes to the model category a decision service selects.
+ Direct {
+ /// Category used when the decision call fails or returns an invalid choice.
+ default_target: Category,
+ /// Direct selection settings.
+ config: DirectClassifierConfig,
+ },
}
impl LlmTaskClassifier {
@@ -726,6 +733,10 @@ impl LlmTaskClassifier {
default_target,
config,
} => Self::build_custom(default_target, config),
+ LlmClassifierConfig::Direct {
+ default_target,
+ config,
+ } => Self::build_direct(default_target, config),
}
}
@@ -776,6 +787,20 @@ impl LlmTaskClassifier {
)
}
+ fn build_direct(default_target: Category, config: DirectClassifierConfig) -> Result<Self> {
+ if !config.options.contains(&default_target) {
+ return Err(LibsyError::AlgorithmError {
+ message: "direct default_target must be one of the options".into(),
+ });
+ }
+ let route = ClassifierRouteConfig {
+ default_target,
+ classify_trigger: config.classify_trigger,
+ message_hash_fallback: config.message_hash_fallback,
+ };
+ Self::from_classifier(Arc::new(DirectClassifier::new(config)?), route)
+ }
+
/// The judge face alone, for composite's own trigger and retained tier.
pub(crate) fn custom_classifier(
config: &CustomClassifierConfig,
@@ -1805,6 +1830,66 @@ mod tests {
Ok(())
}
+ #[tokio::test]
+ async fn direct_judge_falls_back_to_the_default_target() -> Result<()> {
+ use crate::{Call, RuntimeModels, drive};
+ use std::collections::BTreeMap;
+ use switchyard_protocol::{DecisionAnswer, DecisionResponse, DecisionValue};
+
+ for (reply, fail_open, expected) in [
+ (Some("unknown"), true, Some("efficient")),
+ (Some("unknown"), false, None),
+ (None, true, Some("efficient")),
+ (None, false, None),
+ ] {
+ let router: Arc<dyn Algorithm> =
+ Arc::new(LlmTaskClassifier::new(LlmClassifierConfig::Direct {
+ default_target: Category::Efficient,
+ config: DirectClassifierConfig {
+ options: vec![Category::Efficient, Category::Capable],
+ fail_open,
+ classify_trigger: ClassifyTrigger::EveryRequest,
+ message_hash_fallback: false,
+ recent_turn_window: None,
+ },
+ })?);
+ let serve = |call| async move {
+ let Call::Decision(call) = call else {
+ panic!("judge must use the decision step")
+ };
+ let response = match reply {
+ Some(selected) => Ok(DecisionResponse {
+ id: None,
+ model: None,
+ answers: BTreeMap::from([(
+ "route".into(),
+ DecisionAnswer {
+ value: DecisionValue::Choice {
+ selected: selected.into(),
+ probabilities: None,
+ },
+ provider_confidence: None,
+ },
+ )]),
+ usage: Default::default(),
+ }),
+ None => Err(LibsyError::client_call(
+ "judge",
+ LlmClientError::General("unavailable".into()),
+ )),
+ };
+ call.respond(std::future::ready(response)).await
+ };
+ let models = Arc::new(RuntimeModels::new(runtime_models()));
+ let result = drive(router, classify_request(), models, &serve).await;
+ match expected {
+ Some(expected) => assert_eq!(result?.selected_model_id()?, expected),
+ None => assert!(result.is_err()),
+ }
+ }
+ Ok(())
+ }
+
#[test]
fn the_threshold_boundary_is_inclusive() -> Result<()> {
let policy = policy();
diff --git a/crates/libsy/src/algorithms/llm_class/decision.rs b/crates/libsy/src/algorithms/llm_class/decision.rs
index 9142107fd..3762f914e 100644
--- a/crates/libsy/src/algorithms/llm_class/decision.rs
+++ b/crates/libsy/src/algorithms/llm_class/decision.rs
@@ -1,7 +1,8 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
-//! Select a candidate by applying a cutoff to a decision model's choice score.
+//! Select a candidate by applying a cutoff to a decision model's choice score, or
+//! take the category a decision service selects.
use std::collections::{BTreeMap, HashSet};
@@ -13,10 +14,14 @@ use switchyard_protocol::{
};
use crate::algorithms::llm_class::TaskInput;
+use crate::algorithms::util::affinity::ClassifyTrigger;
use crate::algorithms::util::llm_judge::{libsy_error_reason, report_fail_open};
use crate::algorithms::util::robustness::safe_error_summary;
use crate::{Classification, Classifier, Driver, LibsyError, Result, Score, State};
+/// Trailing turns sent to a decision service when the route sets no window.
+const DEFAULT_TURN_WINDOW: usize = 10;
+
/// Instructions, evidence, and cutoff policy for a decision judge.
///
/// Candidate labels keep model names out of the generated context. Evidence must use
@@ -89,7 +94,7 @@ impl DecisionClassifier {
mut input: TaskInput,
fail_open: bool,
) -> Result<Self> {
- input.recent_turn_window.get_or_insert(10);
+ input.recent_turn_window.get_or_insert(DEFAULT_TURN_WINDOW);
let instructions = match config.instructions.take() {
Some(instructions) => instructions,
None => serde_json::from_str(include_str!(
@@ -237,6 +242,132 @@ impl Classifier for DecisionClassifier {
}
}
+/// Settings for a decision service that selects one model category.
+#[derive(Clone, Debug)]
+pub struct DirectClassifierConfig {
+ /// Categories the service may select. Their names are the option IDs.
+ pub options: Vec<Category>,
+ /// Routes to the default target when the decision call fails or returns an
+ /// invalid choice.
+ pub fail_open: bool,
+ /// How often the decision service re-decides this session's target.
+ pub classify_trigger: ClassifyTrigger,
+ /// Uses the first user message when session metadata is unavailable.
+ pub message_hash_fallback: bool,
+ /// Trailing conversation turns sent to the decision service. Defaults to 10.
+ pub recent_turn_window: Option<usize>,
+}
+
+pub(super) struct DirectClassifier {
+ config: DirectClassifierConfig,
+ input: TaskInput,
+ question: DecisionQuestion,
+}
+
+impl DirectClassifier {
+ pub(super) fn new(config: DirectClassifierConfig) -> Result<Self> {
+ if config.options.len() < 2
+ || config
+ .options
+ .iter()
+ .any(|option| matches!(option, Category::Judge | Category::Any))
+ {
+ return Err(LibsyError::AlgorithmError {
+ message: "direct mode needs at least two options other than judge and any".into(),
+ });
+ }
+ let question = DecisionQuestion {
+ instructions: json!("Select the option that should serve this request."),
+ kind: DecisionKind::Choice {
+ options: config
+ .options
+ .iter()
+ .map(|option| ChoiceOption {
+ id: option.as_str().into(),
+ description: None,
+ })
+ .collect(),
+ },
+ };
+ Ok(Self {
+ input: TaskInput {
+ recent_turn_window: Some(config.recent_turn_window.unwrap_or(DEFAULT_TURN_WINDOW)),
+ },
+ config,
+ question,
+ })
+ }
+
+ async fn try_select(
+ &self,
+ decision: DecisionRequest,
+ driver: &Driver,
+ judge: &ModelId,
+ ) -> Result<&Category> {
+ let response = driver.call_decision(decision, judge.clone()).await?;
+ let Some(DecisionValue::Choice { selected, .. }) =
+ response.answers.get("route").map(|answer| &answer.value)
+ else {
+ return Err(LibsyError::invalid_decision(
+ judge.clone(),
+ "expected a route choice",
+ ));
+ };
+ self.config
+ .options
+ .iter()
+ .find(|option| option.as_str() == selected)
+ .ok_or_else(|| {
+ LibsyError::invalid_decision(judge.clone(), "route choice is not an option")
+ })
+ }
+}
+
+#[async_trait]
+impl Classifier for DirectClassifier {
+ async fn score(
+ &self,
+ _state: &mut State,
+ request: &mut Request,
+ driver: &Driver,
+ ) -> Result<(Classification, Option<Response>)> {
+ let judge = driver.first_model_for(&Category::Judge)?;
+ let decision = DecisionRequest {
+ model: None,
+ context: json!({
+ "task": self.input.messages(request),
+ "session": request.metadata.as_ref().and_then(|m| m.session_id.as_deref()),
+ }),
+ questions: BTreeMap::from([("route".into(), self.question.clone())]),
+ };
+ let category = match self.try_select(decision, driver, judge).await {
+ Ok(category) => category,
+ Err(error) if self.config.fail_open => {
+ return Ok(unavailable(
+ driver,
+ judge,
+ safe_error_summary(&error),
+ libsy_error_reason(&error),
+ ));
+ }
+ Err(error) => return Err(error),
+ };
+ let evidence = json!({
+ "source": "decision_classifier",
+ "verdict": "direct",
+ "selected": category.as_str(),
+ });
+ let selected = Score {
+ target: driver.first_model_for(category)?.clone(),
+ confidence: 1.0,
+ category: Some(category.clone()),
+ };
+ driver.record_judgment(Some(selected.clone()), Some(evidence.clone()));
+ driver.set_evidence(evidence);
+ Ok((Classification::Scores(vec![selected]), None))
+ }
+}
+
fn unavailable(
driver: &Driver,
judge: &ModelId,
diff --git a/crates/libsy/src/lib.rs b/crates/libsy/src/lib.rs
index 8f71fffda..1d9a38a65 100644
--- a/crates/libsy/src/lib.rs
+++ b/crates/libsy/src/lib.rs
@@ -23,8 +23,8 @@ pub use algorithms::composite::{CompositeJudgeConfig, CompositeRouter, Composite
pub use algorithms::infra::InfraPolicy;
pub use algorithms::llm_class::{
CapabilityJudgeConfig, CustomClassifierConfig, CustomClassifierPolicy, DEFAULT_UNMATCHED_STEPS,
- DecisionJudgeConfig, LlmCapabilityConfig, LlmClassifierConfig, LlmTaskClassifier,
- TaskClassifierConfig,
+ DecisionJudgeConfig, DirectClassifierConfig, LlmCapabilityConfig, LlmClassifierConfig,
+ LlmTaskClassifier, TaskClassifierConfig,
};
pub use algorithms::noop::Noop;
pub use algorithms::passthrough::Passthrough;
diff --git a/crates/protocol/src/category.rs b/crates/protocol/src/category.rs
index 3f228be13..b038d321a 100644
--- a/crates/protocol/src/category.rs
+++ b/crates/protocol/src/category.rs
@@ -17,8 +17,8 @@ pub enum Category {
Efficient,
/// Models the algorithm can use to decide.
Judge,
- /// A deployment-defined group. Only a custom classifier's policy selects one,
- /// and no algorithm ascribes meaning to the name.
+ /// A deployment-defined group. Only a custom classifier's policy or a direct
+ /// decision selects one, and no algorithm ascribes meaning to the name.
Named(Arc<str>),
}
diff --git a/crates/switchyard-runner/src/algorithm.rs b/crates/switchyard-runner/src/algorithm.rs
index 5d850cef4..74f98970d 100644
--- a/crates/switchyard-runner/src/algorithm.rs
+++ b/crates/switchyard-runner/src/algorithm.rs
@@ -13,11 +13,11 @@ use libsy::{
AdvisorGate, AdvisorGateConfig, Algorithm, BreakerConfig, CapabilityJudgeConfig,
ClassifierContractConfig, ClassifierResponseFormat, ClassifyTrigger, CompositeJudgeConfig,
CompositeRouter, CompositeRouterConfig, CustomClassifierConfig, CustomClassifierPolicy,
- DEFAULT_UNMATCHED_STEPS, DecisionJudgeConfig, EscalationJudgeConfig, GateTrigger,
- HandoffNoteConfig, LlmCapabilityConfig, LlmClassifierConfig, LlmFallback, LlmTaskClassifier,
- Noop, Passthrough, PickerMode, PlanExecute, PlanExecuteConfig, Random, RuntimeModels,
- StageRouter, StageRouterConfig, SubagentRouter, SubagentRouterConfig, TaskClassifierConfig,
- ToolSemantics, Vgr, VgrConfig,
+ DEFAULT_UNMATCHED_STEPS, DecisionJudgeConfig, DirectClassifierConfig, EscalationJudgeConfig,
+ GateTrigger, HandoffNoteConfig, LlmCapabilityConfig, LlmClassifierConfig, LlmFallback,
+ LlmTaskClassifier, Noop, Passthrough, PickerMode, PlanExecute, PlanExecuteConfig, Random,
+ RuntimeModels, StageRouter, StageRouterConfig, SubagentRouter, SubagentRouterConfig,
+ TaskClassifierConfig, ToolSemantics, Vgr, VgrConfig,
};
use serde::Deserialize;
use serde_json::Value;
@@ -72,7 +72,7 @@ pub enum ClassifierPolicyConfig {
},
}
-/// Which of the three `llm_classifier` behaviors a route uses.
+/// Which of the four `llm_classifier` behaviors a route uses.
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClassifierMode {
@@ -83,6 +83,8 @@ pub enum ClassifierMode {
Escalation,
/// Judges against your own JSON schema and routes to any configured target.
Custom,
+ /// Asks a decision target to select one configured model group.
+ Direct,
}
impl ClassifierPolicyConfig {
@@ -98,6 +100,11 @@ enum LlmClassifierModeConfig {
Capability(CapabilityClassifierRouteConfig),
Escalation(EscalationClassifierRouteConfig),
Custom(CustomClassifierRouteConfig),
+ Direct {
+ models: CategoryModelConfig,
+ default_target: Category,
+ config: DirectClassifierConfig,
+ },
}
#[derive(Clone, Debug)]
@@ -309,8 +316,8 @@ pub struct LlmClassifierRouteConfig {
/// Capability mode: threshold steps for an unmatched verdict (no capability rule
/// applies). 1 by default, the same as uncertain; 2 treats it like unsupported.
pub unmatched_steps: Option<u8>,
- /// Capability mode: routes to the capable tier on judge client failures and deadlines.
- /// Defaults to true when capability mode is selected.
+ /// Capability and direct modes: routes to the capable tier or `default_target` when
+ /// the judge call fails. Defaults to true in these modes.
pub fail_open: Option<bool>,
/// How often the judge runs: every request, once per user turn, or once per session.
pub classify_trigger: ClassifyTrigger,
@@ -337,9 +344,11 @@ pub struct LlmClassifierRouteConfig {
pub escalation: Option<EscalationJudgeConfig>,
/// Capability mode: use a decision target as the judge, with relative-advantage scoring.
pub decision: Option<DecisionJudgeRouteConfig>,
- /// Custom mode: runtime model groups.
+ /// Custom and direct modes: runtime model groups. In direct mode, every non-empty
+ /// group except `judge` and `any` is an option the decision target may select.
pub models: Option<CategoryModelConfig>,
- /// Custom mode: category used when the judge fails or its verdict cannot be routed.
+ /// Custom and direct modes: category used when the judge fails or its verdict
+ /// cannot be routed.
pub default_target: Option<String>,
/// Custom mode: JSON Schema the verdict must match, written as a string.
pub response_schema: Option<String>,
@@ -851,7 +860,10 @@ impl AlgorithmSpec {
) -> impl Iterator<Item = (&str, Option<&DecisionJudgeRouteConfig>)> {
let (primary, profiles) = match self {
Self::LlmClassifier { config, .. }
- if !matches!(config.classifier_mode(), ClassifierMode::Custom) =>
+ if !matches!(
+ config.classifier_mode(),
+ ClassifierMode::Custom | ClassifierMode::Direct
+ ) =>
{
(
Some((config.classifier_target.as_str(), config.decision.as_ref())),
@@ -887,6 +899,22 @@ impl AlgorithmSpec {
)
}
+ /// Judge targets that must be decision targets.
+ pub(crate) fn decision_target_names(&self) -> Vec<&str> {
+ let mut names: Vec<&str> = self
+ .classifier_targets()
+ .filter(|(_, decision)| decision.is_some())
+ .map(|(target, _)| target)
+ .collect();
+ if let Self::LlmClassifier { config, .. } = self
+ && matches!(config.classifier_mode(), ClassifierMode::Direct)
+ && let Some(models) = &config.models
+ {
+ names.extend(models.get(&Category::Judge).iter().map(String::as_str));
+ }
+ names
+ }
+
/// Completion targets in algorithm order; judge-only targets are excluded.
pub fn routing_target_names(&self) -> Vec<&str> {
match self {
@@ -919,7 +947,7 @@ impl AlgorithmSpec {
.chain(&config.weak_target)
.map(String::as_str)
.collect(),
- ClassifierMode::Custom => config
+ ClassifierMode::Custom | ClassifierMode::Direct => config
.models
.as_ref()
.map(CategoryModelConfig::routing_names)
@@ -983,10 +1011,13 @@ impl AlgorithmSpec {
pub fn judge_target_names(&self) -> Vec<&str> {
let mut names = Vec::new();
match self {
- // Custom mode names its judge in `models.judge`; the other two modes
- // use the top-level `classifier_target`.
+ // Custom and direct modes name their judge in `models.judge`; the other
+ // two modes use the top-level `classifier_target`.
Self::LlmClassifier { config, .. } => {
- if matches!(config.classifier_mode(), ClassifierMode::Custom) {
+ if matches!(
+ config.classifier_mode(),
+ ClassifierMode::Custom | ClassifierMode::Direct
+ ) {
names.extend(
config
.models
@@ -1244,6 +1275,7 @@ fn classifier_runtime_model_names(
),
]),
LlmClassifierModeConfig::Custom(config) => custom_runtime_model_names(&config.models),
+ LlmClassifierModeConfig::Direct { models, .. } => custom_runtime_model_names(&models),
}
}
@@ -1317,9 +1349,13 @@ impl LlmClassifierRouteConfig {
)));
}
- if !matches!(selected_mode, ClassifierMode::Capability) && *fail_open == Some(true) {
+ if !matches!(
+ selected_mode,
+ ClassifierMode::Capability | ClassifierMode::Direct
+ ) && *fail_open == Some(true)
+ {
return Err(AlgorithmConfigError::new(format!(
- "llm_classifier route {route_name}: fail_open = true requires capability mode"
+ "llm_classifier route {route_name}: fail_open = true requires capability or direct mode"
)));
}
@@ -1459,24 +1495,8 @@ impl LlmClassifierRouteConfig {
"llm_classifier route {route_name} mode custom cannot use capability or escalation fields and response_format_type must be 'json_schema'"
)));
}
- let models = required_classifier_field(route_name, "models", models)?;
- let default_target: Category = required_classifier_field(
- route_name,
- "default_target",
- default_target,
- )?
- .parse()
- .map_err(|error| {
- AlgorithmConfigError::new(format!(
- "llm_classifier route {route_name} has invalid default_target: {error}"
- ))
- })?;
- if default_target == Category::Judge {
- return Err(AlgorithmConfigError::new(format!(
- "llm_classifier route {route_name} default_target cannot be judge"
- )));
- }
- models.validate(route_name, &default_target)?;
+ let (models, default_target) =
+ validated_models(route_name, models, default_target)?;
Ok(LlmClassifierModeConfig::Custom(
CustomClassifierRouteConfig {
models,
@@ -1496,10 +1516,73 @@ impl LlmClassifierRouteConfig {
},
))
}
+ ClassifierMode::Direct => {
+ if !classifier_target.is_empty()
+ || strong_target.is_some()
+ || weak_target.is_some()
+ || base_threshold.is_some()
+ || threshold_step.is_some()
+ || unmatched_steps.is_some()
+ || escalation.is_some()
+ || prompt.is_some()
+ || response_schema.is_some()
+ || policy.is_some()
+ || *response_format_type != ClassifierResponseFormat::JsonSchema
+ || *max_output_tokens != default_classifier_max_output_tokens()
+ || judge_deadline_ms.is_some()
+ {
+ return Err(AlgorithmConfigError::new(format!(
+ "llm_classifier route {route_name} mode direct cannot use capability, escalation, or LLM judge fields"
+ )));
+ }
+ let (models, default_target) =
+ validated_models(route_name, models, default_target)?;
+ let options = models
+ .groups()
+ .filter(|(category, targets)| {
+ !targets.is_empty() && !matches!(category, Category::Judge | Category::Any)
+ })
+ .map(|(category, _)| category)
+ .collect();
+ Ok(LlmClassifierModeConfig::Direct {
+ models,
+ default_target,
+ config: DirectClassifierConfig {
+ options,
+ fail_open: fail_open.unwrap_or(true),
+ classify_trigger: *classify_trigger,
+ message_hash_fallback: *message_hash_fallback,
+ recent_turn_window: *recent_turn_window,
+ },
+ })
+ }
}
}
}
+fn validated_models(
+ route_name: &str,
+ models: &Option<CategoryModelConfig>,
+ default_target: &Option<String>,
+) -> AlgorithmResult<(CategoryModelConfig, Category)> {
+ let models = required_classifier_field(route_name, "models", models)?;
+ let default_target: Category =
+ required_classifier_field(route_name, "default_target", default_target)?
+ .parse()
+ .map_err(|error| {
+ AlgorithmConfigError::new(format!(
+ "llm_classifier route {route_name} has invalid default_target: {error}"
+ ))
+ })?;
+ if default_target == Category::Judge {
+ return Err(AlgorithmConfigError::new(format!(
+ "llm_classifier route {route_name} default_target cannot be judge"
+ )));
+ }
+ models.validate(route_name, &default_target)?;
+ Ok((models, default_target))
+}
+
fn reject_custom_fields(
route_name: &str,
mode: &str,
@@ -1762,6 +1845,14 @@ fn build_algorithm(
config: classifier_config,
})
}
+ LlmClassifierModeConfig::Direct {
+ default_target,
+ config,
+ ..
+ } => LlmTaskClassifier::new(LlmClassifierConfig::Direct {
+ default_target,
+ config,
+ }),
}
.map_err(|error| {
AlgorithmConfigError::with_source(
diff --git a/crates/switchyard-runner/src/config.rs b/crates/switchyard-runner/src/config.rs
index 2e89ab988..5515bc177 100644
--- a/crates/switchyard-runner/src/config.rs
+++ b/crates/switchyard-runner/src/config.rs
@@ -331,12 +331,9 @@ impl DeploymentConfig {
let targets = self.build_targets();
self.routes.iter().map(move |(route_name, config)| {
let classifiers: Vec<_> = config.algorithm.classifier_targets().collect();
- for (name, decision) in classifiers.iter().copied().chain(
- config.callable_target_names().into_iter()
- .filter(|name| !classifiers.iter().any(|(judge, _)| judge == name))
- .map(|name| (name, None)),
- ) {
- let (exists, kind) = if decision.is_some() {
+ let decision_targets = config.algorithm.decision_target_names();
+ for name in config.callable_target_names() {
+ let (exists, kind) = if decision_targets.contains(&name) {
(self.decision_targets.contains_key(name), "decision")
} else {
(self.targets.contains_key(name), "LLM")
@@ -620,12 +617,9 @@ impl DeploymentConfig {
let mut has_mixed_families = false;
let mut forwarding_origins = BTreeSet::new();
let mut decisions_by_model = HashMap::new();
+ let decision_targets = route.algorithm.decision_target_names();
for name in route.callable_target_names() {
- if route
- .algorithm
- .classifier_targets()
- .any(|(judge, decision)| judge == name && decision.is_some())
- {
+ if decision_targets.contains(&name) {
let target = &self.decision_targets[name];
decisions_by_model.insert(
target.id.clone(),
diff --git a/crates/switchyard-runner/tests/openai_decisions.rs b/crates/switchyard-runner/tests/openai_decisions.rs
index 96cc54561..8a40b53c9 100644
--- a/crates/switchyard-runner/tests/openai_decisions.rs
+++ b/crates/switchyard-runner/tests/openai_decisions.rs
@@ -6,7 +6,7 @@ use std::sync::{Arc, mpsc};
use serde_json::{Value, json};
use switchyard_llm_client::RunObservation;
use switchyard_protocol::{Metadata, Request, Usage, text_request};
-use switchyard_runner::Runner;
+use switchyard_runner::{AlgorithmFactory, Runner};
use wiremock::matchers::{body_partial_json, header, method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};
@@ -124,3 +124,130 @@ evidence = {{ description = "Compare the two profiles" }}
server.verify().await;
Ok(())
}
+
+fn direct_config(endpoint: &str) -> String {
+ format!(
+ r#"
+schema_version = 1
+[llm_clients.answers]
+format = "openai_chat"
+base_url = "{endpoint}/v1"
+[targets]
+fast = {{ id = "fast/model", llm_client = "answers" }}
+balanced = {{ id = "balanced/model", llm_client = "answers" }}
+premium = {{ id = "premium/model", llm_client = "answers" }}
+[decision_clients.router]
+format = "openai_decisions"
+endpoint = "{endpoint}/v1/decisions"
+api_key_env = "SWITCHYARD_DIRECT_DECISIONS_TEST_KEY"
+timeout_ms = 2000
+[decision_targets.router]
+id = "router-model"
+decision_client = "router"
+[routes.direct]
+id = "switchyard/direct"
+type = "llm_classifier"
+mode = "direct"
+default_target = "fast"
+[routes.direct.models]
+judge = ["router"]
+any = ["fast", "balanced", "premium"]
+fast = ["fast"]
+balanced = ["balanced"]
+premium = ["premium"]
+unused = []
+"#
+ )
+}
+
+#[tokio::test]
+async fn direct_mode_serves_the_selected_group() -> Result<(), Box<dyn std::error::Error>> {
+ let server = MockServer::start().await;
+ // This unique variable is only read while constructing this client.
+ unsafe {
+ std::env::set_var("SWITCHYARD_DIRECT_DECISIONS_TEST_KEY", "test-key");
+ }
+ let runner = Runner::from_toml(&direct_config(&server.uri()));
+ unsafe {
+ std::env::remove_var("SWITCHYARD_DIRECT_DECISIONS_TEST_KEY");
+ }
+ let runner = runner?;
+ // The choice routes even though another option has the higher probability.
+ Mock::given(method("POST")).and(path("/v1/decisions"))
+ .and(body_partial_json(json!({"model": "router-model", "questions": [{
+ "name": "route", "type": "choice",
+ "choices": [{"value": "balanced"}, {"value": "fast"}, {"value": "premium"}]
+ }]})))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "model": "router-model", "answers": [{
+ "type": "choice", "name": "route", "choice": "premium",
+ "probabilities": [{"value": "balanced", "probability": 0},
+ {"value": "fast", "probability": 1}, {"value": "premium", "probability": 0}]
+ }],
+ "usage": {"input_tokens": 0, "input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
+ "output_tokens": 0, "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 0}
+ }))).expect(1).mount(&server).await;
+ Mock::given(method("POST")).and(path("/v1/chat/completions"))
+ .and(body_partial_json(json!({"model": "premium/model"})))
+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({
+ "id": "answer-1", "object": "chat.completion", "model": "premium/model",
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "Answer"}, "finish_reason": "stop"}]
+ }))).expect(1).mount(&server).await;
+ let output = runner
+ .route("switchyard/direct")
+ .unwrap()
+ .execute(
+ Request {
+ llm_request: text_request(None, "Route this request"),
+ metadata: Some(Metadata {
+ session_id: Some("session-1".into()),
+ ..Metadata::default()
+ }),
+ ..Request::default()
+ },
+ None,
+ )
+ .await?;
+ assert_eq!(output.selected_model, "premium/model");
+ let requests = server.received_requests().await.unwrap();
+ let decision: Value = serde_json::from_slice(&requests[0].body)?;
+ let context: Value = serde_json::from_str(decision["input"].as_str().unwrap())?;
+ assert_eq!(
+ context,
+ json!({
+ "task": [{"role": "user", "content": [{"type": "text", "text": "Route this request"}]}],
+ "session": "session-1",
+ })
+ );
+ server.verify().await;
+ Ok(())
+}
+
+#[test]
+fn direct_mode_rejects_invalid_configuration() {
+ for (from, to, expected) in [
+ (
+ r#"judge = ["router"]"#,
+ r#"judge = ["fast"]"#,
+ "requires target kind decision",
+ ),
+ (
+ "balanced = [\"balanced\"]\npremium = [\"premium\"]\n",
+ "",
+ "at least two options",
+ ),
+ (
+ r#"default_target = "fast""#,
+ r#"default_target = "any""#,
+ "must be one of the options",
+ ),
+ ] {
+ let source = direct_config("http://127.0.0.1:1").replace(from, to);
+ let error = AlgorithmFactory::from_toml(&source)
+ .and_then(|factory| factory.build())
+ .err()
+ .unwrap_or_else(|| panic!("expected a load error for {to}"))
+ .to_string();
+ assert!(error.contains(expected), "{to}: {error}");
+ }
+}
diff --git a/docs/reference/toml_schema.md b/docs/reference/toml_schema.md
index eac1c1eaa..63f7326f6 100644
--- a/docs/reference/toml_schema.md
+++ b/docs/reference/toml_schema.md
@@ -100,9 +100,11 @@ server sends a framed error and ends the stream without a success marker.
The Rust runner collects streams used during routing before the algorithm
continues, preserving provider events for replay. After the configured retries,
an HTTP client failure stops routing unless the call enables recovery.
-Capability classifiers and advisor gates default to `fail_open = true`.
-A capability classifier routes to the capable tier on judge failures, including
-deadlines. An advisor returns the buffered executor turn when its consult fails.
+Capability classifiers, direct classifiers, and advisor gates default to
+`fail_open = true`. A capability classifier routes to the capable tier on judge
+failures, including deadlines. A direct classifier routes to its
+`default_target`. An advisor returns the buffered executor turn when its consult
+fails.
Set `fail_open = false` to stop the request on these failures.
Answer calls keep their usual error behavior.
@@ -334,13 +336,13 @@ checkpoint = "/models/router.pt"
### `llm_classifier`
-Runs one of three judge-backed modes: `capability`, `escalation`, or `custom`.
-`max_output_tokens` and `judge_deadline_ms` apply to all three.
+Runs one of four modes: `capability`, `escalation`, `custom`, or `direct`.
+`max_output_tokens` and `judge_deadline_ms` apply to LLM judges.
| Key | Required | Default | Meaning |
|---|:---:|---|---|
| `mode` | No | `capability` | Classifier behavior. Set it explicitly for new configurations. |
-| `classifier_target` | Capability, escalation | — | Target the judge is called through. Not a routing destination. Custom mode uses `models.judge`. |
+| `classifier_target` | Capability, escalation | — | Target the judge is called through. Not a routing destination. Custom and direct modes use `models.judge`. |
| `max_output_tokens` | No | `4096` | Maximum completion tokens for the judge verdict. Must be at least `1`. |
| `judge_deadline_ms` | No | unset | Bounds the whole judge consultation in milliseconds, the model call and the response drain included. On expiry the judge is treated as unavailable and follows the route's `fail_open` setting. Must be at least `1`. Unset leaves the consultation unbounded. |
| `response_format_type` | No | `json_schema` | Structured-output mode for capability and escalation judges. Use `json_object` when the provider does not support JSON Schema; Switchyard adds the schema to the prompt and validates the verdict locally. Custom mode always uses its configured JSON Schema. |
@@ -353,7 +355,7 @@ Capability mode classifies before serving. See
| `strong_target` | Yes | — | Capable tier. |
| `weak_target` | Yes | — | Efficient tier. |
| `base_threshold` | Yes | — | Lowest solve probability that routes to the weak target. In `[0, 1]`. |
-| `fail_open` | No | `true` | Capability mode only. When `true`, judge client failures and deadlines route to the capable tier and record fail-open evidence. When `false`, they stop the request. Invalid decision-model verdicts route to the capable tier when `fail_open = true` and stop the request with an error when `fail_open = false`. Invalid LLM-judge verdicts still use the capable tier with either setting. |
+| `fail_open` | No | `true` | When `true`, judge client failures and deadlines route to the capable tier and record fail-open evidence. When `false`, they stop the request. Invalid decision-model verdicts route to the capable tier when `fail_open = true` and stop the request with an error when `fail_open = false`. Invalid LLM-judge verdicts still use the capable tier with either setting. |
| `threshold_step` | No | `0.0` | Finite, non-negative amount added once for uncertain verdicts, `unmatched_steps` times for unmatched verdicts, and twice for unsupported verdicts. `base_threshold + 2 * threshold_step` must be at most `1`. |
| `unmatched_steps` | No | `1` | Threshold steps applied to an unmatched verdict (no capability rule applies). `0`, `1`, or `2`; `2` treats it like an unsupported verdict. |
| `classify_trigger` | No | `every_request` | When the judge runs. `every_request` judges every request, tool continuations included. `user_turn` judges each new user message and retains that target across intervening tool calls only when requests carry a session ID; without a session ID, it behaves like `every_request`. `new_session` judges once and reuses that target for the session. |
@@ -416,6 +418,17 @@ Classifier prompts must not contain `{{RESPONSE_SCHEMA}}`. Switchyard supplies
the schema automatically: through the structured-output request in `json_schema`
mode, or in the prompt in `json_object` mode.
+Direct mode asks a decision target to select one model group. See
+[Direct selection](../routing_algorithms/llm_classifier_routing.md#direct-selection).
+`classify_trigger` and `message_hash_fallback` work as in custom mode.
+
+| Key | Required | Default | Meaning |
+|---|:---:|---|---|
+| `models` | Yes | — | Model groups, as in custom mode. Every non-empty group except `judge` and `any` is an option, and its name is the option ID. Needs at least two options. `models.judge` must name a decision target. |
+| `default_target` | Yes | — | Option used when the decision call fails or returns a choice that is not an option. |
+| `fail_open` | No | `true` | When `true`, decision call failures, deadlines, and invalid choices route to `default_target`. When `false`, they stop the request. |
+| `recent_turn_window` | No | `10` | Trailing turns sent as `task` after the opening task. |
+
### `stage_router`
Scores tool signals to pick a tier per turn. See
diff --git a/docs/routing_algorithms/llm_classifier_routing.md b/docs/routing_algorithms/llm_classifier_routing.md
index c267acca1..25b86b3b4 100644
--- a/docs/routing_algorithms/llm_classifier_routing.md
+++ b/docs/routing_algorithms/llm_classifier_routing.md
@@ -4,8 +4,9 @@
an efficient model can handle the task or a capable model is needed. Configure
it with `type = "llm_classifier"` and `mode = "capability"`.
-The same classifier also supports [escalation](escalation_router_routing.md)
-and [custom routing](#custom-multi-target-routing) across two or more targets.
+The same classifier also supports [escalation](escalation_router_routing.md),
+[custom routing](#custom-multi-target-routing) across two or more targets, and
+[direct selection](#direct-selection) by an external decision service.
For a task-level decision-model example with structured instructions, see the
[Jev routing profile](../../benchmark/routing-profiles/tb21-jev-opus-glm.toml).
@@ -243,6 +244,53 @@ If a client sends only a follow-up fragment without the opening task, enable
affinity or include the task history. Threshold tuning changes routing policy;
it cannot recover missing task context.
+## Direct selection
+
+Direct mode asks a decision target to select one of the route's model groups,
+then serves the first model in that group. The decision service owns the
+routing policy.
+
+```toml
+[decision_clients.router]
+format = "openai_decisions"
+endpoint = "https://router.example.com/v1/decisions"
+api_key_env = "ROUTER_API_KEY"
+timeout_ms = 10000
+
+[decision_targets.router]
+id = "router-model"
+decision_client = "router"
+
+[routes.direct]
+id = "direct"
+type = "llm_classifier"
+mode = "direct"
+default_target = "balanced"
+
+[routes.direct.models]
+judge = ["router"]
+fast = ["fast"]
+balanced = ["balanced"]
+premium = ["premium"]
+any = ["balanced", "fast", "premium"]
+```
+
+Every non-empty group except `judge` and `any` is an option, and its name is the
+option ID, so name each group with an ID the decision service returns. Options
+are sent in group-name order. A route needs at least two options. `models.judge`
+must name a decision target.
+
+The request context holds the conversation as `task` and the caller's session ID
+as `session` (or null). `recent_turn_window` sets how many trailing turns `task`
+carries after the opening task. The default is 10.
+
+Switchyard routes on the selected option and ignores the probabilities. When
+the decision call fails, times out, or returns a choice that is not an option,
+the route uses `default_target`. Set `fail_open = false` to stop the request
+instead. The decision client's `timeout_ms` sets how long the call may take.
+
+Direct mode is available only on standalone `llm_classifier` routes.
+
## When the judge runs
`classify_trigger` sets how often the target is re-decided.