1use std::collections::{BTreeMap, BTreeSet, HashMap};
7use std::error::Error;
8use std::fmt::{Display, Formatter};
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use libsy::{
13 AdvisorGate, AdvisorGateConfig, Algorithm, ClassifierContractConfig, ClassifierResponseFormat,
14 ClassifyTrigger, CompositeRouter, CompositeRouterConfig, CustomClassifierConfig,
15 CustomClassifierPolicy, EscalationJudgeConfig, GateTrigger, HandoffNoteConfig,
16 LlmClassifierConfig, LlmFallback, LlmTaskClassifier, Noop, Passthrough, PickerMode,
17 PlanExecute, PlanExecuteConfig, Random, StageRouter, StageRouterConfig, SubagentRouter,
18 SubagentRouterConfig, TaskClassifierConfig, ToolSemantics,
19};
20use serde::Deserialize;
21use switchyard_protocol::{Category, ModelId};
22
23#[derive(Debug)]
25pub struct AlgorithmConfigError {
26 message: String,
27 source: Option<Box<dyn Error + Send + Sync>>,
28}
29
30impl AlgorithmConfigError {
31 fn new(message: impl Into<String>) -> Self {
32 Self {
33 message: message.into(),
34 source: None,
35 }
36 }
37
38 fn with_source(message: impl Into<String>, source: impl Error + Send + Sync + 'static) -> Self {
39 Self {
40 message: message.into(),
41 source: Some(Box::new(source)),
42 }
43 }
44}
45
46impl Display for AlgorithmConfigError {
47 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
48 formatter.write_str(&self.message)
49 }
50}
51
52impl Error for AlgorithmConfigError {
53 fn source(&self) -> Option<&(dyn Error + 'static)> {
54 self.source.as_deref().map(|source| source as _)
55 }
56}
57
58type AlgorithmResult<T> = Result<T, AlgorithmConfigError>;
59
60#[derive(Clone, Debug, Deserialize)]
62#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
63pub enum ClassifierPolicyConfig {
64 TargetSelector {
66 selector: String,
68 },
69}
70
71#[derive(Clone, Copy, Debug, Deserialize)]
73#[serde(rename_all = "snake_case")]
74pub enum ClassifierMode {
75 Capability,
77 Escalation,
80 Custom,
82}
83
84impl ClassifierPolicyConfig {
85 fn into_libsy(self) -> CustomClassifierPolicy {
86 match self {
87 Self::TargetSelector { selector } => CustomClassifierPolicy::target_selector(selector),
88 }
89 }
90}
91
92#[derive(Clone, Debug)]
93enum LlmClassifierModeConfig {
94 Capability(CapabilityClassifierRouteConfig),
95 Escalation(EscalationClassifierRouteConfig),
96 Custom(CustomClassifierRouteConfig),
97}
98
99#[derive(Clone, Debug)]
100struct CapabilityClassifierRouteConfig {
101 classifier_target: String,
102 strong_target: String,
103 weak_target: String,
104 base_threshold: f64,
105 threshold_step: f64,
106 classify_trigger: ClassifyTrigger,
107 message_hash_fallback: bool,
108 recent_turn_window: Option<usize>,
109 prompt: Option<String>,
110 response_format_type: ClassifierResponseFormat,
111 max_output_tokens: u64,
112}
113
114#[derive(Clone, Debug)]
115struct EscalationClassifierRouteConfig {
116 classifier_target: String,
117 strong_target: String,
118 weak_target: String,
119 prompt: Option<String>,
120 response_format_type: ClassifierResponseFormat,
121 max_output_tokens: u64,
122 judge: EscalationJudgeConfig,
123}
124
125#[derive(Clone, Debug)]
126struct CustomClassifierRouteConfig {
127 models: CategoryModelConfig,
128 default_target: Category,
129 prompt: String,
130 response_schema: String,
131 policy: ClassifierPolicyConfig,
132 classify_trigger: ClassifyTrigger,
133 message_hash_fallback: bool,
134 recent_turn_window: Option<usize>,
135 max_output_tokens: u64,
136}
137
138#[derive(Clone, Debug, Default, Deserialize)]
146#[serde(transparent)]
147pub struct CategoryModelConfig(BTreeMap<String, Vec<String>>);
148
149impl CategoryModelConfig {
150 fn validate(&self, route_name: &str, default_target: &Category) -> AlgorithmResult<()> {
151 for category in [Category::Any, Category::Judge] {
152 if self.get(&category).is_empty() {
153 return Err(AlgorithmConfigError::new(format!(
154 "llm_classifier route {route_name} models.{} must contain at least one target",
155 category.as_str()
156 )));
157 }
158 }
159 if self.get(default_target).is_empty() {
160 return Err(AlgorithmConfigError::new(format!(
161 "llm_classifier route {route_name} models.{} must contain at least one target because it is the default_target",
162 default_target.as_str()
163 )));
164 }
165 let any = self.get(&Category::Any);
169 for (name, models) in &self.0 {
170 if name == Category::Judge.as_str() || name == Category::Any.as_str() {
171 continue;
172 }
173 if let Some(missing) = models.iter().find(|model| !any.contains(model)) {
174 return Err(AlgorithmConfigError::new(format!(
175 "llm_classifier route {route_name} models.{name} lists target {missing}, which must also appear in models.any"
176 )));
177 }
178 }
179 Ok(())
180 }
181
182 fn get(&self, category: &Category) -> &[String] {
183 self.0.get(category.as_str()).map_or(&[], Vec::as_slice)
184 }
185
186 fn all_names(&self) -> Vec<&str> {
188 Self::deduped(self.0.values().flatten())
189 }
190
191 fn routing_names(&self) -> Vec<&str> {
196 let others = self
197 .0
198 .iter()
199 .filter(|(name, _)| {
200 *name != Category::Judge.as_str() && *name != Category::Any.as_str()
201 })
202 .flat_map(|(_, models)| models);
203 Self::deduped(self.get(&Category::Any).iter().chain(others))
204 }
205
206 fn deduped<'a>(names: impl Iterator<Item = &'a String>) -> Vec<&'a str> {
207 let mut seen = BTreeSet::new();
208 names
209 .map(String::as_str)
210 .filter(|name| seen.insert(*name))
211 .collect()
212 }
213
214 fn groups(&self) -> impl Iterator<Item = (Category, Vec<String>)> + '_ {
215 self.0
216 .iter()
217 .filter_map(|(name, models)| Some((name.parse::<Category>().ok()?, models.clone())))
218 }
219}
220
221#[derive(Clone, Debug, Default, Deserialize)]
224#[serde(default, deny_unknown_fields)]
225pub struct LlmClassifierRouteConfig {
226 pub classifier_target: String,
228 pub mode: Option<ClassifierMode>,
230 pub strong_target: Option<String>,
232 pub weak_target: Option<String>,
234 pub base_threshold: Option<f64>,
237 pub threshold_step: Option<f64>,
240 pub classify_trigger: ClassifyTrigger,
242 pub message_hash_fallback: bool,
245 pub recent_turn_window: Option<usize>,
248 pub prompt: Option<String>,
250 pub response_format_type: ClassifierResponseFormat,
253 #[serde(default = "default_classifier_max_output_tokens")]
255 pub max_output_tokens: u64,
256 pub escalation: Option<EscalationJudgeConfig>,
259 pub models: Option<CategoryModelConfig>,
261 pub default_target: Option<String>,
263 pub response_schema: Option<String>,
265 pub policy: Option<ClassifierPolicyConfig>,
267}
268
269#[derive(Clone, Debug, Deserialize)]
272#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
273pub enum SubagentRouteConfig {
274 Passthrough {
276 target: String,
278 },
279 LlmClassifier(Box<LlmClassifierRouteConfig>),
281}
282
283impl SubagentRouteConfig {
284 fn routing_target_names(&self) -> Vec<&str> {
285 match self {
286 Self::Passthrough { target } => vec![target],
287 Self::LlmClassifier(classifier) => classifier
288 .models
289 .as_ref()
290 .map(CategoryModelConfig::routing_names)
291 .unwrap_or_default(),
292 }
293 }
294
295 fn judge_target_names(&self) -> Vec<&str> {
296 match self {
297 Self::Passthrough { .. } => Vec::new(),
298 Self::LlmClassifier(classifier) => classifier
299 .models
300 .as_ref()
301 .map(|models| models.get(&Category::Judge))
302 .unwrap_or_default()
303 .iter()
304 .map(String::as_str)
305 .collect(),
306 }
307 }
308}
309
310#[derive(Clone, Debug, Deserialize)]
312#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
313pub enum AlgorithmSpec {
314 Noop {},
316 Random {
318 targets: Vec<String>,
320 weights: Option<Vec<f64>>,
322 seed: Option<u64>,
324 },
325 Passthrough {
327 target: String,
329 #[serde(default)]
331 subagents: Option<SubagentRouteConfig>,
332 },
333 PlanExecute {
335 capable_target: String,
337 efficient_target: String,
339 #[serde(default)]
341 planning_prompt: Option<String>,
342 #[serde(default)]
344 handoff_prompt: Option<String>,
345 #[serde(default)]
347 planner_reasoning_as_text: bool,
348 },
349 LlmClassifier {
351 #[serde(flatten)]
353 config: LlmClassifierRouteConfig,
354 },
355 StageRouter {
357 #[serde(flatten)]
358 tiers: StageTierConfig,
359 picker: PickerMode,
361 #[serde(default)]
363 classifier: Option<StageClassifierConfig>,
364 #[serde(default)]
366 subagents: Option<SubagentRouteConfig>,
367 },
368 Auto {
373 capable_target: String,
375 efficient_target: String,
377 },
378 Composite {
380 classifier: StageClassifierConfig,
382 stage: StageTierConfig,
384 #[serde(default)]
386 subagents: Option<SubagentRouteConfig>,
387 },
388 Advisor {
391 executor_target: String,
393 advisor_target: String,
395 #[serde(default)]
397 reviewer_system_prompt: Option<String>,
398 #[serde(default)]
400 redo_feedback_prefix: Option<String>,
401 #[serde(default)]
403 gate_trigger: AdvisorTriggerConfig,
404 #[serde(default)]
406 gate_trigger_pattern: Option<String>,
407 #[serde(default = "default_max_reviews")]
409 max_reviews: u32,
410 #[serde(default)]
413 gate_stall_turns: u32,
414 #[serde(default)]
416 gate_min_tool_results: u32,
417 #[serde(default = "default_advisor_max_tokens")]
419 advisor_max_tokens: u64,
420 #[serde(default)]
422 advisor_temperature: Option<f64>,
423 #[serde(default = "default_transcript_max_chars")]
426 transcript_max_chars: usize,
427 #[serde(default = "default_fail_open")]
429 fail_open: bool,
430 },
431 PrefillRouter {
433 targets: Vec<String>,
435 checkpoint: PathBuf,
437 device: Option<String>,
440 cache_dir: Option<PathBuf>,
442 max_length: Option<usize>,
444 batch_size: Option<usize>,
446 },
447}
448
449#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
451#[serde(rename_all = "snake_case")]
452pub enum AdvisorTriggerConfig {
453 #[default]
455 NoToolCall,
456 Pattern,
458}
459
460#[derive(Clone, Debug, Deserialize)]
462#[serde(deny_unknown_fields)]
463pub struct StageClassifierConfig {
464 pub target: String,
466 pub base_threshold: f64,
468 #[serde(default)]
471 pub threshold_step: f64,
472 #[serde(default)]
474 pub classify_trigger: ClassifyTrigger,
475 #[serde(default)]
478 pub message_hash_fallback: bool,
479 #[serde(default)]
482 pub recent_turn_window: Option<usize>,
483 #[serde(default)]
485 pub prompt: Option<String>,
486 #[serde(default)]
489 pub response_format_type: ClassifierResponseFormat,
490 #[serde(default = "default_classifier_max_output_tokens")]
492 pub max_output_tokens: u64,
493}
494
495#[derive(Clone, Debug, Deserialize)]
500#[serde(deny_unknown_fields)]
501pub struct StageTierConfig {
502 pub capable_target: String,
504 pub efficient_target: String,
506 pub confidence_threshold: f64,
508 #[serde(default)]
510 pub recent_turn_window: Option<usize>,
511 #[serde(default)]
513 pub tool_semantics: ToolSemantics,
514 #[serde(default)]
516 pub capable_hold_turns: Option<u32>,
517 #[serde(default)]
519 pub handoff_notes: Option<HandoffNoteConfig>,
520}
521
522impl StageClassifierConfig {
523 fn task_classifier_config(&self) -> TaskClassifierConfig {
524 TaskClassifierConfig {
525 base_threshold: self.base_threshold,
526 threshold_step: self.threshold_step,
527 classify_trigger: self.classify_trigger,
528 message_hash_fallback: self.message_hash_fallback,
529 recent_turn_window: self.recent_turn_window,
530 contract: classifier_contract(self.prompt.as_deref())
531 .with_response_format_type(self.response_format_type),
532 max_output_tokens: self.max_output_tokens,
533 }
534 }
535}
536
537impl AlgorithmSpec {
538 pub fn routing_target_names(&self) -> Vec<&str> {
540 match self {
541 Self::Noop { .. } => Vec::new(),
542 Self::Random { targets, .. } => targets.iter().map(String::as_str).collect(),
543 Self::Passthrough {
544 target, subagents, ..
545 } => {
546 let mut names = vec![target.as_str()];
547 if let Some(subagents) = subagents {
548 names.extend(subagents.routing_target_names());
549 }
550 names
551 }
552 Self::PlanExecute {
553 capable_target,
554 efficient_target,
555 ..
556 } => vec![capable_target.as_str(), efficient_target.as_str()],
557 Self::LlmClassifier { config, .. } => match config.classifier_mode() {
558 ClassifierMode::Capability => config
559 .weak_target
560 .iter()
561 .chain(&config.strong_target)
562 .map(String::as_str)
563 .collect(),
564 ClassifierMode::Escalation => config
565 .strong_target
566 .iter()
567 .chain(&config.weak_target)
568 .map(String::as_str)
569 .collect(),
570 ClassifierMode::Custom => config
571 .models
572 .as_ref()
573 .map(CategoryModelConfig::routing_names)
574 .unwrap_or_default(),
575 },
576 Self::StageRouter {
577 tiers, subagents, ..
578 } => {
579 let mut names = vec![
580 tiers.capable_target.as_str(),
581 tiers.efficient_target.as_str(),
582 ];
583 if let Some(subagents) = subagents {
584 names.extend(subagents.routing_target_names());
585 }
586 names
587 }
588 Self::Auto {
589 capable_target,
590 efficient_target,
591 } => vec![capable_target.as_str(), efficient_target.as_str()],
592 Self::Composite {
593 stage, subagents, ..
594 } => {
595 let mut names = vec![
596 stage.capable_target.as_str(),
597 stage.efficient_target.as_str(),
598 ];
599 if let Some(subagents) = subagents {
600 names.extend(subagents.routing_target_names());
601 }
602 names
603 }
604 Self::Advisor {
607 executor_target, ..
608 } => vec![executor_target],
609 Self::PrefillRouter { targets, .. } => targets.iter().map(String::as_str).collect(),
610 }
611 }
612
613 pub fn callable_target_names(&self) -> Vec<&str> {
618 let mut names = self.routing_target_names();
619 match self {
620 Self::LlmClassifier { config, .. } => {
623 if matches!(config.classifier_mode(), ClassifierMode::Custom) {
624 names.extend(
625 config
626 .models
627 .as_ref()
628 .map(|models| models.get(&Category::Judge))
629 .unwrap_or_default()
630 .iter()
631 .map(String::as_str),
632 );
633 } else {
634 names.push(&config.classifier_target);
635 }
636 }
637 Self::StageRouter {
638 classifier: Some(classifier),
639 ..
640 } => names.push(&classifier.target),
641 Self::Composite { classifier, .. } => {
642 names.push(&classifier.target);
643 }
644 Self::Advisor { advisor_target, .. } => names.push(advisor_target),
645 _ => {}
646 }
647 if let Self::Passthrough {
649 subagents: Some(subagents),
650 ..
651 }
652 | Self::StageRouter {
653 subagents: Some(subagents),
654 ..
655 }
656 | Self::Composite {
657 subagents: Some(subagents),
658 ..
659 } = self
660 {
661 names.extend(subagents.judge_target_names());
662 }
663 names
664 }
665
666 pub(crate) fn runtime_model_names(
668 &self,
669 route_name: &str,
670 ) -> AlgorithmResult<RuntimeModelNames> {
671 let parent = match self {
672 Self::Noop { .. } => HashMap::new(),
673 Self::Random { targets, .. } | Self::PrefillRouter { targets, .. } => {
674 category_models([(Category::Any, targets.clone())])
675 }
676 Self::Passthrough { target, .. } => {
677 category_models([(Category::Any, vec![target.clone()])])
678 }
679 Self::PlanExecute {
680 capable_target,
681 efficient_target,
682 ..
683 } => category_models([
684 (Category::Capable, vec![capable_target.clone()]),
685 (Category::Efficient, vec![efficient_target.clone()]),
686 (
687 Category::Any,
688 vec![capable_target.clone(), efficient_target.clone()],
689 ),
690 ]),
691 Self::LlmClassifier { config } => {
692 classifier_runtime_model_names(config.validated_classifier_mode(route_name)?)
693 }
694 Self::StageRouter {
695 tiers, classifier, ..
696 } => {
697 let mut models = category_models([
698 (Category::Capable, vec![tiers.capable_target.clone()]),
699 (Category::Efficient, vec![tiers.efficient_target.clone()]),
700 (
701 Category::Any,
702 vec![tiers.capable_target.clone(), tiers.efficient_target.clone()],
703 ),
704 ]);
705 if let Some(classifier) = classifier {
706 models.insert(Category::Judge, vec![classifier.target.clone()]);
707 }
708 models
709 }
710 Self::Auto {
711 capable_target,
712 efficient_target,
713 } => category_models([
714 (Category::Capable, vec![capable_target.clone()]),
715 (Category::Efficient, vec![efficient_target.clone()]),
716 (
717 Category::Any,
718 vec![capable_target.clone(), efficient_target.clone()],
719 ),
720 ]),
721 Self::Composite {
722 classifier, stage, ..
723 } => category_models([
724 (Category::Judge, vec![classifier.target.clone()]),
725 (Category::Capable, vec![stage.capable_target.clone()]),
726 (Category::Efficient, vec![stage.efficient_target.clone()]),
727 (
728 Category::Any,
729 vec![stage.capable_target.clone(), stage.efficient_target.clone()],
730 ),
731 ]),
732 Self::Advisor {
733 executor_target,
734 advisor_target,
735 ..
736 } => category_models([
737 (Category::Efficient, vec![executor_target.clone()]),
738 (Category::Any, vec![executor_target.clone()]),
739 (Category::Judge, vec![advisor_target.clone()]),
740 ]),
741 };
742
743 let subagents = match self {
744 Self::Passthrough { subagents, .. }
745 | Self::StageRouter { subagents, .. }
746 | Self::Composite { subagents, .. } => subagents.as_ref(),
747 _ => None,
748 };
749 let subagent = subagents
753 .map(|subagents| subagent_runtime_model_names(subagents, route_name))
754 .transpose()?;
755 Ok(RuntimeModelNames { parent, subagent })
756 }
757
758 pub(crate) fn routing_response_and_dependency(&self) -> Option<(&str, &str)> {
760 match self {
761 Self::LlmClassifier { config, .. }
762 if matches!(config.classifier_mode(), ClassifierMode::Escalation) =>
763 {
764 Some((
765 config.weak_target.as_deref()?,
766 config.classifier_target.as_str(),
767 ))
768 }
769 Self::Advisor {
770 executor_target,
771 advisor_target,
772 ..
773 } => Some((executor_target, advisor_target)),
774 Self::Noop { .. }
775 | Self::Random { .. }
776 | Self::Passthrough { .. }
777 | Self::PlanExecute { .. }
778 | Self::LlmClassifier { .. }
779 | Self::StageRouter { .. }
780 | Self::Auto { .. }
781 | Self::Composite { .. }
782 | Self::PrefillRouter { .. } => None,
783 }
784 }
785
786 pub fn build(
788 &self,
789 context: &str,
790 targets: &BTreeMap<String, ModelId>,
791 ) -> AlgorithmResult<Arc<dyn Algorithm>> {
792 build_algorithm(context, self, targets)
793 }
794}
795
796pub(crate) struct RuntimeModelNames {
798 pub(crate) parent: HashMap<Category, Vec<String>>,
800 pub(crate) subagent: Option<HashMap<Category, Vec<String>>>,
802}
803
804fn category_models(
805 entries: impl IntoIterator<Item = (Category, Vec<String>)>,
806) -> HashMap<Category, Vec<String>> {
807 entries.into_iter().collect()
808}
809
810fn custom_runtime_model_names(config: &CategoryModelConfig) -> HashMap<Category, Vec<String>> {
811 config.groups().collect()
812}
813
814fn classifier_runtime_model_names(
815 config: LlmClassifierModeConfig,
816) -> HashMap<Category, Vec<String>> {
817 match config {
818 LlmClassifierModeConfig::Capability(config) => category_models([
819 (Category::Judge, vec![config.classifier_target]),
820 (Category::Efficient, vec![config.weak_target.clone()]),
821 (Category::Capable, vec![config.strong_target.clone()]),
822 (
823 Category::Any,
824 vec![config.weak_target, config.strong_target],
825 ),
826 ]),
827 LlmClassifierModeConfig::Escalation(config) => category_models([
828 (Category::Judge, vec![config.classifier_target]),
829 (Category::Efficient, vec![config.weak_target.clone()]),
830 (Category::Capable, vec![config.strong_target.clone()]),
831 (
832 Category::Any,
833 vec![config.strong_target, config.weak_target],
834 ),
835 ]),
836 LlmClassifierModeConfig::Custom(config) => custom_runtime_model_names(&config.models),
837 }
838}
839
840fn subagent_runtime_model_names(
841 config: &SubagentRouteConfig,
842 route_name: &str,
843) -> AlgorithmResult<HashMap<Category, Vec<String>>> {
844 match config {
845 SubagentRouteConfig::Passthrough { target } => {
846 Ok(category_models([(Category::Any, vec![target.clone()])]))
847 }
848 SubagentRouteConfig::LlmClassifier(config) => {
849 let LlmClassifierModeConfig::Custom(config) =
850 config.validated_classifier_mode(route_name)?
851 else {
852 return Err(AlgorithmConfigError::new(format!(
853 "route {route_name}: subagents llm_classifier only supports mode custom"
854 )));
855 };
856 Ok(custom_runtime_model_names(&config.models))
857 }
858 }
859}
860impl LlmClassifierRouteConfig {
861 fn classifier_mode(&self) -> ClassifierMode {
862 let default = if self.escalation.is_some() {
863 ClassifierMode::Escalation
864 } else {
865 ClassifierMode::Capability
866 };
867 self.mode.unwrap_or(default)
868 }
869
870 fn validated_classifier_mode(
871 &self,
872 route_name: &str,
873 ) -> AlgorithmResult<LlmClassifierModeConfig> {
874 let Self {
875 classifier_target,
876 mode,
877 strong_target,
878 weak_target,
879 base_threshold,
880 threshold_step,
881 classify_trigger,
882 message_hash_fallback,
883 recent_turn_window,
884 prompt,
885 response_format_type,
886 max_output_tokens,
887 escalation,
888 models,
889 default_target,
890 response_schema,
891 policy,
892 } = self;
893
894 let selected_mode = match (mode, escalation.is_some()) {
895 (Some(mode), _) => *mode,
896 (None, true) => ClassifierMode::Escalation,
897 (None, false) => ClassifierMode::Capability,
898 };
899
900 match selected_mode {
901 ClassifierMode::Capability => {
902 if escalation.is_some() {
903 return Err(classifier_field_error(
904 route_name,
905 "escalation",
906 "capability",
907 ));
908 }
909 reject_custom_fields(
910 route_name,
911 "capability",
912 models,
913 default_target,
914 response_schema,
915 policy,
916 )?;
917 Ok(LlmClassifierModeConfig::Capability(
918 CapabilityClassifierRouteConfig {
919 classifier_target: classifier_target.clone(),
920 strong_target: required_classifier_field(
921 route_name,
922 "strong_target",
923 strong_target,
924 )?,
925 weak_target: required_classifier_field(
926 route_name,
927 "weak_target",
928 weak_target,
929 )?,
930 base_threshold: required_classifier_field(
931 route_name,
932 "base_threshold",
933 base_threshold,
934 )?,
935 threshold_step: threshold_step.unwrap_or_default(),
936 classify_trigger: *classify_trigger,
937 message_hash_fallback: *message_hash_fallback,
938 recent_turn_window: *recent_turn_window,
939 prompt: prompt.clone(),
940 response_format_type: *response_format_type,
941 max_output_tokens: *max_output_tokens,
942 },
943 ))
944 }
945 ClassifierMode::Escalation => {
946 reject_custom_fields(
947 route_name,
948 "escalation",
949 models,
950 default_target,
951 response_schema,
952 policy,
953 )?;
954 if *classify_trigger != ClassifyTrigger::EveryRequest {
955 return Err(AlgorithmConfigError::new(format!(
956 "llm_classifier route {route_name} mode escalation cannot use classify_trigger"
957 )));
958 }
959 if mode.is_some()
960 && (base_threshold.is_some()
961 || threshold_step.is_some()
962 || *message_hash_fallback
963 || recent_turn_window.is_some())
964 {
965 return Err(AlgorithmConfigError::new(format!(
966 "llm_classifier route {route_name} mode escalation cannot use capability routing settings"
967 )));
968 }
969 Ok(LlmClassifierModeConfig::Escalation(
970 EscalationClassifierRouteConfig {
971 classifier_target: classifier_target.clone(),
972 strong_target: required_classifier_field(
973 route_name,
974 "strong_target",
975 strong_target,
976 )?,
977 weak_target: required_classifier_field(
978 route_name,
979 "weak_target",
980 weak_target,
981 )?,
982 prompt: prompt.clone(),
983 response_format_type: *response_format_type,
984 max_output_tokens: *max_output_tokens,
985 judge: required_classifier_field(route_name, "escalation", escalation)?,
986 },
987 ))
988 }
989 ClassifierMode::Custom => {
990 if !classifier_target.is_empty()
991 || strong_target.is_some()
992 || weak_target.is_some()
993 || base_threshold.is_some()
994 || threshold_step.is_some()
995 || escalation.is_some()
996 || *response_format_type != ClassifierResponseFormat::JsonSchema
997 {
998 return Err(AlgorithmConfigError::new(format!(
999 "llm_classifier route {route_name} mode custom cannot use capability or escalation fields and response_format_type must be 'json_schema'"
1000 )));
1001 }
1002 let models = required_classifier_field(route_name, "models", models)?;
1003 let default_target: Category = required_classifier_field(
1004 route_name,
1005 "default_target",
1006 default_target,
1007 )?
1008 .parse()
1009 .map_err(|error| {
1010 AlgorithmConfigError::new(format!(
1011 "llm_classifier route {route_name} has invalid default_target: {error}"
1012 ))
1013 })?;
1014 if default_target == Category::Judge {
1015 return Err(AlgorithmConfigError::new(format!(
1016 "llm_classifier route {route_name} default_target cannot be judge"
1017 )));
1018 }
1019 models.validate(route_name, &default_target)?;
1020 Ok(LlmClassifierModeConfig::Custom(
1021 CustomClassifierRouteConfig {
1022 models,
1023 default_target,
1024 prompt: required_classifier_field(route_name, "prompt", prompt)?,
1025 response_schema: required_classifier_field(
1026 route_name,
1027 "response_schema",
1028 response_schema,
1029 )?,
1030 policy: required_classifier_field(route_name, "policy", policy)?,
1031 classify_trigger: *classify_trigger,
1032 message_hash_fallback: *message_hash_fallback,
1033 recent_turn_window: *recent_turn_window,
1034 max_output_tokens: *max_output_tokens,
1035 },
1036 ))
1037 }
1038 }
1039 }
1040}
1041
1042fn reject_custom_fields(
1043 route_name: &str,
1044 mode: &str,
1045 models: &Option<CategoryModelConfig>,
1046 default_target: &Option<String>,
1047 response_schema: &Option<String>,
1048 policy: &Option<ClassifierPolicyConfig>,
1049) -> AlgorithmResult<()> {
1050 if models.is_some() || default_target.is_some() || response_schema.is_some() || policy.is_some()
1051 {
1052 return Err(AlgorithmConfigError::new(format!(
1053 "llm_classifier route {route_name} mode {mode} cannot use custom classifier fields"
1054 )));
1055 }
1056 Ok(())
1057}
1058
1059fn classifier_field_error(route_name: &str, field: &str, mode: &str) -> AlgorithmConfigError {
1060 AlgorithmConfigError::new(format!(
1061 "llm_classifier route {route_name} mode {mode} cannot use {field}"
1062 ))
1063}
1064
1065fn required_classifier_field<T: Clone>(
1066 route_name: &str,
1067 field: &str,
1068 value: &Option<T>,
1069) -> AlgorithmResult<T> {
1070 value.clone().ok_or_else(|| {
1071 AlgorithmConfigError::new(format!(
1072 "llm_classifier route {route_name} requires {field}"
1073 ))
1074 })
1075}
1076
1077fn build_subagent_router_config(
1078 route_name: &str,
1079 config: &SubagentRouteConfig,
1080 targets: &BTreeMap<String, ModelId>,
1081) -> AlgorithmResult<SubagentRouterConfig> {
1082 match config {
1083 SubagentRouteConfig::Passthrough { target } => {
1084 resolve_target_model_id(route_name, target, targets)?;
1085 Ok(SubagentRouterConfig::fixed_target())
1086 }
1087 SubagentRouteConfig::LlmClassifier(config) => {
1088 let LlmClassifierModeConfig::Custom(config) =
1089 config.validated_classifier_mode(route_name)?
1090 else {
1091 return Err(AlgorithmConfigError::new(format!(
1092 "route {route_name}: subagents llm_classifier only supports mode custom"
1093 )));
1094 };
1095 for name in config.models.all_names() {
1096 resolve_target_model_id(route_name, name, targets)?;
1097 }
1098 if config.models.get(&config.default_target).is_empty() {
1099 return Err(AlgorithmConfigError::new(format!(
1100 "route {route_name}: subagents llm_classifier has no model for default category {}",
1101 config.default_target.as_str()
1102 )));
1103 }
1104 let response_schema =
1105 serde_json::from_str(&config.response_schema).map_err(|error| {
1106 AlgorithmConfigError::with_source(
1107 format!(
1108 "route {route_name}: subagents llm_classifier response_schema is invalid JSON: {error}"
1109 ),
1110 error,
1111 )
1112 })?;
1113 warn_single_target_classifier(route_name, &config.models);
1114 let mut classifier_config = CustomClassifierConfig::new(
1115 config.prompt,
1116 response_schema,
1117 config.policy.into_libsy(),
1118 );
1119 classifier_config.recent_turn_window = config.recent_turn_window;
1120 classifier_config.max_output_tokens = config.max_output_tokens;
1121 let classifier = Arc::new(
1122 LlmTaskClassifier::new(LlmClassifierConfig::Custom {
1123 default_target: config.default_target.clone(),
1124 config: classifier_config,
1125 })
1126 .map_err(|error| {
1127 AlgorithmConfigError::with_source(
1128 format!("route {route_name}: subagents llm_classifier: {error}"),
1129 error,
1130 )
1131 })?,
1132 );
1133 Ok(SubagentRouterConfig {
1134 classifier,
1135 default_target: config.default_target,
1136 classify_trigger: config.classify_trigger,
1137 message_hash_fallback: config.message_hash_fallback,
1138 })
1139 }
1140 }
1141}
1142
1143fn attach_subagent_router(
1144 route_name: &str,
1145 parent: Arc<dyn Algorithm>,
1146 config: Option<&SubagentRouteConfig>,
1147 targets: &BTreeMap<String, ModelId>,
1148) -> AlgorithmResult<Arc<dyn Algorithm>> {
1149 let Some(config) = config else {
1150 return Ok(parent);
1151 };
1152 let config = build_subagent_router_config(route_name, config, targets)?;
1153 let algorithm = SubagentRouter::new(parent, config).map_err(|error| {
1154 AlgorithmConfigError::with_source(
1155 format!("route {route_name}: subagent routing: {error}"),
1156 error,
1157 )
1158 })?;
1159 Ok(Arc::new(algorithm))
1160}
1161
1162fn build_algorithm(
1163 route_name: &str,
1164 config: &AlgorithmSpec,
1165 targets: &BTreeMap<String, ModelId>,
1166) -> AlgorithmResult<Arc<dyn Algorithm>> {
1167 match config {
1168 AlgorithmSpec::Noop { .. } => Ok(Arc::new(Noop {})),
1169 AlgorithmSpec::Random {
1170 targets: names,
1171 weights,
1172 seed,
1173 } => {
1174 if let Some(weights) = weights
1177 && weights.len() != names.len()
1178 {
1179 return Err(AlgorithmConfigError::new(format!(
1180 "random route {route_name}: expected {} weights, got {}",
1181 names.len(),
1182 weights.len()
1183 )));
1184 }
1185 let mut seen = BTreeSet::new();
1186 if let Some(duplicate) = names.iter().find(|name| !seen.insert(*name)) {
1187 return Err(AlgorithmConfigError::new(format!(
1188 "random route {route_name}: targets must be unique, {duplicate} is repeated"
1189 )));
1190 }
1191 let algorithm = Random::new(weights.clone(), *seed).map_err(|error| {
1192 AlgorithmConfigError::with_source(
1193 format!("random route {route_name}: {error}"),
1194 error,
1195 )
1196 })?;
1197 Ok(Arc::new(algorithm))
1198 }
1199 AlgorithmSpec::Passthrough { subagents, .. } => {
1200 let algorithm = Passthrough;
1201 let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
1202 attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
1203 }
1204 AlgorithmSpec::PlanExecute {
1205 planning_prompt,
1206 handoff_prompt,
1207 planner_reasoning_as_text,
1208 ..
1209 } => {
1210 let mut config = PlanExecuteConfig::default();
1211 if let Some(prompt) = planning_prompt {
1212 config.planning_prompt = prompt.clone();
1213 }
1214 config.handoff_prompt.clone_from(handoff_prompt);
1215 config.planner_reasoning_as_text = *planner_reasoning_as_text;
1216 let algorithm = PlanExecute::new(config).map_err(|error| {
1217 AlgorithmConfigError::with_source(
1218 format!("plan_execute route {route_name}: {error}"),
1219 error,
1220 )
1221 })?;
1222 Ok(Arc::new(algorithm))
1223 }
1224 AlgorithmSpec::LlmClassifier {
1225 config: classifier_config,
1226 ..
1227 } => {
1228 let mode = classifier_config.validated_classifier_mode(route_name)?;
1229 let algorithm = match mode {
1230 LlmClassifierModeConfig::Capability(config) => {
1231 let classifier_config = TaskClassifierConfig {
1232 base_threshold: config.base_threshold,
1233 threshold_step: config.threshold_step,
1234 classify_trigger: config.classify_trigger,
1235 message_hash_fallback: config.message_hash_fallback,
1236 recent_turn_window: config.recent_turn_window,
1237 contract: classifier_contract(config.prompt.as_deref())
1238 .with_response_format_type(config.response_format_type),
1239 max_output_tokens: config.max_output_tokens,
1240 };
1241 LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1242 config: classifier_config,
1243 })
1244 }
1245 LlmClassifierModeConfig::Escalation(config) => {
1246 LlmTaskClassifier::new(LlmClassifierConfig::Escalation {
1247 contract: classifier_contract(config.prompt.as_deref())
1248 .with_response_format_type(config.response_format_type),
1249 config: config.judge,
1250 max_output_tokens: config.max_output_tokens,
1251 })
1252 }
1253 LlmClassifierModeConfig::Custom(config) => {
1254 let response_schema = serde_json::from_str(&config.response_schema).map_err(
1255 |error| {
1256 AlgorithmConfigError::with_source(
1257 format!(
1258 "llm_classifier route {route_name}: response_schema is invalid JSON: {error}"
1259 ),
1260 error,
1261 )
1262 },
1263 )?;
1264 warn_single_target_classifier(route_name, &config.models);
1265 let mut classifier_config = CustomClassifierConfig::new(
1266 config.prompt,
1267 response_schema,
1268 config.policy.into_libsy(),
1269 );
1270 classifier_config.classify_trigger = config.classify_trigger;
1271 classifier_config.message_hash_fallback = config.message_hash_fallback;
1272 classifier_config.recent_turn_window = config.recent_turn_window;
1273 classifier_config.max_output_tokens = config.max_output_tokens;
1274 LlmTaskClassifier::new(LlmClassifierConfig::Custom {
1275 default_target: config.default_target,
1276 config: classifier_config,
1277 })
1278 }
1279 }
1280 .map_err(|error| {
1281 AlgorithmConfigError::with_source(
1282 format!("llm_classifier route {route_name}: {error}"),
1283 error,
1284 )
1285 })?;
1286 Ok(Arc::new(algorithm))
1287 }
1288 AlgorithmSpec::StageRouter {
1289 tiers,
1290 picker,
1291 classifier,
1292 subagents,
1293 ..
1294 } => {
1295 let StageTierConfig {
1296 confidence_threshold,
1297 recent_turn_window,
1298 tool_semantics,
1299 capable_hold_turns,
1300 handoff_notes,
1301 ..
1302 } = tiers;
1303 if matches!(picker, PickerMode::CapableFirst) {
1304 tracing::warn!(
1305 "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."
1306 );
1307 }
1308 let mut config = StageRouterConfig::new(*picker, *confidence_threshold);
1309 config.recent_window = *recent_turn_window;
1310 if let Some(turns) = capable_hold_turns {
1311 config.capable_hold_turns = *turns;
1312 }
1313 config.tool_semantics = tool_semantics.clone();
1314 config.handoff_notes = handoff_notes.clone();
1315 config.llm_fallback = classifier.as_ref().map(|classifier| LlmFallback {
1318 config: classifier.task_classifier_config(),
1319 });
1320 let algorithm = StageRouter::new(config).map_err(|error| {
1321 AlgorithmConfigError::with_source(
1322 format!("stage_router route {route_name}: {error}"),
1323 error,
1324 )
1325 })?;
1326 let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
1327 attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
1328 }
1329 AlgorithmSpec::Auto { .. } => {
1330 let config = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5);
1331 let algorithm = StageRouter::new(config).map_err(|error| {
1332 AlgorithmConfigError::with_source(
1333 format!("auto route {route_name}: {error}"),
1334 error,
1335 )
1336 })?;
1337 Ok(Arc::new(algorithm))
1338 }
1339 AlgorithmSpec::Composite {
1340 classifier,
1341 stage,
1342 subagents,
1343 } => {
1344 let mut stage_config =
1345 StageRouterConfig::new(PickerMode::EfficientFirst, stage.confidence_threshold);
1346 stage_config.recent_window = stage.recent_turn_window;
1347 if let Some(turns) = stage.capable_hold_turns {
1348 stage_config.capable_hold_turns = turns;
1349 }
1350 stage_config.tool_semantics = stage.tool_semantics.clone();
1351 stage_config.handoff_notes = stage.handoff_notes.clone();
1352 let config = CompositeRouterConfig {
1353 judge: classifier.task_classifier_config(),
1354 stage: stage_config,
1355 };
1356 let algorithm = CompositeRouter::new(config).map_err(|error| {
1357 AlgorithmConfigError::with_source(
1358 format!("composite route {route_name}: {error}"),
1359 error,
1360 )
1361 })?;
1362 let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
1363 attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
1364 }
1365 AlgorithmSpec::Advisor {
1366 reviewer_system_prompt,
1367 redo_feedback_prefix,
1368 gate_trigger,
1369 gate_trigger_pattern,
1370 max_reviews,
1371 gate_stall_turns,
1372 gate_min_tool_results,
1373 advisor_max_tokens,
1374 advisor_temperature,
1375 transcript_max_chars,
1376 fail_open,
1377 ..
1378 } => {
1379 if *gate_trigger == AdvisorTriggerConfig::NoToolCall && gate_trigger_pattern.is_some() {
1382 return Err(AlgorithmConfigError::new(format!(
1383 "advisor route {route_name}: gate_trigger_pattern requires \
1384 gate_trigger = \"pattern\""
1385 )));
1386 }
1387 let mut config = AdvisorGateConfig::default();
1388 if let Some(prompt) = reviewer_system_prompt {
1389 config.reviewer_system_prompt = prompt.clone();
1390 }
1391 if let Some(prefix) = redo_feedback_prefix {
1392 config.redo_feedback_prefix = prefix.clone();
1393 }
1394 config.gate_trigger = match gate_trigger {
1395 AdvisorTriggerConfig::NoToolCall => GateTrigger::NoToolCall,
1396 AdvisorTriggerConfig::Pattern => {
1397 GateTrigger::Pattern(gate_trigger_pattern.clone().unwrap_or_default())
1398 }
1399 };
1400 config.max_reviews = *max_reviews;
1401 config.gate_stall_turns = *gate_stall_turns;
1402 config.gate_min_tool_results = *gate_min_tool_results;
1403 config.advisor_max_tokens = *advisor_max_tokens;
1404 config.advisor_temperature = *advisor_temperature;
1405 config.transcript_max_chars = *transcript_max_chars;
1406 config.fail_open = *fail_open;
1407 let algorithm = AdvisorGate::new(config).map_err(|error| {
1408 AlgorithmConfigError::with_source(
1409 format!("advisor route {route_name}: {error}"),
1410 error,
1411 )
1412 })?;
1413 Ok(Arc::new(algorithm))
1414 }
1415 AlgorithmSpec::PrefillRouter {
1416 targets: names,
1417 checkpoint,
1418 device,
1419 cache_dir,
1420 max_length,
1421 batch_size,
1422 } => {
1423 #[cfg(feature = "prefill-router")]
1424 {
1425 let targets = names
1426 .iter()
1427 .map(|name| resolve_target_model_id(route_name, name, targets))
1428 .collect::<AlgorithmResult<Vec<_>>>()?;
1429 let mut config = prefill_router::PrefillRouterConfig::new(targets, checkpoint);
1430 config.device.clone_from(device);
1431 config.cache_dir.clone_from(cache_dir);
1432 if let Some(max_length) = max_length {
1433 config.max_length = *max_length;
1434 }
1435 if let Some(batch_size) = batch_size {
1436 config.batch_size = *batch_size;
1437 }
1438 let algorithm = config.build().map_err(|error| {
1439 AlgorithmConfigError::with_source(
1440 format!("prefill_router route {route_name}: {error}"),
1441 error,
1442 )
1443 })?;
1444 Ok(Arc::new(algorithm))
1445 }
1446
1447 #[cfg(not(feature = "prefill-router"))]
1448 {
1449 let _ = (
1450 names, checkpoint, device, cache_dir, max_length, batch_size, targets,
1451 );
1452 Err(AlgorithmConfigError::new(format!(
1453 "prefill_router route {route_name} requires the `prefill-router` Cargo feature"
1454 )))
1455 }
1456 }
1457 }
1458}
1459
1460const fn default_max_reviews() -> u32 {
1461 1
1462}
1463
1464const fn default_advisor_max_tokens() -> u64 {
1465 2048
1466}
1467
1468const fn default_transcript_max_chars() -> usize {
1469 200_000
1470}
1471
1472const fn default_fail_open() -> bool {
1473 true
1474}
1475
1476fn classifier_contract(prompt: Option<&str>) -> ClassifierContractConfig {
1477 prompt.map_or_else(ClassifierContractConfig::default, |prompt| {
1478 ClassifierContractConfig::default().with_prompt(prompt)
1479 })
1480}
1481
1482fn default_classifier_max_output_tokens() -> u64 {
1483 TaskClassifierConfig::default().max_output_tokens
1484}
1485
1486fn warn_single_target_classifier(route_name: &str, models: &CategoryModelConfig) {
1487 if models.routing_names().len() < 2 {
1488 tracing::warn!(
1489 route = route_name,
1490 "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."
1491 );
1492 }
1493}
1494
1495fn resolve_target_model_id(
1496 route_name: &str,
1497 name: &str,
1498 targets: &BTreeMap<String, ModelId>,
1499) -> AlgorithmResult<ModelId> {
1500 targets.get(name).cloned().ok_or_else(|| {
1501 AlgorithmConfigError::new(format!(
1502 "route {route_name} references unknown target {name}"
1503 ))
1504 })
1505}