Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion crates/switchyard-py/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
async-trait = "0.1"
futures-util = "0.3"
libsy = { path = "../libsy" }
pyo3 = { version = "0.28.3", features = ["abi3-py312", "extension-module"] }
pyo3-async-runtimes = { version = "0.28", features = ["tokio-runtime"] }
pythonize = "0.28.0"
Expand All @@ -26,8 +27,8 @@ serde_json = "1"
switchyard-core = { path = "../switchyard-core" }
switchyard-components = { path = "../switchyard-components" }
switchyard-components-v2 = { path = "../switchyard-components-v2" }
switchyard-protocol = { path = "../libsy-protocol" }
switchyard-server = { path = "../switchyard-server" }
switchyard-protocol = { path = "../libsy-protocol" }
switchyard-translation = { path = "../switchyard-translation" }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync"] }
tracing = { version = "0.1", default-features = false, features = ["std"] }
5 changes: 4 additions & 1 deletion crates/switchyard-py/src/libsy_bindings.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Python bindings for Switchyard's neutral protocol and libsy targets.
//! Python bindings for Switchyard's neutral protocol and libsy algorithms.

mod protocol;
mod run;
mod target;
mod values;

Expand All @@ -17,6 +18,8 @@ pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {

let libsy_module = PyModule::new(module.py(), "libsy")?;
target::register(&libsy_module)?;
run::register(&libsy_module)?;
libsy_module.add("LibsyError", module.getattr("LibsyError")?)?;
module.add_submodule(&libsy_module)?;
Ok(())
}
43 changes: 39 additions & 4 deletions crates/switchyard-py/src/libsy_bindings/protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
//! Typed Python wrappers for the Rust-owned Switchyard protocol.

use std::collections::BTreeMap;
use std::sync::Arc;

use pyo3::prelude::*;
use pyo3::types::PyType;
use serde::Serialize;
use serde_json::{Map, Value};
use switchyard_protocol::{
AggLlmResponse, ContentBlock, FileSource, FormatId, ImageSource, InstructionBlock, LlmRequest,
LlmResponseChunk, MediaSource, Message, OutputParams, PreservationMetadata, ProviderExtensions,
ReasoningParams, ResponseOutput, Role, SamplingParams, StopReason, ToolCall, ToolChoice,
ToolDefinition, ToolResult, Usage, WireFormat,
AggLlmResponse, ContentBlock, Decision, FileSource, FormatId, ImageSource, InstructionBlock,
LlmRequest, LlmResponseChunk, MediaSource, Message, OutputParams, PreservationMetadata,
ProviderExtensions, ReasoningParams, ResponseOutput, Role, SamplingParams, StopReason,
ToolCall, ToolChoice, ToolDefinition, ToolResult, Usage, WireFormat,
};

use crate::py_serde::{value_from_python, value_to_python};
Expand All @@ -35,6 +36,39 @@ fn json_or_null(py: Python<'_>, value: Option<&Value>) -> PyResult<Py<PyAny>> {
}
}

/// A routing decision exposed through the protocol's neutral interface.
#[pyclass(name = "Decision", module = "switchyard.libsy.protocol", frozen)]
pub(crate) struct PyDecision {
inner: Arc<dyn Decision>,
}

impl PyDecision {
pub(crate) fn new(inner: Arc<dyn Decision>) -> Self {
Self { inner }
}
}

#[pymethods]
impl PyDecision {
#[getter]
fn selected_model(&self) -> String {
self.inner.selected_model().to_string()
}

#[getter]
fn reasoning(&self) -> Option<String> {
self.inner.reasoning().map(str::to_owned)
}

fn __repr__(&self) -> String {
format!(
"Decision(selected_model={:?}, reasoning={:?})",
self.inner.selected_model(),
self.inner.reasoning()
)
}
}

#[pyclass(
name = "WireFormat",
module = "switchyard.libsy.protocol",
Expand Down Expand Up @@ -1520,6 +1554,7 @@ impl PyLlmResponseChunk {
}

pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_class::<PyDecision>()?;
module.add_class::<PyWireFormat>()?;
module.add_class::<PyFormatId>()?;
module.add_class::<PyRole>()?;
Expand Down
83 changes: 83 additions & 0 deletions crates/switchyard-py/src/libsy_bindings/run.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Python execution for Rust-owned libsy algorithms.

use std::sync::Arc;

use libsy::{Algorithm, NoopAlgo, RandomAlgo};
use pyo3::prelude::*;

use super::protocol::PyDecision;
use super::target::PyLlmTargetSet;
use super::values::{PyContext, PyRequest, PyResponse};
use crate::errors::py_libsy_error;

/// Opaque Python handle to a Rust-owned routing algorithm.
#[pyclass(name = "Algorithm", module = "switchyard.libsy", frozen)]
pub(crate) struct PyAlgorithm {
inner: Arc<dyn Algorithm>,
}

impl PyAlgorithm {
fn new(inner: Arc<dyn Algorithm>) -> Self {
Self { inner }
}
}

#[pymethods]
impl PyAlgorithm {
/// Run the algorithm using its targets' default clients.
#[pyo3(signature = (request, *, context=None))]
fn run<'py>(
&self,
py: Python<'py>,
request: PyRef<'_, PyRequest>,
context: Option<PyRef<'_, PyContext>>,
) -> PyResult<Bound<'py, PyAny>> {
let algorithm = Arc::clone(&self.inner);
let context = context
.map(|context| context.clone_core())
.unwrap_or_default();
let request = request.clone_core();
pyo3_async_runtimes::tokio::future_into_py(py, async move {
let (decisions, response) = algorithm
.run(context, request)
.await
.map_err(py_libsy_error)?;
Python::attach(|py| {
let decisions = decisions
.into_iter()
.map(|decision| Py::new(py, PyDecision::new(decision)))
.collect::<PyResult<Vec<_>>>()?;
let response = Py::new(py, PyResponse::from_core(response))?;
Ok((decisions, response))
})
})
}

fn __repr__(&self) -> &'static str {
"Algorithm()"
}
}

/// Construct the no-op reference algorithm.
#[pyfunction(name = "noop")]
fn noop_algorithm() -> PyAlgorithm {
PyAlgorithm::new(Arc::new(NoopAlgo {}))
}

/// Construct uniform random routing over the supplied targets.
#[pyfunction(name = "random")]
fn random_algorithm(py: Python<'_>, targets: PyRef<'_, PyLlmTargetSet>) -> PyResult<PyAlgorithm> {
Ok(PyAlgorithm::new(Arc::new(RandomAlgo::new(
targets.clone_core(py)?,
))))
}

pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_class::<PyAlgorithm>()?;
module.add_function(wrap_pyfunction!(noop_algorithm, module)?)?;
module.add_function(wrap_pyfunction!(random_algorithm, module)?)?;
Ok(())
}
69 changes: 69 additions & 0 deletions crates/switchyard-py/src/libsy_bindings/target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,52 @@

//! Python bindings for libsy routing targets and host-provided clients.

use std::error::Error;
use std::sync::Arc;

use async_trait::async_trait;
use libsy::{LlmTarget, LlmTargetSet};
use pyo3::exceptions::{PyKeyError, PyTypeError};
use pyo3::prelude::*;
use switchyard_protocol::{Context, Decision, Request, Response, RoutedLlmClient};

use super::protocol::PyDecision;
use super::values::{python_error, PyContext, PyRequest, PyResponse};

type BoxError = Box<dyn Error + Send + Sync>;

/// Adapts an object with the protocol's async routed-client method to Rust.
struct PythonRoutedLlmClient {
inner: Py<PyAny>,
}

#[async_trait]
impl RoutedLlmClient for PythonRoutedLlmClient {
async fn call(
&self,
ctx: Context,
request: Request,
decision: Arc<dyn Decision>,
) -> Result<Response, BoxError> {
let future = Python::attach(|py| {
let ctx = Py::new(py, PyContext::from_core(ctx))?;
let request = Py::new(py, PyRequest::from_core(request))?;
let decision = Py::new(py, PyDecision::new(decision))?;
let awaitable = self
.inner
.bind(py)
.call_method1("call", (ctx, request, decision))?;
pyo3_async_runtimes::tokio::into_future(awaitable)
})
.map_err(python_error)?;
let response = future.await.map_err(python_error)?;
Python::attach(|py| {
let response = response.bind(py).extract::<PyRef<'_, PyResponse>>()?;
response.take_core()
})
.map_err(python_error)
}
}

/// A semantic routing target and its optional Python-hosted routed client.
#[pyclass(name = "LlmTarget", module = "switchyard.libsy")]
Expand All @@ -13,6 +57,20 @@ pub(crate) struct PyLlmTarget {
llm_client: Option<Py<PyAny>>,
}

impl PyLlmTarget {
fn clone_core(&self, py: Python<'_>) -> LlmTarget {
let llm_client = self.llm_client.as_ref().map(|client| {
Arc::new(PythonRoutedLlmClient {
inner: client.clone_ref(py),
}) as Arc<dyn RoutedLlmClient>
});
LlmTarget {
semantic_name: self.semantic_name.clone(),
llm_client,
}
}
}

#[pymethods]
impl PyLlmTarget {
#[new]
Expand Down Expand Up @@ -61,6 +119,17 @@ pub(crate) struct PyLlmTargetSet {
targets: Vec<Py<PyLlmTarget>>,
}

impl PyLlmTargetSet {
pub(crate) fn clone_core(&self, py: Python<'_>) -> PyResult<LlmTargetSet> {
let targets = self
.targets
.iter()
.map(|target| Ok(target.bind(py).try_borrow()?.clone_core(py)))
.collect::<PyResult<Vec<_>>>()?;
Ok(LlmTargetSet::new(targets))
}
}

#[pymethods]
impl PyLlmTargetSet {
#[new]
Expand Down
55 changes: 49 additions & 6 deletions crates/switchyard-py/src/libsy_bindings/values.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use pyo3::types::PyType;
use serde::Serialize;
use serde_json::{Map, Value};
use switchyard_protocol::{
Context, LlmResponse, LlmResponseChunk, LlmResponseStream, Metadata, Request,
Context, LlmResponse, LlmResponseChunk, LlmResponseStream, Metadata, Request, Response,
};

use crate::errors::py_libsy_error;
Expand All @@ -37,16 +37,24 @@ pub(crate) struct PyContext {
inner: Context,
}

impl PyContext {
pub(crate) fn from_core(inner: Context) -> Self {
Self { inner }
}

pub(crate) fn clone_core(&self) -> Context {
self.inner.clone()
}
}

#[pymethods]
impl PyContext {
#[new]
#[pyo3(signature = (*, values=None))]
fn new(values: Option<HashMap<String, String>>) -> Self {
Self {
inner: Context {
values: values.unwrap_or_default(),
},
}
Self::from_core(Context {
values: values.unwrap_or_default(),
})
}

#[getter]
Expand Down Expand Up @@ -164,6 +172,16 @@ pub(crate) struct PyRequest {
inner: Request,
}

impl PyRequest {
pub(crate) fn from_core(inner: Request) -> Self {
Self { inner }
}

pub(crate) fn clone_core(&self) -> Request {
self.inner.clone()
}
}

#[pymethods]
impl PyRequest {
#[new]
Expand Down Expand Up @@ -243,6 +261,31 @@ pub(crate) struct PyResponse {
metadata: Option<Metadata>,
}

impl PyResponse {
pub(crate) fn from_core(inner: Response) -> Self {
Self {
llm_response: Mutex::new(Some(inner.llm_response)),
metadata: inner.metadata,
}
}

pub(crate) fn take_core(&self) -> PyResult<Response> {
let mut response = self
.llm_response
.lock()
.map_err(|_| PyRuntimeError::new_err("Response lock is poisoned"))?;
let Some(llm_response) = response.take() else {
return Err(PyRuntimeError::new_err(
"Response has already been consumed",
));
};
Ok(Response {
llm_response,
metadata: self.metadata.clone(),
})
}
}

#[pymethods]
impl PyResponse {
#[new]
Expand Down
Loading
Loading