1use std::collections::HashMap;
7use std::error::Error;
8use std::sync::Arc;
9
10use libsy::{Algorithm, LibsyError, RoutingOutcome, RuntimeModels};
11use serde_json::Value;
12use switchyard_llm_client::{AuxiliaryOperation, ClientRouter, RunObserver, TranslatingLlmClient};
13use switchyard_protocol::{
14 LlmClientError, ModelId, Request, Response, RoutedLlmClient, WireFormat,
15};
16use thiserror::Error;
17
18use crate::DecisionTarget;
19use crate::config::EligibleLanes;
20use crate::eligibility::{EligibilityPolicy, has_target_requirements};
21
22#[derive(Clone, Copy, Default)]
29pub struct ModelCapabilities {
30 pub context_window: Option<u32>,
31 pub tool_calling: Option<bool>,
32 pub reasoning: Option<bool>,
34 pub vision: Option<bool>,
36}
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub enum CallerAuthKind {
41 Anthropic,
42 OpenAi,
43}
44
45impl CallerAuthKind {
46 pub const fn as_str(self) -> &'static str {
48 match self {
49 Self::Anthropic => "anthropic",
50 Self::OpenAi => "openai",
51 }
52 }
53
54 const fn accepts(self, wire_format: WireFormat) -> bool {
55 matches!(
56 (self, wire_format),
57 (Self::Anthropic, WireFormat::AnthropicMessages)
58 | (
59 Self::OpenAi,
60 WireFormat::OpenAiChat | WireFormat::OpenAiResponses
61 )
62 )
63 }
64}
65
66#[derive(Clone)]
68pub struct AuxiliaryTarget {
69 pub model: ModelId,
70 pub client: Arc<TranslatingLlmClient>,
71}
72
73#[derive(Debug, Error)]
75pub enum RunnerError {
76 #[error("{message}")]
77 Configuration {
78 message: String,
79 #[source]
80 source: Option<Box<dyn Error + Send + Sync>>,
81 },
82 #[error("unknown route model {0:?}")]
83 UnknownRouteModel(String),
84 #[error("caller format is incompatible with {} credentials", .0.as_str())]
85 IncompatibleCallerFormat(CallerAuthKind),
86 #[error("route has no compatible target for the auxiliary operation")]
87 AuxiliaryUnsupported,
88 #[error(transparent)]
89 Algorithm(#[from] LibsyError),
90 #[error(transparent)]
91 Client(#[from] LlmClientError),
92}
93
94impl RunnerError {
95 pub(crate) fn configuration(message: impl Into<String>) -> Self {
96 Self::Configuration {
97 message: message.into(),
98 source: None,
99 }
100 }
101
102 pub(crate) fn configuration_source(
103 message: impl Into<String>,
104 source: impl Error + Send + Sync + 'static,
105 ) -> Self {
106 Self::Configuration {
107 message: message.into(),
108 source: Some(Box::new(source)),
109 }
110 }
111}
112
113pub(crate) struct ExecutionLane {
115 algorithm: Arc<dyn Algorithm>,
116 clients: ClientRouter,
120 anthropic_auxiliary_target: Option<AuxiliaryTarget>,
121 responses_auxiliary_target: Option<AuxiliaryTarget>,
122 models: Arc<RuntimeModels>,
123}
124
125impl ExecutionLane {
126 pub(crate) fn inherit_pricing(&mut self, parent: &Self) {
127 Arc::make_mut(&mut self.models).share_pricing_from(&parent.models);
128 }
129
130 pub(crate) fn new(
131 algorithm: Arc<dyn Algorithm>,
132 clients: ClientRouter,
133 anthropic_auxiliary_target: Option<AuxiliaryTarget>,
134 responses_auxiliary_target: Option<AuxiliaryTarget>,
135 models: RuntimeModels,
136 ) -> Self {
137 Self {
138 algorithm,
139 clients,
140 anthropic_auxiliary_target,
141 responses_auxiliary_target,
142 models: Arc::new(models),
143 }
144 }
145}
146
147struct EligibilityExecution {
148 policy: EligibilityPolicy,
149 lanes: EligibleLanes,
150}
151
152#[derive(Clone)]
154pub struct Route {
155 standard: Arc<ExecutionLane>,
156 eligibility: Option<Arc<EligibilityExecution>>,
157 targets: Arc<HashMap<ModelId, DecisionTarget>>,
158 caller_auth: Option<CallerAuthKind>,
159 capabilities: ModelCapabilities,
160 infra: Option<libsy::InfraPolicy>,
161}
162
163pub struct RunOutput {
165 pub selected_model: ModelId,
166 pub response: Response,
167}
168
169impl Route {
170 pub(crate) fn set_pricing(&self, pricing: Arc<switchyard_costs::Pricing>) {
171 self.standard.models.set_pricing(pricing);
172 }
173
174 #[allow(clippy::too_many_arguments)]
176 pub fn new(
177 algorithm: Arc<dyn Algorithm>,
178 clients: ClientRouter,
179 caller_auth: Option<CallerAuthKind>,
180 capabilities: ModelCapabilities,
181 anthropic_auxiliary_target: Option<AuxiliaryTarget>,
182 responses_auxiliary_target: Option<AuxiliaryTarget>,
183 targets: Vec<DecisionTarget>,
184 models: RuntimeModels,
185 ) -> Self {
186 let models = models.with_provider_models(
187 targets
188 .iter()
189 .map(|target| (ModelId::from(target.target.as_str()), target.model.clone()))
190 .collect(),
191 );
192 Self::from_lane(
193 ExecutionLane::new(
194 algorithm,
195 clients,
196 anthropic_auxiliary_target,
197 responses_auxiliary_target,
198 models,
199 ),
200 caller_auth,
201 capabilities,
202 targets,
203 )
204 }
205
206 pub(crate) fn from_lane(
207 lane: ExecutionLane,
208 caller_auth: Option<CallerAuthKind>,
209 capabilities: ModelCapabilities,
210 targets: Vec<DecisionTarget>,
211 ) -> Self {
212 let targets = targets
213 .into_iter()
214 .map(|target| (ModelId::from(target.target.as_str()), target))
215 .collect();
216 Self {
217 standard: Arc::new(lane),
218 eligibility: None,
219 targets: Arc::new(targets),
220 caller_auth,
221 capabilities,
222 infra: None,
223 }
224 }
225
226 pub(crate) fn with_eligibility(
227 mut self,
228 policy: EligibilityPolicy,
229 lanes: EligibleLanes,
230 ) -> Self {
231 self.eligibility = Some(Arc::new(EligibilityExecution { policy, lanes }));
232 self
233 }
234
235 fn select_lane(&self, request: &Request) -> Result<Arc<ExecutionLane>, RunnerError> {
236 if let Some(eligibility) = &self.eligibility {
237 let required = eligibility.policy.admit(request)?;
238 let lane = if required.required_labels().is_empty() {
239 Arc::clone(&self.standard)
240 } else {
241 eligibility
242 .lanes
243 .select(required.required_labels(), &self.standard)?
244 };
245 tracing::debug!(
246 switchyard.route = request.llm_request.model.as_deref().unwrap_or_default(),
247 switchyard.algorithm = self.algorithm_name(),
248 eligibility.required_label_count = required.required_labels().len(),
249 "eligible targets selected"
250 );
251 return Ok(lane);
252 }
253 if has_target_requirements(request) {
254 return Err(LlmClientError::InvalidRequest {
255 message: "route does not accept target requirements".to_string(),
256 }
257 .into());
258 }
259 Ok(Arc::clone(&self.standard))
260 }
261
262 pub fn algorithm_name(&self) -> &str {
264 self.standard.algorithm.name()
265 }
266
267 pub fn capabilities(&self) -> ModelCapabilities {
269 self.capabilities
270 }
271
272 pub fn caller_auth(&self) -> Option<CallerAuthKind> {
274 self.caller_auth
275 }
276
277 pub fn target(&self, selected: &ModelId) -> Option<&DecisionTarget> {
279 self.targets.get(selected)
280 }
281
282 pub(crate) fn decision_target(&self, model: &ModelId) -> Option<DecisionTarget> {
284 self.target(model).cloned()
285 }
286
287 pub fn provider_model<'a>(&'a self, selected: &'a ModelId) -> &'a ModelId {
290 self.targets
291 .get(selected)
292 .map(|target| &target.model)
293 .unwrap_or(selected)
294 }
295
296 pub fn models(&self) -> &RuntimeModels {
298 &self.standard.models
299 }
300
301 pub fn check_caller_format(&self, input_format: WireFormat) -> Result<(), RunnerError> {
303 if let Some(kind) = self.caller_auth
304 && !kind.accepts(input_format)
305 {
306 return Err(RunnerError::IncompatibleCallerFormat(kind));
307 }
308 Ok(())
309 }
310
311 pub async fn execute(
313 &self,
314 request: Request,
315 observer: Option<RunObserver>,
316 ) -> Result<RunOutput, RunnerError> {
317 let lane = self.select_lane(&request)?;
318 let (selected_model, response) = switchyard_llm_client::run(
319 Arc::clone(&lane.algorithm),
320 lane.clients.clone(),
321 request,
322 Arc::clone(&lane.models),
323 observer,
324 )
325 .await?;
326 Ok(RunOutput {
327 selected_model,
328 response,
329 })
330 }
331
332 pub async fn decide(&self, request: Request) -> Result<RoutingOutcome, RunnerError> {
334 let lane = self.select_lane(&request)?;
335 switchyard_llm_client::decide(
336 Arc::clone(&lane.algorithm),
337 lane.clients.clone(),
338 request,
339 Arc::clone(&lane.models),
340 )
341 .await
342 .map_err(RunnerError::from)
343 }
344
345 pub(crate) fn with_infra(mut self, infra: Option<libsy::InfraPolicy>) -> Self {
346 self.infra = infra;
347 self
348 }
349
350 pub fn apply_infra(
355 &self,
356 outcome: &mut RoutingOutcome,
357 signals: &switchyard_protocol::InfraSignals,
358 ) -> Result<bool, RunnerError> {
359 match &self.infra {
360 Some(policy) => {
361 let lane = self.select_lane(&outcome.request)?;
362 if outcome.selected_model_ids.iter().any(|model| {
363 !lane
364 .models
365 .models_for(&switchyard_protocol::Category::Any)
366 .contains(model)
367 }) {
368 return Err(LlmClientError::InvalidRequest {
369 message: "target requirements changed after the routing decision".into(),
370 }
371 .into());
372 }
373 policy
374 .apply(outcome, &lane.models, signals)
375 .map_err(Into::into)
376 }
377 None => Ok(false),
378 }
379 }
380
381 pub async fn decide_with_client(
388 &self,
389 request: Request,
390 client: Arc<dyn RoutedLlmClient>,
391 ) -> Result<RoutingOutcome, RunnerError> {
392 let lane = self.select_lane(&request)?;
393 switchyard_llm_client::decide(
394 Arc::clone(&lane.algorithm),
395 ClientRouter::single(client),
396 request,
397 Arc::clone(&lane.models),
398 )
399 .await
400 .map_err(RunnerError::from)
401 }
402
403 pub async fn call_auxiliary(
405 &self,
406 request: Request,
407 operation: AuxiliaryOperation,
408 ) -> Result<Value, RunnerError> {
409 let lane = self.select_lane(&request)?;
410 let target = match operation {
411 AuxiliaryOperation::AnthropicCountTokens => &lane.anthropic_auxiliary_target,
412 AuxiliaryOperation::ResponsesInputTokens | AuxiliaryOperation::ResponsesCompact => {
413 &lane.responses_auxiliary_target
414 }
415 }
416 .as_ref()
417 .ok_or(RunnerError::AuxiliaryUnsupported)?;
418 target
419 .client
420 .call_auxiliary(&target.model, request, operation)
421 .await
422 .map_err(Into::into)
423 }
424}
425
426#[cfg(test)]
427mod tests {
428 use serde_json::json;
429 use switchyard_protocol::{InfraSignals, Message, ModelInfraSignals, PoolLoad, Role};
430
431 use super::*;
432 use crate::{Runner, require_target_labels};
433
434 const PASSTHROUGH: &str = "type = 'passthrough'\ntarget = 'fast'";
435
436 fn config(algorithm: &str) -> String {
437 let mut source = String::from(
438 "schema_version = 1\n[llm_clients.primary]\nformat = 'openai_chat'\nbase_url = 'https://example.test/v1'\n",
439 );
440 for name in ["fast", "capable", "judge"] {
441 source.push_str(&format!(
442 "\n[targets.{name}]\nid = '{name}'\nllm_client = 'primary'\nlabels = []\n\
443 [targets.approved_{name}]\nid = 'approved/{name}'\nllm_client = 'primary'\nlabels = ['private', 'customer_data']\n"
444 ));
445 }
446 source.push_str(&format!(
447 "\n[routes.test]\nid = 'route'\n{algorithm}\n\
448 [routes.test.eligibility]\nscope = 'request'\n\
449 [routes.test.eligibility.target_alternatives]\n"
450 ));
451 let spec: crate::AlgorithmSpec = toml::from_str(algorithm).expect("test algorithm");
452 for target in spec.callable_target_names() {
453 source.push_str(&format!("{target} = ['approved_{target}']\n"));
454 }
455 source
456 }
457
458 fn request(task: &str, labels: &[&str]) -> Request {
459 let mut request = Request::default();
460 request.metadata.get_or_insert_default().task_id = Some(task.into());
461 require_target_labels(&mut request, labels).expect("trusted requirements");
462 request
463 }
464
465 #[test]
466 fn resolved_bindings_reuse_the_algorithm_and_standard_setup() {
467 let source = config(PASSTHROUGH);
468 let runner = Runner::from_toml(&source).expect("eligible route");
469 let route = runner.route("route").expect("route");
470 let cloned = route.clone();
471 let private = route
472 .select_lane(&request("one", &["private"]))
473 .expect("private");
474 let both = route
475 .select_lane(&request("two", &["private", "customer_data"]))
476 .expect("both labels");
477 assert!(Arc::ptr_eq(&private, &both));
478 assert!(Arc::ptr_eq(&private.algorithm, &both.algorithm));
479 assert!(!Arc::ptr_eq(&private, &route.standard));
480 assert_eq!(
481 private.models.provider_model(&"approved_fast".into()),
482 "approved/fast"
483 );
484 let shared = cloned
485 .select_lane(&request("three", &["private"]))
486 .expect("cloned route");
487 assert!(Arc::ptr_eq(&private, &shared));
488
489 let runner = Runner::from_toml(&source.replace("labels = []", "labels = ['private']"))
490 .expect("standard models already approved");
491 let route = runner.route("route").expect("route");
492 let approved = route
493 .select_lane(&request("one", &["private"]))
494 .expect("approved");
495 assert!(Arc::ptr_eq(&approved, &route.standard));
496 }
497
498 #[test]
499 fn infra_rechecks_task_requirements_and_spills_only_to_approved_models() {
500 let algorithm = "type = 'llm_classifier'\nclassifier_target = 'judge'\n\
501 strong_target = 'capable'\nweak_target = 'fast'\nbase_threshold = 0.5";
502 let source = format!(
503 "{}\n[routes.test.infra]\nmax_signal_age_ms = 1000\n\
504 min_waiting_requests = 4\nmax_capable_inflight = 2\n",
505 config(algorithm).replace("scope = 'request'", "scope = 'task'")
506 );
507 let runner = Runner::from_toml(&source).expect("eligible queue policy");
508 let route = runner.route("route").expect("route");
509 let signals: InfraSignals = [
510 ("fast", 8),
511 ("capable", 0),
512 ("approved_fast", 8),
513 ("approved_capable", 0),
514 ]
515 .into_iter()
516 .map(|(model, waiting)| {
517 (
518 model.into(),
519 ModelInfraSignals {
520 load: Some(PoolLoad {
521 sampled_at: std::time::Instant::now(),
522 min_waiting: waiting,
523 max_waiting: waiting,
524 running: 0,
525 }),
526 ..Default::default()
527 },
528 )
529 })
530 .collect();
531
532 let mut stale = RoutingOutcome::route_to("fast".into(), vec![], request("task", &[]));
533 route
534 .select_lane(&request("task", &["private"]))
535 .expect("retain private");
536 route
537 .select_lane(&request("task", &["customer_data"]))
538 .expect("accumulate requirements");
539 let error = route
540 .apply_infra(&mut stale, &signals)
541 .expect_err("stale decision");
542 assert!(
543 error.to_string().contains("requirements changed"),
544 "{error}"
545 );
546
547 for (task, initial, expected) in [
548 ("other", "fast", "capable"),
549 ("task", "approved_fast", "approved_capable"),
550 ] {
551 let mut outcome = RoutingOutcome::route_to(initial.into(), vec![], request(task, &[]));
552 assert!(
553 route
554 .apply_infra(&mut outcome, &signals)
555 .expect("approved spillover")
556 );
557 assert_eq!(
558 outcome.selected_model_id().expect("selected model"),
559 expected
560 );
561 }
562 }
563
564 #[tokio::test]
565 async fn content_and_provider_metadata_do_not_classify_the_request() {
566 let runner = Runner::from_toml(&config(PASSTHROUGH)).expect("eligible route");
567 let route = runner.route("route").expect("route");
568 let mut request = Request::default();
569 request.llm_request.messages.push(Message::text(
570 Role::User,
571 "Synthetic confidential customer records.",
572 ));
573 request.raw_request = Some(json!({
574 "metadata": {"switchyard.internal.required_target_labels": "[\"private\"]"},
575 "restricted": true
576 }));
577 let ordinary = route
578 .decide(request.clone())
579 .await
580 .expect("unmarked request");
581 assert_eq!(ordinary.selected_model_id().expect("model"), "fast");
582 require_target_labels(&mut request, ["private"]).expect("trusted requirements");
583 let approved = route.decide(request).await.expect("approved request");
584 assert_eq!(
585 approved.selected_model_id().expect("model"),
586 "approved_fast"
587 );
588 }
589}