1use 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#[derive(Clone, Copy, Default)]
24pub struct ModelCapabilities {
25 pub context_window: Option<u32>,
26 pub tool_calling: Option<bool>,
27 pub reasoning: Option<bool>,
29 pub vision: Option<bool>,
31}
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
35pub enum CallerAuthKind {
36 Anthropic,
37 OpenAi,
38}
39
40impl CallerAuthKind {
41 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#[derive(Clone)]
63pub struct AuxiliaryTarget {
64 pub model: ModelId,
65 pub client: Arc<TranslatingLlmClient>,
66}
67
68#[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
108pub struct Route {
110 algorithm: Arc<dyn Algorithm>,
111 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
123pub struct RunOutput {
125 pub selected_model: ModelId,
126 pub response: Response,
127}
128
129impl Route {
130 #[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 pub fn algorithm_name(&self) -> &str {
156 self.algorithm.name()
157 }
158
159 pub fn capabilities(&self) -> ModelCapabilities {
161 self.capabilities
162 }
163
164 pub fn caller_auth(&self) -> Option<CallerAuthKind> {
166 self.caller_auth
167 }
168
169 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 pub fn models(&self) -> &RuntimeModels {
179 &self.models
180 }
181
182 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 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 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 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}