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