Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(ocr): thin Rust OCR Python bridge (#31368)

ishaan-berribdafc9a00842
diff --git a/litellm-rust/Cargo.lock b/litellm-rust/Cargo.lock
index ce86a0ee6ac..9bffe9f9ec6 100644
--- a/litellm-rust/Cargo.lock
+++ b/litellm-rust/Cargo.lock
@@ -673,6 +673,7 @@ dependencies = [
"serde",
"serde_json",
"thiserror 2.0.18",
+ "tokio",
]
[[package]]
diff --git a/litellm-rust/crates/ai-gateway/Cargo.toml b/litellm-rust/crates/ai-gateway/Cargo.toml
index 2f414159158..4055be36785 100644
--- a/litellm-rust/crates/ai-gateway/Cargo.toml
+++ b/litellm-rust/crates/ai-gateway/Cargo.toml
@@ -25,7 +25,7 @@ futures-util.workspace = true
serde_json.workspace = true
base64.workspace = true
axum = { workspace = true, features = ["ws"], optional = true }
-serde = { workspace = true, optional = true }
+serde.workspace = true
subtle = { workspace = true, optional = true }
# sha2 hashes the master key into user_api_key_hash (matches the proxy's
# SHA-256 hash_token) so the plaintext credential never enters a log payload.
@@ -34,7 +34,7 @@ pyo3 = { workspace = true, features = ["auto-initialize"], optional = true }
[features]
default = []
-server = ["dep:axum", "dep:subtle", "dep:serde", "dep:sha2"]
+server = ["dep:axum", "dep:subtle", "dep:sha2"]
# Build the gateway's config from the proxy YAML via an embedded Python
# interpreter (links libpython; requires `litellm` importable at runtime).
python-config = ["dep:pyo3"]
diff --git a/litellm-rust/crates/ai-gateway/src/constants.rs b/litellm-rust/crates/ai-gateway/src/constants.rs
index 3116a4c9932..109b648f5db 100644
--- a/litellm-rust/crates/ai-gateway/src/constants.rs
+++ b/litellm-rust/crates/ai-gateway/src/constants.rs
@@ -26,4 +26,5 @@ pub(crate) const DEFAULT_MAX_BATCH_SIZE: usize = 256;
pub(crate) const DEFAULT_FLUSH_INTERVAL_MS: u64 = 500;
/// Provider attributed to realtime sessions in the logging payload.
+#[cfg(feature = "server")]
pub(crate) const DEFAULT_PROVIDER: &str = "openai";
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/README.md b/litellm-rust/crates/ai-gateway/src/integrations/README.md
new file mode 100644
index 00000000000..16a162dac57
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/integrations/README.md
@@ -0,0 +1,127 @@
+# LiteLLM Rust integrations
+
+This directory contains Rust-native equivalents of LiteLLM integration hooks.
+The first supported surfaces are terminal custom loggers and pre/during-call
+custom guardrails.
+
+## File layout
+
+Every integration is a folder:
+
+- `mod.rs` contains the implementation, trait, runner, or adapter
+- `types.rs` contains the integration-local request, response, error, and future
+ types
+
+Do not add new flat integration files such as `custom_logger.rs`. Shared wire
+contracts that are used by multiple integrations can stay in
+`integrations/types.rs`.
+
+Call ordering and lifecycle timing live in `litellm-core/src/call_lifecycle`.
+Call-type modules, such as OCR, adapt their request and response shapes into
+that generic lifecycle runner.
+
+## CustomLogger
+
+Implement `CustomLogger` when Rust code needs to observe terminal success or
+failure events. Method names intentionally match Python `CustomLogger` names.
+
+```rust
+use litellm_ai_gateway::integrations::custom_logger::{
+ CallbackTiming, CallbackValue, CustomLogger, LogFuture, ModelCallDetails,
+};
+
+struct RecordingLogger;
+
+impl CustomLogger for RecordingLogger {
+ fn async_log_success_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ response_obj: &'a CallbackValue,
+ timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ let model = &model_call_details.model;
+ let provider = &model_call_details.custom_llm_provider;
+ let call_type = model_call_details.call_type.to_string();
+ let request_id = model_call_details.request_id.as_deref();
+ let response_object = &response_obj.object;
+ let duration = timing.end_time - timing.start_time;
+ let standard_payload = model_call_details.standard_logging_payload.as_ref();
+
+ Ok(())
+ })
+ }
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ response_obj: Option<&'a CallbackValue>,
+ timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ let error = model_call_details.failure_error.as_ref();
+ let response_object = response_obj.map(|value| value.object.as_str());
+ let duration = timing.end_time - timing.start_time;
+
+ Ok(())
+ })
+ }
+}
+```
+
+Use `CustomLoggerRunner` to fan out terminal events to configured loggers. The
+runner is a no-op when no loggers are configured, which is the expected fast
+path for requests without callbacks.
+
+## CustomGuardrail
+
+Implement `CustomGuardrail` when Rust code needs to run pre-call or native
+during-call checks. Method names intentionally match Python `CustomGuardrail`
+entrypoints inherited from Python `CustomLogger`.
+
+```rust
+use litellm_ai_gateway::integrations::custom_guardrail::{
+ CustomGuardrail, GuardrailContext, GuardrailDecision, GuardrailEventHook,
+ GuardrailFuture, GuardrailRequest,
+};
+
+struct BlocklistedPromptGuardrail;
+
+impl CustomGuardrail for BlocklistedPromptGuardrail {
+ fn guardrail_name(&self) -> &str {
+ "blocklisted-prompt"
+ }
+
+ fn supported_event_hooks(&self) -> &[GuardrailEventHook] {
+ &[GuardrailEventHook::PreCall]
+ }
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move {
+ if request.data.to_string().contains("blocked phrase") {
+ return Ok(GuardrailDecision::Block(
+ litellm_ai_gateway::integrations::custom_guardrail::GuardrailError::blocked(
+ "blocked phrase detected",
+ ),
+ ));
+ }
+ Ok(GuardrailDecision::Allow(request))
+ })
+ }
+}
+```
+
+Use `CustomGuardrailRunner::run_pre_call` for `pre_call` guardrails and
+`CustomGuardrailRunner::run_during_call` for `during_call` guardrails. A
+`GuardrailDecision::Mask` continues with modified request data.
+`GuardrailDecision::Block` short-circuits the provider call.
+
+## Current boundary
+
+These are Rust-only primitives. Python callback and guardrail adapters are a
+separate layer that should implement these Rust traits instead of changing the
+runner interfaces.
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/custom_guardrail/mod.rs b/litellm-rust/crates/ai-gateway/src/integrations/custom_guardrail/mod.rs
new file mode 100644
index 00000000000..e5d4ce3a708
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/integrations/custom_guardrail/mod.rs
@@ -0,0 +1,468 @@
+//! Rust mirror of Python `CustomGuardrail` entrypoints used by the proxy.
+//!
+//! This module is intentionally Rust-only: Python/PyO3 adapters are a later
+//! layer that should implement this trait rather than changing the runner.
+
+use std::future::Future;
+use std::sync::Arc;
+
+use crate::integrations::custom_logger::{
+ CallbackTiming, CallbackValue, CustomLoggerRunner, LoggingError, ModelCallDetails,
+};
+
+pub mod types;
+
+pub use types::{
+ GuardrailContext, GuardrailDecision, GuardrailDispatchReport, GuardrailError,
+ GuardrailEventHook, GuardrailFuture, GuardrailRequest,
+};
+
+pub trait CustomGuardrail: Send + Sync {
+ fn guardrail_name(&self) -> &str;
+
+ fn supported_event_hooks(&self) -> &[GuardrailEventHook];
+
+ /// Python 1:1 name: `async_pre_call_hook(user_api_key_dict, cache, data, call_type)`.
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move { Ok(GuardrailDecision::Allow(request)) })
+ }
+
+ /// Python 1:1 name: `async_moderation_hook(data, user_api_key_dict, call_type)`.
+ fn async_moderation_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move { Ok(GuardrailDecision::Allow(request)) })
+ }
+}
+
+pub struct CustomGuardrailRunner {
+ guardrails: Vec<Arc<dyn CustomGuardrail>>,
+}
+
+impl CustomGuardrailRunner {
+ pub fn new(guardrails: Vec<Arc<dyn CustomGuardrail>>) -> Self {
+ Self { guardrails }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.guardrails.is_empty()
+ }
+
+ pub async fn run_pre_call(
+ &self,
+ context: &GuardrailContext,
+ request: GuardrailRequest,
+ ) -> Result<(GuardrailRequest, GuardrailDispatchReport), GuardrailError> {
+ self.run_hook(GuardrailEventHook::PreCall, context, request)
+ .await
+ }
+
+ pub async fn run_during_call(
+ &self,
+ context: &GuardrailContext,
+ request: GuardrailRequest,
+ ) -> Result<(GuardrailRequest, GuardrailDispatchReport), GuardrailError> {
+ self.run_hook(GuardrailEventHook::DuringCall, context, request)
+ .await
+ }
+
+ pub async fn run_before_provider<F, Fut, T>(
+ &self,
+ event_hook: GuardrailEventHook,
+ context: &GuardrailContext,
+ request: GuardrailRequest,
+ provider: F,
+ ) -> Result<T, GuardrailError>
+ where
+ F: FnOnce(GuardrailRequest) -> Fut,
+ Fut: Future<Output = Result<T, GuardrailError>>,
+ {
+ let (request, _) = self.run_hook(event_hook, context, request).await?;
+ provider(request).await
+ }
+
+ pub async fn run_pre_call_with_failure_logging(
+ &self,
+ context: &GuardrailContext,
+ request: GuardrailRequest,
+ logger_runner: &CustomLoggerRunner,
+ model_call_details: &ModelCallDetails,
+ timing: CallbackTiming,
+ ) -> Result<(GuardrailRequest, GuardrailDispatchReport), GuardrailError> {
+ match self.run_pre_call(context, request).await {
+ Ok(result) => Ok(result),
+ Err(error) => {
+ let failure_details = model_call_details.clone().with_failure_error(LoggingError {
+ message: error.message.clone(),
+ kind: error.kind.clone(),
+ });
+ let response_obj = CallbackValue::new(
+ "guardrail_error",
+ serde_json::json!({
+ "message": error.message,
+ "kind": error.kind,
+ }),
+ );
+ logger_runner
+ .async_log_failure_event(&failure_details, Some(&response_obj), timing)
+ .await;
+ Err(error)
+ }
+ }
+ }
+
+ async fn run_hook(
+ &self,
+ event_hook: GuardrailEventHook,
+ context: &GuardrailContext,
+ mut request: GuardrailRequest,
+ ) -> Result<(GuardrailRequest, GuardrailDispatchReport), GuardrailError> {
+ if self.guardrails.is_empty() {
+ return Ok((request, GuardrailDispatchReport::default()));
+ }
+
+ let mut report = GuardrailDispatchReport::default();
+ for guardrail in &self.guardrails {
+ if !self.should_run(guardrail.as_ref(), event_hook, context) {
+ continue;
+ }
+
+ report.invoked += 1;
+ let decision = match event_hook {
+ GuardrailEventHook::PreCall => {
+ guardrail
+ .async_pre_call_hook(context, request.clone())
+ .await?
+ }
+ GuardrailEventHook::DuringCall => {
+ guardrail
+ .async_moderation_hook(context, request.clone())
+ .await?
+ }
+ };
+ match decision.into_request() {
+ Ok(next_request) => request = next_request,
+ Err(error) => return Err(error),
+ }
+ }
+
+ Ok((request, report))
+ }
+
+ fn should_run(
+ &self,
+ guardrail: &dyn CustomGuardrail,
+ event_hook: GuardrailEventHook,
+ context: &GuardrailContext,
+ ) -> bool {
+ let supports_hook = guardrail.supported_event_hooks().contains(&event_hook);
+ let selected = context.selected_guardrails.is_empty()
+ || context
+ .selected_guardrails
+ .iter()
+ .any(|name| name == guardrail.guardrail_name());
+ supports_hook && selected
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::integrations::custom_logger::{CallType, CallbackValue, CustomLogger, LogFuture};
+ use crate::integrations::types::{StandardLoggingMetadata, StandardLoggingPayload};
+ use serde_json::json;
+ use std::sync::Mutex;
+
+ #[derive(Clone)]
+ enum TestDecision {
+ Allow,
+ Mask,
+ Block,
+ }
+
+ struct RecordingCustomGuardrail {
+ name: String,
+ hooks: Vec<GuardrailEventHook>,
+ decision: TestDecision,
+ calls: Mutex<Vec<&'static str>>,
+ }
+
+ impl RecordingCustomGuardrail {
+ fn new(name: &str, hooks: Vec<GuardrailEventHook>, decision: TestDecision) -> Self {
+ Self {
+ name: name.to_string(),
+ hooks,
+ decision,
+ calls: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn calls(&self) -> Vec<&'static str> {
+ self.calls.lock().unwrap().clone()
+ }
+
+ fn decision(&self, mut request: GuardrailRequest) -> GuardrailDecision {
+ match self.decision {
+ TestDecision::Allow => GuardrailDecision::Allow(request),
+ TestDecision::Mask => {
+ request.data["masked"] = json!(true);
+ GuardrailDecision::Mask(request)
+ }
+ TestDecision::Block => {
+ GuardrailDecision::Block(GuardrailError::blocked("blocked by guardrail"))
+ }
+ }
+ }
+ }
+
+ impl CustomGuardrail for RecordingCustomGuardrail {
+ fn guardrail_name(&self) -> &str {
+ &self.name
+ }
+
+ fn supported_event_hooks(&self) -> &[GuardrailEventHook] {
+ &self.hooks
+ }
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move {
+ self.calls.lock().unwrap().push("async_pre_call_hook");
+ Ok(self.decision(request))
+ })
+ }
+
+ fn async_moderation_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move {
+ self.calls.lock().unwrap().push("async_moderation_hook");
+ Ok(self.decision(request))
+ })
+ }
+ }
+
+ #[tokio::test]
+ async fn pre_call_dispatches_to_async_pre_call_hook() {
+ let guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "pre",
+ vec![GuardrailEventHook::PreCall],
+ TestDecision::Allow,
+ ));
+ let runner = CustomGuardrailRunner::new(vec![guardrail.clone()]);
+ let context =
+ GuardrailContext::new(CallType::Ocr).with_selected_guardrails(vec!["pre".to_string()]);
+ let request = GuardrailRequest::new(json!({"messages": ["hello"]}));
+
+ let (result, report) = runner
+ .run_pre_call(&context, request)
+ .await
+ .expect("guardrail allows request");
+
+ assert_eq!(report.invoked, 1);
+ assert_eq!(result.data["messages"], json!(["hello"]));
+ assert_eq!(guardrail.calls(), vec!["async_pre_call_hook"]);
+ }
+
+ #[tokio::test]
+ async fn during_call_dispatches_to_async_moderation_hook() {
+ let guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "during",
+ vec![GuardrailEventHook::DuringCall],
+ TestDecision::Allow,
+ ));
+ let runner = CustomGuardrailRunner::new(vec![guardrail.clone()]);
+ let context = GuardrailContext::new(CallType::Completion)
+ .with_selected_guardrails(vec!["during".to_string()]);
+ let request = GuardrailRequest::new(json!({"prompt": "hello"}));
+
+ let (_result, report) = runner
+ .run_during_call(&context, request)
+ .await
+ .expect("guardrail allows request");
+
+ assert_eq!(report.invoked, 1);
+ assert_eq!(guardrail.calls(), vec!["async_moderation_hook"]);
+ }
+
+ #[tokio::test]
+ async fn mask_decision_continues_with_updated_request() {
+ let guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "masker",
+ vec![GuardrailEventHook::PreCall],
+ TestDecision::Mask,
+ ));
+ let runner = CustomGuardrailRunner::new(vec![guardrail]);
+ let context = GuardrailContext::new(CallType::Ocr);
+ let request = GuardrailRequest::new(json!({"document": "secret"}));
+
+ let (result, report) = runner
+ .run_pre_call(&context, request)
+ .await
+ .expect("mask continues");
+
+ assert_eq!(report.invoked, 1);
+ assert_eq!(result.data["masked"], json!(true));
+ }
+
+ #[tokio::test]
+ async fn block_decision_short_circuits_and_logs_failure() {
+ struct RecordingFailureLogger {
+ errors: Mutex<Vec<String>>,
+ }
+
+ impl CustomLogger for RecordingFailureLogger {
+ fn async_log_failure_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ _response_obj: Option<&'a CallbackValue>,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ self.errors.lock().unwrap().push(
+ model_call_details
+ .failure_error
+ .as_ref()
+ .map(|error| error.kind.clone())
+ .unwrap_or_default(),
+ );
+ Ok(())
+ })
+ }
+ }
+
+ let guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "blocker",
+ vec![GuardrailEventHook::PreCall],
+ TestDecision::Block,
+ ));
+ let guardrail_runner = CustomGuardrailRunner::new(vec![guardrail]);
+ let logger = Arc::new(RecordingFailureLogger {
+ errors: Mutex::new(Vec::new()),
+ });
+ let logger_runner = CustomLoggerRunner::new(vec![logger.clone()]);
+ let context = GuardrailContext::new(CallType::Ocr);
+ let details = ModelCallDetails::from_standard_logging_payload(StandardLoggingPayload {
+ id: "req_ocr".to_string(),
+ litellm_call_id: "req_ocr".to_string(),
+ call_type: "ocr".to_string(),
+ model: "mistral-ocr-latest".to_string(),
+ custom_llm_provider: "mistral".to_string(),
+ response_cost: 0.0,
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ total_tokens: 0,
+ start_time: 1.0,
+ end_time: 1.0,
+ stream: false,
+ metadata: StandardLoggingMetadata::default(),
+ messages: None,
+ });
+
+ let err = guardrail_runner
+ .run_pre_call_with_failure_logging(
+ &context,
+ GuardrailRequest::new(json!({"document": "bad"})),
+ &logger_runner,
+ &details,
+ CallbackTiming::new(1.0, 2.0),
+ )
+ .await
+ .expect_err("guardrail blocks request");
+
+ assert_eq!(err.kind, "GuardrailBlocked");
+ assert_eq!(
+ logger.errors.lock().unwrap().as_slice(),
+ ["GuardrailBlocked"]
+ );
+ }
+
+ #[tokio::test]
+ async fn block_decision_short_circuits_later_guardrails_and_provider_work() {
+ let blocking_guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "blocker",
+ vec![GuardrailEventHook::PreCall],
+ TestDecision::Block,
+ ));
+ let later_guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "later",
+ vec![GuardrailEventHook::PreCall],
+ TestDecision::Allow,
+ ));
+ let runner =
+ CustomGuardrailRunner::new(vec![blocking_guardrail.clone(), later_guardrail.clone()]);
+ let provider_called = Arc::new(Mutex::new(false));
+ let provider_called_for_closure = provider_called.clone();
+
+ let result = runner
+ .run_before_provider(
+ GuardrailEventHook::PreCall,
+ &GuardrailContext::new(CallType::Completion),
+ GuardrailRequest::new(json!({"prompt": "blocked"})),
+ move |_request| async move {
+ *provider_called_for_closure.lock().unwrap() = true;
+ Ok("provider response")
+ },
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert_eq!(blocking_guardrail.calls(), vec!["async_pre_call_hook"]);
+ assert_eq!(later_guardrail.calls(), Vec::<&'static str>::new());
+ assert!(!*provider_called.lock().unwrap());
+ }
+
+ #[tokio::test]
+ async fn run_before_provider_returns_provider_guardrail_error_directly() {
+ let guardrail = Arc::new(RecordingCustomGuardrail::new(
+ "allow",
+ vec![GuardrailEventHook::PreCall],
+ TestDecision::Allow,
+ ));
+ let runner = CustomGuardrailRunner::new(vec![guardrail]);
+
+ let result = runner
+ .run_before_provider(
+ GuardrailEventHook::PreCall,
+ &GuardrailContext::new(CallType::Completion),
+ GuardrailRequest::new(json!({"prompt": "allowed"})),
+ |_request| async move {
+ Err::<&'static str, GuardrailError>(GuardrailError::blocked(
+ "provider-side guardrail error",
+ ))
+ },
+ )
+ .await;
+
+ let err = result.expect_err("provider error is returned directly");
+ assert_eq!(err.kind, "GuardrailBlocked");
+ assert_eq!(err.message, "provider-side guardrail error");
+ }
+
+ #[tokio::test]
+ async fn no_guardrails_fast_path_dispatches_nothing() {
+ let runner = CustomGuardrailRunner::new(Vec::new());
+ let context = GuardrailContext::new(CallType::Ocr);
+ let request = GuardrailRequest::new(json!({"document": "ok"}));
+
+ let (result, report) = runner
+ .run_pre_call(&context, request)
+ .await
+ .expect("no guardrails allow request");
+
+ assert!(runner.is_empty());
+ assert_eq!(report, GuardrailDispatchReport::default());
+ assert_eq!(result.data["document"], json!("ok"));
+ }
+}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/custom_guardrail/types.rs b/litellm-rust/crates/ai-gateway/src/integrations/custom_guardrail/types.rs
new file mode 100644
index 00000000000..825e56cc0d7
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/integrations/custom_guardrail/types.rs
@@ -0,0 +1,110 @@
+use std::collections::HashMap;
+use std::future::Future;
+use std::pin::Pin;
+
+use serde_json::Value;
+
+use crate::integrations::custom_logger::CallType;
+
+pub type GuardrailFuture<'a> =
+ Pin<Box<dyn Future<Output = Result<GuardrailDecision, GuardrailError>> + Send + 'a>>;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum GuardrailEventHook {
+ PreCall,
+ DuringCall,
+}
+
+impl GuardrailEventHook {
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ Self::PreCall => "pre_call",
+ Self::DuringCall => "during_call",
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct GuardrailError {
+ pub message: String,
+ pub kind: String,
+}
+
+impl GuardrailError {
+ pub fn blocked(message: impl Into<String>) -> Self {
+ Self {
+ message: message.into(),
+ kind: "GuardrailBlocked".to_string(),
+ }
+ }
+}
+
+impl std::fmt::Display for GuardrailError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}: {}", self.kind, self.message)
+ }
+}
+
+impl std::error::Error for GuardrailError {}
+
+#[derive(Clone, Debug)]
+pub struct GuardrailContext {
+ pub call_type: CallType,
+ pub selected_guardrails: Vec<String>,
+ pub metadata: HashMap<String, Value>,
+ pub user_api_key_hash: Option<String>,
+ pub user_api_key_user_id: Option<String>,
+ pub user_api_key_team_id: Option<String>,
+ pub trace_parent: Option<String>,
+}
+
+impl GuardrailContext {
+ pub fn new(call_type: CallType) -> Self {
+ Self {
+ call_type,
+ selected_guardrails: Vec::new(),
+ metadata: HashMap::new(),
+ user_api_key_hash: None,
+ user_api_key_user_id: None,
+ user_api_key_team_id: None,
+ trace_parent: None,
+ }
+ }
+
+ pub fn with_selected_guardrails(mut self, selected_guardrails: Vec<String>) -> Self {
+ self.selected_guardrails = selected_guardrails;
+ self
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct GuardrailRequest {
+ pub data: Value,
+}
+
+impl GuardrailRequest {
+ pub fn new(data: Value) -> Self {
+ Self { data }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub enum GuardrailDecision {
+ Allow(GuardrailRequest),
+ Mask(GuardrailRequest),
+ Block(GuardrailError),
+}
+
+impl GuardrailDecision {
+ pub(super) fn into_request(self) -> Result<GuardrailRequest, GuardrailError> {
+ match self {
+ Self::Allow(request) | Self::Mask(request) => Ok(request),
+ Self::Block(error) => Err(error),
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GuardrailDispatchReport {
+ pub invoked: usize,
+}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/custom_logger.rs b/litellm-rust/crates/ai-gateway/src/integrations/custom_logger.rs
deleted file mode 100644
index 53b599d8c98..00000000000
--- a/litellm-rust/crates/ai-gateway/src/integrations/custom_logger.rs
+++ /dev/null
@@ -1,24 +0,0 @@
-//! The `CustomLogger` trait — the Rust mirror of Python
-//! `litellm/integrations/custom_logger.py::CustomLogger`.
-//!
-//! Synchronous (no `async_trait`): callbacks are O(1) enqueue-and-return so the
-//! realtime splice never blocks on a logger. Default bodies are no-ops so a
-//! logger can implement only the events it cares about.
-
-use crate::integrations::types::{LogError, LoggingError, StandardLoggingPayload};
-
-pub trait CustomLogger: Send + Sync {
- /// Record a successful call. Default: no-op.
- fn log_success_event(&self, _payload: &StandardLoggingPayload) -> Result<(), LogError> {
- Ok(())
- }
-
- /// Record a failed call. Default: no-op.
- fn log_failure_event(
- &self,
- _payload: &StandardLoggingPayload,
- _error: &LoggingError,
- ) -> Result<(), LogError> {
- Ok(())
- }
-}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/custom_logger/mod.rs b/litellm-rust/crates/ai-gateway/src/integrations/custom_logger/mod.rs
new file mode 100644
index 00000000000..792717dacfc
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/integrations/custom_logger/mod.rs
@@ -0,0 +1,317 @@
+//! The `CustomLogger` trait — the Rust mirror of Python
+//! `litellm/integrations/custom_logger.py::CustomLogger`.
+//!
+//! The Python-named async terminal methods are the public Rust callback shape.
+
+use std::sync::Arc;
+
+pub mod types;
+
+pub use types::{
+ CallType, CallbackDispatchReport, CallbackTiming, CallbackValue, LogError, LogFuture,
+ LoggingError, ModelCallDetails,
+};
+
+pub trait CustomLogger: Send + Sync {
+ /// Python 1:1 name: `async_log_success_event(model_call_details, response_obj, start_time, end_time)`.
+ fn async_log_success_event<'a>(
+ &'a self,
+ _model_call_details: &'a ModelCallDetails,
+ _response_obj: &'a CallbackValue,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async { Ok(()) })
+ }
+
+ /// Python 1:1 name: `async_log_failure_event(model_call_details, response_obj, start_time, end_time)`.
+ fn async_log_failure_event<'a>(
+ &'a self,
+ _model_call_details: &'a ModelCallDetails,
+ _response_obj: Option<&'a CallbackValue>,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async { Ok(()) })
+ }
+}
+
+pub struct CustomLoggerRunner {
+ loggers: Vec<Arc<dyn CustomLogger>>,
+}
+
+impl CustomLoggerRunner {
+ pub fn new(loggers: Vec<Arc<dyn CustomLogger>>) -> Self {
+ Self { loggers }
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.loggers.is_empty()
+ }
+
+ pub async fn async_log_success_event(
+ &self,
+ model_call_details: &ModelCallDetails,
+ response_obj: &CallbackValue,
+ timing: CallbackTiming,
+ ) -> CallbackDispatchReport {
+ if self.loggers.is_empty() {
+ return CallbackDispatchReport::default();
+ }
+
+ let mut report = CallbackDispatchReport::default();
+ for logger in &self.loggers {
+ report.invoked += 1;
+ if let Err(err) = logger
+ .async_log_success_event(model_call_details, response_obj, timing)
+ .await
+ {
+ report.dropped += 1;
+ eprintln!("litellm-ai-gateway: async_log_success_event dropped: {err}");
+ }
+ }
+ report
+ }
+
+ pub async fn async_log_failure_event(
+ &self,
+ model_call_details: &ModelCallDetails,
+ response_obj: Option<&CallbackValue>,
+ timing: CallbackTiming,
+ ) -> CallbackDispatchReport {
+ if self.loggers.is_empty() {
+ return CallbackDispatchReport::default();
+ }
+
+ let mut report = CallbackDispatchReport::default();
+ for logger in &self.loggers {
+ report.invoked += 1;
+ if let Err(err) = logger
+ .async_log_failure_event(model_call_details, response_obj, timing)
+ .await
+ {
+ report.dropped += 1;
+ eprintln!("litellm-ai-gateway: async_log_failure_event dropped: {err}");
+ }
+ }
+ report
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::integrations::types::{StandardLoggingMetadata, StandardLoggingPayload};
+ use serde_json::json;
+ use std::sync::Mutex;
+
+ #[derive(Clone, Debug, PartialEq)]
+ struct RecordedEvent {
+ hook: &'static str,
+ model: String,
+ provider: String,
+ call_type: String,
+ request_id: Option<String>,
+ litellm_call_id: Option<String>,
+ user_id: Option<String>,
+ response_object: Option<String>,
+ error_kind: Option<String>,
+ start_time: f64,
+ end_time: f64,
+ standard_logging_model: Option<String>,
+ }
+
+ #[derive(Default)]
+ struct RecordingCustomLogger {
+ events: Mutex<Vec<RecordedEvent>>,
+ }
+
+ impl RecordingCustomLogger {
+ fn events(&self) -> Vec<RecordedEvent> {
+ self.events.lock().unwrap().clone()
+ }
+ }
+
+ impl CustomLogger for RecordingCustomLogger {
+ fn async_log_success_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ response_obj: &'a CallbackValue,
+ timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push(RecordedEvent {
+ hook: "async_log_success_event",
+ model: model_call_details.model.clone(),
+ provider: model_call_details.custom_llm_provider.clone(),
+ call_type: model_call_details.call_type.to_string(),
+ request_id: model_call_details.request_id.clone(),
+ litellm_call_id: model_call_details.litellm_call_id.clone(),
+ user_id: model_call_details.metadata.user_api_key_user_id.clone(),
+ response_object: Some(response_obj.object.clone()),
+ error_kind: None,
+ start_time: timing.start_time,
+ end_time: timing.end_time,
+ standard_logging_model: model_call_details
+ .standard_logging_payload
+ .as_ref()
+ .map(|payload| payload.model.clone()),
+ });
+ Ok(())
+ })
+ }
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ response_obj: Option<&'a CallbackValue>,
+ timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push(RecordedEvent {
+ hook: "async_log_failure_event",
+ model: model_call_details.model.clone(),
+ provider: model_call_details.custom_llm_provider.clone(),
+ call_type: model_call_details.call_type.to_string(),
+ request_id: model_call_details.request_id.clone(),
+ litellm_call_id: model_call_details.litellm_call_id.clone(),
+ user_id: model_call_details.metadata.user_api_key_user_id.clone(),
+ response_object: response_obj.map(|value| value.object.clone()),
+ error_kind: model_call_details
+ .failure_error
+ .as_ref()
+ .map(|error| error.kind.clone()),
+ start_time: timing.start_time,
+ end_time: timing.end_time,
+ standard_logging_model: model_call_details
+ .standard_logging_payload
+ .as_ref()
+ .map(|payload| payload.model.clone()),
+ });
+ Ok(())
+ })
+ }
+ }
+
+ fn payload(call_type: &str, model: &str, provider: &str) -> StandardLoggingPayload {
+ StandardLoggingPayload {
+ id: format!("req_{call_type}"),
+ litellm_call_id: format!("call_{call_type}"),
+ call_type: call_type.to_string(),
+ model: model.to_string(),
+ custom_llm_provider: provider.to_string(),
+ response_cost: 0.25,
+ prompt_tokens: 3,
+ completion_tokens: 4,
+ total_tokens: 7,
+ start_time: 10.0,
+ end_time: 11.5,
+ stream: false,
+ metadata: StandardLoggingMetadata {
+ user_api_key_hash: Some("hash".to_string()),
+ user_api_key_user_id: Some("user".to_string()),
+ user_api_key_team_id: Some("team".to_string()),
+ ..Default::default()
+ },
+ messages: Some(json!([{"role": "user", "content": "read this"}])),
+ }
+ }
+
+ #[tokio::test]
+ async fn rust_custom_logger_reads_success_payload_for_ocr() {
+ let logger = Arc::new(RecordingCustomLogger::default());
+ let runner = CustomLoggerRunner::new(vec![logger.clone()]);
+ let details = ModelCallDetails::from_standard_logging_payload(payload(
+ "ocr",
+ "mistral-ocr-latest",
+ "mistral",
+ ));
+ let response = CallbackValue::new("ocr", json!({"pages": [{"markdown": "ok"}]}));
+ let report = runner
+ .async_log_success_event(&details, &response, CallbackTiming::new(10.0, 11.5))
+ .await;
+
+ assert_eq!(report.invoked, 1);
+ assert_eq!(report.dropped, 0);
+ assert_eq!(
+ logger.events(),
+ vec![RecordedEvent {
+ hook: "async_log_success_event",
+ model: "mistral-ocr-latest".to_string(),
+ provider: "mistral".to_string(),
+ call_type: "ocr".to_string(),
+ request_id: Some("req_ocr".to_string()),
+ litellm_call_id: Some("call_ocr".to_string()),
+ user_id: Some("user".to_string()),
+ response_object: Some("ocr".to_string()),
+ error_kind: None,
+ start_time: 10.0,
+ end_time: 11.5,
+ standard_logging_model: Some("mistral-ocr-latest".to_string()),
+ }]
+ );
+ }
+
+ #[tokio::test]
+ async fn rust_custom_logger_reads_failure_payload_for_non_ocr_call_type() {
+ let logger = Arc::new(RecordingCustomLogger::default());
+ let runner = CustomLoggerRunner::new(vec![logger.clone()]);
+ let details = ModelCallDetails::from_standard_logging_payload(payload(
+ "acompletion",
+ "gpt-4.1-mini",
+ "openai",
+ ))
+ .with_failure_error(LoggingError {
+ message: "provider failed".to_string(),
+ kind: "ProviderError".to_string(),
+ });
+ let response = CallbackValue::new("error", json!({"message": "provider failed"}));
+ let report = runner
+ .async_log_failure_event(&details, Some(&response), CallbackTiming::new(2.0, 3.0))
+ .await;
+
+ assert_eq!(report.invoked, 1);
+ assert_eq!(report.dropped, 0);
+ assert_eq!(
+ logger.events(),
+ vec![RecordedEvent {
+ hook: "async_log_failure_event",
+ model: "gpt-4.1-mini".to_string(),
+ provider: "openai".to_string(),
+ call_type: "acompletion".to_string(),
+ request_id: Some("req_acompletion".to_string()),
+ litellm_call_id: Some("call_acompletion".to_string()),
+ user_id: Some("user".to_string()),
+ response_object: Some("error".to_string()),
+ error_kind: Some("ProviderError".to_string()),
+ start_time: 2.0,
+ end_time: 3.0,
+ standard_logging_model: Some("gpt-4.1-mini".to_string()),
+ }]
+ );
+ }
+
+ #[tokio::test]
+ async fn no_callback_fast_path_dispatches_nothing() {
+ let runner = CustomLoggerRunner::new(Vec::new());
+ let details = ModelCallDetails::new("mistral-ocr-latest", "mistral", CallType::Ocr);
+ let response = CallbackValue::new("ocr", json!({}));
+
+ let report = runner
+ .async_log_success_event(&details, &response, CallbackTiming::new(1.0, 1.5))
+ .await;
+
+ assert!(runner.is_empty());
+ assert_eq!(report, CallbackDispatchReport::default());
+ }
+
+ #[test]
+ fn with_standard_logging_payload_keeps_top_level_fields_in_sync() {
+ let details = ModelCallDetails::new("old-model", "old-provider", CallType::Completion)
+ .with_standard_logging_payload(payload("ocr", "mistral-ocr-latest", "mistral"));
+
+ assert_eq!(details.model, "mistral-ocr-latest");
+ assert_eq!(details.custom_llm_provider, "mistral");
+ assert_eq!(details.call_type, CallType::Ocr);
+ assert_eq!(details.request_id, Some("req_ocr".to_string()));
+ assert_eq!(details.litellm_call_id, Some("call_ocr".to_string()));
+ }
+}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/custom_logger/types.rs b/litellm-rust/crates/ai-gateway/src/integrations/custom_logger/types.rs
new file mode 100644
index 00000000000..ba7d67bd46e
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/integrations/custom_logger/types.rs
@@ -0,0 +1,194 @@
+use std::collections::HashMap;
+use std::future::Future;
+use std::pin::Pin;
+
+use serde_json::Value;
+
+use crate::integrations::types::{StandardLoggingMetadata, StandardLoggingPayload};
+
+pub type LogFuture<'a> = Pin<Box<dyn Future<Output = Result<(), LogError>> + Send + 'a>>;
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct CallbackDispatchReport {
+ pub invoked: usize,
+ pub dropped: usize,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum CallType {
+ Ocr,
+ Realtime,
+ Completion,
+ Acompletion,
+ ChatCompletion,
+ Other(String),
+}
+
+impl CallType {
+ pub fn as_str(&self) -> &str {
+ match self {
+ Self::Ocr => "ocr",
+ Self::Realtime => "realtime",
+ Self::Completion => "completion",
+ Self::Acompletion => "acompletion",
+ Self::ChatCompletion => "chat_completion",
+ Self::Other(value) => value.as_str(),
+ }
+ }
+}
+
+impl From<&str> for CallType {
+ fn from(value: &str) -> Self {
+ match value {
+ "ocr" => Self::Ocr,
+ "realtime" => Self::Realtime,
+ "completion" => Self::Completion,
+ "acompletion" => Self::Acompletion,
+ "chat_completion" => Self::ChatCompletion,
+ other => Self::Other(other.to_string()),
+ }
+ }
+}
+
+impl std::fmt::Display for CallType {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(self.as_str())
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct CallbackTiming {
+ pub start_time: f64,
+ pub end_time: f64,
+}
+
+impl CallbackTiming {
+ pub fn new(start_time: f64, end_time: f64) -> Self {
+ Self {
+ start_time,
+ end_time,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct CallbackValue {
+ pub object: String,
+ pub value: Value,
+}
+
+impl CallbackValue {
+ pub fn new(object: impl Into<String>, value: Value) -> Self {
+ Self {
+ object: object.into(),
+ value,
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct ModelCallDetails {
+ pub model: String,
+ pub custom_llm_provider: String,
+ pub call_type: CallType,
+ pub metadata: StandardLoggingMetadata,
+ pub extra_metadata: HashMap<String, Value>,
+ pub request_id: Option<String>,
+ pub litellm_call_id: Option<String>,
+ pub response_cost: Option<f64>,
+ pub standard_logging_payload: Option<StandardLoggingPayload>,
+ pub failure_error: Option<LoggingError>,
+}
+
+impl ModelCallDetails {
+ pub fn new(
+ model: impl Into<String>,
+ custom_llm_provider: impl Into<String>,
+ call_type: CallType,
+ ) -> Self {
+ Self {
+ model: model.into(),
+ custom_llm_provider: custom_llm_provider.into(),
+ call_type,
+ metadata: StandardLoggingMetadata::default(),
+ extra_metadata: HashMap::new(),
+ request_id: None,
+ litellm_call_id: None,
+ response_cost: None,
+ standard_logging_payload: None,
+ failure_error: None,
+ }
+ }
+
+ pub fn from_standard_logging_payload(payload: StandardLoggingPayload) -> Self {
+ let request_id = Some(payload.id.clone());
+ let litellm_call_id = Some(payload.litellm_call_id.clone());
+ let response_cost = Some(payload.response_cost);
+ let metadata = payload.metadata.clone();
+ Self {
+ model: payload.model.clone(),
+ custom_llm_provider: payload.custom_llm_provider.clone(),
+ call_type: CallType::from(payload.call_type.as_str()),
+ metadata,
+ extra_metadata: HashMap::new(),
+ request_id,
+ litellm_call_id,
+ response_cost,
+ standard_logging_payload: Some(payload),
+ failure_error: None,
+ }
+ }
+
+ pub fn with_standard_logging_payload(mut self, payload: StandardLoggingPayload) -> Self {
+ self.model = payload.model.clone();
+ self.custom_llm_provider = payload.custom_llm_provider.clone();
+ self.call_type = CallType::from(payload.call_type.as_str());
+ self.request_id = Some(payload.id.clone());
+ self.litellm_call_id = Some(payload.litellm_call_id.clone());
+ self.response_cost = Some(payload.response_cost);
+ self.metadata = payload.metadata.clone();
+ self.standard_logging_payload = Some(payload);
+ self
+ }
+
+ pub fn with_failure_error(mut self, error: LoggingError) -> Self {
+ self.failure_error = Some(error);
+ self
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct LoggingError {
+ pub message: String,
+ pub kind: String,
+}
+
+#[derive(Clone, Debug)]
+pub struct LogError {
+ pub message: String,
+ pub kind: String,
+}
+
+impl LogError {
+ pub fn channel_full() -> Self {
+ Self {
+ message: "logging channel is full; dropping record".to_string(),
+ kind: "ChannelFull".to_string(),
+ }
+ }
+
+ pub fn channel_closed() -> Self {
+ Self {
+ message: "logging channel is closed; worker has shut down".to_string(),
+ kind: "ChannelClosed".to_string(),
+ }
+ }
+}
+
+impl std::fmt::Display for LogError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}: {}", self.kind, self.message)
+ }
+}
+
+impl std::error::Error for LogError {}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api.rs b/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api/mod.rs
similarity index 68%
rename from litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api.rs
rename to litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api/mod.rs
index 165a90d8dbe..3dad18cb7a3 100644
--- a/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api.rs
+++ b/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api/mod.rs
@@ -1,7 +1,8 @@
//! A `CustomLogger` that ships finished events to the LiteLLM Python proxy's
//! `/v1/rust_control_plane/logs` endpoint.
//!
-//! The callback path is non-blocking: `log_success_event` / `log_failure_event`
+//! The callback path is non-blocking: `async_log_success_event` /
+//! `async_log_failure_event`
//! build a `LogRecord` and `try_send` it onto a bounded channel, returning a
//! `LogError` (never panicking, never awaiting) if the channel is full or the
//! worker has gone away. A spawned background worker drains the channel, batches
@@ -15,54 +16,14 @@ use reqwest::Client;
use tokio::sync::mpsc::{self, Receiver, Sender};
use tokio::time::interval;
-use crate::constants::{
- DEFAULT_CHANNEL_CAPACITY, DEFAULT_FLUSH_INTERVAL_MS, DEFAULT_MAX_BATCH_SIZE,
- DEFAULT_PROXY_BASE_URL, RUST_CONTROL_PLANE_LOGS_PATH,
+use crate::constants::{DEFAULT_PROXY_BASE_URL, RUST_CONTROL_PLANE_LOGS_PATH};
+use crate::integrations::custom_logger::{
+ CallbackTiming, CallbackValue, CustomLogger, LogError, LogFuture, LoggingError,
+ ModelCallDetails,
};
-use crate::integrations::custom_logger::CustomLogger;
-use crate::integrations::types::{
- CallbackLogsRequest, LogError, LogRecord, LoggingError, StandardLoggingPayload,
-};
-
-/// Egress worker tunables. Each field defaults to the matching `DEFAULT_*` const
-/// in `crate::constants` and is overridable via an env var (read once at logger
-/// construction).
-struct EgressTunables {
- channel_capacity: usize,
- max_batch_size: usize,
- flush_interval: Duration,
-}
-
-impl EgressTunables {
- fn from_env() -> Self {
- Self {
- channel_capacity: env_positive(
- "LITELLM_LOG_CHANNEL_CAPACITY",
- DEFAULT_CHANNEL_CAPACITY,
- ),
- max_batch_size: env_positive("LITELLM_LOG_BATCH_SIZE", DEFAULT_MAX_BATCH_SIZE),
- flush_interval: Duration::from_millis(env_positive(
- "LITELLM_LOG_FLUSH_INTERVAL_MS",
- DEFAULT_FLUSH_INTERVAL_MS,
- )),
- }
- }
-}
+use types::{CallbackLogsRequest, EgressTunables, LogRecord};
-/// Parse a positive integer env var, falling back to `default` on missing,
-/// unparseable, or non-positive values. Generic over the integer type so one
-/// helper serves both the `usize` capacities and the `u64` interval.
-fn env_positive<T>(name: &str, default: T) -> T
-where
- T: std::str::FromStr + PartialOrd + From<u8>,
-{
- let zero = T::from(0u8);
- std::env::var(name)
- .ok()
- .and_then(|value| value.trim().parse::<T>().ok())
- .filter(|n| *n > zero)
- .unwrap_or(default)
-}
+pub mod types;
/// Ships realtime logging events to the LiteLLM Python proxy.
pub struct LiteLLMPythonProxyAPILogger {
@@ -118,23 +79,50 @@ impl LiteLLMPythonProxyAPILogger {
}
impl CustomLogger for LiteLLMPythonProxyAPILogger {
- fn log_success_event(&self, payload: &StandardLoggingPayload) -> Result<(), LogError> {
- self.enqueue(LogRecord {
- status: "success".to_string(),
- payload: payload.clone(),
- error: None,
+ fn async_log_success_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ _response_obj: &'a CallbackValue,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ if let Some(payload) = &model_call_details.standard_logging_payload {
+ self.enqueue(LogRecord {
+ status: "success".to_string(),
+ payload: payload.clone(),
+ error: None,
+ })?;
+ }
+ Ok(())
})
}
- fn log_failure_event(
- &self,
- payload: &StandardLoggingPayload,
- error: &LoggingError,
- ) -> Result<(), LogError> {
- self.enqueue(LogRecord {
- status: "failure".to_string(),
- payload: payload.clone(),
- error: Some(format!("{}: {}", error.kind, error.message)),
+ fn async_log_failure_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ _response_obj: Option<&'a CallbackValue>,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ if let Some(payload) = &model_call_details.standard_logging_payload {
+ let fallback_error;
+ let error = match &model_call_details.failure_error {
+ Some(error) => error,
+ None => {
+ fallback_error = LoggingError {
+ message: "callback failure event".to_string(),
+ kind: "CallbackFailure".to_string(),
+ };
+ &fallback_error
+ }
+ };
+ self.enqueue(LogRecord {
+ status: "failure".to_string(),
+ payload: payload.clone(),
+ error: Some(format!("{}: {}", error.kind, error.message)),
+ })?;
+ }
+ Ok(())
})
}
}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api/types.rs b/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api/types.rs
new file mode 100644
index 00000000000..481a437747f
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/integrations/litellm_python_proxy_api/types.rs
@@ -0,0 +1,72 @@
+use std::time::Duration;
+
+use serde::Serialize;
+
+use crate::constants::{
+ DEFAULT_CHANNEL_CAPACITY, DEFAULT_FLUSH_INTERVAL_MS, DEFAULT_MAX_BATCH_SIZE,
+};
+use crate::integrations::types::StandardLoggingPayload;
+
+#[derive(Serialize)]
+pub struct CallbackLogsRequest {
+ pub records: Vec<CallbackLogRecord>,
+}
+
+#[derive(Serialize)]
+pub struct CallbackLogRecord {
+ pub status: String,
+ pub standard_logging_payload: StandardLoggingPayload,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error: Option<String>,
+}
+
+#[derive(Clone, Debug)]
+pub struct LogRecord {
+ pub status: String,
+ pub payload: StandardLoggingPayload,
+ pub error: Option<String>,
+}
+
+impl LogRecord {
+ pub fn into_callback_record(self) -> CallbackLogRecord {
+ CallbackLogRecord {
+ status: self.status,
+ standard_logging_payload: self.payload,
+ error: self.error,
+ }
+ }
+}
+
+pub(super) struct EgressTunables {
+ pub channel_capacity: usize,
+ pub max_batch_size: usize,
+ pub flush_interval: Duration,
+}
+
+impl EgressTunables {
+ pub fn from_env() -> Self {
+ Self {
+ channel_capacity: env_positive(
+ "LITELLM_LOG_CHANNEL_CAPACITY",
+ DEFAULT_CHANNEL_CAPACITY,
+ ),
+ max_batch_size: env_positive("LITELLM_LOG_BATCH_SIZE", DEFAULT_MAX_BATCH_SIZE),
+ flush_interval: Duration::from_millis(env_positive(
+ "LITELLM_LOG_FLUSH_INTERVAL_MS",
+ DEFAULT_FLUSH_INTERVAL_MS,
+ )),
+ }
+ }
+}
+
+fn env_positive<T>(name: &str, default: T) -> T
+where
+ T: std::str::FromStr + PartialOrd + From<u8>,
+{
+ let zero = T::from(0u8);
+ std::env::var(name)
+ .ok()
+ .and_then(|value| value.trim().parse::<T>().ok())
+ .filter(|n| *n > zero)
+ .unwrap_or(default)
+}
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/mod.rs b/litellm-rust/crates/ai-gateway/src/integrations/mod.rs
index 8799be0c040..c62f1821ef8 100644
--- a/litellm-rust/crates/ai-gateway/src/integrations/mod.rs
+++ b/litellm-rust/crates/ai-gateway/src/integrations/mod.rs
@@ -1,10 +1,12 @@
//! Pure-Rust logging integrations. Names map 1:1 to Python
//! `litellm/integrations/`:
+//! - [`custom_guardrail::CustomGuardrail`] — the guardrail callback trait
//! - [`custom_logger::CustomLogger`] — the callback trait
//! - [`litellm_python_proxy_api::LiteLLMPythonProxyAPILogger`] — ships events
-//! to the Python proxy's `/v1/callbacks/logs` endpoint
+//! to the Python proxy's `/v1/rust_control_plane/logs` endpoint
//! - [`types`] — the typed `StandardLoggingPayload` wire contract
+pub mod custom_guardrail;
pub mod custom_logger;
pub mod litellm_python_proxy_api;
pub mod types;
diff --git a/litellm-rust/crates/ai-gateway/src/integrations/types.rs b/litellm-rust/crates/ai-gateway/src/integrations/types.rs
index d61a1f816a7..34dce93d8e0 100644
--- a/litellm-rust/crates/ai-gateway/src/integrations/types.rs
+++ b/litellm-rust/crates/ai-gateway/src/integrations/types.rs
@@ -28,68 +28,6 @@ pub struct RequestMetadata {
pub user_api_key_team_id: Option<String>,
}
-/// A logging-callback failure (e.g. a custom logger raised). Mirrors the Python
-/// failure-event shape: a message plus an exception kind/class name.
-#[derive(Clone, Debug)]
-pub struct LoggingError {
- pub message: String,
- pub kind: String,
-}
-
-/// A non-fatal error returned by a `CustomLogger` when it cannot enqueue an
-/// event (channel full or the background worker has shut down).
-#[derive(Clone, Debug)]
-pub struct LogError {
- pub message: String,
- pub kind: String,
-}
-
-impl LogError {
- pub fn channel_full() -> Self {
- Self {
- message: "logging channel is full; dropping record".to_string(),
- kind: "ChannelFull".to_string(),
- }
- }
-
- pub fn channel_closed() -> Self {
- Self {
- message: "logging channel is closed; worker has shut down".to_string(),
- kind: "ChannelClosed".to_string(),
- }
- }
-}
-
-impl std::fmt::Display for LogError {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- write!(f, "{}: {}", self.kind, self.message)
- }
-}
-
-impl std::error::Error for LogError {}
-
-/// Batch wrapper — the top-level request body.
-/// Matches Python `CallbackLogsRequest { records: list[CallbackLogRecord] }`.
-#[derive(Serialize)]
-pub struct CallbackLogsRequest {
- pub records: Vec<CallbackLogRecord>,
-}
-
-/// One finished logging event.
-/// Matches `CallbackLogRecord { status, standard_logging_payload, error? }`.
-#[derive(Serialize)]
-pub struct CallbackLogRecord {
- /// "success" | "failure". On "failure", `error` (or payload.error_str)
- /// becomes the replayed exception string.
- pub status: String,
-
- pub standard_logging_payload: StandardLoggingPayload,
-
- /// Only meaningful when status == "failure". Omitted on success.
- #[serde(skip_serializing_if = "Option::is_none")]
- pub error: Option<String>,
-}
-
/// The self-describing payload. Field names are the EXACT JSON keys the Python
/// replay path + spend-logs builder read.
#[derive(Clone, Debug, Serialize)]
@@ -143,22 +81,3 @@ pub struct StandardLoggingMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub spend_logs_metadata: Option<HashMap<String, Value>>,
}
-
-/// The unit handed to a `CustomLogger` sink: a finished payload plus its status
-/// and (on failure) the replayed error string.
-#[derive(Clone, Debug)]
-pub struct LogRecord {
- pub status: String,
- pub payload: StandardLoggingPayload,
- pub error: Option<String>,
-}
-
-impl LogRecord {
- pub fn into_callback_record(self) -> CallbackLogRecord {
- CallbackLogRecord {
- status: self.status,
- standard_logging_payload: self.payload,
- error: self.error,
- }
- }
-}
diff --git a/litellm-rust/crates/ai-gateway/src/io/ocr.rs b/litellm-rust/crates/ai-gateway/src/io/ocr.rs
index 35e511fa982..55e02839c4e 100644
--- a/litellm-rust/crates/ai-gateway/src/io/ocr.rs
+++ b/litellm-rust/crates/ai-gateway/src/io/ocr.rs
@@ -1,406 +1 @@
-//! End-to-end OCR orchestration.
-//!
-//! Owns supported OCR provider calls so the Python side stays a thin bridge:
-//! resolve the API key, build the URL + body via the pure transforms, POST it,
-//! and normalize the response. The HTTP client is built once and reused.
-
-use std::sync::OnceLock;
-use std::time::Duration;
-
-use litellm_core::error::CoreError;
-use litellm_core::ocr::transformation::{OcrAuthStrategy, OcrResponseHandling};
-use litellm_core::CoreResult;
-use serde_json::{Map, Value};
-
-mod common_utils;
-
-use common_utils::{
- convert_document_url_to_data_uri, has_header, ocr_provider_config, poll_document_intelligence,
- string_headers, truncate_error_body,
-};
-
-/// OCR over large documents can take a while; bound it generously rather than
-/// hanging forever on an unresponsive upstream. The client-level limit is the
-/// outer ceiling; callers can tighten it per request via ``run_ocr``'s ``timeout``.
-const OCR_TIMEOUT_SECS: u64 = 600;
-
-/// Process-wide async HTTP client (connection pool + TLS reused across calls).
-///
-/// The Python fallback path uses LiteLLM's standard `BaseLLMHTTPHandler`. This
-/// Rust path is opt-in and owns end-to-end OCR I/O, so it cannot call the
-/// Python handler directly; keep this route-scoped until litellm-rust has a
-/// shared HTTP abstraction.
-fn http_client() -> &'static reqwest::Client {
- static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
- CLIENT.get_or_init(|| {
- reqwest::Client::builder()
- .timeout(Duration::from_secs(OCR_TIMEOUT_SECS))
- .build()
- .expect("failed to build reqwest client")
- })
-}
-
-fn upstream_headers(
- headers: &[(String, String)],
- auth_strategy: OcrAuthStrategy,
- api_key: Option<&str>,
-) -> Vec<(String, String)> {
- let auth_header = api_key.map(|api_key| match auth_strategy {
- OcrAuthStrategy::Bearer => ("Authorization".to_string(), format!("Bearer {api_key}")),
- OcrAuthStrategy::Header(header_name) => (header_name.to_string(), api_key.to_string()),
- });
- auth_header
- .into_iter()
- .chain(headers.iter().cloned())
- .collect()
-}
-
-pub struct OcrRequest<'a> {
- pub model: &'a str,
- pub document: Value,
- pub api_key: Option<&'a str>,
- pub api_base: Option<&'a str>,
- pub custom_llm_provider: &'a str,
- pub extra_headers: Option<Map<String, Value>>,
- pub optional_params: Map<String, Value>,
- pub timeout: Option<Duration>,
-}
-
-/// Perform an OCR call end to end and return the normalized response as
-/// JSON (the shape the Python `OCRResponse` model expects).
-///
-/// Async: intended to be awaited directly by the Python bridge's async entrypoint.
-pub async fn ocr(request: OcrRequest<'_>) -> CoreResult<Value> {
- let model = request.model;
- let config = ocr_provider_config(request.custom_llm_provider, model)
- .ok_or_else(|| CoreError::InvalidProvider(request.custom_llm_provider.to_string()))?;
- let env_lookup = |key: &str| std::env::var(key).ok();
-
- let headers = string_headers(request.extra_headers)?;
- let auth_strategy = config.auth_strategy();
- let api_key = (!has_header(&headers, auth_strategy.header_name()))
- .then(|| config.resolve_api_key(request.api_key, &env_lookup))
- .transpose()?;
- let url = config.complete_url(
- request.api_base,
- model,
- &request.optional_params,
- &env_lookup,
- )?;
- let filtered_params = config.map_ocr_params(&request.optional_params);
- let document = if config.requires_data_uri_document() {
- convert_document_url_to_data_uri(request.document).await?
- } else {
- request.document
- };
- let body = config
- .transform_ocr_request(model, document, filtered_params)?
- .data;
- let upstream_headers = upstream_headers(&headers, auth_strategy, api_key.as_deref());
-
- let mut request_builder = http_client().post(&url).json(&body);
- for (key, value) in &upstream_headers {
- request_builder = request_builder.header(key, value);
- }
- if let Some(duration) = request.timeout {
- request_builder = request_builder.timeout(duration);
- }
-
- let response = request_builder
- .send()
- .await
- .map_err(|err| CoreError::Network(err.to_string()))?;
-
- let status = response.status();
- if config.response_handling() == OcrResponseHandling::AzureDocumentIntelligencePoll
- && status.as_u16() == 202
- {
- let operation_url = response
- .headers()
- .get("operation-location")
- .and_then(|value| value.to_str().ok())
- .map(str::to_string)
- .ok_or_else(|| {
- CoreError::InvalidResponse(
- "Azure Document Intelligence returned 202 but no Operation-Location header found"
- .to_string(),
- )
- })?;
- let response_json =
- poll_document_intelligence(&operation_url, &url, &upstream_headers, request.timeout)
- .await?;
- return Ok(config
- .transform_ocr_response(model, response_json)?
- .into_json());
- }
-
- let text = response
- .text()
- .await
- .map_err(|err| CoreError::Network(err.to_string()))?;
-
- if !status.is_success() {
- return Err(CoreError::Http {
- status: status.as_u16(),
- body: truncate_error_body(&text),
- });
- }
-
- let response_json: Value = serde_json::from_str(&text)
- .map_err(|err| CoreError::InvalidResponse(format!("invalid OCR response JSON: {err}")))?;
-
- Ok(config
- .transform_ocr_response(model, response_json)?
- .into_json())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use serde_json::json;
- use tokio::io::{AsyncReadExt, AsyncWriteExt};
- use tokio::net::{TcpListener, TcpStream};
-
- async fn read_http_headers(socket: &mut TcpStream) -> String {
- let mut request = Vec::new();
- let mut buffer = [0_u8; 1024];
- loop {
- let n = socket.read(&mut buffer).await.expect("reads request");
- if n == 0 {
- break;
- }
- request.extend_from_slice(&buffer[..n]);
- if request.windows(4).any(|window| window == b"\r\n\r\n") {
- break;
- }
- }
- String::from_utf8(request).expect("request is utf8")
- }
-
- #[test]
- fn truncate_error_body_passes_short_strings_through() {
- let body = "Unauthorized";
- assert_eq!(truncate_error_body(body), "Unauthorized");
- }
-
- #[test]
- fn truncate_error_body_caps_long_payloads() {
- let body = "x".repeat(306);
- let truncated = truncate_error_body(&body);
-
- assert!(truncated.ends_with("... (truncated)"));
- let prefix_chars = truncated
- .strip_suffix("... (truncated)")
- .expect("truncated marker present")
- .chars()
- .count();
- assert_eq!(prefix_chars, 256);
- }
-
- #[test]
- fn truncate_error_body_does_not_split_multibyte_chars() {
- let body = "é".repeat(266);
- let truncated = truncate_error_body(&body);
- assert!(truncated.is_char_boundary(truncated.len()));
- }
-
- #[test]
- fn ocr_dispatch_supports_migrated_providers() {
- assert!(ocr_provider_config("mistral", "mistral-ocr-latest").is_some());
- assert!(ocr_provider_config("azure_ai", "pixtral-12b-2409")
- .expect("azure ai config resolves")
- .requires_data_uri_document());
- assert_eq!(
- ocr_provider_config("azure_ai", "doc-intelligence/prebuilt-read")
- .expect("document intelligence config resolves")
- .response_handling(),
- OcrResponseHandling::AzureDocumentIntelligencePoll
- );
- assert!(ocr_provider_config("vertex_ai", "deepseek-ocr-maas")
- .expect("vertex deepseek config resolves")
- .supported_ocr_params()
- .contains(&"temperature"));
- assert!(ocr_provider_config("openai", "gpt-4o").is_none());
- }
-
- #[test]
- fn string_headers_accepts_string_values() {
- let headers = json!({
- "x-trace-id": "trace-1"
- })
- .as_object()
- .unwrap()
- .clone();
-
- assert_eq!(
- string_headers(Some(headers)).expect("string headers accepted"),
- vec![("x-trace-id".to_string(), "trace-1".to_string())]
- );
- }
-
- #[test]
- fn auth_header_detection_is_case_insensitive() {
- let headers = vec![
- ("x-trace-id".to_string(), "trace-1".to_string()),
- ("authorization".to_string(), "Bearer sk-test".to_string()),
- ];
-
- assert!(has_header(&headers, "authorization"));
-
- let headers = vec![("Authorization".to_string(), "Bearer sk-test".to_string())];
- assert!(has_header(&headers, "authorization"));
-
- let headers = vec![("x-trace-id".to_string(), "trace-1".to_string())];
- assert!(!has_header(&headers, "authorization"));
- }
-
- #[tokio::test]
- async fn ocr_does_not_duplicate_authorization_header_when_header_is_supplied() {
- let listener = TcpListener::bind("127.0.0.1:0")
- .await
- .expect("test listener binds");
- let addr = listener.local_addr().expect("listener has local addr");
-
- let server = tokio::spawn(async move {
- let (mut socket, _) = listener.accept().await.expect("accepts one request");
- let request = read_http_headers(&mut socket).await;
-
- let response_body = r#"{"pages":[{"index":0,"markdown":"ok"}],"model":"mistral-ocr-latest","usage_info":{"pages_processed":1}}"#;
- let response = format!(
- "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
- response_body.len(),
- response_body
- );
- socket
- .write_all(response.as_bytes())
- .await
- .expect("writes response");
- request
- });
-
- let mut headers = Map::new();
- headers.insert(
- "Authorization".to_string(),
- Value::String("Bearer sk-from-python".to_string()),
- );
- headers.insert(
- "x-trace-id".to_string(),
- Value::String("trace-1".to_string()),
- );
-
- let response = ocr(OcrRequest {
- model: "mistral-ocr-latest",
- document: json!({
- "type": "document_url",
- "document_url": "https://example.com/doc.pdf"
- }),
- api_key: Some("sk-for-rust-fallback"),
- api_base: Some(&format!("http://{addr}")),
- custom_llm_provider: "mistral",
- extra_headers: Some(headers),
- optional_params: Map::new(),
- timeout: Some(Duration::from_secs(5)),
- })
- .await
- .expect("ocr request succeeds");
-
- assert_eq!(response["pages"][0]["markdown"], "ok");
-
- let request = server.await.expect("server task completes");
- let authorization_count = request
- .lines()
- .filter(|line| line.to_ascii_lowercase().starts_with("authorization:"))
- .count();
- assert_eq!(authorization_count, 1, "{request}");
- assert!(
- request.contains("authorization: Bearer sk-from-python")
- || request.contains("Authorization: Bearer sk-from-python"),
- "{request}"
- );
- }
-
- #[tokio::test]
- async fn document_intelligence_poll_uses_resolved_subscription_key() {
- let listener = TcpListener::bind("127.0.0.1:0")
- .await
- .expect("test listener binds");
- let addr = listener.local_addr().expect("listener has local addr");
- let operation_url = format!("http://{addr}/operations/1");
-
- let server = tokio::spawn(async move {
- let (mut post_socket, _) = listener.accept().await.expect("accepts post request");
- let post_request = read_http_headers(&mut post_socket).await;
- let post_response = format!(
- "HTTP/1.1 202 Accepted\r\noperation-location: {operation_url}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
- );
- post_socket
- .write_all(post_response.as_bytes())
- .await
- .expect("writes post response");
-
- let (mut poll_socket, _) = listener.accept().await.expect("accepts poll request");
- let poll_request = read_http_headers(&mut poll_socket).await;
- let response_body = r#"{"status":"succeeded","analyzeResult":{"pages":[{"pageNumber":1,"lines":[{"content":"ok"}]}]}}"#;
- let poll_response = format!(
- "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
- response_body.len(),
- response_body
- );
- poll_socket
- .write_all(poll_response.as_bytes())
- .await
- .expect("writes poll response");
- (post_request, poll_request)
- });
-
- let response = ocr(OcrRequest {
- model: "prebuilt-read",
- document: json!({
- "type": "document_url",
- "document_url": "https://example.com/doc.pdf"
- }),
- api_key: Some("di-key"),
- api_base: Some(&format!("http://{addr}")),
- custom_llm_provider: "azure_ai/doc-intelligence",
- extra_headers: None,
- optional_params: Map::new(),
- timeout: Some(Duration::from_secs(5)),
- })
- .await
- .expect("document intelligence request succeeds");
-
- assert_eq!(response["pages"][0]["markdown"], "ok");
-
- let (post_request, poll_request) = server.await.expect("server task completes");
- assert!(
- post_request
- .to_ascii_lowercase()
- .contains("ocp-apim-subscription-key: di-key"),
- "{post_request}"
- );
- assert!(
- poll_request
- .to_ascii_lowercase()
- .contains("ocp-apim-subscription-key: di-key"),
- "{poll_request}"
- );
- }
-
- #[test]
- fn string_headers_rejects_non_string_values() {
- let headers = json!({
- "x-retry-count": 3
- })
- .as_object()
- .unwrap()
- .clone();
-
- let err = string_headers(Some(headers)).expect_err("non-string header rejected");
- assert_eq!(
- err,
- CoreError::InvalidRequest(
- "OCR extra_headers.x-retry-count must be a string, got number".to_string()
- )
- );
- }
-}
+pub use crate::ocr::{ocr, OcrRequest};
diff --git a/litellm-rust/crates/ai-gateway/src/io/realtime.rs b/litellm-rust/crates/ai-gateway/src/io/realtime.rs
index 4047de5cb26..40a38c1579a 100644
--- a/litellm-rust/crates/ai-gateway/src/io/realtime.rs
+++ b/litellm-rust/crates/ai-gateway/src/io/realtime.rs
@@ -1,8 +1,8 @@
//! End-to-end OpenAI realtime invocation.
//!
-//! The host-facing entry point, mirroring `crate::io::ocr::run_ocr`: open the
-//! WebSocket to OpenAI, then splice a client realtime stream to the upstream,
-//! driving typed events through the pure `OPENAI_REALTIME_CONFIG` transforms.
+//! The host-facing entry point opens the WebSocket to OpenAI, then splices a
+//! client realtime stream to the upstream, driving typed events through the pure
+//! `OPENAI_REALTIME_CONFIG` transforms.
//! Network, auth header, key resolution, and wire (de)serialization live here so
//! the `transformation` module stays pure and typed.
//!
diff --git a/litellm-rust/crates/ai-gateway/src/lib.rs b/litellm-rust/crates/ai-gateway/src/lib.rs
index 6c04fbb7626..d8ef7bb5ba1 100644
--- a/litellm-rust/crates/ai-gateway/src/lib.rs
+++ b/litellm-rust/crates/ai-gateway/src/lib.rs
@@ -3,15 +3,16 @@
//! Two layers, split by feature so the Python `cdylib` can depend on the I/O
//! without pulling in the HTTP server:
//!
-//! - [`io`]: all network I/O (OCR HTTP call, realtime WebSocket splice, the
-//! pre-warmed realtime pool). Always available — no feature required. The
-//! Python bridge links this for `run_ocr`.
+//! - Call-type modules such as [`ocr`]: provider transforms, lifecycle hooks,
+//! and provider I/O. Always available — no feature required.
+//! - [`io`]: compatibility exports and realtime WebSocket splice helpers.
//! - The server modules ([`auth`], [`routes`], [`state`]) and anything pulling
//! `axum` are gated behind the `server` feature, which the `litellm-ai-gateway`
//! binary turns on. The `python-config` feature additionally pulls in [`python`]
//! for the load-time config reader.
pub mod io;
+pub mod ocr;
/// GIL-activity tracking. Pure (atomics only); shared by the `server` routes and
/// the `python-config` reader, so it is available without either feature.
@@ -27,9 +28,7 @@ pub mod state;
// Realtime request logging. Only the server serves realtime, so these are
// `server`-gated; `io::realtime` exposes the generic `observe` hook while the
// collector and callback fan-out live here.
-#[cfg(feature = "server")]
mod constants;
-#[cfg(feature = "server")]
pub mod integrations;
#[cfg(feature = "server")]
mod realtime;
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/client.rs b/litellm-rust/crates/ai-gateway/src/ocr/client.rs
new file mode 100644
index 00000000000..79cc7816227
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/client.rs
@@ -0,0 +1,14 @@
+use std::sync::OnceLock;
+use std::time::Duration;
+
+const OCR_TIMEOUT_SECS: u64 = 600;
+
+pub(super) fn http_client() -> &'static reqwest::Client {
+ static CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
+ CLIENT.get_or_init(|| {
+ reqwest::Client::builder()
+ .timeout(Duration::from_secs(OCR_TIMEOUT_SECS))
+ .build()
+ .expect("failed to build reqwest client")
+ })
+}
diff --git a/litellm-rust/crates/ai-gateway/src/io/ocr/common_utils.rs b/litellm-rust/crates/ai-gateway/src/ocr/common_utils.rs
similarity index 99%
rename from litellm-rust/crates/ai-gateway/src/io/ocr/common_utils.rs
rename to litellm-rust/crates/ai-gateway/src/ocr/common_utils.rs
index ee0d86c3000..d4b4d9338e7 100644
--- a/litellm-rust/crates/ai-gateway/src/io/ocr/common_utils.rs
+++ b/litellm-rust/crates/ai-gateway/src/ocr/common_utils.rs
@@ -18,7 +18,7 @@ use litellm_core::providers::vertex_ai::ocr::transformation::{
VERTEX_AI_DEEPSEEK_OCR_CONFIG, VERTEX_AI_OCR_CONFIG,
};
-use super::http_client;
+use super::client::http_client;
const ERROR_BODY_MAX_CHARS: usize = 256;
const AZURE_DOCUMENT_INTELLIGENCE_POLL_TIMEOUT_SECS: u64 = 120;
@@ -42,7 +42,6 @@ pub(super) fn ocr_provider_config(
"azure_ai" if is_azure_document_intelligence_model(model) => {
Some(&AZURE_DOCUMENT_INTELLIGENCE_OCR_CONFIG)
}
- "azure_ai/doc-intelligence" => Some(&AZURE_DOCUMENT_INTELLIGENCE_OCR_CONFIG),
"azure_ai" => Some(&AZURE_AI_OCR_CONFIG),
"vertex_ai" if vertex_ai::is_deepseek_model(model) => Some(&VERTEX_AI_DEEPSEEK_OCR_CONFIG),
"vertex_ai" => Some(&VERTEX_AI_OCR_CONFIG),
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/handler.rs b/litellm-rust/crates/ai-gateway/src/ocr/handler.rs
new file mode 100644
index 00000000000..4d93c2a25db
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/handler.rs
@@ -0,0 +1,71 @@
+use litellm_core::error::CoreError;
+use litellm_core::ocr::transformation::OcrResponseHandling;
+use litellm_core::CoreResult;
+use serde_json::Value;
+
+use super::client::http_client;
+use super::common_utils::{poll_document_intelligence, truncate_error_body};
+use super::types::ProviderOcrRequest;
+
+pub(crate) async fn execute_ocr_provider_call(request: ProviderOcrRequest) -> CoreResult<Value> {
+ let mut request_builder = http_client().post(&request.url).json(&request.body);
+ for (key, value) in &request.upstream_headers {
+ request_builder = request_builder.header(key, value);
+ }
+ if let Some(duration) = request.timeout {
+ request_builder = request_builder.timeout(duration);
+ }
+
+ let response = request_builder
+ .send()
+ .await
+ .map_err(|err| CoreError::Network(err.to_string()))?;
+
+ let status = response.status();
+ if request.config.response_handling() == OcrResponseHandling::AzureDocumentIntelligencePoll
+ && status.as_u16() == 202
+ {
+ let operation_url = response
+ .headers()
+ .get("operation-location")
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_string)
+ .ok_or_else(|| {
+ CoreError::InvalidResponse(
+ "Azure Document Intelligence returned 202 but no Operation-Location header found"
+ .to_string(),
+ )
+ })?;
+ let response_json = poll_document_intelligence(
+ &operation_url,
+ &request.url,
+ &request.upstream_headers,
+ request.timeout,
+ )
+ .await?;
+ return Ok(request
+ .config
+ .transform_ocr_response(&request.model, response_json)?
+ .into_json());
+ }
+
+ let text = response
+ .text()
+ .await
+ .map_err(|err| CoreError::Network(err.to_string()))?;
+
+ if !status.is_success() {
+ return Err(CoreError::Http {
+ status: status.as_u16(),
+ body: truncate_error_body(&text),
+ });
+ }
+
+ let response_json: Value = serde_json::from_str(&text)
+ .map_err(|err| CoreError::InvalidResponse(format!("invalid OCR response JSON: {err}")))?;
+
+ Ok(request
+ .config
+ .transform_ocr_response(&request.model, response_json)?
+ .into_json())
+}
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs b/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs
new file mode 100644
index 00000000000..6be74ed2714
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/hooks.rs
@@ -0,0 +1,329 @@
+use std::future::Future;
+use std::pin::Pin;
+
+use litellm_core::call_lifecycle::{CallLifecycleContext, CallLifecycleHooks, CallLifecycleTiming};
+use litellm_core::error::CoreError;
+use litellm_core::ocr::transformation::OcrAuthStrategy;
+use litellm_core::CoreResult;
+use serde_json::{json, Map, Value};
+
+use super::common_utils::{
+ convert_document_url_to_data_uri, has_header, ocr_provider_config, string_headers,
+};
+use super::types::{PreparedOcrRequest, ProviderOcrRequest};
+use crate::integrations::custom_guardrail::{
+ CustomGuardrailRunner, GuardrailContext, GuardrailError, GuardrailRequest,
+};
+use crate::integrations::custom_logger::{
+ CallType, CallbackTiming, CallbackValue, CustomLoggerRunner, LoggingError, ModelCallDetails,
+};
+use crate::integrations::types::{
+ RequestMetadata, StandardLoggingMetadata, StandardLoggingPayload,
+};
+
+pub(crate) struct OcrLifecycleHooks {
+ logger_runner: CustomLoggerRunner,
+ guardrail_runner: CustomGuardrailRunner,
+ request_metadata: RequestMetadata,
+}
+
+type OcrFuture<'a, T> = Pin<Box<dyn Future<Output = CoreResult<T>> + Send + 'a>>;
+type OcrLogFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;
+
+impl OcrLifecycleHooks {
+ pub(crate) fn new(
+ logger_runner: CustomLoggerRunner,
+ guardrail_runner: CustomGuardrailRunner,
+ request_metadata: RequestMetadata,
+ ) -> Self {
+ Self {
+ logger_runner,
+ guardrail_runner,
+ request_metadata,
+ }
+ }
+
+ async fn run_pre_call_guardrails(
+ &self,
+ request: PreparedOcrRequest,
+ ) -> CoreResult<PreparedOcrRequest> {
+ if self.guardrail_runner.is_empty() {
+ return Ok(request);
+ }
+
+ let context = guardrail_context(&self.request_metadata);
+ let guardrail_request = GuardrailRequest::new(json!({
+ "model": request.model,
+ "custom_llm_provider": request.custom_llm_provider,
+ "document": request.document,
+ "optional_params": request.optional_params,
+ }));
+ let (guardrail_request, _) = self
+ .guardrail_runner
+ .run_pre_call(&context, guardrail_request)
+ .await
+ .map_err(guardrail_error_to_core_error)?;
+ let (document, optional_params) = parse_ocr_pre_call_guardrail_request(guardrail_request)?;
+ Ok(PreparedOcrRequest {
+ document,
+ optional_params,
+ ..request
+ })
+ }
+
+ async fn prepare_provider_request(
+ &self,
+ request: PreparedOcrRequest,
+ ) -> CoreResult<ProviderOcrRequest> {
+ let config = ocr_provider_config(&request.custom_llm_provider, &request.model)
+ .ok_or_else(|| CoreError::InvalidProvider(request.custom_llm_provider.clone()))?;
+ let env_lookup = |key: &str| std::env::var(key).ok();
+ let headers = string_headers(request.extra_headers)?;
+ let auth_strategy = config.auth_strategy();
+ let api_key = (!has_header(&headers, auth_strategy.header_name()))
+ .then(|| config.resolve_api_key(request.api_key.as_deref(), &env_lookup))
+ .transpose()?;
+ let url = config.complete_url(
+ request.api_base.as_deref(),
+ &request.model,
+ &request.optional_params,
+ &env_lookup,
+ )?;
+ let filtered_params = config.map_ocr_params(&request.optional_params);
+ let model = request.model.clone();
+ let custom_llm_provider = request.custom_llm_provider.clone();
+ let document = if config.requires_data_uri_document() {
+ convert_document_url_to_data_uri(request.document).await?
+ } else {
+ request.document
+ };
+ let body = config
+ .transform_ocr_request(&request.model, document, filtered_params)?
+ .data;
+ let upstream_headers = upstream_headers(&headers, auth_strategy, api_key.as_deref());
+ let body = self
+ .run_during_call_guardrails(&model, &custom_llm_provider, &url, body)
+ .await?;
+ Ok(ProviderOcrRequest {
+ model,
+ config,
+ url,
+ body,
+ upstream_headers,
+ timeout: request.timeout,
+ })
+ }
+
+ async fn run_during_call_guardrails(
+ &self,
+ model: &str,
+ custom_llm_provider: &str,
+ url: &str,
+ body: Value,
+ ) -> CoreResult<Value> {
+ if self.guardrail_runner.is_empty() {
+ return Ok(body);
+ }
+
+ let context = guardrail_context(&self.request_metadata);
+ let guardrail_request = GuardrailRequest::new(json!({
+ "model": model,
+ "custom_llm_provider": custom_llm_provider,
+ "url": url,
+ "body": body,
+ }));
+ let (guardrail_request, _) = self
+ .guardrail_runner
+ .run_during_call(&context, guardrail_request)
+ .await
+ .map_err(guardrail_error_to_core_error)?;
+ parse_ocr_during_call_guardrail_request(guardrail_request)
+ }
+
+ fn standard_logging_payload(
+ &self,
+ context: &CallLifecycleContext,
+ timing: &CallLifecycleTiming,
+ ) -> StandardLoggingPayload {
+ StandardLoggingPayload {
+ id: context.litellm_call_id.clone(),
+ litellm_call_id: context.litellm_call_id.clone(),
+ call_type: context.call_type.clone(),
+ model: context.model.clone(),
+ custom_llm_provider: context.custom_llm_provider.clone(),
+ response_cost: 0.0,
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ total_tokens: 0,
+ start_time: timing.start_time,
+ end_time: timing.end_time,
+ stream: false,
+ metadata: StandardLoggingMetadata {
+ user_api_key_hash: self.request_metadata.user_api_key_hash.clone(),
+ user_api_key_user_id: self.request_metadata.user_api_key_user_id.clone(),
+ user_api_key_team_id: self.request_metadata.user_api_key_team_id.clone(),
+ ..Default::default()
+ },
+ messages: None,
+ }
+ }
+}
+
+impl CallLifecycleHooks<PreparedOcrRequest, ProviderOcrRequest, Value> for OcrLifecycleHooks {
+ type PreCallFuture<'a> = OcrFuture<'a, PreparedOcrRequest>;
+ type DuringCallFuture<'a> = OcrFuture<'a, ProviderOcrRequest>;
+ type SuccessFuture<'a> = OcrLogFuture<'a>;
+ type FailureFuture<'a> = OcrLogFuture<'a>;
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ request: PreparedOcrRequest,
+ ) -> Self::PreCallFuture<'a> {
+ Box::pin(async move { self.run_pre_call_guardrails(request).await })
+ }
+
+ fn async_during_call_hook<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ request: PreparedOcrRequest,
+ ) -> Self::DuringCallFuture<'a> {
+ Box::pin(async move { self.prepare_provider_request(request).await })
+ }
+
+ fn async_log_success_event<'a>(
+ &'a self,
+ context: &'a CallLifecycleContext,
+ response: &'a Value,
+ timing: &'a CallLifecycleTiming,
+ ) -> Self::SuccessFuture<'a> {
+ Box::pin(async move {
+ if self.logger_runner.is_empty() {
+ return;
+ }
+ let response_obj = CallbackValue::new("ocr", response.clone());
+ self.logger_runner
+ .async_log_success_event(
+ &ModelCallDetails::from_standard_logging_payload(
+ self.standard_logging_payload(context, timing),
+ ),
+ &response_obj,
+ CallbackTiming::new(timing.start_time, timing.end_time),
+ )
+ .await;
+ })
+ }
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ context: &'a CallLifecycleContext,
+ error: &'a CoreError,
+ timing: &'a CallLifecycleTiming,
+ ) -> Self::FailureFuture<'a> {
+ Box::pin(async move {
+ if self.logger_runner.is_empty() {
+ return;
+ }
+ let logging_error = LoggingError {
+ message: error.to_string(),
+ kind: core_error_kind(error).to_string(),
+ };
+ let response_obj = CallbackValue::new(
+ "error",
+ json!({
+ "message": logging_error.message,
+ "kind": logging_error.kind,
+ }),
+ );
+ self.logger_runner
+ .async_log_failure_event(
+ &ModelCallDetails::from_standard_logging_payload(
+ self.standard_logging_payload(context, timing),
+ )
+ .with_failure_error(logging_error),
+ Some(&response_obj),
+ CallbackTiming::new(timing.start_time, timing.end_time),
+ )
+ .await;
+ })
+ }
+}
+
+fn upstream_headers(
+ headers: &[(String, String)],
+ auth_strategy: OcrAuthStrategy,
+ api_key: Option<&str>,
+) -> Vec<(String, String)> {
+ api_key
+ .map(|api_key| match auth_strategy {
+ OcrAuthStrategy::Bearer => ("Authorization".to_string(), format!("Bearer {api_key}")),
+ OcrAuthStrategy::Header(header_name) => (header_name.to_string(), api_key.to_string()),
+ })
+ .into_iter()
+ .chain(headers.iter().cloned())
+ .collect()
+}
+
+fn guardrail_context(metadata: &RequestMetadata) -> GuardrailContext {
+ GuardrailContext {
+ call_type: CallType::Ocr,
+ selected_guardrails: Vec::new(),
+ metadata: std::collections::HashMap::new(),
+ user_api_key_hash: metadata.user_api_key_hash.clone(),
+ user_api_key_user_id: metadata.user_api_key_user_id.clone(),
+ user_api_key_team_id: metadata.user_api_key_team_id.clone(),
+ trace_parent: None,
+ }
+}
+
+fn parse_ocr_pre_call_guardrail_request(
+ request: GuardrailRequest,
+) -> CoreResult<(Value, Map<String, Value>)> {
+ let Value::Object(mut data) = request.data else {
+ return Err(CoreError::InvalidRequest(
+ "OCR pre_call guardrail must return an object".to_string(),
+ ));
+ };
+ let document = data.remove("document").ok_or_else(|| {
+ CoreError::InvalidRequest("OCR pre_call guardrail removed document".to_string())
+ })?;
+ let optional_params = match data.remove("optional_params") {
+ Some(Value::Object(params)) => params,
+ Some(_) => {
+ return Err(CoreError::InvalidRequest(
+ "OCR pre_call guardrail optional_params must be an object".to_string(),
+ ))
+ }
+ None => Map::new(),
+ };
+ Ok((document, optional_params))
+}
+
+fn parse_ocr_during_call_guardrail_request(request: GuardrailRequest) -> CoreResult<Value> {
+ let Value::Object(mut data) = request.data else {
+ return Err(CoreError::InvalidRequest(
+ "OCR during_call guardrail must return an object".to_string(),
+ ));
+ };
+ data.remove("body").ok_or_else(|| {
+ CoreError::InvalidRequest("OCR during_call guardrail removed body".to_string())
+ })
+}
+
+fn guardrail_error_to_core_error(error: GuardrailError) -> CoreError {
+ CoreError::InvalidRequest(format!("{}: {}", error.kind, error.message))
+}
+
+fn core_error_kind(error: &CoreError) -> &'static str {
+ match error {
+ CoreError::Auth(_) => "AuthError",
+ CoreError::InvalidProvider(_) => "InvalidProvider",
+ CoreError::InvalidRequest(_) => "InvalidRequest",
+ CoreError::InvalidType { .. } => "InvalidType",
+ CoreError::MissingField(_) => "MissingField",
+ CoreError::Http { .. } => "HttpError",
+ CoreError::InvalidResponse(_) => "InvalidResponse",
+ CoreError::Network(_) => "NetworkError",
+ CoreError::Routing(_) => "RoutingError",
+ }
+}
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/mod.rs b/litellm-rust/crates/ai-gateway/src/ocr/mod.rs
new file mode 100644
index 00000000000..b54ee39b21d
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/mod.rs
@@ -0,0 +1,25 @@
+use litellm_core::call_lifecycle::CallLifecycle;
+use litellm_core::CoreResult;
+use serde_json::Value;
+
+mod client;
+mod common_utils;
+mod handler;
+mod hooks;
+mod prepare;
+mod types;
+
+pub use types::OcrRequest;
+
+use handler::execute_ocr_provider_call;
+use prepare::{prepare_ocr_call, PreparedOcrCall};
+
+pub async fn ocr(request: OcrRequest<'_>) -> CoreResult<Value> {
+ let PreparedOcrCall { request, hooks } = prepare_ocr_call(request);
+ CallLifecycle::default()
+ .run_request(request, &hooks, execute_ocr_provider_call)
+ .await
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/prepare.rs b/litellm-rust/crates/ai-gateway/src/ocr/prepare.rs
new file mode 100644
index 00000000000..5a4b350a4c4
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/prepare.rs
@@ -0,0 +1,57 @@
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+use litellm_core::routing_utils::provider::{get_custom_llm_provider, CustomLlmProvider};
+
+use super::hooks::OcrLifecycleHooks;
+use super::types::{OcrRequest, PreparedOcrRequest};
+use crate::integrations::custom_guardrail::CustomGuardrailRunner;
+use crate::integrations::custom_logger::CustomLoggerRunner;
+
+pub(crate) struct PreparedOcrCall {
+ pub(crate) request: PreparedOcrRequest,
+ pub(crate) hooks: OcrLifecycleHooks,
+}
+
+pub(crate) fn prepare_ocr_call(request: OcrRequest<'_>) -> PreparedOcrCall {
+ let call_id = request
+ .litellm_call_id
+ .map(str::to_string)
+ .unwrap_or_else(new_ocr_call_id);
+ let provider_info = get_custom_llm_provider(request.model, request.custom_llm_provider)
+ .unwrap_or(CustomLlmProvider {
+ model: request.model,
+ custom_llm_provider: "mistral",
+ });
+ let model = provider_info.model.to_string();
+ let custom_llm_provider = provider_info.custom_llm_provider.to_string();
+
+ PreparedOcrCall {
+ request: PreparedOcrRequest {
+ model,
+ custom_llm_provider,
+ litellm_call_id: call_id,
+ document: request.document,
+ api_key: request.api_key.map(str::to_string),
+ api_base: request.api_base.map(str::to_string),
+ extra_headers: request.extra_headers,
+ optional_params: request.optional_params,
+ timeout: request.timeout,
+ },
+ hooks: OcrLifecycleHooks::new(
+ CustomLoggerRunner::new(request.callbacks),
+ CustomGuardrailRunner::new(request.guardrails),
+ request.request_metadata,
+ ),
+ }
+}
+
+fn new_ocr_call_id() -> String {
+ static COUNTER: AtomicU64 = AtomicU64::new(1);
+ let sequence = COUNTER.fetch_add(1, Ordering::Relaxed);
+ let timestamp = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|duration| duration.as_nanos())
+ .unwrap_or(0);
+ format!("ocr-{timestamp}-{sequence}")
+}
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/tests.rs b/litellm-rust/crates/ai-gateway/src/ocr/tests.rs
new file mode 100644
index 00000000000..35747dc6985
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/tests.rs
@@ -0,0 +1,610 @@
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use litellm_core::error::CoreError;
+use litellm_core::ocr::transformation::OcrResponseHandling;
+use serde_json::{json, Map, Value};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+
+use super::common_utils::{has_header, ocr_provider_config, string_headers, truncate_error_body};
+use super::{ocr, OcrRequest};
+use crate::integrations::custom_guardrail::{
+ CustomGuardrail, GuardrailContext, GuardrailDecision, GuardrailError, GuardrailEventHook,
+ GuardrailFuture, GuardrailRequest,
+};
+use crate::integrations::custom_logger::{
+ CallbackTiming, CallbackValue, CustomLogger, LogFuture, ModelCallDetails,
+};
+use crate::integrations::types::RequestMetadata;
+
+async fn read_http_headers(socket: &mut TcpStream) -> String {
+ let mut request = Vec::new();
+ let mut buffer = [0_u8; 1024];
+ loop {
+ let n = socket.read(&mut buffer).await.expect("reads request");
+ if n == 0 {
+ break;
+ }
+ request.extend_from_slice(&buffer[..n]);
+ if request.windows(4).any(|window| window == b"\r\n\r\n") {
+ break;
+ }
+ }
+ String::from_utf8(request).expect("request is utf8")
+}
+
+async fn read_http_request(socket: &mut TcpStream) -> String {
+ let mut request = Vec::new();
+ let mut buffer = [0_u8; 1024];
+ let header_end = loop {
+ let n = socket.read(&mut buffer).await.expect("reads request");
+ if n == 0 {
+ break request.len();
+ }
+ request.extend_from_slice(&buffer[..n]);
+ if let Some(position) = request.windows(4).position(|window| window == b"\r\n\r\n") {
+ break position + 4;
+ }
+ };
+ let headers = String::from_utf8_lossy(&request[..header_end]);
+ let content_length = headers
+ .lines()
+ .find_map(|line| {
+ let (name, value) = line.split_once(':')?;
+ name.eq_ignore_ascii_case("content-length")
+ .then(|| value.trim().parse::<usize>().ok())
+ .flatten()
+ })
+ .unwrap_or(0);
+ while request.len().saturating_sub(header_end) < content_length {
+ let n = socket.read(&mut buffer).await.expect("reads body");
+ if n == 0 {
+ break;
+ }
+ request.extend_from_slice(&buffer[..n]);
+ }
+ String::from_utf8(request).expect("request is utf8")
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct RecordedLogEvent {
+ hook: &'static str,
+ model: String,
+ call_type: String,
+ user_id: Option<String>,
+ response_object: Option<String>,
+ error_kind: Option<String>,
+}
+
+#[derive(Default)]
+struct RecordingOcrLogger {
+ events: Mutex<Vec<RecordedLogEvent>>,
+}
+
+impl RecordingOcrLogger {
+ fn events(&self) -> Vec<RecordedLogEvent> {
+ self.events.lock().unwrap().clone()
+ }
+}
+
+impl CustomLogger for RecordingOcrLogger {
+ fn async_log_success_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ response_obj: &'a CallbackValue,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push(RecordedLogEvent {
+ hook: "async_log_success_event",
+ model: model_call_details.model.clone(),
+ call_type: model_call_details.call_type.to_string(),
+ user_id: model_call_details.metadata.user_api_key_user_id.clone(),
+ response_object: Some(response_obj.object.clone()),
+ error_kind: None,
+ });
+ Ok(())
+ })
+ }
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ response_obj: Option<&'a CallbackValue>,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push(RecordedLogEvent {
+ hook: "async_log_failure_event",
+ model: model_call_details.model.clone(),
+ call_type: model_call_details.call_type.to_string(),
+ user_id: model_call_details.metadata.user_api_key_user_id.clone(),
+ response_object: response_obj.map(|value| value.object.clone()),
+ error_kind: model_call_details
+ .failure_error
+ .as_ref()
+ .map(|error| error.kind.clone()),
+ });
+ Ok(())
+ })
+ }
+}
+
+struct RecordingOcrGuardrail {
+ hooks: Vec<GuardrailEventHook>,
+ events: Mutex<Vec<&'static str>>,
+ block_pre_call: bool,
+}
+
+impl RecordingOcrGuardrail {
+ fn new(hooks: Vec<GuardrailEventHook>) -> Self {
+ Self {
+ hooks,
+ events: Mutex::new(Vec::new()),
+ block_pre_call: false,
+ }
+ }
+
+ fn blocking_pre_call() -> Self {
+ Self {
+ hooks: vec![GuardrailEventHook::PreCall],
+ events: Mutex::new(Vec::new()),
+ block_pre_call: true,
+ }
+ }
+
+ fn events(&self) -> Vec<&'static str> {
+ self.events.lock().unwrap().clone()
+ }
+}
+
+impl CustomGuardrail for RecordingOcrGuardrail {
+ fn guardrail_name(&self) -> &str {
+ "recording-ocr-guardrail"
+ }
+
+ fn supported_event_hooks(&self) -> &[GuardrailEventHook] {
+ &self.hooks
+ }
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ mut request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("async_pre_call_hook");
+ if self.block_pre_call {
+ return Ok(GuardrailDecision::Block(GuardrailError::blocked(
+ "blocked before provider",
+ )));
+ }
+ request.data["document"]["guarded_pre"] = json!(true);
+ Ok(GuardrailDecision::Mask(request))
+ })
+ }
+
+ fn async_moderation_hook<'a>(
+ &'a self,
+ _context: &'a GuardrailContext,
+ mut request: GuardrailRequest,
+ ) -> GuardrailFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("async_moderation_hook");
+ request.data["body"]["guarded_during"] = json!(true);
+ Ok(GuardrailDecision::Mask(request))
+ })
+ }
+}
+
+#[test]
+fn truncate_error_body_passes_short_strings_through() {
+ let body = "Unauthorized";
+ assert_eq!(truncate_error_body(body), "Unauthorized");
+}
+
+#[test]
+fn truncate_error_body_caps_long_payloads() {
+ let body = "x".repeat(306);
+ let truncated = truncate_error_body(&body);
+
+ assert!(truncated.ends_with("... (truncated)"));
+ let prefix_chars = truncated
+ .strip_suffix("... (truncated)")
+ .expect("truncated marker present")
+ .chars()
+ .count();
+ assert_eq!(prefix_chars, 256);
+}
+
+#[test]
+fn truncate_error_body_does_not_split_multibyte_chars() {
+ let body = "é".repeat(266);
+ let truncated = truncate_error_body(&body);
+ assert!(truncated.is_char_boundary(truncated.len()));
+}
+
+#[test]
+fn ocr_dispatch_supports_migrated_providers() {
+ assert!(ocr_provider_config("mistral", "mistral-ocr-latest").is_some());
+ assert!(ocr_provider_config("azure_ai", "pixtral-12b-2409")
+ .expect("azure ai config resolves")
+ .requires_data_uri_document());
+ assert_eq!(
+ ocr_provider_config("azure_ai", "doc-intelligence/prebuilt-read")
+ .expect("document intelligence config resolves")
+ .response_handling(),
+ OcrResponseHandling::AzureDocumentIntelligencePoll
+ );
+ assert!(ocr_provider_config("vertex_ai", "deepseek-ocr-maas")
+ .expect("vertex deepseek config resolves")
+ .supported_ocr_params()
+ .contains(&"temperature"));
+ assert!(ocr_provider_config("openai", "gpt-4o").is_none());
+}
+
+#[test]
+fn string_headers_accepts_string_values() {
+ let headers = json!({
+ "x-trace-id": "trace-1"
+ })
+ .as_object()
+ .unwrap()
+ .clone();
+
+ assert_eq!(
+ string_headers(Some(headers)).expect("string headers accepted"),
+ vec![("x-trace-id".to_string(), "trace-1".to_string())]
+ );
+}
+
+#[test]
+fn auth_header_detection_is_case_insensitive() {
+ let headers = vec![
+ ("x-trace-id".to_string(), "trace-1".to_string()),
+ ("authorization".to_string(), "Bearer sk-test".to_string()),
+ ];
+
+ assert!(has_header(&headers, "authorization"));
+
+ let headers = vec![("Authorization".to_string(), "Bearer sk-test".to_string())];
+ assert!(has_header(&headers, "authorization"));
+
+ let headers = vec![("x-trace-id".to_string(), "trace-1".to_string())];
+ assert!(!has_header(&headers, "authorization"));
+}
+
+#[tokio::test]
+async fn ocr_lifecycle_runs_pre_during_and_success_hooks() {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("test listener binds");
+ let addr = listener.local_addr().expect("listener has local addr");
+
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accepts one request");
+ let request = read_http_request(&mut socket).await;
+ let response_body = r#"{"pages":[{"index":0,"markdown":"ok"}],"model":"mistral-ocr-latest","usage_info":{"pages_processed":1}}"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
+ response_body.len(),
+ response_body
+ );
+ socket
+ .write_all(response.as_bytes())
+ .await
+ .expect("writes response");
+ request
+ });
+
+ let logger = Arc::new(RecordingOcrLogger::default());
+ let guardrail = Arc::new(RecordingOcrGuardrail::new(vec![
+ GuardrailEventHook::PreCall,
+ GuardrailEventHook::DuringCall,
+ ]));
+ let response = ocr(OcrRequest {
+ model: "mistral-ocr-latest",
+ document: json!({
+ "type": "document_url",
+ "document_url": "https://example.com/doc.pdf"
+ }),
+ api_key: Some("sk-test"),
+ api_base: Some(&format!("http://{addr}")),
+ custom_llm_provider: Some("mistral"),
+ extra_headers: None,
+ optional_params: Map::new(),
+ timeout: Some(Duration::from_secs(5)),
+ callbacks: vec![logger.clone()],
+ guardrails: vec![guardrail.clone()],
+ request_metadata: RequestMetadata {
+ user_api_key_user_id: Some("user-1".to_string()),
+ ..Default::default()
+ },
+ litellm_call_id: Some("ocr-call-1"),
+ })
+ .await
+ .expect("ocr request succeeds");
+
+ assert_eq!(response["pages"][0]["markdown"], "ok");
+ assert_eq!(
+ guardrail.events(),
+ vec!["async_pre_call_hook", "async_moderation_hook"]
+ );
+ assert_eq!(
+ logger.events(),
+ vec![RecordedLogEvent {
+ hook: "async_log_success_event",
+ model: "mistral-ocr-latest".to_string(),
+ call_type: "ocr".to_string(),
+ user_id: Some("user-1".to_string()),
+ response_object: Some("ocr".to_string()),
+ error_kind: None,
+ }]
+ );
+
+ let request = server.await.expect("server task completes");
+ assert!(request.contains(r#""guarded_pre":true"#), "{request}");
+ assert!(request.contains(r#""guarded_during":true"#), "{request}");
+}
+
+#[tokio::test]
+async fn ocr_lifecycle_runs_failure_hook_on_provider_error() {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("test listener binds");
+ let addr = listener.local_addr().expect("listener has local addr");
+
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accepts one request");
+ let _request = read_http_request(&mut socket).await;
+ let response_body = "provider failed";
+ let response = format!(
+ "HTTP/1.1 500 Internal Server Error\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
+ response_body.len(),
+ response_body
+ );
+ socket
+ .write_all(response.as_bytes())
+ .await
+ .expect("writes response");
+ });
+
+ let logger = Arc::new(RecordingOcrLogger::default());
+ let err = ocr(OcrRequest {
+ model: "mistral-ocr-latest",
+ document: json!({
+ "type": "document_url",
+ "document_url": "https://example.com/doc.pdf"
+ }),
+ api_key: Some("sk-test"),
+ api_base: Some(&format!("http://{addr}")),
+ custom_llm_provider: Some("mistral"),
+ extra_headers: None,
+ optional_params: Map::new(),
+ timeout: Some(Duration::from_secs(5)),
+ callbacks: vec![logger.clone()],
+ guardrails: Vec::new(),
+ request_metadata: RequestMetadata::default(),
+ litellm_call_id: Some("ocr-call-2"),
+ })
+ .await
+ .expect_err("provider error propagates");
+
+ assert!(matches!(err, CoreError::Http { status: 500, .. }));
+ server.await.expect("server task completes");
+ assert_eq!(
+ logger.events(),
+ vec![RecordedLogEvent {
+ hook: "async_log_failure_event",
+ model: "mistral-ocr-latest".to_string(),
+ call_type: "ocr".to_string(),
+ user_id: None,
+ response_object: Some("error".to_string()),
+ error_kind: Some("HttpError".to_string()),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn ocr_lifecycle_pre_call_block_skips_provider_socket() {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("test listener binds");
+ let addr = listener.local_addr().expect("listener has local addr");
+ let logger = Arc::new(RecordingOcrLogger::default());
+ let guardrail = Arc::new(RecordingOcrGuardrail::blocking_pre_call());
+
+ let err = ocr(OcrRequest {
+ model: "mistral-ocr-latest",
+ document: json!({
+ "type": "document_url",
+ "document_url": "https://example.com/doc.pdf"
+ }),
+ api_key: Some("sk-test"),
+ api_base: Some(&format!("http://{addr}")),
+ custom_llm_provider: Some("mistral"),
+ extra_headers: None,
+ optional_params: Map::new(),
+ timeout: Some(Duration::from_millis(100)),
+ callbacks: vec![logger.clone()],
+ guardrails: vec![guardrail.clone()],
+ request_metadata: RequestMetadata::default(),
+ litellm_call_id: Some("ocr-call-3"),
+ })
+ .await
+ .expect_err("guardrail blocks request");
+
+ assert!(matches!(err, CoreError::InvalidRequest(_)));
+ assert_eq!(guardrail.events(), vec!["async_pre_call_hook"]);
+ assert_eq!(
+ logger.events(),
+ vec![RecordedLogEvent {
+ hook: "async_log_failure_event",
+ model: "mistral-ocr-latest".to_string(),
+ call_type: "ocr".to_string(),
+ user_id: None,
+ response_object: Some("error".to_string()),
+ error_kind: Some("InvalidRequest".to_string()),
+ }]
+ );
+ let accepted = tokio::time::timeout(Duration::from_millis(100), listener.accept()).await;
+ assert!(accepted.is_err(), "provider socket should not be touched");
+}
+
+#[tokio::test]
+async fn ocr_does_not_duplicate_authorization_header_when_header_is_supplied() {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("test listener binds");
+ let addr = listener.local_addr().expect("listener has local addr");
+
+ let server = tokio::spawn(async move {
+ let (mut socket, _) = listener.accept().await.expect("accepts one request");
+ let request = read_http_headers(&mut socket).await;
+ let response_body = r#"{"pages":[{"index":0,"markdown":"ok"}],"model":"mistral-ocr-latest","usage_info":{"pages_processed":1}}"#;
+ let response = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
+ response_body.len(),
+ response_body
+ );
+ socket
+ .write_all(response.as_bytes())
+ .await
+ .expect("writes response");
+ request
+ });
+
+ let mut headers = Map::new();
+ headers.insert(
+ "Authorization".to_string(),
+ Value::String("Bearer sk-from-python".to_string()),
+ );
+ headers.insert(
+ "x-trace-id".to_string(),
+ Value::String("trace-1".to_string()),
+ );
+
+ let response = ocr(OcrRequest {
+ model: "mistral-ocr-latest",
+ document: json!({
+ "type": "document_url",
+ "document_url": "https://example.com/doc.pdf"
+ }),
+ api_key: Some("sk-for-rust-fallback"),
+ api_base: Some(&format!("http://{addr}")),
+ custom_llm_provider: Some("mistral"),
+ extra_headers: Some(headers),
+ optional_params: Map::new(),
+ timeout: Some(Duration::from_secs(5)),
+ callbacks: Vec::new(),
+ guardrails: Vec::new(),
+ request_metadata: RequestMetadata::default(),
+ litellm_call_id: None,
+ })
+ .await
+ .expect("ocr request succeeds");
+
+ assert_eq!(response["pages"][0]["markdown"], "ok");
+
+ let request = server.await.expect("server task completes");
+ let authorization_count = request
+ .lines()
+ .filter(|line| line.to_ascii_lowercase().starts_with("authorization:"))
+ .count();
+ assert_eq!(authorization_count, 1, "{request}");
+ assert!(
+ request.contains("authorization: Bearer sk-from-python")
+ || request.contains("Authorization: Bearer sk-from-python"),
+ "{request}"
+ );
+}
+
+#[tokio::test]
+async fn document_intelligence_poll_uses_resolved_subscription_key() {
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("test listener binds");
+ let addr = listener.local_addr().expect("listener has local addr");
+ let operation_url = format!("http://{addr}/operations/1");
+
+ let server = tokio::spawn(async move {
+ let (mut post_socket, _) = listener.accept().await.expect("accepts post request");
+ let post_request = read_http_headers(&mut post_socket).await;
+ let post_response = format!(
+ "HTTP/1.1 202 Accepted\r\noperation-location: {operation_url}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n"
+ );
+ post_socket
+ .write_all(post_response.as_bytes())
+ .await
+ .expect("writes post response");
+
+ let (mut poll_socket, _) = listener.accept().await.expect("accepts poll request");
+ let poll_request = read_http_headers(&mut poll_socket).await;
+ let response_body = r#"{"status":"succeeded","analyzeResult":{"pages":[{"pageNumber":1,"lines":[{"content":"ok"}]}]}}"#;
+ let poll_response = format!(
+ "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
+ response_body.len(),
+ response_body
+ );
+ poll_socket
+ .write_all(poll_response.as_bytes())
+ .await
+ .expect("writes poll response");
+ (post_request, poll_request)
+ });
+
+ let response = ocr(OcrRequest {
+ model: "doc-intelligence/prebuilt-read",
+ document: json!({
+ "type": "document_url",
+ "document_url": "https://example.com/doc.pdf"
+ }),
+ api_key: Some("di-key"),
+ api_base: Some(&format!("http://{addr}")),
+ custom_llm_provider: Some("azure_ai"),
+ extra_headers: None,
+ optional_params: Map::new(),
+ timeout: Some(Duration::from_secs(5)),
+ callbacks: Vec::new(),
+ guardrails: Vec::new(),
+ request_metadata: RequestMetadata::default(),
+ litellm_call_id: None,
+ })
+ .await
+ .expect("document intelligence request succeeds");
+
+ assert_eq!(response["pages"][0]["markdown"], "ok");
+
+ let (post_request, poll_request) = server.await.expect("server task completes");
+ assert!(
+ post_request
+ .to_ascii_lowercase()
+ .contains("ocp-apim-subscription-key: di-key"),
+ "{post_request}"
+ );
+ assert!(
+ poll_request
+ .to_ascii_lowercase()
+ .contains("ocp-apim-subscription-key: di-key"),
+ "{poll_request}"
+ );
+}
+
+#[test]
+fn string_headers_rejects_non_string_values() {
+ let headers = json!({
+ "x-retry-count": 3
+ })
+ .as_object()
+ .unwrap()
+ .clone();
+
+ let err = string_headers(Some(headers)).expect_err("non-string header rejected");
+ assert_eq!(
+ err,
+ CoreError::InvalidRequest(
+ "OCR extra_headers.x-retry-count must be a string, got number".to_string()
+ )
+ );
+}
diff --git a/litellm-rust/crates/ai-gateway/src/ocr/types.rs b/litellm-rust/crates/ai-gateway/src/ocr/types.rs
new file mode 100644
index 00000000000..bde734a4dd1
--- /dev/null
+++ b/litellm-rust/crates/ai-gateway/src/ocr/types.rs
@@ -0,0 +1,57 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use litellm_core::call_lifecycle::{CallLifecycleContext, CallLifecycleRequest};
+use litellm_core::ocr::transformation::OcrProviderConfig;
+use serde_json::{Map, Value};
+
+use crate::integrations::custom_guardrail::CustomGuardrail;
+use crate::integrations::custom_logger::CustomLogger;
+use crate::integrations::types::RequestMetadata;
+
+pub struct OcrRequest<'a> {
+ pub model: &'a str,
+ pub document: Value,
+ pub api_key: Option<&'a str>,
+ pub api_base: Option<&'a str>,
+ pub custom_llm_provider: Option<&'a str>,
+ pub extra_headers: Option<Map<String, Value>>,
+ pub optional_params: Map<String, Value>,
+ pub timeout: Option<Duration>,
+ pub callbacks: Vec<Arc<dyn CustomLogger>>,
+ pub guardrails: Vec<Arc<dyn CustomGuardrail>>,
+ pub request_metadata: RequestMetadata,
+ pub litellm_call_id: Option<&'a str>,
+}
+
+pub(crate) struct PreparedOcrRequest {
+ pub(crate) model: String,
+ pub(crate) custom_llm_provider: String,
+ pub(crate) litellm_call_id: String,
+ pub(crate) document: Value,
+ pub(crate) api_key: Option<String>,
+ pub(crate) api_base: Option<String>,
+ pub(crate) extra_headers: Option<Map<String, Value>>,
+ pub(crate) optional_params: Map<String, Value>,
+ pub(crate) timeout: Option<Duration>,
+}
+
+impl CallLifecycleRequest for PreparedOcrRequest {
+ fn lifecycle_context(&self) -> CallLifecycleContext {
+ CallLifecycleContext::new(
+ "ocr",
+ self.model.clone(),
+ self.custom_llm_provider.clone(),
+ self.litellm_call_id.clone(),
+ )
+ }
+}
+
+pub(crate) struct ProviderOcrRequest {
+ pub(crate) model: String,
+ pub(crate) config: &'static dyn OcrProviderConfig,
+ pub(crate) url: String,
+ pub(crate) body: Value,
+ pub(crate) upstream_headers: Vec<(String, String)>,
+ pub(crate) timeout: Option<Duration>,
+}
diff --git a/litellm-rust/crates/ai-gateway/src/realtime/streaming.rs b/litellm-rust/crates/ai-gateway/src/realtime/streaming.rs
index 34c82897808..c32e727de54 100644
--- a/litellm-rust/crates/ai-gateway/src/realtime/streaming.rs
+++ b/litellm-rust/crates/ai-gateway/src/realtime/streaming.rs
@@ -13,7 +13,9 @@ use litellm_core::realtime::types::RealtimeEvent;
use serde_json::Value;
use crate::constants::DEFAULT_PROVIDER;
-use crate::integrations::custom_logger::CustomLogger;
+use crate::integrations::custom_logger::{
+ CallbackTiming, CallbackValue, CustomLogger, CustomLoggerRunner, LoggingError, ModelCallDetails,
+};
use crate::integrations::types::{
RequestMetadata, StandardLoggingMetadata, StandardLoggingPayload, Usage,
};
@@ -183,30 +185,45 @@ impl RealTimeStreaming {
/// Finish the session: stamp the end time and fan the payload out to every
/// callback. On a logger enqueue error we bump a non-fatal counter (the
/// realtime session has already ended; a dropped log must never propagate).
- pub fn log_messages(&mut self, status: SessionStatus) {
+ pub async fn log_messages(&mut self, status: SessionStatus) {
self.end_time = epoch_seconds();
let payload = self.build_payload();
+ let timing = CallbackTiming::new(payload.start_time, payload.end_time);
+ let runner = CustomLoggerRunner::new(self.callbacks.clone());
match status {
SessionStatus::Success => {
- for callback in &self.callbacks {
- if let Err(err) = callback.log_success_event(&payload) {
- self.dropped += 1;
- eprintln!("litellm-ai-gateway: log_success_event dropped: {err}");
- }
- }
+ let response = CallbackValue::new("realtime", serde_json::Value::Null);
+ let report = runner
+ .async_log_success_event(
+ &ModelCallDetails::from_standard_logging_payload(payload),
+ &response,
+ timing,
+ )
+ .await;
+ self.dropped += report.dropped as u64;
}
SessionStatus::Failure => {
- let error = crate::integrations::types::LoggingError {
+ let error = LoggingError {
message: "realtime session ended in failure".to_string(),
kind: "RealtimeSessionError".to_string(),
};
- for callback in &self.callbacks {
- if let Err(err) = callback.log_failure_event(&payload, &error) {
- self.dropped += 1;
- eprintln!("litellm-ai-gateway: log_failure_event dropped: {err}");
- }
- }
+ let response = CallbackValue::new(
+ "error",
+ serde_json::json!({
+ "message": error.message,
+ "kind": error.kind,
+ }),
+ );
+ let report = runner
+ .async_log_failure_event(
+ &ModelCallDetails::from_standard_logging_payload(payload)
+ .with_failure_error(error),
+ Some(&response),
+ timing,
+ )
+ .await;
+ self.dropped += report.dropped as u64;
}
}
}
@@ -215,7 +232,8 @@ impl RealTimeStreaming {
#[cfg(test)]
mod tests {
use super::*;
- use crate::integrations::types::{LogError, LoggingError};
+ use crate::integrations::custom_logger::LogError;
+ use crate::integrations::custom_logger::LogFuture;
use std::sync::atomic::{AtomicU64, Ordering};
fn event(raw: &str) -> RealtimeEvent {
@@ -231,17 +249,28 @@ mod tests {
}
impl CustomLogger for CapturingLogger {
- fn log_success_event(&self, payload: &StandardLoggingPayload) -> Result<(), LogError> {
- self.calls.fetch_add(1, Ordering::SeqCst);
- *self.last_model.lock().unwrap() = Some(payload.model.clone());
- self.last_total_tokens
- .store(payload.total_tokens, Ordering::SeqCst);
- Ok(())
+ fn async_log_success_event<'a>(
+ &'a self,
+ model_call_details: &'a ModelCallDetails,
+ _response_obj: &'a CallbackValue,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async move {
+ let payload = model_call_details
+ .standard_logging_payload
+ .as_ref()
+ .expect("standard logging payload");
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ *self.last_model.lock().unwrap() = Some(payload.model.clone());
+ self.last_total_tokens
+ .store(payload.total_tokens, Ordering::SeqCst);
+ Ok(())
+ })
}
}
- #[test]
- fn observe_accumulates_model_and_tokens_then_logs() {
+ #[tokio::test]
+ async fn observe_accumulates_model_and_tokens_then_logs() {
let logger = Arc::new(CapturingLogger::default());
let callbacks: Vec<Arc<dyn CustomLogger>> = vec![logger.clone()];
let mut streaming = RealTimeStreaming::new(
@@ -284,7 +313,7 @@ mod tests {
Some("hash123")
);
- streaming.log_messages(SessionStatus::Success);
+ streaming.log_messages(SessionStatus::Success).await;
assert_eq!(logger.calls.load(Ordering::SeqCst), 1);
assert_eq!(
logger.last_model.lock().unwrap().as_deref(),
@@ -324,19 +353,26 @@ mod tests {
/// A logger whose enqueue always fails should bump the dropped counter, not
/// panic or propagate.
- #[test]
- fn failing_logger_bumps_dropped_counter() {
+ #[tokio::test]
+ async fn failing_logger_bumps_dropped_counter() {
struct FailingLogger;
impl CustomLogger for FailingLogger {
- fn log_success_event(&self, _p: &StandardLoggingPayload) -> Result<(), LogError> {
- Err(LogError::channel_full())
+ fn async_log_success_event<'a>(
+ &'a self,
+ _model_call_details: &'a ModelCallDetails,
+ _response_obj: &'a CallbackValue,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async { Err(LogError::channel_full()) })
}
- fn log_failure_event(
- &self,
- _p: &StandardLoggingPayload,
- _e: &LoggingError,
- ) -> Result<(), LogError> {
- Err(LogError::channel_closed())
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ _model_call_details: &'a ModelCallDetails,
+ _response_obj: Option<&'a CallbackValue>,
+ _timing: CallbackTiming,
+ ) -> LogFuture<'a> {
+ Box::pin(async { Err(LogError::channel_closed()) })
}
}
let callbacks: Vec<Arc<dyn CustomLogger>> = vec![Arc::new(FailingLogger)];
@@ -346,7 +382,7 @@ mod tests {
"gpt-realtime".to_string(),
RequestMetadata::default(),
);
- streaming.log_messages(SessionStatus::Success);
+ streaming.log_messages(SessionStatus::Success).await;
assert_eq!(streaming.dropped(), 1);
}
}
diff --git a/litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs b/litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs
index 899ad73829f..c3f929f5f0b 100644
--- a/litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs
+++ b/litellm-rust/crates/ai-gateway/src/routes/realtime/mod.rs
@@ -162,5 +162,5 @@ async fn bridge(
} else {
SessionStatus::Failure
};
- collector.log_messages(status);
+ collector.log_messages(status).await;
}
diff --git a/litellm-rust/crates/core/Cargo.toml b/litellm-rust/crates/core/Cargo.toml
index 1881bcfa602..9bd4634cc2a 100644
--- a/litellm-rust/crates/core/Cargo.toml
+++ b/litellm-rust/crates/core/Cargo.toml
@@ -10,3 +10,6 @@ rand.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/litellm-rust/crates/core/src/call_lifecycle/README.md b/litellm-rust/crates/core/src/call_lifecycle/README.md
new file mode 100644
index 00000000000..692e249ef27
--- /dev/null
+++ b/litellm-rust/crates/core/src/call_lifecycle/README.md
@@ -0,0 +1,167 @@
+# Call lifecycle
+
+`litellm_core::call_lifecycle` is the shared execution wrapper for LiteLLM call
+types migrated to Rust. It owns lifecycle ordering, phase timing, and trace
+observer calls. It must not know about OCR, chat, messages, responses,
+completions, provider auth, request transforms, or response normalization.
+
+Call-type modules own their domain behavior. For example, OCR owns document
+payloads, OCR provider transforms, safe document fetch, guardrail payload shape,
+callback payload shape, and provider HTTP execution.
+
+## Runtime order
+
+Every wrapped call runs in this order:
+
+1. `async_pre_call_hook`
+2. `async_during_call_hook`
+3. provider call
+4. `async_log_success_event` or `async_log_failure_event`
+
+`async_pre_call_hook` receives the initial LiteLLM request shape. It is where
+pre-call custom guardrails run.
+
+`async_during_call_hook` converts the initial request into the provider-ready
+request. It is where provider config selection, parameter mapping, auth/header
+resolution, request transforms, and during-call guardrails belong.
+
+The provider call receives only the provider-ready request. It should execute
+I/O and call the provider response transform.
+
+Success and failure callbacks receive `CallLifecycleTiming`. Callback failures
+must not replace the original provider or guardrail result.
+
+## Trace contract
+
+The lifecycle runner records:
+
+- full call start and end time
+- `pre_call` phase timing
+- `during_call` phase timing
+- `provider_call` phase timing
+- `success_callback` phase timing
+- `failure_callback` phase timing
+
+`CallLifecycleObserver` receives phase start and end events. The default
+observer is a no-op. Future OTEL support should implement this observer instead
+of editing OCR, chat, messages, responses, completions, or provider modules.
+
+## Required shape
+
+Each migrated call type should use this folder shape:
+
+```text
+litellm-rust/crates/ai-gateway/src/<call_type>/
+ mod.rs # thin public entrypoint
+ types.rs # public request, prepared request, provider request, response types
+ prepare.rs # model/provider/callback/guardrail setup
+ hooks.rs # CallLifecycleHooks implementation
+ handler.rs # provider I/O and response normalization
+ tests.rs # call-type lifecycle and handler tests
+```
+
+Provider transforms can live in `litellm-rust/crates/core/src/providers/...`.
+Shared call-type helpers can live beside the call type, but generic lifecycle
+code stays in this folder.
+
+## Core API
+
+The prepared request implements `CallLifecycleRequest`:
+
+```rust
+impl CallLifecycleRequest for PreparedMessagesRequest {
+ fn lifecycle_context(&self) -> CallLifecycleContext {
+ CallLifecycleContext::new(
+ "messages",
+ self.model.clone(),
+ self.custom_llm_provider.clone(),
+ self.litellm_call_id.clone(),
+ )
+ }
+}
+```
+
+The call-type hooks implement `CallLifecycleHooks`:
+
+```rust
+impl CallLifecycleHooks<
+ PreparedMessagesRequest,
+ ProviderMessagesRequest,
+ MessagesResponse,
+> for MessagesLifecycleHooks {
+ fn async_pre_call_hook(...) {
+ // run pre-call custom guardrails against the LiteLLM request shape
+ }
+
+ fn async_during_call_hook(...) {
+ // map params, validate env, transform request, run during-call guardrails
+ }
+
+ fn async_log_success_event(...) {
+ // call async_log_success_event on configured custom loggers
+ }
+
+ fn async_log_failure_event(...) {
+ // call async_log_failure_event without swallowing the original error
+ }
+}
+```
+
+The public entrypoint stays thin:
+
+```rust
+pub async fn messages(request: MessagesRequest<'_>) -> CoreResult<MessagesResponse> {
+ let PreparedMessagesCall { request, hooks } = prepare_messages_call(request)?;
+
+ CallLifecycle::default()
+ .run_request(request, &hooks, execute_messages_provider_call)
+ .await
+}
+```
+
+Use `run_request` for new call types. Keep `run` available only for specialized
+tests or existing code that already has a `CallLifecycleContext`.
+
+## Adding a new call type
+
+1. Add `<call_type>/types.rs`
+
+Define the public request accepted by the bridge, the prepared request used by
+the lifecycle runner, and the provider request consumed by the handler.
+
+2. Implement `CallLifecycleRequest`
+
+Return `call_type`, `model`, `custom_llm_provider`, and `litellm_call_id`.
+Do not put provider-specific logic here.
+
+3. Add `<call_type>/prepare.rs`
+
+Resolve model/provider once, generate or preserve `litellm_call_id`, construct
+callback and guardrail runners, and return `Prepared<CallType>Call`.
+
+4. Add `<call_type>/hooks.rs`
+
+Implement `CallLifecycleHooks`. Put pre-call guardrail payload construction,
+provider config selection, param mapping, request transform, during-call
+guardrail payload construction, and callback payload construction here.
+
+5. Add `<call_type>/handler.rs`
+
+Execute the provider request and normalize the provider response. Do not repeat
+provider-specific transforms here; call the provider config.
+
+6. Add tests
+
+Cover hook order, success callback payload, failure callback payload, pre-call
+guardrail blocking before provider I/O, during-call body mutation, and provider
+error mapping.
+
+## Review checklist
+
+- Core lifecycle has no call-type or provider-specific branches
+- Public call-type entrypoint only prepares and calls `run_request`
+- Provider behavior lives behind provider config/transformation code
+- Hook method names map to the Python custom logger and guardrail concepts
+- Phase timing is recorded once in lifecycle, not separately per call type
+- Callback failures never hide the original provider or guardrail error
+- Tests prove the provider socket is not touched when pre-call guardrails block
diff --git a/litellm-rust/crates/core/src/call_lifecycle/mod.rs b/litellm-rust/crates/core/src/call_lifecycle/mod.rs
new file mode 100644
index 00000000000..d9b68a1b726
--- /dev/null
+++ b/litellm-rust/crates/core/src/call_lifecycle/mod.rs
@@ -0,0 +1,414 @@
+use std::future::Future;
+use std::time::{Instant, SystemTime, UNIX_EPOCH};
+
+use crate::{CoreError, CoreResult};
+
+pub mod types;
+
+pub use types::{
+ CallLifecycleContext, CallLifecyclePhase, CallLifecyclePhaseTiming, CallLifecycleRequest,
+ CallLifecycleTiming,
+};
+
+pub trait CallLifecycleHooks<InitialReq, ProviderReq, Resp>: Send + Sync {
+ type PreCallFuture<'a>: Future<Output = CoreResult<InitialReq>> + Send + 'a
+ where
+ Self: 'a,
+ InitialReq: 'a,
+ ProviderReq: 'a,
+ Resp: 'a;
+
+ type DuringCallFuture<'a>: Future<Output = CoreResult<ProviderReq>> + Send + 'a
+ where
+ Self: 'a,
+ InitialReq: 'a,
+ ProviderReq: 'a,
+ Resp: 'a;
+
+ type SuccessFuture<'a>: Future<Output = ()> + Send + 'a
+ where
+ Self: 'a,
+ Resp: 'a;
+
+ type FailureFuture<'a>: Future<Output = ()> + Send + 'a
+ where
+ Self: 'a;
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ context: &'a CallLifecycleContext,
+ request: InitialReq,
+ ) -> Self::PreCallFuture<'a>;
+
+ fn async_during_call_hook<'a>(
+ &'a self,
+ context: &'a CallLifecycleContext,
+ request: InitialReq,
+ ) -> Self::DuringCallFuture<'a>;
+
+ fn async_log_success_event<'a>(
+ &'a self,
+ context: &'a CallLifecycleContext,
+ response: &'a Resp,
+ timing: &'a CallLifecycleTiming,
+ ) -> Self::SuccessFuture<'a>;
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ context: &'a CallLifecycleContext,
+ error: &'a CoreError,
+ timing: &'a CallLifecycleTiming,
+ ) -> Self::FailureFuture<'a>;
+}
+
+pub trait CallLifecycleObserver: Send + Sync {
+ fn on_phase_start(&self, _context: &CallLifecycleContext, _phase: CallLifecyclePhase) {}
+
+ fn on_phase_end(&self, _context: &CallLifecycleContext, _timing: &CallLifecyclePhaseTiming) {}
+}
+
+#[derive(Default)]
+pub struct NoopCallLifecycleObserver;
+
+impl CallLifecycleObserver for NoopCallLifecycleObserver {}
+
+pub struct CallLifecycle<'a> {
+ observer: &'a dyn CallLifecycleObserver,
+}
+
+impl<'a> CallLifecycle<'a> {
+ pub fn new(observer: &'a dyn CallLifecycleObserver) -> Self {
+ Self { observer }
+ }
+
+ pub async fn run_request<InitialReq, ProviderReq, Resp, Hooks, ProviderCall, ProviderFuture>(
+ &self,
+ request: InitialReq,
+ hooks: &Hooks,
+ provider_call: ProviderCall,
+ ) -> CoreResult<Resp>
+ where
+ InitialReq: CallLifecycleRequest,
+ Hooks: CallLifecycleHooks<InitialReq, ProviderReq, Resp>,
+ ProviderCall: FnOnce(ProviderReq) -> ProviderFuture,
+ ProviderFuture: Future<Output = CoreResult<Resp>>,
+ {
+ let context = request.lifecycle_context();
+ self.run(context, request, hooks, provider_call).await
+ }
+
+ pub async fn run<InitialReq, ProviderReq, Resp, Hooks, ProviderCall, ProviderFuture>(
+ &self,
+ context: CallLifecycleContext,
+ request: InitialReq,
+ hooks: &Hooks,
+ provider_call: ProviderCall,
+ ) -> CoreResult<Resp>
+ where
+ Hooks: CallLifecycleHooks<InitialReq, ProviderReq, Resp>,
+ ProviderCall: FnOnce(ProviderReq) -> ProviderFuture,
+ ProviderFuture: Future<Output = CoreResult<Resp>>,
+ {
+ let call_start = epoch_seconds();
+ let mut phases = Vec::new();
+
+ let pre_call = self.start_phase(&context, CallLifecyclePhase::PreCall);
+ let request = match hooks.async_pre_call_hook(&context, request).await {
+ Ok(request) => {
+ phases.push(self.finish_phase(&context, pre_call));
+ request
+ }
+ Err(error) => {
+ phases.push(self.finish_phase(&context, pre_call));
+ self.log_failure(&context, hooks, &error, call_start, &mut phases)
+ .await;
+ return Err(error);
+ }
+ };
+
+ let during_call = self.start_phase(&context, CallLifecyclePhase::DuringCall);
+ let provider_request = match hooks.async_during_call_hook(&context, request).await {
+ Ok(request) => {
+ phases.push(self.finish_phase(&context, during_call));
+ request
+ }
+ Err(error) => {
+ phases.push(self.finish_phase(&context, during_call));
+ self.log_failure(&context, hooks, &error, call_start, &mut phases)
+ .await;
+ return Err(error);
+ }
+ };
+
+ let provider_phase = self.start_phase(&context, CallLifecyclePhase::ProviderCall);
+ let result = provider_call(provider_request).await;
+ phases.push(self.finish_phase(&context, provider_phase));
+
+ match &result {
+ Ok(response) => {
+ let success_phase = self.start_phase(&context, CallLifecyclePhase::SuccessCallback);
+ let timing = CallLifecycleTiming::new(call_start, epoch_seconds(), phases.clone());
+ hooks
+ .async_log_success_event(&context, response, &timing)
+ .await;
+ phases.push(self.finish_phase(&context, success_phase));
+ }
+ Err(error) => {
+ self.log_failure(&context, hooks, error, call_start, &mut phases)
+ .await;
+ }
+ }
+
+ result
+ }
+
+ async fn log_failure<InitialReq, ProviderReq, Resp, Hooks>(
+ &self,
+ context: &CallLifecycleContext,
+ hooks: &Hooks,
+ error: &CoreError,
+ call_start: f64,
+ phases: &mut Vec<CallLifecyclePhaseTiming>,
+ ) where
+ Hooks: CallLifecycleHooks<InitialReq, ProviderReq, Resp>,
+ {
+ let failure_phase = self.start_phase(context, CallLifecyclePhase::FailureCallback);
+ let timing = CallLifecycleTiming::new(call_start, epoch_seconds(), phases.clone());
+ hooks.async_log_failure_event(context, error, &timing).await;
+ phases.push(self.finish_phase(context, failure_phase));
+ }
+
+ fn start_phase(&self, context: &CallLifecycleContext, phase: CallLifecyclePhase) -> PhaseStart {
+ self.observer.on_phase_start(context, phase);
+ PhaseStart {
+ phase,
+ start_time: epoch_seconds(),
+ started_at: Instant::now(),
+ }
+ }
+
+ fn finish_phase(
+ &self,
+ context: &CallLifecycleContext,
+ phase_start: PhaseStart,
+ ) -> CallLifecyclePhaseTiming {
+ let timing = CallLifecyclePhaseTiming {
+ phase: phase_start.phase,
+ start_time: phase_start.start_time,
+ end_time: epoch_seconds(),
+ duration: phase_start.started_at.elapsed(),
+ };
+ self.observer.on_phase_end(context, &timing);
+ timing
+ }
+}
+
+impl Default for CallLifecycle<'static> {
+ fn default() -> Self {
+ static OBSERVER: NoopCallLifecycleObserver = NoopCallLifecycleObserver;
+ Self::new(&OBSERVER)
+ }
+}
+
+struct PhaseStart {
+ phase: CallLifecyclePhase,
+ start_time: f64,
+ started_at: Instant,
+}
+
+fn epoch_seconds() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|duration| duration.as_secs_f64())
+ .unwrap_or(0.0)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::pin::Pin;
+ use std::sync::Mutex;
+
+ type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
+
+ #[derive(Default)]
+ struct RecordingHooks {
+ events: Mutex<Vec<&'static str>>,
+ }
+
+ struct RecordingRequest(String);
+
+ impl CallLifecycleRequest for RecordingRequest {
+ fn lifecycle_context(&self) -> CallLifecycleContext {
+ CallLifecycleContext::new("ocr", "mistral-ocr-latest", "mistral", "call_1")
+ }
+ }
+
+ impl RecordingHooks {
+ fn events(&self) -> Vec<&'static str> {
+ self.events.lock().unwrap().clone()
+ }
+ }
+
+ impl CallLifecycleHooks<String, String, String> for RecordingHooks {
+ type PreCallFuture<'a> = BoxFuture<'a, CoreResult<String>>;
+ type DuringCallFuture<'a> = BoxFuture<'a, CoreResult<String>>;
+ type SuccessFuture<'a> = BoxFuture<'a, ()>;
+ type FailureFuture<'a> = BoxFuture<'a, ()>;
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ request: String,
+ ) -> Self::PreCallFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("pre_call");
+ Ok(format!("{request}:pre"))
+ })
+ }
+
+ fn async_during_call_hook<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ request: String,
+ ) -> Self::DuringCallFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("during_call");
+ Ok(format!("{request}:during"))
+ })
+ }
+
+ fn async_log_success_event<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ _response: &'a String,
+ timing: &'a CallLifecycleTiming,
+ ) -> Self::SuccessFuture<'a> {
+ Box::pin(async move {
+ assert!(timing.end_time >= timing.start_time);
+ assert_eq!(timing.phases.len(), 3);
+ self.events.lock().unwrap().push("success");
+ })
+ }
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ _error: &'a CoreError,
+ _timing: &'a CallLifecycleTiming,
+ ) -> Self::FailureFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("failure");
+ })
+ }
+ }
+
+ impl CallLifecycleHooks<RecordingRequest, String, String> for RecordingHooks {
+ type PreCallFuture<'a> = BoxFuture<'a, CoreResult<RecordingRequest>>;
+ type DuringCallFuture<'a> = BoxFuture<'a, CoreResult<String>>;
+ type SuccessFuture<'a> = BoxFuture<'a, ()>;
+ type FailureFuture<'a> = BoxFuture<'a, ()>;
+
+ fn async_pre_call_hook<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ request: RecordingRequest,
+ ) -> Self::PreCallFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("pre_call");
+ Ok(RecordingRequest(format!("{}:pre", request.0)))
+ })
+ }
+
+ fn async_during_call_hook<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ request: RecordingRequest,
+ ) -> Self::DuringCallFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("during_call");
+ Ok(format!("{}:during", request.0))
+ })
+ }
+
+ fn async_log_success_event<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ _response: &'a String,
+ _timing: &'a CallLifecycleTiming,
+ ) -> Self::SuccessFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("success");
+ })
+ }
+
+ fn async_log_failure_event<'a>(
+ &'a self,
+ _context: &'a CallLifecycleContext,
+ _error: &'a CoreError,
+ _timing: &'a CallLifecycleTiming,
+ ) -> Self::FailureFuture<'a> {
+ Box::pin(async move {
+ self.events.lock().unwrap().push("failure");
+ })
+ }
+ }
+
+ #[tokio::test]
+ async fn lifecycle_runs_hooks_around_provider_call() {
+ let hooks = RecordingHooks::default();
+ let response = CallLifecycle::default()
+ .run(
+ CallLifecycleContext::new("ocr", "mistral-ocr-latest", "mistral", "call_1"),
+ "request".to_string(),
+ &hooks,
+ |request| async move {
+ assert_eq!(request, "request:pre:during");
+ Ok("response".to_string())
+ },
+ )
+ .await
+ .expect("call succeeds");
+
+ assert_eq!(response, "response");
+ assert_eq!(hooks.events(), vec!["pre_call", "during_call", "success"]);
+ }
+
+ #[tokio::test]
+ async fn lifecycle_logs_failure_when_provider_fails() {
+ let hooks = RecordingHooks::default();
+ let error = CallLifecycle::default()
+ .run(
+ CallLifecycleContext::new("ocr", "mistral-ocr-latest", "mistral", "call_1"),
+ "request".to_string(),
+ &hooks,
+ |_request| async move {
+ Err::<String, CoreError>(CoreError::Network("provider down".to_string()))
+ },
+ )
+ .await
+ .expect_err("call fails");
+
+ assert_eq!(error, CoreError::Network("provider down".to_string()));
+ assert_eq!(hooks.events(), vec!["pre_call", "during_call", "failure"]);
+ }
+
+ #[tokio::test]
+ async fn lifecycle_can_run_any_request_with_embedded_context() {
+ let hooks = RecordingHooks::default();
+ let response = CallLifecycle::default()
+ .run_request(
+ RecordingRequest("request".to_string()),
+ &hooks,
+ |request| async move {
+ assert_eq!(request, "request:pre:during");
+ Ok("response".to_string())
+ },
+ )
+ .await
+ .expect("call succeeds");
+
+ assert_eq!(response, "response");
+ assert_eq!(hooks.events(), vec!["pre_call", "during_call", "success"]);
+ }
+}
diff --git a/litellm-rust/crates/core/src/call_lifecycle/types.rs b/litellm-rust/crates/core/src/call_lifecycle/types.rs
new file mode 100644
index 00000000000..8819c8830d2
--- /dev/null
+++ b/litellm-rust/crates/core/src/call_lifecycle/types.rs
@@ -0,0 +1,75 @@
+use std::time::Duration;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CallLifecycleContext {
+ pub call_type: String,
+ pub model: String,
+ pub custom_llm_provider: String,
+ pub litellm_call_id: String,
+}
+
+impl CallLifecycleContext {
+ pub fn new(
+ call_type: impl Into<String>,
+ model: impl Into<String>,
+ custom_llm_provider: impl Into<String>,
+ litellm_call_id: impl Into<String>,
+ ) -> Self {
+ Self {
+ call_type: call_type.into(),
+ model: model.into(),
+ custom_llm_provider: custom_llm_provider.into(),
+ litellm_call_id: litellm_call_id.into(),
+ }
+ }
+}
+
+pub trait CallLifecycleRequest {
+ fn lifecycle_context(&self) -> CallLifecycleContext;
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum CallLifecyclePhase {
+ PreCall,
+ DuringCall,
+ ProviderCall,
+ SuccessCallback,
+ FailureCallback,
+}
+
+impl CallLifecyclePhase {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::PreCall => "pre_call",
+ Self::DuringCall => "during_call",
+ Self::ProviderCall => "provider_call",
+ Self::SuccessCallback => "success_callback",
+ Self::FailureCallback => "failure_callback",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct CallLifecyclePhaseTiming {
+ pub phase: CallLifecyclePhase,
+ pub start_time: f64,
+ pub end_time: f64,
+ pub duration: Duration,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct CallLifecycleTiming {
+ pub start_time: f64,
+ pub end_time: f64,
+ pub phases: Vec<CallLifecyclePhaseTiming>,
+}
+
+impl CallLifecycleTiming {
+ pub fn new(start_time: f64, end_time: f64, phases: Vec<CallLifecyclePhaseTiming>) -> Self {
+ Self {
+ start_time,
+ end_time,
+ phases,
+ }
+ }
+}
diff --git a/litellm-rust/crates/core/src/lib.rs b/litellm-rust/crates/core/src/lib.rs
index 2ac479cc725..555a04ce853 100644
--- a/litellm-rust/crates/core/src/lib.rs
+++ b/litellm-rust/crates/core/src/lib.rs
@@ -1,7 +1,9 @@
+pub mod call_lifecycle;
pub mod error;
pub mod ocr;
pub mod providers;
pub mod realtime;
pub mod router;
+pub mod routing_utils;
pub use error::{CoreError, CoreResult};
diff --git a/litellm-rust/crates/core/src/routing_utils/README.md b/litellm-rust/crates/core/src/routing_utils/README.md
new file mode 100644
index 00000000000..8585c18e421
--- /dev/null
+++ b/litellm-rust/crates/core/src/routing_utils/README.md
@@ -0,0 +1,7 @@
+# Routing Utils
+
+Shared helpers for deciding how a LiteLLM model routes to an LLM provider.
+Keep provider-name parsing, explicit `custom_llm_provider` handling, and model-prefix normalization here.
+Do not put deployment selection or load-balancing logic here; that belongs in `router`.
+Do not put provider HTTP transformation logic here; that belongs in `providers`.
+Helpers in this folder should be deterministic and easy to unit test without network calls.
diff --git a/litellm-rust/crates/core/src/routing_utils/mod.rs b/litellm-rust/crates/core/src/routing_utils/mod.rs
new file mode 100644
index 00000000000..8336397f870
--- /dev/null
+++ b/litellm-rust/crates/core/src/routing_utils/mod.rs
@@ -0,0 +1 @@
+pub mod provider;
diff --git a/litellm-rust/crates/core/src/routing_utils/provider.rs b/litellm-rust/crates/core/src/routing_utils/provider.rs
new file mode 100644
index 00000000000..6333eedebfc
--- /dev/null
+++ b/litellm-rust/crates/core/src/routing_utils/provider.rs
@@ -0,0 +1,77 @@
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CustomLlmProvider<'a> {
+ pub model: &'a str,
+ pub custom_llm_provider: &'a str,
+}
+
+pub fn get_custom_llm_provider<'a>(
+ model: &'a str,
+ custom_llm_provider: Option<&'a str>,
+) -> Option<CustomLlmProvider<'a>> {
+ if let Some(custom_llm_provider) = custom_llm_provider.filter(|provider| !provider.is_empty()) {
+ return Some(CustomLlmProvider {
+ model: strip_custom_llm_provider_prefix(model, custom_llm_provider),
+ custom_llm_provider,
+ });
+ }
+
+ let (custom_llm_provider, model) = model.split_once('/')?;
+ if custom_llm_provider.is_empty() || model.is_empty() {
+ return None;
+ }
+ Some(CustomLlmProvider {
+ model,
+ custom_llm_provider,
+ })
+}
+
+fn strip_custom_llm_provider_prefix<'a>(model: &'a str, custom_llm_provider: &str) -> &'a str {
+ model
+ .strip_prefix(custom_llm_provider)
+ .and_then(|model| model.strip_prefix('/'))
+ .unwrap_or(model)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn gets_custom_llm_provider_from_model_prefix() {
+ assert_eq!(
+ get_custom_llm_provider("mistral/mistral-ocr-latest", None),
+ Some(CustomLlmProvider {
+ model: "mistral-ocr-latest",
+ custom_llm_provider: "mistral",
+ })
+ );
+ assert_eq!(
+ get_custom_llm_provider("azure_ai/doc-intelligence/prebuilt-layout", None),
+ Some(CustomLlmProvider {
+ model: "doc-intelligence/prebuilt-layout",
+ custom_llm_provider: "azure_ai",
+ })
+ );
+ assert_eq!(get_custom_llm_provider("mistral-ocr-latest", None), None);
+ assert_eq!(get_custom_llm_provider("/model", None), None);
+ assert_eq!(get_custom_llm_provider("provider/", None), None);
+ }
+
+ #[test]
+ fn explicit_custom_llm_provider_strips_matching_model_prefix() {
+ assert_eq!(
+ get_custom_llm_provider("mistral/mistral-ocr-latest", Some("mistral")),
+ Some(CustomLlmProvider {
+ model: "mistral-ocr-latest",
+ custom_llm_provider: "mistral",
+ })
+ );
+ assert_eq!(
+ get_custom_llm_provider("mistral/mistral-ocr-latest", Some("vertex_ai")),
+ Some(CustomLlmProvider {
+ model: "mistral/mistral-ocr-latest",
+ custom_llm_provider: "vertex_ai",
+ })
+ );
+ }
+}
diff --git a/litellm-rust/crates/python-bridge/src/lib.rs b/litellm-rust/crates/python-bridge/src/lib.rs
index 82024e1bf47..946a99f990c 100644
--- a/litellm-rust/crates/python-bridge/src/lib.rs
+++ b/litellm-rust/crates/python-bridge/src/lib.rs
@@ -96,7 +96,6 @@ fn ocr(
optional_params: Option<Py<PyAny>>,
timeout_seconds: Option<f64>,
) -> PyResult<Py<PyAny>> {
- let custom_llm_provider = custom_llm_provider.unwrap_or_else(|| "mistral".to_string());
let (document, extra_headers, optional_params, timeout) = marshal_inputs(
py,
document,
@@ -111,10 +110,14 @@ fn ocr(
document,
api_key: api_key.as_deref(),
api_base: api_base.as_deref(),
- custom_llm_provider: &custom_llm_provider,
+ custom_llm_provider: custom_llm_provider.as_deref(),
extra_headers,
optional_params,
timeout,
+ callbacks: Vec::new(),
+ guardrails: Vec::new(),
+ request_metadata: Default::default(),
+ litellm_call_id: None,
}))
});
@@ -138,7 +141,6 @@ fn aocr(
optional_params: Option<Py<PyAny>>,
timeout_seconds: Option<f64>,
) -> PyResult<Bound<'_, PyAny>> {
- let custom_llm_provider = custom_llm_provider.unwrap_or_else(|| "mistral".to_string());
let (document, extra_headers, optional_params, timeout) = marshal_inputs(
py,
document,
@@ -153,10 +155,14 @@ fn aocr(
document,
api_key: api_key.as_deref(),
api_base: api_base.as_deref(),
- custom_llm_provider: &custom_llm_provider,
+ custom_llm_provider: custom_llm_provider.as_deref(),
extra_headers,
optional_params,
timeout,
+ callbacks: Vec::new(),
+ guardrails: Vec::new(),
+ request_metadata: Default::default(),
+ litellm_call_id: None,
})
.await
.map_err(core_error_to_pyerr)?;
diff --git a/litellm/__init__.py b/litellm/__init__.py
index 9650dc12c97..5ae5942f32f 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -1394,7 +1394,7 @@ from .skills.main import (
)
from .containers.main import *
from .ocr.main import *
-from .ocr.rust_bridge import use_litellm_rust
+from .rust_bridge.ocr import use_litellm_rust
from .rag.main import *
from .sandbox.main import *
from .search.main import *
diff --git a/litellm/ocr/main.py b/litellm/ocr/main.py
index 6a196d41768..93b3a892659 100644
--- a/litellm/ocr/main.py
+++ b/litellm/ocr/main.py
@@ -19,13 +19,7 @@ from litellm.constants import request_timeout
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
from litellm.llms.base_llm.ocr.transformation import BaseOCRConfig, OCRResponse
from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
-from litellm.ocr.rust_bridge import (
- RustAocr,
- RustOcr,
- load_rust_aocr,
- load_rust_ocr,
- rust_ocr_enabled,
-)
+from litellm.rust_bridge import ocr as rust_ocr_bridge
from litellm.types.router import GenericLiteLLMParams
from litellm.utils import ProviderConfigManager, client
@@ -60,27 +54,10 @@ class _PreparedRustOCRCall:
_RUST_OCR_PROVIDERS = {
"mistral",
"azure_ai",
- "azure_ai/doc-intelligence",
"vertex_ai",
}
-def _timeout_to_seconds(
- timeout: Union[float, httpx.Timeout] | None,
-) -> float | None:
- """Convert the Python OCR timeout to a single seconds value for the Rust bridge.
-
- The Rust HTTP client takes one duration; ``httpx.Timeout`` carries separate
- connect/read/write/pool values, so pick the read deadline as the closest
- analog to a total-request timeout.
- """
- if timeout is None:
- return None
- if isinstance(timeout, httpx.Timeout):
- return timeout.read
- return float(timeout)
-
-
def _prepare_ocr_request(
model: str,
document: dict[str, Any],
@@ -218,13 +195,9 @@ def _rust_bridge_api_base(
) -> str | None:
if prepared_request.api_base is not None:
return prepared_request.api_base
- if prepared_request.custom_llm_provider == "azure_ai/doc-intelligence":
- return resolve_secret("AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT")
if prepared_request.custom_llm_provider == "azure_ai":
- if (
- "doc-intelligence" in prepared_request.model
- or "documentintelligence" in prepared_request.model
- ):
+ model = prepared_request.model.lower()
+ if "doc-intelligence" in model or "documentintelligence" in model:
return resolve_secret("AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT")
return resolve_secret("AZURE_AI_API_BASE")
return None
@@ -278,57 +251,53 @@ def _prepare_rust_ocr_call(
def _run_rust_ocr(
- rust_ocr: RustOcr,
prepared_request: _PreparedOCRRequest,
resolve_api_key: Callable[[str], str | None],
-) -> OCRResponse:
- """Run the Mistral OCR call through the Rust bridge and wrap the result.
-
- Resolves the key the same way the Python path does so secret-manager backends
- (AWS/Azure/GCP/Vault) work; the Rust bridge's own fallback only reads the
- process environment. The request that Rust actually sends (resolved URL and
- headers) is mirrored into pre_call so logs match the wire. Dependencies are
- injected so this stays unit-testable without patching module globals.
- """
+) -> OCRResponse | None:
+ if rust_ocr_bridge.load_rust_ocr() is None:
+ return None
prepared = _prepare_rust_ocr_call(
prepared_request=prepared_request,
resolve_api_key=resolve_api_key,
)
- return OCRResponse.model_validate(
- rust_ocr(
- model=prepared_request.model,
- document=cast(dict[str, object], prepared_request.document),
- api_key=prepared.api_key,
- api_base=prepared.api_base,
- custom_llm_provider=prepared_request.custom_llm_provider,
- extra_headers=prepared.headers,
- optional_params=prepared.optional_params,
- timeout_seconds=_timeout_to_seconds(prepared_request.effective_timeout),
- )
+ rust_response = rust_ocr_bridge.ocr(
+ model=prepared_request.model,
+ document=prepared_request.document,
+ api_key=prepared.api_key,
+ api_base=prepared.api_base,
+ custom_llm_provider=prepared_request.custom_llm_provider,
+ extra_headers=prepared.headers,
+ optional_params=prepared.optional_params,
+ timeout=prepared_request.effective_timeout,
)
+ if rust_response is None:
+ return None
+ return OCRResponse.model_validate(rust_response)
async def _run_rust_aocr(
- rust_aocr: RustAocr,
prepared_request: _PreparedOCRRequest,
resolve_api_key: Callable[[str], str | None],
-) -> OCRResponse:
+) -> OCRResponse | None:
+ if rust_ocr_bridge.load_rust_aocr() is None:
+ return None
prepared = _prepare_rust_ocr_call(
prepared_request=prepared_request,
resolve_api_key=resolve_api_key,
)
- return OCRResponse.model_validate(
- await rust_aocr(
- model=prepared_request.model,
- document=cast(dict[str, object], prepared_request.document),
- api_key=prepared.api_key,
- api_base=prepared.api_base,
- custom_llm_provider=prepared_request.custom_llm_provider,
- extra_headers=prepared.headers,
- optional_params=prepared.optional_params,
- timeout_seconds=_timeout_to_seconds(prepared_request.effective_timeout),
- )
+ rust_response = await rust_ocr_bridge.aocr(
+ model=prepared_request.model,
+ document=prepared_request.document,
+ api_key=prepared.api_key,
+ api_base=prepared.api_base,
+ custom_llm_provider=prepared_request.custom_llm_provider,
+ extra_headers=prepared.headers,
+ optional_params=prepared.optional_params,
+ timeout=prepared_request.effective_timeout,
)
+ if rust_response is None:
+ return None
+ return OCRResponse.model_validate(rust_response)
@client
@@ -427,21 +396,19 @@ async def aocr(
{"model": model, "custom_llm_provider": custom_llm_provider}
)
- if _rust_ocr_supported(prepared) and rust_ocr_enabled():
- rust_aocr = load_rust_aocr()
- if rust_aocr is None:
+ if _rust_ocr_supported(prepared) and rust_ocr_bridge.rust_ocr_enabled():
+ from litellm.secret_managers.main import get_secret_str
+
+ rust_response = await _run_rust_aocr(
+ prepared_request=prepared,
+ resolve_api_key=get_secret_str,
+ )
+ if rust_response is None:
verbose_logger.debug(
"Async Rust OCR bridge unavailable; falling back to Python path"
)
else:
- from litellm.secret_managers.main import get_secret_str
-
- response = await _run_rust_aocr(
- rust_aocr=rust_aocr,
- prepared_request=prepared,
- resolve_api_key=get_secret_str,
- )
- return response
+ return rust_response
response = base_llm_http_handler.ocr(
model=prepared.model,
@@ -704,21 +671,19 @@ def ocr(
{"model": model, "custom_llm_provider": custom_llm_provider}
)
- # Optional Rust path: hand supported OCR calls to the Rust bridge.
- if _rust_ocr_supported(prepared) and rust_ocr_enabled():
- rust_ocr = load_rust_ocr()
- if rust_ocr is None:
+ if _rust_ocr_supported(prepared) and rust_ocr_bridge.rust_ocr_enabled():
+ from litellm.secret_managers.main import get_secret_str
+
+ rust_response = _run_rust_ocr(
+ prepared_request=prepared,
+ resolve_api_key=get_secret_str,
+ )
+ if rust_response is None:
verbose_logger.debug(
"Rust OCR bridge unavailable; falling back to Python path"
)
else:
- from litellm.secret_managers.main import get_secret_str
-
- return _run_rust_ocr(
- rust_ocr=rust_ocr,
- prepared_request=prepared,
- resolve_api_key=get_secret_str,
- )
+ return rust_response
response = base_llm_http_handler.ocr(
model=prepared.model,
diff --git a/litellm/rust_bridge/__init__.py b/litellm/rust_bridge/__init__.py
index ec89e3b65b4..3da5b98449b 100644
--- a/litellm/rust_bridge/__init__.py
+++ b/litellm/rust_bridge/__init__.py
@@ -4,5 +4,6 @@ from litellm.rust_bridge.loader import (
get_native_bridge,
native_bridge_available,
)
+from litellm.rust_bridge.ocr import use_litellm_rust
-__all__ = ["get_native_bridge", "native_bridge_available"]
+__all__ = ["get_native_bridge", "native_bridge_available", "use_litellm_rust"]
diff --git a/litellm/ocr/rust_bridge.py b/litellm/rust_bridge/ocr.py
similarity index 52%
rename from litellm/ocr/rust_bridge.py
rename to litellm/rust_bridge/ocr.py
index 631fd4c63c5..36a088b6b1a 100644
--- a/litellm/ocr/rust_bridge.py
+++ b/litellm/rust_bridge/ocr.py
@@ -1,30 +1,21 @@
-"""
-Optional Rust-backed OCR path.
-
-Enable with ``litellm.use_litellm_rust()``; the sync ``litellm.ocr()`` entrypoint
-then routes supported Mistral calls through the compiled ``litellm.rust_bridge._native``
-extension, which performs the whole OCR call (URL, headers, HTTP, parse) in Rust.
-
-No module-level ``litellm`` imports keep this a leaf so ``litellm/ocr/main.py``
-can import it statically without forming an import cycle.
-"""
+"""Thin Python wrapper for the native Rust OCR bridge."""
from __future__ import annotations
import os
-from typing import Awaitable, Final, Protocol, cast
+from typing import Any, Awaitable, Final, Protocol, Union, cast
+import httpx
-class RustOcr(Protocol):
- """Signature of the compiled Rust OCR entrypoint."""
+class RustOcr(Protocol):
def __call__(
self,
model: str,
document: dict[str, object],
api_key: str | None,
api_base: str | None,
- custom_llm_provider: str,
+ custom_llm_provider: str | None,
extra_headers: dict[str, object] | None,
optional_params: dict[str, object],
timeout_seconds: float | None,
@@ -33,15 +24,13 @@ class RustOcr(Protocol):
class RustAocr(Protocol):
- """Signature of the compiled ``litellm_python_bridge.aocr`` entrypoint."""
-
def __call__(
self,
model: str,
document: dict[str, object],
api_key: str | None,
api_base: str | None,
- custom_llm_provider: str,
+ custom_llm_provider: str | None,
extra_headers: dict[str, object] | None,
optional_params: dict[str, object],
timeout_seconds: float | None,
@@ -50,7 +39,7 @@ class RustAocr(Protocol):
class _Unset:
- """Sentinel type so ``ocr=None`` can clear a prior injection while omission preserves it."""
+ pass
_UNSET: Final[_Unset] = _Unset()
@@ -76,12 +65,6 @@ def use_litellm_rust(
ocr: RustOcr | None | _Unset = _UNSET,
aocr: RustAocr | None | _Unset = _UNSET,
) -> None:
- """Route supported OCR calls through the packaged Rust extension.
-
- ``ocr`` and ``aocr`` inject bridge callables; when omitted the compiled
- extension is loaded on demand and any previously injected bridge is
- preserved. Pass ``None`` explicitly to clear a prior injection.
- """
global _rust_ocr_enabled, _rust_ocr_impl, _rust_aocr_impl
_rust_ocr_enabled = enabled
if not isinstance(ocr, _Unset):
@@ -91,17 +74,10 @@ def use_litellm_rust(
def rust_ocr_enabled() -> bool:
- """Whether the Rust OCR path has been turned on via ``use_litellm_rust()``."""
return _rust_ocr_enabled
def load_rust_ocr() -> RustOcr | None:
- """Return the Rust OCR callable, or ``None`` when no bridge is available.
-
- Prefers an injected implementation, otherwise loads the compiled
- ``litellm.rust_bridge._native`` extension; a missing extension yields ``None`` so
- the caller can fall back to the Python path instead of hard-failing.
- """
if _rust_ocr_impl is not None:
return _rust_ocr_impl
from litellm.rust_bridge import get_native_bridge
@@ -113,7 +89,6 @@ def load_rust_ocr() -> RustOcr | None:
def load_rust_aocr() -> RustAocr | None:
- """Return the async Rust OCR callable, or ``None`` when unavailable."""
if _rust_aocr_impl is not None:
return _rust_aocr_impl
from litellm.rust_bridge import get_native_bridge
@@ -122,3 +97,63 @@ def load_rust_aocr() -> RustAocr | None:
if native_bridge is None:
return None
return cast(RustAocr, getattr(native_bridge, "aocr", None))
+
+
+def _timeout_to_seconds(timeout: Union[float, httpx.Timeout] | None) -> float | None:
+ if timeout is None:
+ return None
+ if isinstance(timeout, httpx.Timeout):
+ return timeout.read
+ return float(timeout)
+
+
+def ocr(
+ *,
+ model: str,
+ document: dict[str, Any],
+ api_key: str | None,
+ api_base: str | None,
+ custom_llm_provider: str | None,
+ extra_headers: dict[str, Any] | None,
+ optional_params: dict[str, object],
+ timeout: Union[float, httpx.Timeout] | None,
+) -> dict[str, object] | None:
+ rust_ocr = load_rust_ocr()
+ if rust_ocr is None:
+ return None
+ return rust_ocr(
+ model=model,
+ document=cast(dict[str, object], document),
+ api_key=api_key,
+ api_base=api_base,
+ custom_llm_provider=custom_llm_provider,
+ extra_headers=cast(dict[str, object] | None, extra_headers),
+ optional_params=optional_params,
+ timeout_seconds=_timeout_to_seconds(timeout),
+ )
+
+
+async def aocr(
+ *,
+ model: str,
+ document: dict[str, Any],
+ api_key: str | None,
+ api_base: str | None,
+ custom_llm_provider: str | None,
+ extra_headers: dict[str, Any] | None,
+ optional_params: dict[str, object],
+ timeout: Union[float, httpx.Timeout] | None,
+) -> dict[str, object] | None:
+ rust_aocr = load_rust_aocr()
+ if rust_aocr is None:
+ return None
+ return await rust_aocr(
+ model=model,
+ document=cast(dict[str, object], document),
+ api_key=api_key,
+ api_base=api_base,
+ custom_llm_provider=custom_llm_provider,
+ extra_headers=cast(dict[str, object] | None, extra_headers),
+ optional_params=optional_params,
+ timeout_seconds=_timeout_to_seconds(timeout),
+ )
diff --git a/tests/test_litellm/ocr/test_rust_bridge.py b/tests/test_litellm/ocr/test_rust_bridge.py
index 7e23e441f50..acad249a2bb 100644
--- a/tests/test_litellm/ocr/test_rust_bridge.py
+++ b/tests/test_litellm/ocr/test_rust_bridge.py
@@ -1,4 +1,4 @@
-"""Tests for the optional Rust-backed OCR path (``litellm/ocr/rust_bridge.py``)."""
+"""Tests for the optional Rust-backed OCR path."""
import importlib
import builtins
@@ -15,7 +15,7 @@ from litellm.llms.base_llm.ocr.transformation import OCRResponse
# function onto `litellm.ocr` and shadows the submodule, so import the modules
# explicitly via importlib rather than attribute traversal.
ocr_main = importlib.import_module("litellm.ocr.main")
-rust_bridge = importlib.import_module("litellm.ocr.rust_bridge")
+rust_bridge = importlib.import_module("litellm.rust_bridge.ocr")
rust_bridge_loader = importlib.import_module("litellm.rust_bridge.loader")
MODEL = "mistral/mistral-ocr-latest"
@@ -49,7 +49,7 @@ class RecordingBridge:
document: dict[str, object],
api_key: str | None,
api_base: str | None,
- custom_llm_provider: str,
+ custom_llm_provider: str | None,
extra_headers: dict[str, object] | None,
optional_params: dict[str, object],
timeout_seconds: float | None,
@@ -81,7 +81,7 @@ class RecordingAsyncBridge:
document: dict[str, object],
api_key: str | None,
api_base: str | None,
- custom_llm_provider: str,
+ custom_llm_provider: str | None,
extra_headers: dict[str, object] | None,
optional_params: dict[str, object],
timeout_seconds: float | None,
@@ -108,7 +108,7 @@ class RaisingBridge:
document: dict[str, object],
api_key: str | None,
api_base: str | None,
- custom_llm_provider: str,
+ custom_llm_provider: str | None,
extra_headers: dict[str, object] | None,
optional_params: dict[str, object],
timeout_seconds: float | None,
@@ -123,7 +123,7 @@ class RaisingAsyncBridge:
document: dict[str, object],
api_key: str | None,
api_base: str | None,
- custom_llm_provider: str,
+ custom_llm_provider: str | None,
extra_headers: dict[str, object] | None,
optional_params: dict[str, object],
timeout_seconds: float | None,
@@ -366,17 +366,78 @@ def test_load_rust_ocr_uses_compiled_extension(monkeypatch):
def test_timeout_to_seconds_handles_float_timeout_and_none():
- assert ocr_main._timeout_to_seconds(12.5) == 12.5
- assert ocr_main._timeout_to_seconds(None) is None
- assert ocr_main._timeout_to_seconds(httpx.Timeout(30.0, read=42.0)) == 42.0
+ assert rust_bridge._timeout_to_seconds(12.5) == 12.5
+ assert rust_bridge._timeout_to_seconds(None) is None
+ assert rust_bridge._timeout_to_seconds(httpx.Timeout(30.0, read=42.0)) == 42.0
-def test_run_rust_ocr_forwards_args_and_wraps_response():
+def test_bridge_wrapper_forwards_prepared_args_and_wraps_response():
+ bridge = RecordingBridge()
+
+ litellm.use_litellm_rust(True, ocr=bridge)
+ response = rust_bridge.ocr(
+ model="mistral-ocr-latest",
+ document=DOCUMENT,
+ api_key="sk-test",
+ api_base="https://proxy.internal",
+ custom_llm_provider="mistral",
+ extra_headers={"Authorization": "Bearer sk-test", "x-trace-id": "trace-1"},
+ optional_params={"include_image_base64": True, "pages": [0]},
+ timeout=12.5,
+ )
+
+ assert response == FAKE_OCR_RESPONSE
+ call = bridge.calls[0]
+ assert call == {
+ "model": "mistral-ocr-latest",
+ "document": DOCUMENT,
+ "api_key": "sk-test",
+ "api_base": "https://proxy.internal",
+ "custom_llm_provider": "mistral",
+ "extra_headers": {
+ "Authorization": "Bearer sk-test",
+ "x-trace-id": "trace-1",
+ },
+ "optional_params": {"include_image_base64": True, "pages": [0]},
+ "timeout_seconds": 12.5,
+ }
+
+
+async def test_bridge_wrapper_forwards_prepared_async_args_and_wraps_response():
+ bridge = RecordingAsyncBridge()
+
+ litellm.use_litellm_rust(True, aocr=bridge)
+ response = await rust_bridge.aocr(
+ model="mistral-ocr-maas",
+ document=DOCUMENT,
+ api_key=None,
+ api_base=None,
+ custom_llm_provider="vertex_ai",
+ extra_headers=None,
+ optional_params={"vertex_project": "project-1"},
+ timeout=httpx.Timeout(30.0, read=42.0),
+ )
+
+ assert response == FAKE_OCR_RESPONSE
+ assert bridge.calls[0] == {
+ "model": "mistral-ocr-maas",
+ "document": DOCUMENT,
+ "api_key": None,
+ "api_base": None,
+ "custom_llm_provider": "vertex_ai",
+ "extra_headers": None,
+ "optional_params": {"vertex_project": "project-1"},
+ "timeout_seconds": 42.0,
+ }
+
+
+def test_run_rust_ocr_prepares_request_and_wraps_response():
bridge = RecordingBridge()
logging_obj = RecordingLogging()
+ litellm.use_litellm_rust(True, ocr=bridge)
response = ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(
logging_obj=logging_obj,
api_base="https://proxy.internal",
@@ -389,8 +450,7 @@ def test_run_rust_ocr_forwards_args_and_wraps_response():
assert isinstance(response, OCRResponse)
assert response.pages[0].markdown == "hello world"
- call = bridge.calls[0]
- assert call == {
+ assert bridge.calls[0] == {
"model": "mistral-ocr-latest",
"document": DOCUMENT,
"api_key": "sk-test",
@@ -406,12 +466,10 @@ def test_run_rust_ocr_forwards_args_and_wraps_response():
def test_run_rust_ocr_resolves_key_via_secret_manager_when_missing():
- """No explicit api_key: the resolver (get_secret_str in production) supplies it,
- so secret-manager backends (AWS/Azure/GCP/Vault) work like the Python path."""
bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(api_key=None, timeout=None),
resolve_api_key=lambda name: (
"sk-from-vault" if name == "MISTRAL_API_KEY" else None
@@ -421,16 +479,34 @@ def test_run_rust_ocr_resolves_key_via_secret_manager_when_missing():
assert bridge.calls[0]["api_key"] == "sk-from-vault"
+def test_run_rust_ocr_prefers_explicit_key_over_resolver():
+ bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
+
+ def _resolver(name: str) -> str | None:
+ raise AssertionError(f"resolver should not be called for {name}")
+
+ ocr_main._run_rust_ocr(
+ prepared_request=build_prepared_request(
+ api_key="sk-explicit",
+ timeout=None,
+ ),
+ resolve_api_key=_resolver,
+ )
+
+ assert bridge.calls[0]["api_key"] == "sk-explicit"
+
+
def test_run_rust_ocr_uses_provider_api_key_env_var():
bridge = RecordingBridge()
resolver_calls = []
+ litellm.use_litellm_rust(True, ocr=bridge)
def _resolver(name):
resolver_calls.append(name)
return "sk-provider-env"
ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(
provider_config=FakeOCRConfig(api_key_env_var="PROVIDER_OCR_API_KEY"),
model="provider-ocr-model",
@@ -446,9 +522,9 @@ def test_run_rust_ocr_uses_provider_api_key_env_var():
def test_prepare_rust_ocr_call_forwards_vertex_routing_metadata():
bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(
custom_llm_provider="vertex_ai",
model="mistral-ocr-maas",
@@ -472,6 +548,7 @@ def test_prepare_rust_ocr_call_forwards_vertex_routing_metadata():
def test_prepare_rust_ocr_call_resolves_vertex_routing_metadata_from_secret_manager():
bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
def _resolver(name: str) -> str | None:
return {
@@ -480,7 +557,6 @@ def test_prepare_rust_ocr_call_resolves_vertex_routing_metadata_from_secret_mana
}.get(name)
ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(
custom_llm_provider="vertex_ai",
model="mistral-ocr-maas",
@@ -495,9 +571,9 @@ def test_prepare_rust_ocr_call_resolves_vertex_routing_metadata_from_secret_mana
def test_prepare_rust_ocr_call_resolves_azure_ai_api_base_from_secret_manager():
bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(
custom_llm_provider="azure_ai",
model="pixtral-12b-2409",
@@ -514,12 +590,12 @@ def test_prepare_rust_ocr_call_resolves_azure_ai_api_base_from_secret_manager():
def test_prepare_rust_ocr_call_resolves_document_intelligence_endpoint():
bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
ocr_main._run_rust_ocr(
- rust_ocr=bridge,
prepared_request=build_prepared_request(
- custom_llm_provider="azure_ai/doc-intelligence",
- model="prebuilt-layout",
+ custom_llm_provider="azure_ai",
+ model="doc-intelligence/prebuilt-layout",
api_base=None,
timeout=None,
),
@@ -533,30 +609,12 @@ def test_prepare_rust_ocr_call_resolves_document_intelligence_endpoint():
assert bridge.calls[0]["api_base"] == "https://document-intelligence.example.com"
-def test_run_rust_ocr_prefers_explicit_key_over_resolver():
- bridge = RecordingBridge()
- resolver_calls = []
-
- def _resolver(name):
- resolver_calls.append(name)
- return "sk-from-vault"
-
- ocr_main._run_rust_ocr(
- rust_ocr=bridge,
- prepared_request=build_prepared_request(api_key="sk-explicit", timeout=None),
- resolve_api_key=_resolver,
- )
-
- assert bridge.calls[0]["api_key"] == "sk-explicit"
- assert resolver_calls == [] # resolver never consulted when a key is supplied
-
-
def test_run_rust_ocr_runs_pre_call_logging():
- """The Rust shortcut must run pre_call so callbacks and spend tracking fire."""
logging_obj = RecordingLogging()
+ bridge = RecordingBridge()
+ litellm.use_litellm_rust(True, ocr=bridge)
ocr_main._run_rust_ocr(
- rust_ocr=RecordingBridge(),
prepared_request=build_prepared_request(
logging_obj=logging_obj,
api_base="https://api.mistral.ai/v1",
@@ -573,7 +631,6 @@ def test_run_rust_ocr_runs_pre_call_logging():
complete_input = additional_args["complete_input_dict"]
assert complete_input["document"] == DOCUMENT
assert complete_input["include_image_base64"] is True
- # The logged request mirrors what Rust sends: resolved URL + headers.
assert additional_args["api_base"] == "https://api.mistral.ai/v1/ocr"
assert additional_args["headers"] == {
"Authorization": "Bearer sk-test",
@@ -594,7 +651,6 @@ def test_ocr_routes_to_rust_when_enabled(fake_bridge):
assert response.pages[0].markdown == "hello world"
assert len(fake_bridge.calls) == 1
call = fake_bridge.calls[0]
- # Provider prefix is stripped before reaching the bridge.
assert call["model"] == "mistral-ocr-latest"
assert call["document"] == DOCUMENT
assert call["api_key"] == "sk-test"
@@ -603,7 +659,6 @@ def test_ocr_routes_to_rust_when_enabled(fake_bridge):
"Authorization": "Bearer sk-test",
"x-trace-id": "trace-1",
}
- # Raw OCR params ride along in optional_params; Rust filters to supported keys.
assert call["optional_params"].get("include_image_base64") is True
@@ -621,6 +676,19 @@ def test_ocr_routes_azure_ai_to_rust_when_enabled(fake_bridge):
assert fake_bridge.calls[0]["custom_llm_provider"] == "azure_ai"
+def test_ocr_rust_path_converts_file_document_before_bridge(fake_bridge):
+ response = litellm.ocr(
+ model=MODEL,
+ document={"type": "file", "file": b"%PDF-1.4", "mime_type": "application/pdf"},
+ api_key="sk-test",
+ )
+
+ assert isinstance(response, OCRResponse)
+ document = fake_bridge.calls[0]["document"]
+ assert document["type"] == "document_url"
+ assert document["document_url"].startswith("data:application/pdf;base64,")
+
+
def test_ocr_exception_type_uses_resolved_provider_context(
monkeypatch: pytest.MonkeyPatch,
):
@@ -694,12 +762,10 @@ def test_ocr_forwards_timeout_to_rust(fake_bridge):
def test_ocr_passes_default_request_timeout_to_rust(fake_bridge):
- """When no explicit timeout is given, the library default (request_timeout)
- must still be forwarded so the Rust path matches the Python path's deadline."""
- from litellm.constants import request_timeout
-
litellm.ocr(model=MODEL, document=DOCUMENT, api_key="sk-test")
+ from litellm.constants import request_timeout
+
assert fake_bridge.calls[0]["timeout_seconds"] == float(request_timeout)
@@ -717,7 +783,7 @@ def test_ocr_does_not_route_to_rust_when_disabled():
def test_ocr_falls_back_to_python_when_bridge_unavailable(monkeypatch):
"""Rust enabled but no bridge available (no injected impl, no compiled wheel):
ocr() must degrade to the Python HTTP handler instead of raising."""
- monkeypatch.setattr(ocr_main, "load_rust_ocr", lambda: None)
+ monkeypatch.setattr(rust_bridge, "load_rust_ocr", lambda: None)
litellm.use_litellm_rust(True) # enabled, but load_rust_ocr() returns None in CI
captured = {}