switchyard_runner/
runner.rs1use 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
19pub 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
27pub struct ModelInfo<'a> {
29 pub id: &'a ModelId,
30 pub algorithm: &'a str,
31 pub capabilities: ModelCapabilities,
32}
33
34pub struct DecisionDescription {
36 pub selected: DecisionTarget,
37 pub fallbacks: Vec<DecisionTarget>,
38 pub metadata: Option<libsy::OutcomeMetadata>,
40}
41
42#[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 pub reasoning_effort: Option<String>,
52}
53
54pub(crate) struct ModelPropertiesProbe {
55 pub(crate) model: ModelId,
56 pub(crate) format: WireFormat,
57 pub(crate) client: Arc<TranslatingLlmClient>,
58}
59
60impl Runner {
61 pub fn load(path: impl AsRef<Path>) -> Result<Self, RunnerError> {
63 config::load_runner(path)
64 }
65
66 pub fn from_toml(source: &str) -> Result<Self, RunnerError> {
70 config::runner_from_toml(source)
71 }
72
73 pub fn new(routes: Vec<(ModelId, Route)>) -> Self {
76 Self {
77 routes,
78 fallback_base_url: None,
79 provider_api_keys: Vec::new(),
80 model_properties_probes: BTreeMap::new(),
81 }
82 }
83
84 pub fn with_provider_api_keys(mut self, keys: Vec<String>) -> Self {
87 self.provider_api_keys = keys;
88 self
89 }
90
91 pub fn provider_api_keys(&self) -> &[String] {
93 &self.provider_api_keys
94 }
95
96 pub(crate) fn with_fallback_url(mut self, fallback_base_url: Option<String>) -> Self {
97 self.fallback_base_url = fallback_base_url;
98 self
99 }
100
101 pub(crate) fn with_model_properties_probes(
102 mut self,
103 probes: BTreeMap<ModelId, ModelPropertiesProbe>,
104 ) -> Self {
105 self.model_properties_probes = probes;
106 self
107 }
108
109 pub fn route(&self, model: &str) -> Option<&Route> {
111 self.routes
112 .iter()
113 .find(|(id, _)| id.as_str() == model)
114 .map(|(_, route)| route)
115 }
116
117 pub fn set_pricing(&self, pricing: Arc<switchyard_costs::Pricing>) {
119 for (_, route) in &self.routes {
120 route.set_pricing(Arc::clone(&pricing));
121 }
122 }
123
124 pub fn models(&self) -> impl Iterator<Item = ModelInfo<'_>> {
126 self.routes.iter().map(|(id, route)| ModelInfo {
127 id,
128 algorithm: route.algorithm_name(),
129 capabilities: route.capabilities(),
130 })
131 }
132
133 pub async fn model_properties(&self, model: &str, timeout: Duration) -> Option<Value> {
135 let probe = self.model_properties_probes.get(model)?;
136 probe
137 .client
138 .get_model_properties(&probe.model, probe.format, timeout)
139 .await
140 .ok()
141 }
142
143 pub fn fallback_base_url(&self) -> Option<&str> {
145 self.fallback_base_url.as_deref()
146 }
147
148 pub fn describe_decision(
150 &self,
151 model: &ModelId,
152 outcome: &RoutingOutcome,
153 ) -> Option<DecisionDescription> {
154 let route = self.route(model.as_str())?;
155 let resolve = |selected: &ModelId| {
156 let mut target = route.decision_target(selected)?;
157 let mut url = reqwest::Url::parse(&target.base_url).ok()?;
158 let query: Vec<_> = url
159 .query_pairs()
160 .filter(|(name, _)| !matches!(name.as_ref(), "key" | "api_key"))
161 .map(|(name, value)| (name.into_owned(), value.into_owned()))
162 .collect();
163 if query.len() != url.query_pairs().count() {
164 url.set_query(None);
165 if !query.is_empty() {
166 url.query_pairs_mut().extend_pairs(query);
167 }
168 target.base_url = url.into();
170 }
171 Some(target)
172 };
173 let mut model_ids = outcome.selected_model_ids.iter();
174 Some(DecisionDescription {
175 selected: resolve(model_ids.next()?)?,
176 fallbacks: model_ids.map(resolve).collect::<Option<Vec<_>>>()?,
177 metadata: outcome.metadata.clone(),
178 })
179 }
180}