use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::sync::Arc;
use libsy::{
AdvisorGate, AdvisorGateConfig, Algorithm, ClassifierContractConfig, ClassifierResponseFormat,
ClassifyTrigger, CompositeRouter, CompositeRouterConfig, CustomClassifierConfig,
CustomClassifierPolicy, EscalationJudgeConfig, GateTrigger, HandoffNoteConfig,
LlmClassifierConfig, LlmFallback, LlmTaskClassifier, Noop, Passthrough, PickerMode,
PlanExecute, PlanExecuteConfig, Random, StageRouter, StageRouterConfig, SubagentRouter,
SubagentRouterConfig, TaskClassifierConfig, ToolSemantics,
};
use serde::Deserialize;
use switchyard_protocol::{Category, ModelId};
#[derive(Debug)]
pub struct AlgorithmConfigError {
message: String,
source: Option<Box<dyn Error + Send + Sync>>,
}
impl AlgorithmConfigError {
fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
source: None,
}
}
fn with_source(message: impl Into<String>, source: impl Error + Send + Sync + 'static) -> Self {
Self {
message: message.into(),
source: Some(Box::new(source)),
}
}
}
impl Display for AlgorithmConfigError {
fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.message)
}
}
impl Error for AlgorithmConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.as_deref().map(|source| source as _)
}
}
type AlgorithmResult<T> = Result<T, AlgorithmConfigError>;
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum ClassifierPolicyConfig {
TargetSelector {
selector: String,
},
}
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClassifierMode {
Capability,
Escalation,
Custom,
}
impl ClassifierPolicyConfig {
fn into_libsy(self) -> CustomClassifierPolicy {
match self {
Self::TargetSelector { selector } => CustomClassifierPolicy::target_selector(selector),
}
}
}
#[derive(Clone, Debug)]
enum LlmClassifierModeConfig {
Capability(CapabilityClassifierRouteConfig),
Escalation(EscalationClassifierRouteConfig),
Custom(CustomClassifierRouteConfig),
}
#[derive(Clone, Debug)]
struct CapabilityClassifierRouteConfig {
classifier_target: String,
strong_target: String,
weak_target: String,
base_threshold: f64,
threshold_step: f64,
classify_trigger: ClassifyTrigger,
message_hash_fallback: bool,
recent_turn_window: Option<usize>,
prompt: Option<String>,
response_format_type: ClassifierResponseFormat,
max_output_tokens: u64,
}
#[derive(Clone, Debug)]
struct EscalationClassifierRouteConfig {
classifier_target: String,
strong_target: String,
weak_target: String,
prompt: Option<String>,
response_format_type: ClassifierResponseFormat,
max_output_tokens: u64,
judge: EscalationJudgeConfig,
}
#[derive(Clone, Debug)]
struct CustomClassifierRouteConfig {
models: CategoryModelConfig,
default_target: Category,
prompt: String,
response_schema: String,
policy: ClassifierPolicyConfig,
classify_trigger: ClassifyTrigger,
message_hash_fallback: bool,
recent_turn_window: Option<usize>,
max_output_tokens: u64,
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(transparent)]
pub struct CategoryModelConfig(BTreeMap<String, Vec<String>>);
impl CategoryModelConfig {
fn validate(&self, route_name: &str, default_target: &Category) -> AlgorithmResult<()> {
for category in [Category::Any, Category::Judge] {
if self.get(&category).is_empty() {
return Err(AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} models.{} must contain at least one target",
category.as_str()
)));
}
}
if self.get(default_target).is_empty() {
return Err(AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} models.{} must contain at least one target because it is the default_target",
default_target.as_str()
)));
}
let any = self.get(&Category::Any);
for (name, models) in &self.0 {
if name == Category::Judge.as_str() || name == Category::Any.as_str() {
continue;
}
if let Some(missing) = models.iter().find(|model| !any.contains(model)) {
return Err(AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} models.{name} lists target {missing}, which must also appear in models.any"
)));
}
}
Ok(())
}
fn get(&self, category: &Category) -> &[String] {
self.0.get(category.as_str()).map_or(&[], Vec::as_slice)
}
fn all_names(&self) -> Vec<&str> {
Self::deduped(self.0.values().flatten())
}
fn routing_names(&self) -> Vec<&str> {
let others = self
.0
.iter()
.filter(|(name, _)| {
*name != Category::Judge.as_str() && *name != Category::Any.as_str()
})
.flat_map(|(_, models)| models);
Self::deduped(self.get(&Category::Any).iter().chain(others))
}
fn deduped<'a>(names: impl Iterator<Item = &'a String>) -> Vec<&'a str> {
let mut seen = BTreeSet::new();
names
.map(String::as_str)
.filter(|name| seen.insert(*name))
.collect()
}
fn groups(&self) -> impl Iterator<Item = (Category, Vec<String>)> + '_ {
self.0
.iter()
.filter_map(|(name, models)| Some((name.parse::<Category>().ok()?, models.clone())))
}
}
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LlmClassifierRouteConfig {
pub classifier_target: String,
pub mode: Option<ClassifierMode>,
pub strong_target: Option<String>,
pub weak_target: Option<String>,
pub base_threshold: Option<f64>,
pub threshold_step: Option<f64>,
pub classify_trigger: ClassifyTrigger,
pub message_hash_fallback: bool,
pub recent_turn_window: Option<usize>,
pub prompt: Option<String>,
pub response_format_type: ClassifierResponseFormat,
#[serde(default = "default_classifier_max_output_tokens")]
pub max_output_tokens: u64,
pub escalation: Option<EscalationJudgeConfig>,
pub models: Option<CategoryModelConfig>,
pub default_target: Option<String>,
pub response_schema: Option<String>,
pub policy: Option<ClassifierPolicyConfig>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum SubagentRouteConfig {
Passthrough {
target: String,
},
LlmClassifier(Box<LlmClassifierRouteConfig>),
}
impl SubagentRouteConfig {
fn routing_target_names(&self) -> Vec<&str> {
match self {
Self::Passthrough { target } => vec![target],
Self::LlmClassifier(classifier) => classifier
.models
.as_ref()
.map(CategoryModelConfig::routing_names)
.unwrap_or_default(),
}
}
fn judge_target_names(&self) -> Vec<&str> {
match self {
Self::Passthrough { .. } => Vec::new(),
Self::LlmClassifier(classifier) => classifier
.models
.as_ref()
.map(|models| models.get(&Category::Judge))
.unwrap_or_default()
.iter()
.map(String::as_str)
.collect(),
}
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum AlgorithmSpec {
Noop {},
Random {
targets: Vec<String>,
weights: Option<Vec<f64>>,
seed: Option<u64>,
},
Passthrough {
target: String,
#[serde(default)]
subagents: Option<SubagentRouteConfig>,
},
PlanExecute {
capable_target: String,
efficient_target: String,
#[serde(default)]
planning_prompt: Option<String>,
#[serde(default)]
handoff_prompt: Option<String>,
#[serde(default)]
planner_reasoning_as_text: bool,
},
LlmClassifier {
#[serde(flatten)]
config: LlmClassifierRouteConfig,
},
StageRouter {
#[serde(flatten)]
tiers: StageTierConfig,
picker: PickerMode,
#[serde(default)]
classifier: Option<StageClassifierConfig>,
#[serde(default)]
subagents: Option<SubagentRouteConfig>,
},
Auto {
capable_target: String,
efficient_target: String,
},
Composite {
classifier: StageClassifierConfig,
stage: StageTierConfig,
#[serde(default)]
subagents: Option<SubagentRouteConfig>,
},
Advisor {
executor_target: String,
advisor_target: String,
#[serde(default)]
reviewer_system_prompt: Option<String>,
#[serde(default)]
redo_feedback_prefix: Option<String>,
#[serde(default)]
gate_trigger: AdvisorTriggerConfig,
#[serde(default)]
gate_trigger_pattern: Option<String>,
#[serde(default = "default_max_reviews")]
max_reviews: u32,
#[serde(default)]
gate_stall_turns: u32,
#[serde(default)]
gate_min_tool_results: u32,
#[serde(default = "default_advisor_max_tokens")]
advisor_max_tokens: u64,
#[serde(default)]
advisor_temperature: Option<f64>,
#[serde(default = "default_transcript_max_chars")]
transcript_max_chars: usize,
#[serde(default = "default_fail_open")]
fail_open: bool,
},
PrefillRouter {
targets: Vec<String>,
checkpoint: PathBuf,
device: Option<String>,
cache_dir: Option<PathBuf>,
max_length: Option<usize>,
batch_size: Option<usize>,
},
}
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AdvisorTriggerConfig {
#[default]
NoToolCall,
Pattern,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StageClassifierConfig {
pub target: String,
pub base_threshold: f64,
#[serde(default)]
pub threshold_step: f64,
#[serde(default)]
pub classify_trigger: ClassifyTrigger,
#[serde(default)]
pub message_hash_fallback: bool,
#[serde(default)]
pub recent_turn_window: Option<usize>,
#[serde(default)]
pub prompt: Option<String>,
#[serde(default)]
pub response_format_type: ClassifierResponseFormat,
#[serde(default = "default_classifier_max_output_tokens")]
pub max_output_tokens: u64,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StageTierConfig {
pub capable_target: String,
pub efficient_target: String,
pub confidence_threshold: f64,
#[serde(default)]
pub recent_turn_window: Option<usize>,
#[serde(default)]
pub tool_semantics: ToolSemantics,
#[serde(default)]
pub capable_hold_turns: Option<u32>,
#[serde(default)]
pub handoff_notes: Option<HandoffNoteConfig>,
}
impl StageClassifierConfig {
fn task_classifier_config(&self) -> TaskClassifierConfig {
TaskClassifierConfig {
base_threshold: self.base_threshold,
threshold_step: self.threshold_step,
classify_trigger: self.classify_trigger,
message_hash_fallback: self.message_hash_fallback,
recent_turn_window: self.recent_turn_window,
contract: classifier_contract(self.prompt.as_deref())
.with_response_format_type(self.response_format_type),
max_output_tokens: self.max_output_tokens,
}
}
}
impl AlgorithmSpec {
pub fn routing_target_names(&self) -> Vec<&str> {
match self {
Self::Noop { .. } => Vec::new(),
Self::Random { targets, .. } => targets.iter().map(String::as_str).collect(),
Self::Passthrough {
target, subagents, ..
} => {
let mut names = vec![target.as_str()];
if let Some(subagents) = subagents {
names.extend(subagents.routing_target_names());
}
names
}
Self::PlanExecute {
capable_target,
efficient_target,
..
} => vec![capable_target.as_str(), efficient_target.as_str()],
Self::LlmClassifier { config, .. } => match config.classifier_mode() {
ClassifierMode::Capability => config
.weak_target
.iter()
.chain(&config.strong_target)
.map(String::as_str)
.collect(),
ClassifierMode::Escalation => config
.strong_target
.iter()
.chain(&config.weak_target)
.map(String::as_str)
.collect(),
ClassifierMode::Custom => config
.models
.as_ref()
.map(CategoryModelConfig::routing_names)
.unwrap_or_default(),
},
Self::StageRouter {
tiers, subagents, ..
} => {
let mut names = vec![
tiers.capable_target.as_str(),
tiers.efficient_target.as_str(),
];
if let Some(subagents) = subagents {
names.extend(subagents.routing_target_names());
}
names
}
Self::Auto {
capable_target,
efficient_target,
} => vec![capable_target.as_str(), efficient_target.as_str()],
Self::Composite {
stage, subagents, ..
} => {
let mut names = vec![
stage.capable_target.as_str(),
stage.efficient_target.as_str(),
];
if let Some(subagents) = subagents {
names.extend(subagents.routing_target_names());
}
names
}
Self::Advisor {
executor_target, ..
} => vec![executor_target],
Self::PrefillRouter { targets, .. } => targets.iter().map(String::as_str).collect(),
}
}
pub fn callable_target_names(&self) -> Vec<&str> {
let mut names = self.routing_target_names();
match self {
Self::LlmClassifier { config, .. } => {
if matches!(config.classifier_mode(), ClassifierMode::Custom) {
names.extend(
config
.models
.as_ref()
.map(|models| models.get(&Category::Judge))
.unwrap_or_default()
.iter()
.map(String::as_str),
);
} else {
names.push(&config.classifier_target);
}
}
Self::StageRouter {
classifier: Some(classifier),
..
} => names.push(&classifier.target),
Self::Composite { classifier, .. } => {
names.push(&classifier.target);
}
Self::Advisor { advisor_target, .. } => names.push(advisor_target),
_ => {}
}
if let Self::Passthrough {
subagents: Some(subagents),
..
}
| Self::StageRouter {
subagents: Some(subagents),
..
}
| Self::Composite {
subagents: Some(subagents),
..
} = self
{
names.extend(subagents.judge_target_names());
}
names
}
pub(crate) fn runtime_model_names(
&self,
route_name: &str,
) -> AlgorithmResult<RuntimeModelNames> {
let parent = match self {
Self::Noop { .. } => HashMap::new(),
Self::Random { targets, .. } | Self::PrefillRouter { targets, .. } => {
category_models([(Category::Any, targets.clone())])
}
Self::Passthrough { target, .. } => {
category_models([(Category::Any, vec![target.clone()])])
}
Self::PlanExecute {
capable_target,
efficient_target,
..
} => category_models([
(Category::Capable, vec![capable_target.clone()]),
(Category::Efficient, vec![efficient_target.clone()]),
(
Category::Any,
vec![capable_target.clone(), efficient_target.clone()],
),
]),
Self::LlmClassifier { config } => {
classifier_runtime_model_names(config.validated_classifier_mode(route_name)?)
}
Self::StageRouter {
tiers, classifier, ..
} => {
let mut models = category_models([
(Category::Capable, vec![tiers.capable_target.clone()]),
(Category::Efficient, vec![tiers.efficient_target.clone()]),
(
Category::Any,
vec![tiers.capable_target.clone(), tiers.efficient_target.clone()],
),
]);
if let Some(classifier) = classifier {
models.insert(Category::Judge, vec![classifier.target.clone()]);
}
models
}
Self::Auto {
capable_target,
efficient_target,
} => category_models([
(Category::Capable, vec![capable_target.clone()]),
(Category::Efficient, vec![efficient_target.clone()]),
(
Category::Any,
vec![capable_target.clone(), efficient_target.clone()],
),
]),
Self::Composite {
classifier, stage, ..
} => category_models([
(Category::Judge, vec![classifier.target.clone()]),
(Category::Capable, vec![stage.capable_target.clone()]),
(Category::Efficient, vec![stage.efficient_target.clone()]),
(
Category::Any,
vec![stage.capable_target.clone(), stage.efficient_target.clone()],
),
]),
Self::Advisor {
executor_target,
advisor_target,
..
} => category_models([
(Category::Efficient, vec![executor_target.clone()]),
(Category::Any, vec![executor_target.clone()]),
(Category::Judge, vec![advisor_target.clone()]),
]),
};
let subagents = match self {
Self::Passthrough { subagents, .. }
| Self::StageRouter { subagents, .. }
| Self::Composite { subagents, .. } => subagents.as_ref(),
_ => None,
};
let subagent = subagents
.map(|subagents| subagent_runtime_model_names(subagents, route_name))
.transpose()?;
Ok(RuntimeModelNames { parent, subagent })
}
pub(crate) fn routing_response_and_dependency(&self) -> Option<(&str, &str)> {
match self {
Self::LlmClassifier { config, .. }
if matches!(config.classifier_mode(), ClassifierMode::Escalation) =>
{
Some((
config.weak_target.as_deref()?,
config.classifier_target.as_str(),
))
}
Self::Advisor {
executor_target,
advisor_target,
..
} => Some((executor_target, advisor_target)),
Self::Noop { .. }
| Self::Random { .. }
| Self::Passthrough { .. }
| Self::PlanExecute { .. }
| Self::LlmClassifier { .. }
| Self::StageRouter { .. }
| Self::Auto { .. }
| Self::Composite { .. }
| Self::PrefillRouter { .. } => None,
}
}
pub fn build(
&self,
context: &str,
targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<Arc<dyn Algorithm>> {
build_algorithm(context, self, targets)
}
}
pub(crate) struct RuntimeModelNames {
pub(crate) parent: HashMap<Category, Vec<String>>,
pub(crate) subagent: Option<HashMap<Category, Vec<String>>>,
}
fn category_models(
entries: impl IntoIterator<Item = (Category, Vec<String>)>,
) -> HashMap<Category, Vec<String>> {
entries.into_iter().collect()
}
fn custom_runtime_model_names(config: &CategoryModelConfig) -> HashMap<Category, Vec<String>> {
config.groups().collect()
}
fn classifier_runtime_model_names(
config: LlmClassifierModeConfig,
) -> HashMap<Category, Vec<String>> {
match config {
LlmClassifierModeConfig::Capability(config) => category_models([
(Category::Judge, vec![config.classifier_target]),
(Category::Efficient, vec![config.weak_target.clone()]),
(Category::Capable, vec![config.strong_target.clone()]),
(
Category::Any,
vec![config.weak_target, config.strong_target],
),
]),
LlmClassifierModeConfig::Escalation(config) => category_models([
(Category::Judge, vec![config.classifier_target]),
(Category::Efficient, vec![config.weak_target.clone()]),
(Category::Capable, vec![config.strong_target.clone()]),
(
Category::Any,
vec![config.strong_target, config.weak_target],
),
]),
LlmClassifierModeConfig::Custom(config) => custom_runtime_model_names(&config.models),
}
}
fn subagent_runtime_model_names(
config: &SubagentRouteConfig,
route_name: &str,
) -> AlgorithmResult<HashMap<Category, Vec<String>>> {
match config {
SubagentRouteConfig::Passthrough { target } => {
Ok(category_models([(Category::Any, vec![target.clone()])]))
}
SubagentRouteConfig::LlmClassifier(config) => {
let LlmClassifierModeConfig::Custom(config) =
config.validated_classifier_mode(route_name)?
else {
return Err(AlgorithmConfigError::new(format!(
"route {route_name}: subagents llm_classifier only supports mode custom"
)));
};
Ok(custom_runtime_model_names(&config.models))
}
}
}
impl LlmClassifierRouteConfig {
fn classifier_mode(&self) -> ClassifierMode {
let default = if self.escalation.is_some() {
ClassifierMode::Escalation
} else {
ClassifierMode::Capability
};
self.mode.unwrap_or(default)
}
fn validated_classifier_mode(
&self,
route_name: &str,
) -> AlgorithmResult<LlmClassifierModeConfig> {
let Self {
classifier_target,
mode,
strong_target,
weak_target,
base_threshold,
threshold_step,
classify_trigger,
message_hash_fallback,
recent_turn_window,
prompt,
response_format_type,
max_output_tokens,
escalation,
models,
default_target,
response_schema,
policy,
} = self;
let selected_mode = match (mode, escalation.is_some()) {
(Some(mode), _) => *mode,
(None, true) => ClassifierMode::Escalation,
(None, false) => ClassifierMode::Capability,
};
match selected_mode {
ClassifierMode::Capability => {
if escalation.is_some() {
return Err(classifier_field_error(
route_name,
"escalation",
"capability",
));
}
reject_custom_fields(
route_name,
"capability",
models,
default_target,
response_schema,
policy,
)?;
Ok(LlmClassifierModeConfig::Capability(
CapabilityClassifierRouteConfig {
classifier_target: classifier_target.clone(),
strong_target: required_classifier_field(
route_name,
"strong_target",
strong_target,
)?,
weak_target: required_classifier_field(
route_name,
"weak_target",
weak_target,
)?,
base_threshold: required_classifier_field(
route_name,
"base_threshold",
base_threshold,
)?,
threshold_step: threshold_step.unwrap_or_default(),
classify_trigger: *classify_trigger,
message_hash_fallback: *message_hash_fallback,
recent_turn_window: *recent_turn_window,
prompt: prompt.clone(),
response_format_type: *response_format_type,
max_output_tokens: *max_output_tokens,
},
))
}
ClassifierMode::Escalation => {
reject_custom_fields(
route_name,
"escalation",
models,
default_target,
response_schema,
policy,
)?;
if *classify_trigger != ClassifyTrigger::EveryRequest {
return Err(AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} mode escalation cannot use classify_trigger"
)));
}
if mode.is_some()
&& (base_threshold.is_some()
|| threshold_step.is_some()
|| *message_hash_fallback
|| recent_turn_window.is_some())
{
return Err(AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} mode escalation cannot use capability routing settings"
)));
}
Ok(LlmClassifierModeConfig::Escalation(
EscalationClassifierRouteConfig {
classifier_target: classifier_target.clone(),
strong_target: required_classifier_field(
route_name,
"strong_target",
strong_target,
)?,
weak_target: required_classifier_field(
route_name,
"weak_target",
weak_target,
)?,
prompt: prompt.clone(),
response_format_type: *response_format_type,
max_output_tokens: *max_output_tokens,
judge: required_classifier_field(route_name, "escalation", escalation)?,
},
))
}
ClassifierMode::Custom => {
if !classifier_target.is_empty()
|| strong_target.is_some()
|| weak_target.is_some()
|| base_threshold.is_some()
|| threshold_step.is_some()
|| escalation.is_some()
|| *response_format_type != ClassifierResponseFormat::JsonSchema
{
return Err(AlgorithmConfigError::new(format!(
"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)?;
Ok(LlmClassifierModeConfig::Custom(
CustomClassifierRouteConfig {
models,
default_target,
prompt: required_classifier_field(route_name, "prompt", prompt)?,
response_schema: required_classifier_field(
route_name,
"response_schema",
response_schema,
)?,
policy: required_classifier_field(route_name, "policy", policy)?,
classify_trigger: *classify_trigger,
message_hash_fallback: *message_hash_fallback,
recent_turn_window: *recent_turn_window,
max_output_tokens: *max_output_tokens,
},
))
}
}
}
}
fn reject_custom_fields(
route_name: &str,
mode: &str,
models: &Option<CategoryModelConfig>,
default_target: &Option<String>,
response_schema: &Option<String>,
policy: &Option<ClassifierPolicyConfig>,
) -> AlgorithmResult<()> {
if models.is_some() || default_target.is_some() || response_schema.is_some() || policy.is_some()
{
return Err(AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} mode {mode} cannot use custom classifier fields"
)));
}
Ok(())
}
fn classifier_field_error(route_name: &str, field: &str, mode: &str) -> AlgorithmConfigError {
AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} mode {mode} cannot use {field}"
))
}
fn required_classifier_field<T: Clone>(
route_name: &str,
field: &str,
value: &Option<T>,
) -> AlgorithmResult<T> {
value.clone().ok_or_else(|| {
AlgorithmConfigError::new(format!(
"llm_classifier route {route_name} requires {field}"
))
})
}
fn build_subagent_router_config(
route_name: &str,
config: &SubagentRouteConfig,
targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<SubagentRouterConfig> {
match config {
SubagentRouteConfig::Passthrough { target } => {
resolve_target_model_id(route_name, target, targets)?;
Ok(SubagentRouterConfig::fixed_target())
}
SubagentRouteConfig::LlmClassifier(config) => {
let LlmClassifierModeConfig::Custom(config) =
config.validated_classifier_mode(route_name)?
else {
return Err(AlgorithmConfigError::new(format!(
"route {route_name}: subagents llm_classifier only supports mode custom"
)));
};
for name in config.models.all_names() {
resolve_target_model_id(route_name, name, targets)?;
}
if config.models.get(&config.default_target).is_empty() {
return Err(AlgorithmConfigError::new(format!(
"route {route_name}: subagents llm_classifier has no model for default category {}",
config.default_target.as_str()
)));
}
let response_schema =
serde_json::from_str(&config.response_schema).map_err(|error| {
AlgorithmConfigError::with_source(
format!(
"route {route_name}: subagents llm_classifier response_schema is invalid JSON: {error}"
),
error,
)
})?;
warn_single_target_classifier(route_name, &config.models);
let mut classifier_config = CustomClassifierConfig::new(
config.prompt,
response_schema,
config.policy.into_libsy(),
);
classifier_config.recent_turn_window = config.recent_turn_window;
classifier_config.max_output_tokens = config.max_output_tokens;
let classifier = Arc::new(
LlmTaskClassifier::new(LlmClassifierConfig::Custom {
default_target: config.default_target.clone(),
config: classifier_config,
})
.map_err(|error| {
AlgorithmConfigError::with_source(
format!("route {route_name}: subagents llm_classifier: {error}"),
error,
)
})?,
);
Ok(SubagentRouterConfig {
classifier,
default_target: config.default_target,
classify_trigger: config.classify_trigger,
message_hash_fallback: config.message_hash_fallback,
})
}
}
}
fn attach_subagent_router(
route_name: &str,
parent: Arc<dyn Algorithm>,
config: Option<&SubagentRouteConfig>,
targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<Arc<dyn Algorithm>> {
let Some(config) = config else {
return Ok(parent);
};
let config = build_subagent_router_config(route_name, config, targets)?;
let algorithm = SubagentRouter::new(parent, config).map_err(|error| {
AlgorithmConfigError::with_source(
format!("route {route_name}: subagent routing: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
fn build_algorithm(
route_name: &str,
config: &AlgorithmSpec,
targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<Arc<dyn Algorithm>> {
match config {
AlgorithmSpec::Noop { .. } => Ok(Arc::new(Noop {})),
AlgorithmSpec::Random {
targets: names,
weights,
seed,
} => {
if let Some(weights) = weights
&& weights.len() != names.len()
{
return Err(AlgorithmConfigError::new(format!(
"random route {route_name}: expected {} weights, got {}",
names.len(),
weights.len()
)));
}
let mut seen = BTreeSet::new();
if let Some(duplicate) = names.iter().find(|name| !seen.insert(*name)) {
return Err(AlgorithmConfigError::new(format!(
"random route {route_name}: targets must be unique, {duplicate} is repeated"
)));
}
let algorithm = Random::new(weights.clone(), *seed).map_err(|error| {
AlgorithmConfigError::with_source(
format!("random route {route_name}: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
AlgorithmSpec::Passthrough { subagents, .. } => {
let algorithm = Passthrough;
let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
}
AlgorithmSpec::PlanExecute {
planning_prompt,
handoff_prompt,
planner_reasoning_as_text,
..
} => {
let mut config = PlanExecuteConfig::default();
if let Some(prompt) = planning_prompt {
config.planning_prompt = prompt.clone();
}
config.handoff_prompt.clone_from(handoff_prompt);
config.planner_reasoning_as_text = *planner_reasoning_as_text;
let algorithm = PlanExecute::new(config).map_err(|error| {
AlgorithmConfigError::with_source(
format!("plan_execute route {route_name}: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
AlgorithmSpec::LlmClassifier {
config: classifier_config,
..
} => {
let mode = classifier_config.validated_classifier_mode(route_name)?;
let algorithm = match mode {
LlmClassifierModeConfig::Capability(config) => {
let classifier_config = TaskClassifierConfig {
base_threshold: config.base_threshold,
threshold_step: config.threshold_step,
classify_trigger: config.classify_trigger,
message_hash_fallback: config.message_hash_fallback,
recent_turn_window: config.recent_turn_window,
contract: classifier_contract(config.prompt.as_deref())
.with_response_format_type(config.response_format_type),
max_output_tokens: config.max_output_tokens,
};
LlmTaskClassifier::new(LlmClassifierConfig::Capability {
config: classifier_config,
})
}
LlmClassifierModeConfig::Escalation(config) => {
LlmTaskClassifier::new(LlmClassifierConfig::Escalation {
contract: classifier_contract(config.prompt.as_deref())
.with_response_format_type(config.response_format_type),
config: config.judge,
max_output_tokens: config.max_output_tokens,
})
}
LlmClassifierModeConfig::Custom(config) => {
let response_schema = serde_json::from_str(&config.response_schema).map_err(
|error| {
AlgorithmConfigError::with_source(
format!(
"llm_classifier route {route_name}: response_schema is invalid JSON: {error}"
),
error,
)
},
)?;
warn_single_target_classifier(route_name, &config.models);
let mut classifier_config = CustomClassifierConfig::new(
config.prompt,
response_schema,
config.policy.into_libsy(),
);
classifier_config.classify_trigger = config.classify_trigger;
classifier_config.message_hash_fallback = config.message_hash_fallback;
classifier_config.recent_turn_window = config.recent_turn_window;
classifier_config.max_output_tokens = config.max_output_tokens;
LlmTaskClassifier::new(LlmClassifierConfig::Custom {
default_target: config.default_target,
config: classifier_config,
})
}
}
.map_err(|error| {
AlgorithmConfigError::with_source(
format!("llm_classifier route {route_name}: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
AlgorithmSpec::StageRouter {
tiers,
picker,
classifier,
subagents,
..
} => {
let StageTierConfig {
confidence_threshold,
recent_turn_window,
tool_semantics,
capable_hold_turns,
handoff_notes,
..
} = tiers;
if matches!(picker, PickerMode::CapableFirst) {
tracing::warn!(
"stage_router route {route_name} uses picker \"capable_first\", which is experimental: published thresholds and routing results all come from \"efficient_first\", so there is no calibrated confidence_threshold for it and no measured accuracy or cost. Use \"efficient_first\" unless you are running your own calibration."
);
}
let mut config = StageRouterConfig::new(*picker, *confidence_threshold);
config.recent_window = *recent_turn_window;
if let Some(turns) = capable_hold_turns {
config.capable_hold_turns = *turns;
}
config.tool_semantics = tool_semantics.clone();
config.handoff_notes = handoff_notes.clone();
config.llm_fallback = classifier.as_ref().map(|classifier| LlmFallback {
config: classifier.task_classifier_config(),
});
let algorithm = StageRouter::new(config).map_err(|error| {
AlgorithmConfigError::with_source(
format!("stage_router route {route_name}: {error}"),
error,
)
})?;
let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
}
AlgorithmSpec::Auto { .. } => {
let config = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5);
let algorithm = StageRouter::new(config).map_err(|error| {
AlgorithmConfigError::with_source(
format!("auto route {route_name}: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
AlgorithmSpec::Composite {
classifier,
stage,
subagents,
} => {
let mut stage_config =
StageRouterConfig::new(PickerMode::EfficientFirst, stage.confidence_threshold);
stage_config.recent_window = stage.recent_turn_window;
if let Some(turns) = stage.capable_hold_turns {
stage_config.capable_hold_turns = turns;
}
stage_config.tool_semantics = stage.tool_semantics.clone();
stage_config.handoff_notes = stage.handoff_notes.clone();
let config = CompositeRouterConfig {
judge: classifier.task_classifier_config(),
stage: stage_config,
};
let algorithm = CompositeRouter::new(config).map_err(|error| {
AlgorithmConfigError::with_source(
format!("composite route {route_name}: {error}"),
error,
)
})?;
let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
}
AlgorithmSpec::Advisor {
reviewer_system_prompt,
redo_feedback_prefix,
gate_trigger,
gate_trigger_pattern,
max_reviews,
gate_stall_turns,
gate_min_tool_results,
advisor_max_tokens,
advisor_temperature,
transcript_max_chars,
fail_open,
..
} => {
if *gate_trigger == AdvisorTriggerConfig::NoToolCall && gate_trigger_pattern.is_some() {
return Err(AlgorithmConfigError::new(format!(
"advisor route {route_name}: gate_trigger_pattern requires \
gate_trigger = \"pattern\""
)));
}
let mut config = AdvisorGateConfig::default();
if let Some(prompt) = reviewer_system_prompt {
config.reviewer_system_prompt = prompt.clone();
}
if let Some(prefix) = redo_feedback_prefix {
config.redo_feedback_prefix = prefix.clone();
}
config.gate_trigger = match gate_trigger {
AdvisorTriggerConfig::NoToolCall => GateTrigger::NoToolCall,
AdvisorTriggerConfig::Pattern => {
GateTrigger::Pattern(gate_trigger_pattern.clone().unwrap_or_default())
}
};
config.max_reviews = *max_reviews;
config.gate_stall_turns = *gate_stall_turns;
config.gate_min_tool_results = *gate_min_tool_results;
config.advisor_max_tokens = *advisor_max_tokens;
config.advisor_temperature = *advisor_temperature;
config.transcript_max_chars = *transcript_max_chars;
config.fail_open = *fail_open;
let algorithm = AdvisorGate::new(config).map_err(|error| {
AlgorithmConfigError::with_source(
format!("advisor route {route_name}: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
AlgorithmSpec::PrefillRouter {
targets: names,
checkpoint,
device,
cache_dir,
max_length,
batch_size,
} => {
#[cfg(feature = "prefill-router")]
{
let targets = names
.iter()
.map(|name| resolve_target_model_id(route_name, name, targets))
.collect::<AlgorithmResult<Vec<_>>>()?;
let mut config = prefill_router::PrefillRouterConfig::new(targets, checkpoint);
config.device.clone_from(device);
config.cache_dir.clone_from(cache_dir);
if let Some(max_length) = max_length {
config.max_length = *max_length;
}
if let Some(batch_size) = batch_size {
config.batch_size = *batch_size;
}
let algorithm = config.build().map_err(|error| {
AlgorithmConfigError::with_source(
format!("prefill_router route {route_name}: {error}"),
error,
)
})?;
Ok(Arc::new(algorithm))
}
#[cfg(not(feature = "prefill-router"))]
{
let _ = (
names, checkpoint, device, cache_dir, max_length, batch_size, targets,
);
Err(AlgorithmConfigError::new(format!(
"prefill_router route {route_name} requires the `prefill-router` Cargo feature"
)))
}
}
}
}
const fn default_max_reviews() -> u32 {
1
}
const fn default_advisor_max_tokens() -> u64 {
2048
}
const fn default_transcript_max_chars() -> usize {
200_000
}
const fn default_fail_open() -> bool {
true
}
fn classifier_contract(prompt: Option<&str>) -> ClassifierContractConfig {
prompt.map_or_else(ClassifierContractConfig::default, |prompt| {
ClassifierContractConfig::default().with_prompt(prompt)
})
}
fn default_classifier_max_output_tokens() -> u64 {
TaskClassifierConfig::default().max_output_tokens
}
fn warn_single_target_classifier(route_name: &str, models: &CategoryModelConfig) {
if models.routing_names().len() < 2 {
tracing::warn!(
route = route_name,
"custom classifier has only one routing target; judge calls add cost without a routing choice. Use passthrough or add another completion target in routes.<name>, or in routes.<name>.subagents for a subagent classifier."
);
}
}
fn resolve_target_model_id(
route_name: &str,
name: &str,
targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<ModelId> {
targets.get(name).cloned().ok_or_else(|| {
AlgorithmConfigError::new(format!(
"route {route_name} references unknown target {name}"
))
})
}