Skip to main content

switchyard_runner/
route.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One configured algorithm and the clients that serve its targets.
5
6use std::error::Error;
7use std::sync::Arc;
8
9use libsy::{Algorithm, LibsyError, RoutingOutcome, RuntimeModels};
10use serde_json::Value;
11use switchyard_llm_client::{AuxiliaryOperation, ClientRouter, RunObserver, TranslatingLlmClient};
12use switchyard_protocol::{LlmClientError, ModelId, Request, Response, WireFormat};
13use thiserror::Error;
14
15use crate::DecisionTarget;
16
17/// Capabilities declared for one route.
18///
19/// `GET /v1/models` includes `context_window`, `tool_calling`, and `vision` in each
20/// standard `data` entry, using `null` for unset values. It omits `reasoning`.
21/// The server rejects tool inputs, reasoning controls, or images when the
22/// corresponding declaration is explicitly `false` for the selected route.
23#[derive(Clone, Copy, Default)]
24pub struct ModelCapabilities {
25    pub context_window: Option<u32>,
26    pub tool_calling: Option<bool>,
27    /// Whether the routed model accepts reasoning controls, as declared in config.
28    pub reasoning: Option<bool>,
29    /// Whether the routed model accepts image input, as declared in config.
30    pub vision: Option<bool>,
31}
32
33/// Caller credential family required by a forwarded-auth route.
34#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub enum CallerAuthKind {
36    Anthropic,
37    OpenAi,
38}
39
40impl CallerAuthKind {
41    /// Stable provider name used by the server compatibility API.
42    pub const fn as_str(self) -> &'static str {
43        match self {
44            Self::Anthropic => "anthropic",
45            Self::OpenAi => "openai",
46        }
47    }
48
49    const fn accepts(self, wire_format: WireFormat) -> bool {
50        matches!(
51            (self, wire_format),
52            (Self::Anthropic, WireFormat::AnthropicMessages)
53                | (
54                    Self::OpenAi,
55                    WireFormat::OpenAiChat | WireFormat::OpenAiResponses
56                )
57        )
58    }
59}
60
61/// Exact upstream model and client used for an auxiliary provider operation.
62#[derive(Clone)]
63pub struct AuxiliaryTarget {
64    pub model: ModelId,
65    pub client: Arc<TranslatingLlmClient>,
66}
67
68/// Error returned while loading or executing configured routes.
69#[derive(Debug, Error)]
70pub enum RunnerError {
71    #[error("{message}")]
72    Configuration {
73        message: String,
74        #[source]
75        source: Option<Box<dyn Error + Send + Sync>>,
76    },
77    #[error("unknown route model {0:?}")]
78    UnknownRouteModel(String),
79    #[error("caller format is incompatible with {} credentials", .0.as_str())]
80    IncompatibleCallerFormat(CallerAuthKind),
81    #[error("route has no compatible target for the auxiliary operation")]
82    AuxiliaryUnsupported,
83    #[error(transparent)]
84    Algorithm(#[from] LibsyError),
85    #[error(transparent)]
86    Client(#[from] LlmClientError),
87}
88
89impl RunnerError {
90    pub(crate) fn configuration(message: impl Into<String>) -> Self {
91        Self::Configuration {
92            message: message.into(),
93            source: None,
94        }
95    }
96
97    pub(crate) fn configuration_source(
98        message: impl Into<String>,
99        source: impl Error + Send + Sync + 'static,
100    ) -> Self {
101        Self::Configuration {
102            message: message.into(),
103            source: Some(Box::new(source)),
104        }
105    }
106}
107
108/// A configured algorithm and the per-target clients its calls resolve through.
109pub struct Route {
110    algorithm: Arc<dyn Algorithm>,
111    // Resolves each offloaded call to the client configured for the target the algorithm
112    // selected. A route is a synthetic model with no upstream of its own, so this is a
113    // per-target lookup, never one client serving the whole route.
114    clients: ClientRouter,
115    caller_auth: Option<CallerAuthKind>,
116    capabilities: ModelCapabilities,
117    anthropic_auxiliary_target: Option<AuxiliaryTarget>,
118    responses_auxiliary_target: Option<AuxiliaryTarget>,
119    decision_targets: Vec<DecisionTarget>,
120    models: Arc<RuntimeModels>,
121}
122
123/// The selected model and untouched response produced by a route execution.
124pub struct RunOutput {
125    pub selected_model: ModelId,
126    pub response: Response,
127}
128
129impl Route {
130    /// Creates a fully configured execution route.
131    #[allow(clippy::too_many_arguments)]
132    pub fn new(
133        algorithm: Arc<dyn Algorithm>,
134        clients: ClientRouter,
135        caller_auth: Option<CallerAuthKind>,
136        capabilities: ModelCapabilities,
137        anthropic_auxiliary_target: Option<AuxiliaryTarget>,
138        responses_auxiliary_target: Option<AuxiliaryTarget>,
139        decision_targets: Vec<DecisionTarget>,
140        models: RuntimeModels,
141    ) -> Self {
142        Self {
143            algorithm,
144            clients,
145            caller_auth,
146            capabilities,
147            anthropic_auxiliary_target,
148            responses_auxiliary_target,
149            decision_targets,
150            models: Arc::new(models),
151        }
152    }
153
154    /// Returns the configured libsy algorithm name.
155    pub fn algorithm_name(&self) -> &str {
156        self.algorithm.name()
157    }
158
159    /// Returns model-list capability metadata.
160    pub fn capabilities(&self) -> ModelCapabilities {
161        self.capabilities
162    }
163
164    /// Returns the forwarded caller credential family.
165    pub fn caller_auth(&self) -> Option<CallerAuthKind> {
166        self.caller_auth
167    }
168
169    /// Resolves a selected model to this route's non-secret target metadata.
170    pub(crate) fn decision_target(&self, model: &ModelId) -> Option<DecisionTarget> {
171        self.decision_targets
172            .iter()
173            .find(|target| target.model == *model)
174            .cloned()
175    }
176
177    /// Returns the models grouped for one algorithm execution.
178    pub fn models(&self) -> &RuntimeModels {
179        &self.models
180    }
181
182    /// Rejects a caller format incompatible with forwarded credentials.
183    pub fn check_caller_format(&self, input_format: WireFormat) -> Result<(), RunnerError> {
184        if let Some(kind) = self.caller_auth
185            && !kind.accepts(input_format)
186        {
187            return Err(RunnerError::IncompatibleCallerFormat(kind));
188        }
189        Ok(())
190    }
191
192    /// Executes the configured route without consuming or proxying streamed responses.
193    pub async fn execute(
194        &self,
195        request: Request,
196        observer: Option<RunObserver>,
197    ) -> Result<RunOutput, RunnerError> {
198        let (selected_model, response) = switchyard_llm_client::run(
199            Arc::clone(&self.algorithm),
200            self.clients.clone(),
201            request,
202            Arc::clone(&self.models),
203            observer,
204        )
205        .await?;
206        Ok(RunOutput {
207            selected_model,
208            response,
209        })
210    }
211
212    /// Completes routing-time calls without serving a post-routing completion.
213    pub async fn decide(&self, request: Request) -> Result<RoutingOutcome, RunnerError> {
214        switchyard_llm_client::decide(
215            Arc::clone(&self.algorithm),
216            self.clients.clone(),
217            request,
218            Arc::clone(&self.models),
219        )
220        .await
221        .map_err(Into::into)
222    }
223
224    /// Executes a model-bearing provider operation through a compatible target.
225    pub async fn call_auxiliary(
226        &self,
227        request: Request,
228        operation: AuxiliaryOperation,
229    ) -> Result<Value, RunnerError> {
230        let target = match operation {
231            AuxiliaryOperation::AnthropicCountTokens => &self.anthropic_auxiliary_target,
232            AuxiliaryOperation::ResponsesInputTokens | AuxiliaryOperation::ResponsesCompact => {
233                &self.responses_auxiliary_target
234            }
235        }
236        .as_ref()
237        .ok_or(RunnerError::AuxiliaryUnsupported)?;
238        target
239            .client
240            .call_auxiliary(&target.model, request, operation)
241            .await
242            .map_err(Into::into)
243    }
244}