Skip to main content

switchyard_runner/
runner.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Named route table and server-facing route metadata.
5
6use std::collections::BTreeMap;
7use std::path::Path;
8use std::sync::Arc;
9use std::time::Duration;
10
11use libsy::RoutingOutcome;
12use serde_json::Value;
13use switchyard_llm_client::TranslatingLlmClient;
14use switchyard_protocol::{ModelId, WireFormat};
15
16use crate::config;
17use crate::{ModelCapabilities, Route, RunnerError};
18
19/// Immutable named route table.
20pub struct Runner {
21    routes: Vec<(ModelId, Route)>,
22    fallback_base_url: Option<String>,
23    provider_api_keys: Vec<String>,
24    model_properties_probes: BTreeMap<ModelId, ModelPropertiesProbe>,
25}
26
27/// Borrowed model metadata returned while listing routes.
28pub struct ModelInfo<'a> {
29    pub id: &'a ModelId,
30    pub algorithm: &'a str,
31    pub capabilities: ModelCapabilities,
32}
33
34/// Fully resolved routing decision.
35pub struct DecisionDescription {
36    pub selected: DecisionTarget,
37    pub fallbacks: Vec<DecisionTarget>,
38    /// Metadata the algorithm attached to the routing outcome, if any.
39    pub metadata: Option<libsy::OutcomeMetadata>,
40}
41
42/// Non-secret configured target details returned by the decision endpoint.
43#[derive(Clone)]
44pub struct DecisionTarget {
45    pub target: String,
46    pub model: ModelId,
47    pub format: WireFormat,
48    pub base_url: String,
49    pub extra_body: BTreeMap<String, Value>,
50}
51
52pub(crate) struct ModelPropertiesProbe {
53    pub(crate) model: ModelId,
54    pub(crate) format: WireFormat,
55    pub(crate) client: Arc<TranslatingLlmClient>,
56}
57
58impl Runner {
59    /// Loads and validates a version-1 deployment TOML file.
60    pub fn load(path: impl AsRef<Path>) -> Result<Self, RunnerError> {
61        config::load_runner(path)
62    }
63
64    /// Loads and validates a version-1 deployment TOML document.
65    ///
66    /// Use [`Self::load`] when the deployment is stored in a file.
67    pub fn from_toml(source: &str) -> Result<Self, RunnerError> {
68        config::runner_from_toml(source)
69    }
70
71    /// Builds a runner from named routes in caller-provided order.
72    /// Pre-condition: There must be at least one route.
73    pub fn new(routes: Vec<(ModelId, Route)>) -> Self {
74        Self {
75            routes,
76            fallback_base_url: None,
77            provider_api_keys: Vec::new(),
78            model_properties_probes: BTreeMap::new(),
79        }
80    }
81
82    /// Registers deployment-owned API keys for serving-surface output redaction.
83    /// TOML loading registers these automatically; programmatic hosts must supply them.
84    pub fn with_provider_api_keys(mut self, keys: Vec<String>) -> Self {
85        self.provider_api_keys = keys;
86        self
87    }
88
89    /// Returns deployment-owned secrets for serving-surface output redactors.
90    pub fn provider_api_keys(&self) -> &[String] {
91        &self.provider_api_keys
92    }
93
94    pub(crate) fn with_fallback_url(mut self, fallback_base_url: Option<String>) -> Self {
95        self.fallback_base_url = fallback_base_url;
96        self
97    }
98
99    pub(crate) fn with_model_properties_probes(
100        mut self,
101        probes: BTreeMap<ModelId, ModelPropertiesProbe>,
102    ) -> Self {
103        self.model_properties_probes = probes;
104        self
105    }
106
107    /// Returns the route registered for a model.
108    pub fn route(&self, model: &str) -> Option<&Route> {
109        self.routes
110            .iter()
111            .find(|(id, _)| id.as_str() == model)
112            .map(|(_, route)| route)
113    }
114
115    /// Iterates over configured routes in caller-provided order.
116    pub fn models(&self) -> impl Iterator<Item = ModelInfo<'_>> {
117        self.routes.iter().map(|(id, route)| ModelInfo {
118            id,
119            algorithm: route.algorithm_name(),
120            capabilities: route.capabilities(),
121        })
122    }
123
124    /// Reads one route's configured local backend properties without exposing its credentials.
125    pub async fn model_properties(&self, model: &str, timeout: Duration) -> Option<Value> {
126        let probe = self.model_properties_probes.get(model)?;
127        probe
128            .client
129            .get_model_properties(&probe.model, probe.format, timeout)
130            .await
131            .ok()
132    }
133
134    /// Returns the validated API root used for unmatched HTTP requests.
135    pub fn fallback_base_url(&self) -> Option<&str> {
136        self.fallback_base_url.as_deref()
137    }
138
139    /// Resolves an outcome to configured target names and non-secret client settings.
140    pub fn describe_decision(
141        &self,
142        model: &ModelId,
143        outcome: &RoutingOutcome,
144    ) -> Option<DecisionDescription> {
145        let route = self.route(model.as_str())?;
146        let resolve = |selected: &ModelId| {
147            let mut target = route.decision_target(selected)?;
148            let mut url = reqwest::Url::parse(&target.base_url).ok()?;
149            let query: Vec<_> = url
150                .query_pairs()
151                .filter(|(name, _)| !matches!(name.as_ref(), "key" | "api_key"))
152                .map(|(name, value)| (name.into_owned(), value.into_owned()))
153                .collect();
154            if query.len() != url.query_pairs().count() {
155                url.set_query(None);
156                if !query.is_empty() {
157                    url.query_pairs_mut().extend_pairs(query);
158                }
159                // Only the returned metadata changes; inference still needs its credentials.
160                target.base_url = url.into();
161            }
162            Some(target)
163        };
164        let mut model_ids = outcome.selected_model_ids.iter();
165        Some(DecisionDescription {
166            selected: resolve(model_ids.next()?)?,
167            fallbacks: model_ids.map(resolve).collect::<Option<Vec<_>>>()?,
168            metadata: outcome.metadata.clone(),
169        })
170    }
171}