mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-23 22:07:29 +00:00
feat(gateway): route models through Switchyard
Signed-off-by: Alex Fournier <afournier@nvidia.com>
This commit is contained in:
parent
dddbaa803d
commit
1bc923cce9
13 changed files with 880 additions and 37 deletions
249
litellm-rust/Cargo.lock
generated
249
litellm-rust/Cargo.lock
generated
|
|
@ -209,9 +209,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.91"
|
||||
version = "0.1.92"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"
|
||||
checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
|
@ -2109,6 +2109,16 @@ dependencies = [
|
|||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fraction"
|
||||
version = "0.15.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e076045bb43dac435333ed5f04caf35c7463631d0dae2deb2638d94dd0a5b872"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
"num",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fraction"
|
||||
version = "0.17.0"
|
||||
|
|
@ -2657,9 +2667,9 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
|||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.3"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
|
||||
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
|
|
@ -3236,6 +3246,45 @@ dependencies = [
|
|||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonptr"
|
||||
version = "0.8.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72c22d99362c7aac7d77efab6b49c2181674b165d7e6e7c755b3432ded64bf51"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.49.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ec8a241beed129f06114aa68007e905ca350e7baeb6e17a7631bb7978d91b2"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"data-encoding",
|
||||
"email_address",
|
||||
"fancy-regex 0.19.2",
|
||||
"fraction 0.15.4",
|
||||
"getrandom 0.3.4",
|
||||
"idna",
|
||||
"itoa",
|
||||
"jsonschema-regex 0.49.9",
|
||||
"jsonschema-value 0.49.9",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
"percent-encoding",
|
||||
"referencing 0.49.9",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"strum",
|
||||
"unicode-general-category",
|
||||
"uuid-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema"
|
||||
version = "0.55.1"
|
||||
|
|
@ -3247,15 +3296,15 @@ dependencies = [
|
|||
"data-encoding",
|
||||
"email_address",
|
||||
"fancy-regex 0.19.2",
|
||||
"fraction",
|
||||
"fraction 0.17.0",
|
||||
"getrandom 0.3.4",
|
||||
"itoa",
|
||||
"jsonschema-regex",
|
||||
"jsonschema-value",
|
||||
"jsonschema-regex 0.55.1",
|
||||
"jsonschema-value 0.55.1",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
"percent-encoding",
|
||||
"referencing",
|
||||
"referencing 0.55.1",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
|
@ -3264,6 +3313,15 @@ dependencies = [
|
|||
"uuid-simd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.49.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91994f45017ed5e66aa8e59b8415f4cb033a6380d7200387b7cf117595fbdf85"
|
||||
dependencies = [
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-regex"
|
||||
version = "0.55.1"
|
||||
|
|
@ -3273,6 +3331,20 @@ dependencies = [
|
|||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.49.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ec7637f83e510868ae6ed625f7ebfbbde4554ee8ce49854caa5126a8b9b9ecb"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"fraction 0.15.4",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "jsonschema-value"
|
||||
version = "0.55.1"
|
||||
|
|
@ -3281,7 +3353,7 @@ checksum = "0230ac05e09c6111e96c147b75c390579f5cbd45654b980c68ac60fe17b3f129"
|
|||
dependencies = [
|
||||
"ahash",
|
||||
"bytecount",
|
||||
"fraction",
|
||||
"fraction 0.17.0",
|
||||
"getrandom 0.3.4",
|
||||
"num-cmp",
|
||||
"num-traits",
|
||||
|
|
@ -3784,6 +3856,7 @@ dependencies = [
|
|||
name = "litellm-gateway-inference"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"axum",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
|
|
@ -3791,6 +3864,7 @@ dependencies = [
|
|||
"litellm-auth",
|
||||
"litellm-cache-memory",
|
||||
"litellm-cache-response",
|
||||
"litellm-config",
|
||||
"litellm-gateway-auth",
|
||||
"litellm-host",
|
||||
"litellm-host-http",
|
||||
|
|
@ -3808,6 +3882,11 @@ dependencies = [
|
|||
"rstest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"switchyard-libsy",
|
||||
"switchyard-llm-client",
|
||||
"switchyard-protocol",
|
||||
"switchyard-runner",
|
||||
"switchyard-translation",
|
||||
"thiserror 2.0.19",
|
||||
"tokio",
|
||||
"tower",
|
||||
|
|
@ -4195,7 +4274,7 @@ name = "litellm-model-catalog"
|
|||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"jsonschema",
|
||||
"jsonschema 0.55.1",
|
||||
"litellm-llms-types",
|
||||
"rstest",
|
||||
"schemars 1.2.2",
|
||||
|
|
@ -4508,7 +4587,7 @@ dependencies = [
|
|||
"tempfile",
|
||||
"thiserror 2.0.19",
|
||||
"tokio",
|
||||
"toml",
|
||||
"toml 0.9.12+spec-1.1.0",
|
||||
"zip",
|
||||
]
|
||||
|
||||
|
|
@ -5266,9 +5345,9 @@ checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3"
|
|||
|
||||
[[package]]
|
||||
name = "portable-atomic-util"
|
||||
version = "0.2.8"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
|
||||
checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"
|
||||
dependencies = [
|
||||
"portable-atomic",
|
||||
]
|
||||
|
|
@ -5811,6 +5890,23 @@ dependencies = [
|
|||
"syn 3.0.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.49.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6efa2154ea6f5ce0fdecdd2a8d18f2fa1a39a8fbba91564f555a592e4dce8278"
|
||||
dependencies = [
|
||||
"ahash",
|
||||
"fluent-uri",
|
||||
"getrandom 0.3.4",
|
||||
"hashbrown 0.17.1",
|
||||
"itoa",
|
||||
"micromap",
|
||||
"parking_lot",
|
||||
"percent-encoding",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "referencing"
|
||||
version = "0.55.1"
|
||||
|
|
@ -7032,6 +7128,103 @@ version = "2.6.1"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "switchyard-libsy"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0646b0891f703d91ba97492d1d0527a7fdeb7b0269c53757e7b9388953550c16"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures",
|
||||
"http 1.4.2",
|
||||
"jsonptr",
|
||||
"jsonschema 0.49.9",
|
||||
"opentelemetry 0.32.0",
|
||||
"parking_lot",
|
||||
"rand 0.10.2",
|
||||
"regex",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"switchyard-protocol",
|
||||
"thiserror 2.0.19",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tracing",
|
||||
"tracing-opentelemetry",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "switchyard-llm-client"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c07bffb8f677431f9530fc8335140134a743d3e1618c595cfd6953ed3b009360"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures",
|
||||
"futures-util",
|
||||
"http 1.4.2",
|
||||
"httpdate",
|
||||
"opentelemetry 0.32.0",
|
||||
"parking_lot",
|
||||
"reqwest 0.13.5",
|
||||
"serde_json",
|
||||
"switchyard-libsy",
|
||||
"switchyard-protocol",
|
||||
"switchyard-translation",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-opentelemetry",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "switchyard-protocol"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c49a9e7884e7f50669250463a58a21bc79084adb87ef03647cbe7ba5c3b22ee"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"futures",
|
||||
"http 1.4.2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.19",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "switchyard-runner"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cbaeff25e505e0b5f06beec4dd6a6db58d844b0c08c80bc9e5c4f0f8e6c7079"
|
||||
dependencies = [
|
||||
"reqwest 0.13.5",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"strum_macros",
|
||||
"switchyard-libsy",
|
||||
"switchyard-llm-client",
|
||||
"switchyard-protocol",
|
||||
"thiserror 2.0.19",
|
||||
"toml 1.1.6+spec-1.1.0",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "switchyard-translation"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "629f9c47cb198da7e92569384fec4da8486852c38a7af922e0c9d6b62ed74fa1"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"switchyard-protocol",
|
||||
"thiserror 2.0.19",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "1.0.109"
|
||||
|
|
@ -7345,6 +7538,7 @@ dependencies = [
|
|||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2 0.6.5",
|
||||
|
|
@ -7439,6 +7633,21 @@ dependencies = [
|
|||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "1.1.6+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
|
||||
dependencies = [
|
||||
"indexmap 2.14.0",
|
||||
"serde_core",
|
||||
"serde_spanned",
|
||||
"toml_datetime 1.1.1+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow 1.0.4",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.7.5+spec-1.1.0"
|
||||
|
|
@ -7708,6 +7917,17 @@ dependencies = [
|
|||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-log"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-opentelemetry"
|
||||
version = "0.33.0"
|
||||
|
|
@ -7715,9 +7935,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "adbc64cba7137545b8044cb1fe9814f7aacf3c6b5f9b45be8bb5db538befdb26"
|
||||
dependencies = [
|
||||
"js-sys",
|
||||
"opentelemetry",
|
||||
"opentelemetry 0.32.0",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
"tracing-subscriber",
|
||||
"web-time",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -5,7 +5,19 @@ edition.workspace = true
|
|||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[features]
|
||||
switchyard = [
|
||||
"dep:async-trait",
|
||||
"dep:litellm-config",
|
||||
"dep:switchyard-libsy",
|
||||
"dep:switchyard-llm-client",
|
||||
"dep:switchyard-protocol",
|
||||
"dep:switchyard-runner",
|
||||
"dep:switchyard-translation",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
async-trait = { version = "0.1.92", optional = true }
|
||||
litellm-cache-response.workspace = true
|
||||
axum = { workspace = true, features = ["json", "multipart", "original-uri"] }
|
||||
base64.workspace = true
|
||||
|
|
@ -18,6 +30,7 @@ litellm-inference-responses.workspace = true
|
|||
litellm-inference-messages.workspace = true
|
||||
litellm-inference-chat.workspace = true
|
||||
litellm-inference-ocr.workspace = true
|
||||
litellm-config = { workspace = true, optional = true }
|
||||
litellm-host-http.workspace = true
|
||||
litellm-host.workspace = true
|
||||
litellm-http.workspace = true
|
||||
|
|
@ -27,6 +40,11 @@ litellm-secrets.workspace = true
|
|||
litellm-llms-types.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
switchyard-libsy = { version = "0.3.0", optional = true }
|
||||
switchyard-llm-client = { version = "0.3.0", optional = true }
|
||||
switchyard-protocol = { version = "0.3.0", optional = true }
|
||||
switchyard-runner = { version = "0.3.0", optional = true }
|
||||
switchyard-translation = { version = "0.3.0", optional = true }
|
||||
thiserror.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
|
|
|
|||
|
|
@ -101,11 +101,22 @@ impl litellm_host::interceptors::Interceptors<litellm_inference::Error> for Cach
|
|||
|
||||
impl CacheHeaders {
|
||||
pub(crate) fn apply(&self, mut response: axum::response::Response) -> axum::response::Response {
|
||||
if let Some(key) = self.0.get()
|
||||
&& let Ok(value) = axum::http::HeaderValue::from_str(key)
|
||||
{
|
||||
if let Some(value) = self.value() {
|
||||
response.headers_mut().insert("x-litellm-cache-key", value);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(feature = "switchyard")]
|
||||
pub(crate) fn headers(&self) -> axum::http::HeaderMap {
|
||||
let mut headers = axum::http::HeaderMap::new();
|
||||
if let Some(value) = self.value() {
|
||||
headers.insert("x-litellm-cache-key", value);
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
fn value(&self) -> Option<axum::http::HeaderValue> {
|
||||
axum::http::HeaderValue::from_str(self.0.get()?).ok()
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,38 @@
|
|||
use litellm_gateway_auth::AuthenticatedRequest;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "switchyard")]
|
||||
use axum::http::HeaderMap;
|
||||
use axum::{
|
||||
Json,
|
||||
extract::{Path, State},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use litellm_inference_chat::types::ChatCompletionsCall;
|
||||
use litellm_inference_chat::types::{ChatCompletionsCall, ChatCompletionsRequest};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
use crate::{Error, Gateway, JsonObject, request};
|
||||
use crate::{Deployment, Error, Gateway, JsonObject, request};
|
||||
|
||||
pub(crate) async fn create(
|
||||
State(gateway): State<Arc<Gateway>>,
|
||||
identity: AuthenticatedRequest,
|
||||
#[cfg(feature = "switchyard")] headers: HeaderMap,
|
||||
JsonObject(body): JsonObject,
|
||||
) -> Result<impl IntoResponse, Error> {
|
||||
handle(&gateway, &identity, body).await
|
||||
handle(
|
||||
&gateway,
|
||||
&identity,
|
||||
#[cfg(feature = "switchyard")]
|
||||
headers,
|
||||
body,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn create_from_model_path(
|
||||
State(gateway): State<Arc<Gateway>>,
|
||||
identity: AuthenticatedRequest,
|
||||
#[cfg(feature = "switchyard")] headers: HeaderMap,
|
||||
Path(model): Path<String>,
|
||||
JsonObject(body): JsonObject,
|
||||
) -> Result<impl IntoResponse, Error> {
|
||||
|
|
@ -32,16 +43,29 @@ pub(crate) async fn create_from_model_path(
|
|||
.collect(),
|
||||
Some(_) => body,
|
||||
};
|
||||
handle(&gateway, &identity, body).await
|
||||
handle(
|
||||
&gateway,
|
||||
&identity,
|
||||
#[cfg(feature = "switchyard")]
|
||||
headers,
|
||||
body,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handle(
|
||||
gateway: &Gateway,
|
||||
identity: &AuthenticatedRequest,
|
||||
#[cfg(feature = "switchyard")] inbound_headers: HeaderMap,
|
||||
body: Map<String, Value>,
|
||||
) -> Result<Response, Error> {
|
||||
let deployment = request::resolve_deployment(gateway, &body)?;
|
||||
request::authorize_model(identity, deployment, &body).await?;
|
||||
#[cfg(feature = "switchyard")]
|
||||
let switchyard_route = body
|
||||
.get("model")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|model| gateway.switchyard_routes.get(model));
|
||||
let (body, cache_options) = crate::caching::prepare(identity, body)?;
|
||||
let route = gateway.chat_completions.clone();
|
||||
let route = match &gateway.cache {
|
||||
|
|
@ -52,23 +76,19 @@ async fn handle(
|
|||
None => route,
|
||||
};
|
||||
|
||||
let messages = body.get("messages").cloned().unwrap_or_default();
|
||||
#[cfg(feature = "switchyard")]
|
||||
if let Some(switchyard_route) = switchyard_route {
|
||||
let (body, upstream_headers) = switchyard_route
|
||||
.execute(route, cache_options.policy, body, inbound_headers)
|
||||
.await?;
|
||||
let mut response = Json(body).into_response();
|
||||
response.headers_mut().extend(upstream_headers);
|
||||
return Ok(response);
|
||||
}
|
||||
let headers = crate::caching::CacheHeaders::default();
|
||||
let response = litellm_host_http::serve_unary(
|
||||
route.machine(
|
||||
ChatCompletionsCall {
|
||||
model: deployment.model.clone(),
|
||||
messages,
|
||||
optional_params: body
|
||||
.into_iter()
|
||||
.filter(|(name, _)| !matches!(name.as_str(), "model" | "messages"))
|
||||
.collect(),
|
||||
api_key: deployment.api_key.clone(),
|
||||
api_base: deployment.api_base.clone(),
|
||||
custom_llm_provider: deployment.custom_llm_provider.clone(),
|
||||
extra_headers: None,
|
||||
timeout: deployment.timeout,
|
||||
},
|
||||
ChatCompletionsCall::from(provider_request(deployment, body)),
|
||||
cache_options.policy,
|
||||
),
|
||||
(),
|
||||
|
|
@ -79,3 +99,21 @@ async fn handle(
|
|||
.await?;
|
||||
Ok(headers.apply(response))
|
||||
}
|
||||
|
||||
pub(crate) fn provider_request(
|
||||
deployment: &Deployment,
|
||||
mut body: Map<String, Value>,
|
||||
) -> ChatCompletionsRequest<'_> {
|
||||
let messages = body.remove("messages").unwrap_or_default();
|
||||
body.remove("model");
|
||||
ChatCompletionsRequest {
|
||||
model: &deployment.model,
|
||||
messages,
|
||||
optional_params: body,
|
||||
api_key: deployment.api_key.as_deref(),
|
||||
api_base: deployment.api_base.as_deref(),
|
||||
custom_llm_provider: deployment.custom_llm_provider.as_deref(),
|
||||
extra_headers: None,
|
||||
timeout: deployment.timeout,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,15 @@ use litellm_inference::Error as InferenceError;
|
|||
use litellm_llms::base_llm::ocr::error::Error as OcrError;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
/// Invalid configuration for a Switchyard virtual model.
|
||||
#[cfg(feature = "switchyard")]
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("invalid Switchyard model {model}: {reason}")]
|
||||
pub struct SwitchyardConfigError {
|
||||
pub(crate) model: String,
|
||||
pub(crate) reason: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error(transparent)]
|
||||
|
|
|
|||
|
|
@ -11,6 +11,8 @@ pub mod messages;
|
|||
mod ocr;
|
||||
mod request;
|
||||
mod responses;
|
||||
#[cfg(feature = "switchyard")]
|
||||
mod switchyard;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
|
|
@ -26,11 +28,15 @@ use litellm_llms::base_llm::ocr::{handler::OcrClient, settings::OcrSettings};
|
|||
use litellm_secrets::source::SecretSource;
|
||||
|
||||
pub use error::Error;
|
||||
#[cfg(feature = "switchyard")]
|
||||
pub use error::SwitchyardConfigError;
|
||||
pub use litellm_router::{Deployment, Router as ModelRouter};
|
||||
pub use request::{JsonObject, RequestId};
|
||||
|
||||
pub struct Gateway {
|
||||
cache: Option<Arc<dyn litellm_cache_response::ResponseCacheService>>,
|
||||
#[cfg(feature = "switchyard")]
|
||||
switchyard_routes: switchyard::Routes,
|
||||
pub audio_transcription: AudioTranscriptionRoute,
|
||||
pub chat_completions: ChatCompletionsRoute,
|
||||
pub messages: MessagesRoute,
|
||||
|
|
@ -60,6 +66,8 @@ impl Gateway {
|
|||
let auth = resources.auth.clone();
|
||||
Ok(Self {
|
||||
cache: None,
|
||||
#[cfg(feature = "switchyard")]
|
||||
switchyard_routes: switchyard::Routes::default(),
|
||||
audio_transcription: AudioTranscriptionRoute::new(
|
||||
provider.clone(),
|
||||
auth.clone(),
|
||||
|
|
@ -86,6 +94,17 @@ impl Gateway {
|
|||
http,
|
||||
})
|
||||
}
|
||||
|
||||
/// Configure Switchyard virtual models from LiteLLM's model list.
|
||||
#[cfg(feature = "switchyard")]
|
||||
pub fn with_switchyard_models(
|
||||
mut self,
|
||||
models: &[litellm_config::Model],
|
||||
) -> Result<Self, SwitchyardConfigError> {
|
||||
self.switchyard_routes =
|
||||
switchyard::Routes::from_models(models, Arc::new(self.models.clone()))?;
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn router(gateway: Arc<Gateway>) -> Router {
|
||||
|
|
|
|||
311
litellm-rust/crates/gateway-inference/src/switchyard.rs
Normal file
311
litellm-rust/crates/gateway-inference/src/switchyard.rs
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
use std::{
|
||||
collections::{BTreeMap, HashMap, HashSet},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use axum::http::HeaderMap;
|
||||
use litellm_cache_response::CachePolicy;
|
||||
use litellm_config::Model;
|
||||
use litellm_inference::RouteError;
|
||||
use litellm_inference_chat::ChatCompletionsRoute;
|
||||
use litellm_http::transport::Error as TransportError;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value};
|
||||
use switchyard_libsy::{Algorithm, LibsyError, RuntimeModels};
|
||||
use switchyard_llm_client::ClientRouter;
|
||||
use switchyard_protocol::{
|
||||
BoxError, LlmClientError, LlmResponse, Metadata, ModelId, Request, Response, RoutedLlmClient,
|
||||
WireFormat,
|
||||
};
|
||||
use switchyard_runner::AlgorithmSpec;
|
||||
use switchyard_translation::{
|
||||
decode_aggregated_response, decode_request, encode_aggregated_response_with_extensions,
|
||||
encode_request,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
Error, ModelRouter, SwitchyardConfigError, caching::CacheHeaders,
|
||||
chat_completions::provider_request,
|
||||
};
|
||||
|
||||
const SWITCHYARD_MODEL: &str = "switchyard/algorithm";
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Routes(HashMap<String, Route>);
|
||||
|
||||
impl Routes {
|
||||
pub(crate) fn from_models(
|
||||
model_list: &[Model],
|
||||
deployments: Arc<ModelRouter>,
|
||||
) -> Result<Self, SwitchyardConfigError> {
|
||||
let mut routes = HashMap::new();
|
||||
let mut seen = HashSet::new();
|
||||
// ModelRouter uses the final entry when public model names repeat.
|
||||
for model in model_list.iter().rev() {
|
||||
if !seen.insert(model.model_name.as_str())
|
||||
|| model.litellm_params.model != SWITCHYARD_MODEL
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if deployments
|
||||
.get(&model.model_name)
|
||||
.is_none_or(|deployment| deployment.model != SWITCHYARD_MODEL)
|
||||
{
|
||||
return Err(invalid(model, "model is not a Switchyard route"));
|
||||
}
|
||||
let config = model
|
||||
.litellm_params
|
||||
.extra
|
||||
.get("switchyard_config")
|
||||
.ok_or_else(|| invalid(model, "switchyard_config is required"))?;
|
||||
let config = AlgorithmSpec::deserialize(config)
|
||||
.map_err(|error| invalid(model, error.to_string()))?;
|
||||
let targets = targets(model, &config, &deployments)?;
|
||||
let (algorithm, runtime_models) = config
|
||||
.build_with_runtime_models(&model.model_name, &targets)
|
||||
.map_err(|error| invalid(model, error.to_string()))?;
|
||||
routes.insert(
|
||||
model.model_name.clone(),
|
||||
Route {
|
||||
algorithm,
|
||||
runtime_models: Arc::new(runtime_models),
|
||||
deployments: Arc::clone(&deployments),
|
||||
},
|
||||
);
|
||||
}
|
||||
Ok(Self(routes))
|
||||
}
|
||||
|
||||
pub(crate) fn get(&self, model: &str) -> Option<&Route> {
|
||||
self.0.get(model)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Route {
|
||||
algorithm: Arc<dyn Algorithm>,
|
||||
runtime_models: Arc<RuntimeModels>,
|
||||
deployments: Arc<ModelRouter>,
|
||||
}
|
||||
|
||||
impl Route {
|
||||
pub(crate) async fn execute(
|
||||
&self,
|
||||
route: ChatCompletionsRoute,
|
||||
cache_policy: CachePolicy,
|
||||
body: Map<String, Value>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(Value, HeaderMap), Error> {
|
||||
let llm_request = decode_request(WireFormat::OpenAiChat, &Value::Object(body))
|
||||
.map_err(|error| Error::InvalidBody(error.to_string()))?;
|
||||
// Reject unsupported streaming before a classifier or judge can make a model call.
|
||||
if llm_request.stream {
|
||||
return Err(Error::Route(RouteError::Unsupported("streaming")));
|
||||
}
|
||||
let extensions = llm_request.extensions.clone();
|
||||
let mut metadata = Metadata::from_headers(&headers);
|
||||
metadata.http_headers = Some(headers);
|
||||
metadata.wire_format = Some(WireFormat::OpenAiChat);
|
||||
let request = Request {
|
||||
llm_request,
|
||||
raw_request: None,
|
||||
metadata: Some(metadata),
|
||||
};
|
||||
let client = Arc::new(LiteLlmClient {
|
||||
route,
|
||||
deployments: Arc::clone(&self.deployments),
|
||||
cache_policy,
|
||||
});
|
||||
let (_, response) = switchyard_llm_client::run(
|
||||
Arc::clone(&self.algorithm),
|
||||
ClientRouter::single(client),
|
||||
request,
|
||||
Arc::clone(&self.runtime_models),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(map_libsy_error)?;
|
||||
let upstream_headers = response.upstream_headers;
|
||||
let response = response
|
||||
.llm_response
|
||||
.into_agg()
|
||||
.await
|
||||
.map_err(map_client_error)?;
|
||||
let body = encode_aggregated_response_with_extensions(
|
||||
&response,
|
||||
WireFormat::OpenAiChat,
|
||||
None,
|
||||
&extensions,
|
||||
)
|
||||
.map_err(|error| Error::Internal(error.to_string()))?;
|
||||
Ok((body, upstream_headers))
|
||||
}
|
||||
}
|
||||
|
||||
struct LiteLlmClient {
|
||||
route: ChatCompletionsRoute,
|
||||
deployments: Arc<ModelRouter>,
|
||||
cache_policy: CachePolicy,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RoutedLlmClient for LiteLlmClient {
|
||||
async fn call(&self, request: Request) -> Result<Response, LlmClientError> {
|
||||
let Some(model) = request.llm_request.model.as_deref() else {
|
||||
return Err(LlmClientError::InvalidRequest {
|
||||
message: "routed request has no model".to_string(),
|
||||
});
|
||||
};
|
||||
let deployment =
|
||||
self.deployments
|
||||
.get(model)
|
||||
.ok_or_else(|| LlmClientError::Configuration {
|
||||
message: format!("unknown LiteLLM deployment {model}"),
|
||||
})?;
|
||||
let Request {
|
||||
llm_request,
|
||||
metadata,
|
||||
..
|
||||
} = request;
|
||||
let Value::Object(body) = encode_request(&llm_request, WireFormat::OpenAiChat)
|
||||
.map_err(|error| LlmClientError::RequestEncoding(error.to_string()))?
|
||||
else {
|
||||
return Err(LlmClientError::RequestEncoding(
|
||||
"OpenAI Chat request is not an object".to_string(),
|
||||
));
|
||||
};
|
||||
let cache_headers = CacheHeaders::default();
|
||||
let response = self
|
||||
.route
|
||||
.execute(
|
||||
provider_request(deployment, body),
|
||||
&cache_headers,
|
||||
self.cache_policy,
|
||||
)
|
||||
.await
|
||||
.map_err(map_route_error)?;
|
||||
let body = serde_json::to_value(response)
|
||||
.map_err(|error| LlmClientError::ResponseTranslation(error.to_string()))?;
|
||||
let response = decode_aggregated_response(&body, WireFormat::OpenAiChat)
|
||||
.map_err(|error| LlmClientError::ResponseTranslation(error.to_string()))?;
|
||||
Ok(Response {
|
||||
llm_response: LlmResponse::Agg(response),
|
||||
metadata,
|
||||
upstream_headers: cache_headers.headers(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn targets(
|
||||
route: &Model,
|
||||
config: &AlgorithmSpec,
|
||||
deployments: &ModelRouter,
|
||||
) -> Result<BTreeMap<String, ModelId>, SwitchyardConfigError> {
|
||||
config
|
||||
.callable_target_names()
|
||||
.into_iter()
|
||||
.map(|target| {
|
||||
let deployment = deployments
|
||||
.get(target)
|
||||
.ok_or_else(|| invalid(route, format!("target {target:?} is not configured")))?;
|
||||
if deployment.model == SWITCHYARD_MODEL {
|
||||
return Err(invalid(
|
||||
route,
|
||||
format!("target {target:?} is another Switchyard route"),
|
||||
));
|
||||
}
|
||||
Ok((target.to_string(), ModelId::from(target)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn invalid(model: &Model, message: impl Into<String>) -> SwitchyardConfigError {
|
||||
SwitchyardConfigError {
|
||||
model: model.model_name.clone(),
|
||||
reason: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_route_error(error: RouteError) -> LlmClientError {
|
||||
match error {
|
||||
RouteError::Transport(TransportError::Http { status, body }) => {
|
||||
match axum::http::StatusCode::from_u16(status) {
|
||||
Ok(status) => LlmClientError::UpstreamHttp { status, body },
|
||||
Err(source) => LlmClientError::InvalidResponse {
|
||||
source: Box::new(source),
|
||||
},
|
||||
}
|
||||
}
|
||||
// Only Connect is known to precede dispatch, so only it is safe to fall back from.
|
||||
error @ RouteError::Transport(TransportError::Connect(_)) => LlmClientError::Transport {
|
||||
source: Box::new(error),
|
||||
},
|
||||
error @ RouteError::InvalidResponse(_) => LlmClientError::InvalidResponse {
|
||||
source: Box::new(error),
|
||||
},
|
||||
error => LlmClientError::Host {
|
||||
source: Box::new(error),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn map_libsy_error(error: LibsyError) -> Error {
|
||||
match error {
|
||||
LibsyError::ClientCall { source, .. } => map_client_error(source),
|
||||
error => Error::Internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_client_error(error: LlmClientError) -> Error {
|
||||
match error {
|
||||
LlmClientError::InvalidRequest { message }
|
||||
| LlmClientError::RequestTranslation(message) => {
|
||||
Error::Route(RouteError::InvalidRequest(message.into()))
|
||||
}
|
||||
LlmClientError::UpstreamHttp { status, body } => {
|
||||
Error::Route(RouteError::Transport(TransportError::Http {
|
||||
status: status.as_u16(),
|
||||
body,
|
||||
}))
|
||||
}
|
||||
LlmClientError::Transport { source }
|
||||
| LlmClientError::Timeout { source }
|
||||
| LlmClientError::InvalidResponse { source }
|
||||
| LlmClientError::Host { source }
|
||||
| LlmClientError::Ffi { source } => map_source(source),
|
||||
LlmClientError::ContextWindowExceeded { message, .. } => {
|
||||
Error::Route(RouteError::InvalidRequest(message.into()))
|
||||
}
|
||||
LlmClientError::ResponseTranslation(message) => {
|
||||
Error::Route(RouteError::InvalidResponse(message.into()))
|
||||
}
|
||||
error => Error::Internal(error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn map_source(source: BoxError) -> Error {
|
||||
match source.downcast::<RouteError>() {
|
||||
Ok(error) => Error::Route(*error),
|
||||
Err(source) => Error::Internal(source.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rstest::rstest;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[rstest]
|
||||
fn host_errors_keep_their_gateway_classification() {
|
||||
let error = RouteError::Auth(litellm_auth::Error::MissingApiKey {
|
||||
provider: "OpenAI",
|
||||
environment_variable: "OPENAI_API_KEY",
|
||||
});
|
||||
|
||||
assert!(matches!(
|
||||
map_client_error(map_route_error(error)),
|
||||
Error::Route(RouteError::Auth(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -102,6 +102,14 @@ fn configured_app(
|
|||
Some(cache) => gateway.with_cache(cache),
|
||||
None => gateway,
|
||||
};
|
||||
authenticated_app(gateway, permissions, principal)
|
||||
}
|
||||
|
||||
pub fn authenticated_app(
|
||||
gateway: Gateway,
|
||||
permissions: litellm_gateway_auth::Permissions,
|
||||
principal: Option<litellm_gateway_auth::Principal>,
|
||||
) -> Router {
|
||||
router(Arc::new(gateway)).layer(axum::middleware::from_fn_with_state(
|
||||
(permissions, principal),
|
||||
test_identity,
|
||||
|
|
|
|||
173
litellm-rust/crates/gateway-inference/tests/switchyard.rs
Normal file
173
litellm-rust/crates/gateway-inference/tests/switchyard.rs
Normal file
|
|
@ -0,0 +1,173 @@
|
|||
#![cfg(feature = "switchyard")]
|
||||
|
||||
mod support;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use litellm_config::Config;
|
||||
use litellm_inference::resources::CoreResources;
|
||||
use litellm_gateway_auth::{AccessRequest, Permissions};
|
||||
use litellm_gateway_inference::{Gateway, ModelRouter};
|
||||
use litellm_http::{HttpClientPool, HttpSettings, Resolution, media::PublicDnsResolver};
|
||||
use rstest::rstest;
|
||||
use serde_json::json;
|
||||
use wiremock::{
|
||||
Mock, MockServer, ResponseTemplate,
|
||||
matchers::{body_partial_json, method, path},
|
||||
};
|
||||
|
||||
#[rstest]
|
||||
#[tokio::test]
|
||||
async fn configured_switchyard_routes_answer_and_fall_back() {
|
||||
let upstream = MockServer::start().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/chat/completions"))
|
||||
.and(body_partial_json(json!({"model": "judge-model"})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"model": "judge-model",
|
||||
"choices": [{
|
||||
"message": {
|
||||
"content": r#"{"crux":"bounded task","primary_rule":"SUP-1","capability_boundary":"supported","p_solve":0.9}"#
|
||||
}
|
||||
}]
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/chat/completions"))
|
||||
.and(body_partial_json(json!({
|
||||
"model": "fast-model",
|
||||
"messages": [{"role": "user", "content": "fix this"}],
|
||||
"service_tier": "flex"
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(503).set_body_json(json!({
|
||||
"error": {"message": "unavailable"}
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/v1/chat/completions"))
|
||||
.and(body_partial_json(json!({
|
||||
"model": "strong-model",
|
||||
"messages": [{"role": "user", "content": "fix this"}],
|
||||
"service_tier": "flex"
|
||||
})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"model": "strong-model",
|
||||
"choices": [{
|
||||
"message": {"content": "fallback answer"}
|
||||
}]
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
|
||||
let config = Config::from_yaml(&format!(
|
||||
r#"
|
||||
model_list:
|
||||
- model_name: fast
|
||||
litellm_params:
|
||||
model: fast-model
|
||||
api_base: {base}/v1
|
||||
api_key: test-key
|
||||
custom_llm_provider: openai_like
|
||||
- model_name: strong
|
||||
litellm_params:
|
||||
model: strong-model
|
||||
api_base: {base}/v1
|
||||
api_key: test-key
|
||||
custom_llm_provider: openai_like
|
||||
- model_name: judge
|
||||
litellm_params:
|
||||
model: judge-model
|
||||
api_base: {base}/v1
|
||||
api_key: test-key
|
||||
custom_llm_provider: openai_like
|
||||
- model_name: coding-router
|
||||
litellm_params:
|
||||
model: switchyard/algorithm
|
||||
switchyard_config:
|
||||
type: llm_classifier
|
||||
mode: capability
|
||||
classifier_target: judge
|
||||
weak_target: fast
|
||||
strong_target: strong
|
||||
base_threshold: 0.5
|
||||
- model_name: noop-router
|
||||
litellm_params:
|
||||
model: switchyard/algorithm
|
||||
switchyard_config:
|
||||
type: noop
|
||||
"#,
|
||||
base = upstream.uri()
|
||||
))
|
||||
.expect("valid config");
|
||||
let pool = Arc::new(HttpClientPool::new(Arc::new(PublicDnsResolver)));
|
||||
let resources = CoreResources::new(pool);
|
||||
let http = Resolution::from(&HttpSettings::default()).config;
|
||||
let gateway = Gateway::new(
|
||||
resources,
|
||||
http,
|
||||
Arc::new(support::NoSecrets),
|
||||
ModelRouter::from_model_list(&config.model_list),
|
||||
)
|
||||
.expect("gateway")
|
||||
.with_switchyard_models(&config.model_list)
|
||||
.expect("Switchyard routes");
|
||||
let app = support::authenticated_app(
|
||||
gateway,
|
||||
Permissions::Only(Arc::from([
|
||||
AccessRequest::Model {
|
||||
name: "coding-router".into(),
|
||||
deployment: "switchyard/algorithm".into(),
|
||||
},
|
||||
AccessRequest::Model {
|
||||
name: "noop-router".into(),
|
||||
deployment: "switchyard/algorithm".into(),
|
||||
},
|
||||
])),
|
||||
None,
|
||||
);
|
||||
|
||||
let response = support::post(
|
||||
app.clone(),
|
||||
"/v1/chat/completions",
|
||||
json!({
|
||||
"model": "coding-router",
|
||||
"messages": [{"role": "user", "content": "fix this"}],
|
||||
"stream": true
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 501);
|
||||
|
||||
let response = support::post(
|
||||
app.clone(),
|
||||
"/v1/chat/completions",
|
||||
json!({
|
||||
"model": "coding-router",
|
||||
"messages": [{"role": "user", "content": "fix this"}],
|
||||
"service_tier": "flex"
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let body = support::json(response).await;
|
||||
assert_eq!(body["model"], "strong-model");
|
||||
assert_eq!(body["choices"][0]["message"]["content"], "fallback answer");
|
||||
|
||||
let response = support::post(
|
||||
app,
|
||||
"/v1/chat/completions",
|
||||
json!({
|
||||
"model": "noop-router",
|
||||
"messages": [{"role": "user", "content": "health check"}]
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(response.status(), 200);
|
||||
let body = support::json(response).await;
|
||||
assert_eq!(body["choices"][0]["message"]["content"], "OK");
|
||||
}
|
||||
|
|
@ -5,6 +5,9 @@ edition.workspace = true
|
|||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[features]
|
||||
switchyard = ["litellm-gateway-inference/switchyard"]
|
||||
|
||||
[dependencies]
|
||||
axum.workspace = true
|
||||
envy = "0.4.2"
|
||||
|
|
|
|||
|
|
@ -10,4 +10,7 @@ pub enum Error {
|
|||
Mcp(#[from] litellm_gateway_mcp::ConnectError),
|
||||
#[error("MCP requires a configured master key")]
|
||||
Auth(#[from] litellm_gateway_auth::Error),
|
||||
#[cfg(feature = "switchyard")]
|
||||
#[error(transparent)]
|
||||
Switchyard(#[from] litellm_gateway_inference::SwitchyardConfigError),
|
||||
}
|
||||
|
|
|
|||
|
|
@ -62,12 +62,15 @@ pub fn build_inference(config: &Config) -> Result<Arc<Gateway>, Error> {
|
|||
Arc::new(EnvironmentSecrets::python_compatible(client)),
|
||||
));
|
||||
let resources = CoreResources::new(pool);
|
||||
Ok(Arc::new(Gateway::new(
|
||||
let gateway = Gateway::new(
|
||||
resources,
|
||||
http,
|
||||
secrets,
|
||||
ModelRouter::from_model_list(&config.model_list),
|
||||
)?))
|
||||
)?;
|
||||
#[cfg(feature = "switchyard")]
|
||||
let gateway = gateway.with_switchyard_models(&config.model_list)?;
|
||||
Ok(Arc::new(gateway))
|
||||
}
|
||||
|
||||
pub async fn build_mcp(
|
||||
|
|
|
|||
|
|
@ -33,6 +33,32 @@ fn inference() -> Arc<Gateway> {
|
|||
litellm_gateway::build_inference(&Config::from_yaml("model_list: []").unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[cfg(feature = "switchyard")]
|
||||
#[rstest]
|
||||
fn validates_only_winning_switchyard_models() {
|
||||
let config = Config::from_yaml(
|
||||
r#"
|
||||
model_list:
|
||||
- model_name: coding-router
|
||||
litellm_params:
|
||||
model: switchyard/algorithm
|
||||
switchyard_config: { type: passthrough, target: missing }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(litellm_gateway::build_inference(&config).is_err());
|
||||
|
||||
let config = Config::from_yaml(
|
||||
r#"
|
||||
model_list:
|
||||
- { model_name: coding-router, litellm_params: { model: switchyard/algorithm, switchyard_config: { type: passthrough, target: missing } } }
|
||||
- { model_name: coding-router, litellm_params: { model: openai/model } }
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(litellm_gateway::build_inference(&config).is_ok());
|
||||
}
|
||||
|
||||
#[rstest]
|
||||
#[case::authorized("/v1/messages", Some("Bearer gateway-key"), Some("gateway-key"), 400)]
|
||||
#[case::missing_token("/v1/messages", None, Some("gateway-key"), 401)]
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue