From 619a19b8a2491c1ad3446f420ea5f023450fddf2 Mon Sep 17 00:00:00 2001 From: Yujong Lee Date: Sat, 19 Sep 2026 16:46:34 +0000 Subject: [PATCH] refactor(rust): use typed pyo3 APIs instead of getattr/import strings Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .../crates/callbacks-legacy/src/adapter.rs | 7 ++--- .../crates/host-python/src/callable.rs | 16 ++--------- litellm-rust/crates/host-python/src/driver.rs | 28 +++++-------------- .../python-bridge/src/routes/ocr/document.rs | 6 ++-- 4 files changed, 15 insertions(+), 42 deletions(-) diff --git a/litellm-rust/crates/callbacks-legacy/src/adapter.rs b/litellm-rust/crates/callbacks-legacy/src/adapter.rs index 6c013cd1ea5..883a35f0df5 100644 --- a/litellm-rust/crates/callbacks-legacy/src/adapter.rs +++ b/litellm-rust/crates/callbacks-legacy/src/adapter.rs @@ -12,7 +12,7 @@ use pyo3::{ exceptions::{PyBaseException, PyException}, gc::{PyTraverseError, PyVisit}, prelude::*, - types::{PyDict, PyList}, + types::{PyDateTime, PyDict, PyList}, }; use serde_json::Value; @@ -73,10 +73,7 @@ pub struct LegacyLogging { } fn datetime(py: Python<'_>, epoch_seconds: f64) -> PyResult> { - py.import("datetime")? - .getattr("datetime")? - .call_method1("fromtimestamp", (epoch_seconds,)) - .map(Bound::unbind) + PyDateTime::from_timestamp(py, epoch_seconds, None).map(|value| value.into_any().unbind()) } fn is_cancellation(py: Python<'_>, error: &PyErr) -> bool { diff --git a/litellm-rust/crates/host-python/src/callable.rs b/litellm-rust/crates/host-python/src/callable.rs index 424db002b0a..2e454422e95 100644 --- a/litellm-rust/crates/host-python/src/callable.rs +++ b/litellm-rust/crates/host-python/src/callable.rs @@ -73,13 +73,7 @@ abort = KeyboardInterrupt('cancelled') let wrapped = wrap_failure(py, TEMPLATE, failure(&original)).unwrap_err(); assert!(wrapped.is_instance_of::(py)); assert!(wrapped.cause(py).unwrap().value(py).is(&original)); - assert!( - wrapped - .value(py) - .getattr("__context__") - .unwrap() - .is(&original) - ); + assert!(wrapped.context(py).unwrap().value(py).is(&original)); assert_eq!( wrapped.value(py).str().unwrap().to_str().unwrap(), "Failed to reach the caller: unavailable" @@ -115,13 +109,7 @@ original = Unformattable('cannot render') let original = raised(&locals, "original"); let error = wrap_failure(py, TEMPLATE, failure(&original)).unwrap_err(); assert!(error.is_instance_of::(py)); - assert!( - error - .value(py) - .getattr("__context__") - .unwrap() - .is(&original) - ); + assert!(error.context(py).unwrap().value(py).is(&original)); }); } diff --git a/litellm-rust/crates/host-python/src/driver.rs b/litellm-rust/crates/host-python/src/driver.rs index 392d36e10f4..77a294d274b 100644 --- a/litellm-rust/crates/host-python/src/driver.rs +++ b/litellm-rust/crates/host-python/src/driver.rs @@ -445,14 +445,8 @@ where Ok(failure) => return failure.into(), Err(classifier_error) => classifier_error, }; - let attached = classifier_error.value(py).setattr( - "__context__", - PyRuntimeError::new_err(native).into_value(py), - ); - match attached { - Ok(()) => classifier_error, - Err(error) => error, - } + classifier_error.set_context(py, Some(PyRuntimeError::new_err(native))); + classifier_error } fn succeeded(&mut self, py: Python<'_>, response: Py) -> PyResult { @@ -1071,9 +1065,9 @@ sys.modules.setdefault('litellm.rust_bridge', types.ModuleType('litellm.rust_bri let error = result.unwrap_err(); assert!(error.is_instance_of::(py)); assert_eq!(error.value(py).to_string(), "classifier failed"); - let context = error.value(py).getattr("__context__").unwrap(); - assert!(context.is_instance_of::()); - assert_eq!(context.str().unwrap().to_string(), "provider exploded"); + let context = error.context(py).unwrap(); + assert!(context.is_instance_of::(py)); + assert_eq!(context.value(py).to_string(), "provider exploded"); assert_eq!( log, [ @@ -1186,20 +1180,12 @@ sys.modules.setdefault('litellm.rust_bridge', types.ModuleType('litellm.rust_bri type Failure = Classified; fn invoke( &mut self, - py: Python<'_>, + _: Python<'_>, _: &Bound<'_, PyDict>, _: &'static str, ) -> Result> { self.0.push("route"); - Err(PyErr::from_value( - py.import("asyncio") - .unwrap() - .getattr("CancelledError") - .unwrap() - .call0() - .unwrap(), - ) - .into()) + Err(pyo3::exceptions::asyncio::CancelledError::new_err(()).into()) } fn chunk( &mut self, diff --git a/litellm-rust/crates/python-bridge/src/routes/ocr/document.rs b/litellm-rust/crates/python-bridge/src/routes/ocr/document.rs index ed840dec70c..a928e62d5b7 100644 --- a/litellm-rust/crates/python-bridge/src/routes/ocr/document.rs +++ b/litellm-rust/crates/python-bridge/src/routes/ocr/document.rs @@ -7,7 +7,8 @@ use pyo3::{ gc::{PyTraverseError, PyVisit}, prelude::*, pybacked::PyBackedBytes, - types::{PyBytes, PyString}, + sync::PyOnceLock, + types::{PyBytes, PyString, PyType}, }; #[derive(Debug)] @@ -84,7 +85,8 @@ impl FromPyObject<'_, '_> for FileDocumentInput { "OCR file input does not accept bare str values. Pass bytes, a pathlib.Path, or a file-like object.", )); } - if file.is_instance(&py.import("os")?.getattr("PathLike")?)? { + static PATH_LIKE: PyOnceLock> = PyOnceLock::new(); + if file.is_instance(PATH_LIKE.import(py, "os", "PathLike")?)? { return Ok(Self { input: OcrDocumentInput::Path { path: file.extract::()?,