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}
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 pub fn load(path: impl AsRef<Path>) -> Result<Self, RunnerError> {
61 config::load_runner(path)
62 }
63
64 pub fn from_toml(source: &str) -> Result<Self, RunnerError> {
68 config::runner_from_toml(source)
69 }
70
71 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 pub fn with_provider_api_keys(mut self, keys: Vec<String>) -> Self {
85 self.provider_api_keys = keys;
86 self
87 }
88
89 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 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 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 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 pub fn fallback_base_url(&self) -> Option<&str> {
136 self.fallback_base_url.as_deref()
137 }
138
139 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 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}