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]

refactor(rust): update OCR route orchestration (#47216)

yujongleebfcb9a028f7d
diff --git a/litellm-rust/crates/inference-ocr/src/arguments.rs b/litellm-rust/crates/inference-ocr/src/arguments.rs
index 05aa345f01d..1ee61189619 100644
--- a/litellm-rust/crates/inference-ocr/src/arguments.rs
+++ b/litellm-rust/crates/inference-ocr/src/arguments.rs
@@ -44,8 +44,8 @@ pub fn consumed_optional_param_names(
model: &str,
custom_llm_provider: Option<&str>,
) -> Result<Vec<&'static str>, Error> {
- let (model, config) = resolve_provider_config(model, custom_llm_provider)?;
- let provider_fields = config.get_supported_ocr_params(&model);
+ let (provider, config) = resolve_provider_config(model, custom_llm_provider)?;
+ let provider_fields = config.get_supported_ocr_params(provider.model);
let auth_fields: &[&str] = match config {
OcrConfigKind::AwsTextract | OcrConfigKind::AwsTextractAnalyze => AWS_AUTH_OPTION_FIELDS,
OcrConfigKind::AzureAi
diff --git a/litellm-rust/crates/inference-ocr/src/client.rs b/litellm-rust/crates/inference-ocr/src/client.rs
deleted file mode 100644
index 21a4490048d..00000000000
--- a/litellm-rust/crates/inference-ocr/src/client.rs
+++ /dev/null
@@ -1,81 +0,0 @@
-use litellm_host::observation::ObservationSender;
-use std::sync::Arc;
-
-use litellm_host::interceptors::Interceptors;
-use litellm_llms::base_llm::ocr::{error::Error, handler::OcrClient};
-use litellm_llms_types::formats::ocr::LiteLLMOcrResponse;
-
-use super::{
- handler::perform_ocr_request,
- types::{LiteLLMOcrRequest, OcrDocumentInput, ResolvedOcrRequest},
-};
-
-#[derive(Clone)]
-pub struct OcrRoute {
- client: OcrClient,
-}
-
-impl OcrRoute {
- pub fn new(client: OcrClient) -> Self {
- Self { client }
- }
-
- pub async fn execute(
- &self,
- request: LiteLLMOcrRequest,
- interceptors: &impl Interceptors<Error>,
- observers: Option<ObservationSender>,
- ) -> Result<LiteLLMOcrResponse, Error> {
- litellm_host::lifecycle::observe_unary(
- observers.clone(),
- self.run(request, interceptors, observers.as_ref()),
- )
- .await
- }
-
- #[tracing::instrument(name = "litellm.route", skip_all, fields(
- route = "ocr",
- model = %request.model,
- resolved_model = %request.model,
- provider = <&str>::from(request.config.provider()),
- stream = false,
- outcome
- ))]
- pub(super) async fn run(
- &self,
- request: LiteLLMOcrRequest,
- interceptors: &impl Interceptors<Error>,
- observers: Option<&ObservationSender>,
- ) -> Result<LiteLLMOcrResponse, Error> {
- litellm_inference::diagnostic::unary(async {
- let caller_document = matches!(&request.document, OcrDocumentInput::Document(_));
- let prepared = prepare_request_document(request).await?;
- let execute: futures_util::future::BoxFuture<'_, Result<LiteLLMOcrResponse, Error>> =
- Box::pin(perform_ocr_request(
- &self.client,
- prepared,
- interceptors,
- caller_document,
- observers,
- ));
- execute.await
- })
- .await
- }
-}
-
-#[tracing::instrument(name = "litellm.prepare", level = "debug", skip_all)]
-async fn prepare_request_document(
- request: LiteLLMOcrRequest<OcrDocumentInput>,
-) -> Result<ResolvedOcrRequest, Error> {
- if let OcrDocumentInput::Document(_) = &request.document {
- return request.map_document(super::document::prepare_document);
- }
- let logger = litellm_tracing::Logger::current();
- let span = tracing::Span::current();
- tokio::task::spawn_blocking(move || {
- logger.scope(|| span.in_scope(|| request.map_document(super::document::prepare_document)))
- })
- .await
- .map_err(|error| Error::DocumentTask(Arc::new(error)))?
-}
diff --git a/litellm-rust/crates/inference-ocr/src/document.rs b/litellm-rust/crates/inference-ocr/src/document.rs
index ede0ef2a510..0d9a296d289 100644
--- a/litellm-rust/crates/inference-ocr/src/document.rs
+++ b/litellm-rust/crates/inference-ocr/src/document.rs
@@ -1,10 +1,10 @@
-use std::{collections::BTreeMap as Map, io::Read, path::Path};
+use std::{collections::BTreeMap as Map, io::Read, path::Path, sync::Arc};
use base64::{Engine, engine::general_purpose::STANDARD};
use litellm_llms::base_llm::ocr::{error::Error, transformation::OCR_INLINE_MAX_BYTES};
use litellm_llms_types::formats::ocr::OcrDocument;
-use crate::types::OcrDocumentInput;
+use crate::types::{LiteLLMOcrRequest, OcrDocumentInput, ResolvedOcrRequest};
pub fn prepare_document(input: OcrDocumentInput) -> Result<OcrDocument, Error> {
match input {
@@ -24,6 +24,21 @@ pub fn prepare_document(input: OcrDocumentInput) -> Result<OcrDocument, Error> {
}
}
+pub(crate) async fn resolve_document(
+ request: LiteLLMOcrRequest<OcrDocumentInput>,
+) -> Result<ResolvedOcrRequest, Error> {
+ if let OcrDocumentInput::Document(_) = &request.document {
+ return request.map_document(prepare_document);
+ }
+ let logger = litellm_tracing::Logger::current();
+ let span = tracing::Span::current();
+ tokio::task::spawn_blocking(move || {
+ logger.scope(|| span.in_scope(|| request.map_document(prepare_document)))
+ })
+ .await
+ .map_err(|error| Error::DocumentTask(Arc::new(error)))?
+}
+
pub fn read_path_document(path: &Path, mime_type: Option<&str>) -> Result<OcrDocument, Error> {
let mut bytes = Vec::new();
std::fs::File::open(path)
diff --git a/litellm-rust/crates/inference-ocr/src/handler.rs b/litellm-rust/crates/inference-ocr/src/handler.rs
index 51b739f47ba..e9cfc9a8989 100644
--- a/litellm-rust/crates/inference-ocr/src/handler.rs
+++ b/litellm-rust/crates/inference-ocr/src/handler.rs
@@ -4,29 +4,45 @@ use litellm_host::{lifecycle::ExecutionEvent, observation::ObservationSender};
use litellm_llms::base_llm::ocr::{
error::Error,
handler::{CallHooks, OcrClient},
- transformation::PreparedOcrRequest,
+ transformation::{OcrConnection, PreparedOcrRequest},
};
use litellm_llms_types::formats::ocr::LiteLLMOcrResponse;
+use litellm_secrets::source::Secrets;
use serde_json::Value;
-use super::{arguments::is_secret_param, prepare::prepare_request, provider_config::OcrConfigKind};
-use crate::types::ResolvedOcrRequest;
+use super::{arguments::is_secret_param, provider_config::OcrConfigKind};
+use crate::types::{LiteLLMOcrRequest, ResolvedOcrRequest};
-pub(crate) async fn perform_ocr_request(
+pub(crate) async fn execute(
client: &OcrClient,
- request: ResolvedOcrRequest,
+ config: OcrConfigKind,
+ call: ResolvedOcrRequest,
+ secrets: Secrets,
host: &impl Interceptors<Error>,
caller_document: bool,
observers: Option<&ObservationSender>,
) -> Result<LiteLLMOcrResponse, Error> {
- request.response_format()?;
- let config = request.config;
- let secrets = client
- .secret_source()
- .resolve(&config.secret_names())
- .await
- .map_err(|error| Error::Secret(std::sync::Arc::new(error)))?;
- let request = prepare_request(request, caller_document, client, secrets);
+ call.response_format()?;
+ let LiteLLMOcrRequest {
+ model,
+ document,
+ credentials,
+ transport,
+ optional_params,
+ input_sources,
+ azure_ad_token_provider,
+ ..
+ } = call;
+ let resolved = config.resolve_credentials(credentials, &secrets);
+ let request = PreparedOcrRequest {
+ model,
+ document,
+ connection: OcrConnection::new(resolved, transport, client.settings().clone(), secrets),
+ caller_document,
+ optional_params,
+ input_sources,
+ azure_ad_token_provider,
+ };
let interceptors = OcrCallHooks::new(host, &request, config, observers);
config.ocr(client, &request, &interceptors).await
}
@@ -86,3 +102,257 @@ impl<H: Interceptors<Error>> CallHooks<Error> for OcrCallHooks<'_, H> {
Box::pin(self.interceptors.after_provider_response(raw))
}
}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use litellm_core_utils::call_arguments::{CallArguments, compose_body, parse_options};
+ use litellm_llms_types::formats::ocr::OcrResponseFormat;
+ use rstest::rstest;
+ use serde_json::{Value, json};
+ use wiremock::{Mock, MockServer, ResponseTemplate, matchers::any};
+
+ use super::*;
+ use crate::{
+ OcrRoute,
+ types::LiteLLMOcrRequest,
+ wire::{OcrWireRequest, decode_request},
+ };
+
+ fn client() -> OcrClient {
+ OcrClient::for_test(
+ litellm_http::Client::plain_for_test(),
+ litellm_http::Client::no_redirect_for_test(),
+ )
+ .with_secrets(litellm_inference_testing::no_secrets())
+ }
+
+ fn request(model: &str, base: &str, document: Value, options: Value) -> LiteLLMOcrRequest {
+ decode_request(OcrWireRequest {
+ model: model.into(),
+ document,
+ api_key: Some(litellm_auth::SecretValue::new("test-key")),
+ api_base: Some(base.into()),
+ custom_llm_provider: None,
+ extra_headers: None,
+ optional_params: options.as_object().unwrap().clone(),
+ input_sources: Default::default(),
+ timeout_seconds: Some(2.0),
+ })
+ .unwrap()
+ }
+
+ async fn run_request(request: LiteLLMOcrRequest) -> Result<LiteLLMOcrResponse, Error> {
+ OcrRoute::new(client()).execute(request, &(), None).await
+ }
+
+ async fn upstream(request_count: u64, response: Value) -> MockServer {
+ let server = MockServer::start().await;
+ Mock::given(any())
+ .respond_with(ResponseTemplate::new(200).set_body_json(response))
+ .up_to_n_times(request_count)
+ .mount(&server)
+ .await;
+ server
+ }
+
+ fn image(url: &str) -> Value {
+ json!({"type": "image_url", "image_url": url})
+ }
+
+ fn body(request: &wiremock::Request) -> Value {
+ serde_json::from_slice(&request.body).unwrap()
+ }
+
+ fn assert_mistral_request(request: &wiremock::Request) {
+ assert_eq!(
+ request
+ .headers
+ .get("authorization")
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ "Bearer test-key"
+ );
+ assert_eq!(
+ request
+ .headers
+ .get("content-type")
+ .unwrap()
+ .to_str()
+ .unwrap(),
+ "application/json"
+ );
+ assert_eq!(
+ body(request),
+ json!({
+ "model": "mistral-ocr-maas",
+ "document": {"type": "document_url", "document_url": "data:application/pdf;base64,YWJj"},
+ "pages": [0, 2],
+ "include_image_base64": true,
+ "unknown": "preserved"
+ })
+ );
+ }
+
+ #[rstest]
+ #[tokio::test]
+ async fn cohere_body_keeps_native_document_fields_and_untyped_overrides() {
+ let upstream = upstream(
+ 1,
+ json!({"pages": [{"index": 0, "markdown": {"content": "hello"}}]}),
+ )
+ .await;
+ let request = request(
+ "cohere/parse",
+ &upstream.uri(),
+ image("https://example.com/original.png"),
+ json!({
+ "output_format": "markdown", "timeout": 30,
+ "extra_body": {
+ "output_format": {"future": true},
+ "document": {"type": "image_url", "image_url": "https://example.com/a.png",
+ "provider_options": {"nested": [false, 0, null]}}
+ }
+ }),
+ );
+
+ run_request(request).await.unwrap();
+
+ let [request] = upstream
+ .received_requests()
+ .await
+ .unwrap()
+ .try_into()
+ .unwrap();
+ assert_eq!(
+ body(&request),
+ json!({
+ "model": "parse", "output_format": {"future": true},
+ "document": {"type": "image_url", "image_url": "https://example.com/a.png",
+ "provider_options": {"nested": [false, 0, null]}}
+ })
+ );
+ }
+
+ #[rstest]
+ #[tokio::test]
+ async fn explicit_null_options_use_defaults_before_http() {
+ let upstream = upstream(
+ 1,
+ json!({"pages": [{"index": 0, "markdown": {"content": "hello"}}]}),
+ )
+ .await;
+ let request = request(
+ "cohere/parse",
+ &upstream.uri(),
+ image("https://example.com/a.png"),
+ json!({"output_format": null, "req_format": null}),
+ );
+ assert_eq!(
+ request.response_format().unwrap(),
+ OcrResponseFormat::Litellm
+ );
+
+ run_request(request).await.unwrap();
+
+ let [request] = upstream
+ .received_requests()
+ .await
+ .unwrap()
+ .try_into()
+ .unwrap();
+ let body = body(&request);
+ assert_eq!(body["output_format"], "markdown");
+ assert!(body.get("req_format").is_none());
+ }
+
+ #[rstest]
+ #[tokio::test]
+ async fn direct_and_vertex_mistral_build_the_same_request_and_share_normalization() {
+ let upstream = upstream(
+ 2,
+ json!({
+ "pages": [{"index": 0, "markdown": "hello"}],
+ "extra": "preserved"
+ }),
+ )
+ .await;
+ let options = json!({
+ "pages": [0, 2],
+ "include_image_base64": true,
+ "vertex_project": "project-1",
+ "vertex_location": "us-central1",
+ "unknown": "preserved"
+ });
+ let document =
+ json!({"type": "document_url", "document_url": "data:application/pdf;base64,YWJj"});
+ let direct_call = request(
+ "mistral/mistral-ocr-maas",
+ &upstream.uri(),
+ document.clone(),
+ options.clone(),
+ );
+ let vertex_call = request(
+ "vertex_ai/mistral-ocr-maas",
+ &upstream.uri(),
+ document,
+ options,
+ );
+ assert_eq!(direct_call.transport.timeout, Some(Duration::from_secs(2)));
+ assert_eq!(vertex_call.transport.timeout, Some(Duration::from_secs(2)));
+ let direct_response = run_request(direct_call).await.unwrap().into_json();
+ let vertex_response = run_request(vertex_call).await.unwrap().into_json();
+
+ let [direct_http, vertex_http] = upstream
+ .received_requests()
+ .await
+ .unwrap()
+ .try_into()
+ .unwrap();
+ assert_eq!(direct_http.url.path(), "/v1/ocr");
+ assert_eq!(
+ vertex_http.url.path(),
+ "/v1/projects/project-1/locations/us-central1/publishers/mistralai/models/mistral-ocr-maas:rawPredict"
+ );
+ assert_mistral_request(&direct_http);
+ assert_mistral_request(&vertex_http);
+ assert_eq!(direct_response, vertex_response);
+ assert_eq!(direct_response["model"], "mistral-ocr-maas");
+ assert_eq!(direct_response["object"], "ocr");
+ assert_eq!(direct_response["extra"], "preserved");
+ }
+
+ #[derive(serde::Deserialize)]
+ struct KnownParams {
+ pages: Option<Vec<i64>>,
+ }
+
+ #[rstest]
+ fn parsed_provider_params_separates_known_and_extra_params() {
+ let arguments: CallArguments = serde_json::from_value(json!({
+ "pages": [0, 2],
+ "future_ocr_option": true,
+ "extra_body": {"provider_option": "value"}
+ }))
+ .unwrap();
+ let known: KnownParams = parse_options(&arguments).unwrap();
+ assert_eq!(known.pages, Some(vec![0, 2]));
+ assert_eq!(arguments["future_ocr_option"], true);
+ assert_eq!(arguments["extra_body"], json!({"provider_option": "value"}));
+ assert_eq!(
+ arguments
+ .iter()
+ .filter(|(name, _)| name.as_str() != "pages")
+ .count(),
+ 2
+ );
+ assert_eq!(
+ compose_body(&arguments, &json!({"pages": known.pages}), &["pages"]).unwrap(),
+ json!({
+ "pages": [0, 2], "future_ocr_option": true, "provider_option": "value"
+ })
+ );
+ }
+}
diff --git a/litellm-rust/crates/inference-ocr/src/lib.rs b/litellm-rust/crates/inference-ocr/src/lib.rs
index 45b664961b2..5320aa12583 100644
--- a/litellm-rust/crates/inference-ocr/src/lib.rs
+++ b/litellm-rust/crates/inference-ocr/src/lib.rs
@@ -1,10 +1,82 @@
pub mod arguments;
-mod client;
-pub use client::OcrRoute;
pub mod document;
pub(crate) mod handler;
-pub(crate) mod prepare;
pub mod provider_config;
pub mod route;
pub mod types;
pub mod wire;
+
+use std::sync::Arc;
+
+use litellm_host::interceptors::Interceptors;
+use litellm_host::observation::ObservationSender;
+use litellm_llms::base_llm::ocr::{error::Error, handler::OcrClient};
+use litellm_llms_types::formats::ocr::LiteLLMOcrResponse;
+
+use crate::{
+ handler::execute,
+ types::{LiteLLMOcrRequest, OcrDocumentInput},
+};
+
+#[derive(Clone)]
+pub struct OcrRoute {
+ client: OcrClient,
+}
+
+impl OcrRoute {
+ pub fn new(client: OcrClient) -> Self {
+ Self { client }
+ }
+
+ pub async fn execute(
+ &self,
+ request: LiteLLMOcrRequest,
+ interceptors: &impl Interceptors<Error>,
+ observers: Option<ObservationSender>,
+ ) -> Result<LiteLLMOcrResponse, Error> {
+ litellm_host::lifecycle::observe_unary(
+ observers.clone(),
+ self.run(request, interceptors, observers.as_ref()),
+ )
+ .await
+ }
+
+ #[tracing::instrument(name = "litellm.route", skip_all, fields(
+ route = "ocr",
+ model = %call.model,
+ resolved_model = %call.model,
+ provider = <&str>::from(call.config.provider()),
+ stream = false,
+ outcome
+ ))]
+ async fn run(
+ &self,
+ call: LiteLLMOcrRequest,
+ interceptors: &impl Interceptors<Error>,
+ observers: Option<&ObservationSender>,
+ ) -> Result<LiteLLMOcrResponse, Error> {
+ litellm_inference::diagnostic::unary(async {
+ let caller_document = matches!(&call.document, OcrDocumentInput::Document(_));
+ let call = document::resolve_document(call).await?;
+ let config = call.config;
+ let secrets = self
+ .client
+ .secret_source()
+ .resolve(&config.secret_names())
+ .await
+ .map_err(|error| Error::Secret(Arc::new(error)))?;
+ let execute: futures_util::future::BoxFuture<'_, Result<LiteLLMOcrResponse, Error>> =
+ Box::pin(execute(
+ &self.client,
+ config,
+ call,
+ secrets,
+ interceptors,
+ caller_document,
+ observers,
+ ));
+ execute.await
+ })
+ .await
+ }
+}
diff --git a/litellm-rust/crates/inference-ocr/src/prepare.rs b/litellm-rust/crates/inference-ocr/src/prepare.rs
deleted file mode 100644
index 14120606864..00000000000
--- a/litellm-rust/crates/inference-ocr/src/prepare.rs
+++ /dev/null
@@ -1,309 +0,0 @@
-use litellm_auth::{InputSource, SecretValue, Sourced};
-use litellm_core_utils::get_llm_provider_logic::LlmProviders;
-use litellm_llms::base_llm::ocr::{
- handler::OcrClient,
- transformation::{OcrConnection, OcrCredentialInputs, PreparedOcrRequest},
-};
-use litellm_secrets::source::Secrets;
-
-use crate::types::{LiteLLMOcrRequest, ResolvedOcrRequest};
-
-pub(crate) fn prepare_request(
- request: ResolvedOcrRequest,
- caller_document: bool,
- client: &OcrClient,
- secrets: Secrets,
-) -> PreparedOcrRequest {
- let credentials = request.credentials.clone();
- let (preferred_api_key_env, api_base_env) = match request.config.provider() {
- LlmProviders::Mistral => (
- Some("MISTRAL_AZURE_API_KEY"),
- Some("MISTRAL_AZURE_API_BASE"),
- ),
- LlmProviders::AzureAi => (None, Some("AZURE_AI_API_BASE")),
- _ => (None, None),
- };
- let secret = |name: &str| secrets.truthy(name);
- let dynamic_api_key = credentials.dynamic_api_key.or_else(|| {
- credentials.api_key.clone().or_else(|| {
- preferred_api_key_env
- .into_iter()
- .chain(request.config.get_api_key_env_var())
- .find_map(secret)
- .map(|value| Sourced::new(SecretValue::new(value), InputSource::Environment))
- })
- });
- let dynamic_api_base = credentials.dynamic_api_base.or_else(|| {
- credentials.api_base.clone().or_else(|| {
- api_base_env
- .and_then(secret)
- .map(|value| Sourced::new(value, InputSource::Environment))
- })
- });
- let resolved = request
- .config
- .resolve_connection_params(OcrCredentialInputs {
- dynamic_api_key,
- dynamic_api_base,
- ..credentials
- });
- let LiteLLMOcrRequest {
- model,
- document,
- transport,
- optional_params,
- input_sources,
- azure_ad_token_provider,
- ..
- } = request;
- PreparedOcrRequest {
- model,
- document,
- connection: OcrConnection::new(resolved, transport, client.settings().clone(), secrets),
- caller_document,
- optional_params,
- input_sources,
- azure_ad_token_provider,
- }
-}
-
-#[cfg(test)]
-mod tests {
- use std::time::Duration;
-
- use futures_util::future::BoxFuture;
- use litellm_core_utils::call_arguments::{CallArguments, compose_body, parse_options};
- use litellm_host::interceptors::WireRequest;
- use litellm_llms::{
- base_llm::ocr::{
- error::Error,
- handler::{CallHooks, OcrClient},
- transformation::BaseOcrConfig,
- },
- cohere::ocr::transformation::CohereParseConfig,
- mistral::ocr::transformation::MistralOcrConfig,
- vertex_ai::ocr::transformation::VertexAiOcrConfig,
- };
- use litellm_llms_types::formats::ocr::OcrResponseFormat;
- use serde_json::{Value, json};
-
- use super::*;
- use crate::{
- document::prepare_document,
- types::LiteLLMOcrRequest,
- wire::{OcrWireRequest, decode_request},
- };
-
- /// Stands in for a host with no interceptors registered.
- struct NoHooks;
-
- impl CallHooks<Error> for NoHooks {
- fn before_provider_request(
- &self,
- wire: WireRequest,
- ) -> BoxFuture<'_, Result<WireRequest, Error>> {
- Box::pin(async move { Ok(wire) })
- }
-
- fn response_received<'a>(&'a self, _body: &'a [u8]) -> BoxFuture<'a, Result<(), Error>> {
- Box::pin(async { Ok(()) })
- }
- }
-
- fn client() -> OcrClient {
- OcrClient::for_test(
- litellm_http::Client::plain_for_test(),
- litellm_http::Client::no_redirect_for_test(),
- )
- }
-
- fn request(model: &str, base: &str, document: Value, options: Value) -> LiteLLMOcrRequest {
- decode_request(OcrWireRequest {
- model: model.into(),
- document,
- api_key: Some(litellm_auth::SecretValue::new("test-key")),
- api_base: Some(base.into()),
- custom_llm_provider: None,
- extra_headers: None,
- optional_params: options.as_object().unwrap().clone(),
- input_sources: Default::default(),
- timeout_seconds: Some(2.0),
- })
- .unwrap()
- }
-
- fn prepared(request: LiteLLMOcrRequest) -> PreparedOcrRequest {
- prepare_request(
- request.map_document(prepare_document).unwrap(),
- true,
- &client(),
- std::sync::Arc::new(litellm_core_utils::settings::ProcessEnvironment),
- )
- }
-
- fn image(url: &str) -> Value {
- json!({"type": "image_url", "image_url": url})
- }
-
- #[rstest::rstest]
- #[tokio::test]
- async fn cohere_body_keeps_native_document_fields_and_untyped_overrides() {
- let request = request(
- "cohere/parse",
- "https://example.com",
- image("https://example.com/original.png"),
- json!({
- "output_format": "markdown", "timeout": 30,
- "extra_body": {
- "output_format": {"future": true},
- "document": {"type": "image_url", "image_url": "https://example.com/a.png",
- "provider_options": {"nested": [false, 0, null]}}
- }
- }),
- );
-
- let http = CohereParseConfig
- .prepare_request(&prepared(request), &client(), &NoHooks)
- .await
- .unwrap();
-
- let body: Value = serde_json::from_slice(http.body()).unwrap();
- assert_eq!(
- body,
- json!({
- "model": "parse", "output_format": {"future": true},
- "document": {"type": "image_url", "image_url": "https://example.com/a.png",
- "provider_options": {"nested": [false, 0, null]}}
- })
- );
- }
-
- #[rstest::rstest]
- #[tokio::test]
- async fn explicit_null_options_use_defaults_before_http() {
- let request = request(
- "cohere/parse",
- "https://example.com",
- image("https://example.com/a.png"),
- json!({"output_format": null, "req_format": null}),
- );
- assert_eq!(
- request.response_format().unwrap(),
- OcrResponseFormat::Litellm
- );
-
- let http = CohereParseConfig
- .prepare_request(&prepared(request), &client(), &NoHooks)
- .await
- .unwrap();
-
- let body: Value = serde_json::from_slice(http.body()).unwrap();
- assert_eq!(body["output_format"], "markdown");
- assert!(body.get("req_format").is_none());
- }
-
- #[rstest::rstest]
- #[tokio::test]
- async fn direct_and_vertex_mistral_build_the_same_request_and_share_normalization() {
- let options = json!({
- "pages": [0, 2],
- "include_image_base64": true,
- "vertex_project": "project-1",
- "vertex_location": "us-central1",
- "unknown": "preserved"
- });
- let document =
- json!({"type": "document_url", "document_url": "data:application/pdf;base64,YWJj"});
- let direct = prepared(request(
- "mistral/mistral-ocr-maas",
- "https://mistral.test",
- document.clone(),
- options.clone(),
- ));
- let vertex = prepared(request(
- "vertex_ai/mistral-ocr-maas",
- "https://vertex.test",
- document,
- options,
- ));
-
- let direct_http = MistralOcrConfig
- .prepare_request(&direct, &client(), &NoHooks)
- .await
- .unwrap();
- let vertex_http = VertexAiOcrConfig
- .prepare_request(&vertex, &client(), &NoHooks)
- .await
- .unwrap();
-
- assert_eq!(direct_http.url(), "https://mistral.test/v1/ocr");
- assert_eq!(
- vertex_http.url(),
- "https://vertex.test/v1/projects/project-1/locations/us-central1/publishers/mistralai/models/mistral-ocr-maas:rawPredict"
- );
- for http in [&direct_http, &vertex_http] {
- assert_eq!(http.header("authorization").unwrap(), "Bearer test-key");
- assert_eq!(http.header("content-type").unwrap(), "application/json");
- assert_eq!(http.timeout(), Some(Duration::from_secs(2)));
- let body: Value = serde_json::from_slice(http.body()).unwrap();
- assert_eq!(
- body,
- json!({
- "model": "mistral-ocr-maas",
- "document": {"type": "document_url", "document_url": "data:application/pdf;base64,YWJj"},
- "pages": [0, 2],
- "include_image_base64": true,
- "unknown": "preserved"
- })
- );
- }
- let payload = serde_json::to_vec(
- &json!({"pages": [{"index": 0, "markdown": "hello"}], "extra": "preserved"}),
- )
- .unwrap();
- let direct_response = MistralOcrConfig
- .transform_ocr_response(&direct.model, &payload, OcrResponseFormat::Litellm)
- .unwrap()
- .into_json();
- let vertex_response = VertexAiOcrConfig
- .transform_ocr_response(&vertex.model, &payload, OcrResponseFormat::Litellm)
- .unwrap()
- .into_json();
- assert_eq!(direct_response, vertex_response);
- assert_eq!(direct_response["model"], "mistral-ocr-maas");
- assert_eq!(direct_response["object"], "ocr");
- assert_eq!(direct_response["extra"], "preserved");
- }
-
- #[derive(serde::Deserialize)]
- struct KnownParams {
- pages: Option<Vec<i64>>,
- }
-
- #[rstest::rstest]
- fn parsed_provider_params_separates_known_and_extra_params() {
- let arguments: CallArguments = serde_json::from_value(json!({
- "pages": [0, 2],
- "future_ocr_option": true,
- "extra_body": {"provider_option": "value"}
- }))
- .unwrap();
- let known: KnownParams = parse_options(&arguments).unwrap();
- assert_eq!(known.pages, Some(vec![0, 2]));
- assert_eq!(arguments["future_ocr_option"], true);
- assert_eq!(arguments["extra_body"], json!({"provider_option": "value"}));
- assert_eq!(
- arguments
- .iter()
- .filter(|(name, _)| name.as_str() != "pages")
- .count(),
- 2
- );
- assert_eq!(
- compose_body(&arguments, &json!({"pages": known.pages}), &["pages"]).unwrap(),
- json!({
- "pages": [0, 2], "future_ocr_option": true, "provider_option": "value"
- })
- );
- }
-}
diff --git a/litellm-rust/crates/inference-ocr/src/provider_config.rs b/litellm-rust/crates/inference-ocr/src/provider_config.rs
index da708d17b86..2f0346f6e47 100644
--- a/litellm-rust/crates/inference-ocr/src/provider_config.rs
+++ b/litellm-rust/crates/inference-ocr/src/provider_config.rs
@@ -1,5 +1,6 @@
-use litellm_core_utils::get_llm_provider_logic::LlmProviders;
-use litellm_core_utils::get_llm_provider_logic::{CustomLlmProvider, get_custom_llm_provider};
+use litellm_auth::{InputSource, SecretValue, Sourced};
+use litellm_core_utils::get_llm_provider_logic::{LlmProviders, get_custom_llm_provider};
+use litellm_inference::provider::{ResolvedProvider, resolve_llm_provider};
use litellm_llms::{
aws_textract::ocr::{
analyze_transformation::TextractAnalyzeDocumentConfig, common_utils::TextractOperation,
@@ -25,6 +26,7 @@ use litellm_llms::{
},
};
use litellm_llms_types::formats::ocr::{LiteLLMOcrResponse, OcrDocument, OcrResponseFormat};
+use litellm_secrets::source::Secrets;
macro_rules! with_config {
($kind:expr, $config:ident => $body:expr) => {
@@ -115,7 +117,18 @@ impl OcrConfigKind {
}
pub(crate) fn secret_names(self) -> Vec<&'static str> {
- with_config!(self, config => config.secret_names())
+ let names = with_config!(self, config => config.secret_names());
+ let fallback_names: &[&str] = match self.provider() {
+ LlmProviders::Mistral => &["MISTRAL_AZURE_API_KEY", "MISTRAL_AZURE_API_BASE"],
+ LlmProviders::AzureAi => &["AZURE_AI_API_BASE"],
+ _ => &[],
+ };
+ let additional_names = fallback_names
+ .iter()
+ .copied()
+ .filter(|name| !names.contains(name))
+ .collect::<Vec<_>>();
+ names.into_iter().chain(additional_names).collect()
}
pub(crate) fn get_health_check_document(self) -> OcrDocument {
@@ -129,6 +142,43 @@ impl OcrConfigKind {
with_config!(self, config => config.resolve_connection_params(inputs))
}
+ pub(crate) fn resolve_credentials(
+ self,
+ credentials: OcrCredentialInputs,
+ secrets: &Secrets,
+ ) -> ResolvedOcrCredentials {
+ let (preferred_api_key_env, api_base_env) = match self.provider() {
+ LlmProviders::Mistral => (
+ Some("MISTRAL_AZURE_API_KEY"),
+ Some("MISTRAL_AZURE_API_BASE"),
+ ),
+ LlmProviders::AzureAi => (None, Some("AZURE_AI_API_BASE")),
+ _ => (None, None),
+ };
+ let secret = |name: &str| secrets.truthy(name);
+ let dynamic_api_key = credentials.dynamic_api_key.or_else(|| {
+ credentials.api_key.clone().or_else(|| {
+ preferred_api_key_env
+ .into_iter()
+ .chain(self.get_api_key_env_var())
+ .find_map(secret)
+ .map(|value| Sourced::new(SecretValue::new(value), InputSource::Environment))
+ })
+ });
+ let dynamic_api_base = credentials.dynamic_api_base.or_else(|| {
+ credentials.api_base.clone().or_else(|| {
+ api_base_env
+ .and_then(secret)
+ .map(|value| Sourced::new(value, InputSource::Environment))
+ })
+ });
+ self.resolve_connection_params(OcrCredentialInputs {
+ dynamic_api_key,
+ dynamic_api_base,
+ ..credentials
+ })
+ }
+
pub(crate) async fn ocr(
self,
client: &OcrClient,
@@ -164,7 +214,7 @@ pub fn passthrough_response(
endpoint: &str,
body: &[u8],
) -> Result<Option<LiteLLMOcrResponse>, Error> {
- let (model, config) = resolve_provider_config(model, Some("azure_ai"))?;
+ let (provider, config) = resolve_provider_config(model, Some("azure_ai"))?;
let segments: Vec<&str> = endpoint
.split('/')
.filter(|segment| !segment.is_empty())
@@ -173,7 +223,7 @@ pub fn passthrough_response(
OcrConfigKind::AzureAi => segments == AZURE_AI_OCR_PATH,
OcrConfigKind::AzureCohere => segments == AZURE_COHERE_PARSE_PATH,
OcrConfigKind::AzureDocumentIntelligence => {
- segments == AzureDocumentIntelligenceOcrConfig::analyze_path(&model)?
+ segments == AzureDocumentIntelligenceOcrConfig::analyze_path(provider.model)?
}
other => {
let provider: &'static str = other.provider().into();
@@ -183,24 +233,28 @@ pub fn passthrough_response(
if !is_ocr_endpoint {
return Ok(None);
}
- with_config!(config, config => config.transform_ocr_response(&model, body, OcrResponseFormat::Litellm))
+ with_config!(config, config => config.transform_ocr_response(provider.model, body, OcrResponseFormat::Litellm))
.map(Some)
}
-pub(crate) fn resolve_provider_config(
- model: &str,
- custom_llm_provider: Option<&str>,
-) -> Result<(String, OcrConfigKind), Error> {
- let provider =
- get_custom_llm_provider(model, custom_llm_provider).unwrap_or(CustomLlmProvider {
- model,
- custom_llm_provider: LlmProviders::Mistral.into(),
- });
- let llm_provider = provider
- .custom_llm_provider
- .parse::<LlmProviders>()
- .map_err(|_| Error::InvalidProvider(provider.custom_llm_provider.to_string()))?;
- let config = match llm_provider {
+pub(crate) fn resolve_provider_config<'a>(
+ model: &'a str,
+ custom_llm_provider: Option<&'a str>,
+) -> Result<(ResolvedProvider<'a>, OcrConfigKind), Error> {
+ let provider = match resolve_llm_provider(model, custom_llm_provider, "ocr") {
+ Ok(provider) => provider,
+ Err(_) if get_custom_llm_provider(model, custom_llm_provider).is_none() => {
+ ResolvedProvider {
+ model,
+ provider: LlmProviders::Mistral,
+ }
+ }
+ Err(litellm_inference::RouteError::InvalidProvider(provider)) => {
+ return Err(Error::InvalidProvider(provider));
+ }
+ Err(error) => return Err(Error::InvalidProvider(error.to_string())),
+ };
+ let config = match provider.provider {
LlmProviders::AwsTextract => match TextractOperation::from_model(provider.model)? {
TextractOperation::DetectDocumentText => OcrConfigKind::AwsTextract,
TextractOperation::AnalyzeDocument => OcrConfigKind::AwsTextractAnalyze,
@@ -227,11 +281,11 @@ pub(crate) fn resolve_provider_config(
LlmProviders::VertexAi => OcrConfigKind::VertexAi,
_ => {
return Err(Error::InvalidProvider(
- provider.custom_llm_provider.to_string(),
+ <&'static str>::from(provider.provider).to_string(),
));
}
};
- Ok((provider.model.to_string(), config))
+ Ok((provider, config))
}
fn is_document_intelligence_model(model: &str) -> bool {
@@ -243,7 +297,7 @@ fn is_document_intelligence_model(model: &str) -> bool {
mod tests {
use std::collections::HashSet;
- use litellm_auth::{InputSource, Sourced};
+ use litellm_auth::Sourced;
use litellm_llms::{
base_llm::ocr::document::InlineDocument, cohere::ocr::transformation::validate_document,
};
@@ -484,8 +538,8 @@ mod tests {
#[case] expected_config: OcrConfigKind,
) {
let expected_model = qualified_model.split_once('/').unwrap().1;
- let (model, config) = resolve_provider_config(qualified_model, None).unwrap();
- assert_eq!(model, expected_model);
+ let (provider, config) = resolve_provider_config(qualified_model, None).unwrap();
+ assert_eq!(provider.model, expected_model);
assert_eq!(config, expected_config);
}
@@ -528,7 +582,7 @@ mod tests {
expected_config
);
assert_eq!(
- resolve_provider_config(model, None).unwrap().0,
+ resolve_provider_config(model, None).unwrap().0.model,
model.split_once('/').unwrap().1
);
}
diff --git a/litellm-rust/crates/inference-ocr/src/types.rs b/litellm-rust/crates/inference-ocr/src/types.rs
index fda65e3284e..1bd70c06116 100644
--- a/litellm-rust/crates/inference-ocr/src/types.rs
+++ b/litellm-rust/crates/inference-ocr/src/types.rs
@@ -75,6 +75,8 @@ impl OcrConnectionInputs {
pub struct LiteLLMOcrRequest<D = OcrDocumentInput> {
pub model: String,
+ pub(crate) requested_model: String,
+ pub(crate) custom_llm_provider: Option<String>,
pub document: D,
pub credentials: OcrCredentialInputs,
pub transport: OcrTransportConfig,
@@ -91,7 +93,8 @@ impl LiteLLMOcrRequest {
custom_llm_provider: Option<&str>,
optional_params: CallArguments,
) -> Result<Self, Error> {
- let (model, config) = resolve_provider_config(&model, custom_llm_provider)?;
+ let (provider, config) = resolve_provider_config(&model, custom_llm_provider)?;
+ let resolved_model = provider.model.to_owned();
let default_transport = OcrTransportConfig::default();
let max_response_bytes = optional_params
.get("max_response_bytes")
@@ -116,7 +119,9 @@ impl LiteLLMOcrRequest {
.collect();
Ok(Self {
- model,
+ model: resolved_model,
+ requested_model: model,
+ custom_llm_provider: custom_llm_provider.map(str::to_owned),
document: document.into(),
credentials: OcrCredentialInputs::default(),
transport,
@@ -135,6 +140,8 @@ impl<D> LiteLLMOcrRequest<D> {
) -> Result<LiteLLMOcrRequest<T>, E> {
Ok(LiteLLMOcrRequest {
model: self.model,
+ requested_model: self.requested_model,
+ custom_llm_provider: self.custom_llm_provider,
document: map(self.document)?,
credentials: self.credentials,
transport: self.transport,
@@ -148,6 +155,8 @@ impl<D> LiteLLMOcrRequest<D> {
pub fn with_document<T>(self, document: T) -> LiteLLMOcrRequest<T> {
LiteLLMOcrRequest {
model: self.model,
+ requested_model: self.requested_model,
+ custom_llm_provider: self.custom_llm_provider,
document,
credentials: self.credentials,
transport: self.transport,
diff --git a/litellm-rust/crates/inference-ocr/tests/ocr/lifecycle.rs b/litellm-rust/crates/inference-ocr/tests/ocr/lifecycle.rs
index d10a2e23c9a..e413781f1a3 100644
--- a/litellm-rust/crates/inference-ocr/tests/ocr/lifecycle.rs
+++ b/litellm-rust/crates/inference-ocr/tests/ocr/lifecycle.rs
@@ -66,6 +66,19 @@ async fn interception_runs_once_and_observers_receive_ordered_success_events() {
assert_eq!(received(&upstream).await.len(), 1);
}
+#[rstest::rstest]
+#[case::mutated_model("model-b")]
+#[tokio::test]
+async fn provider_request_uses_the_request_model_after_it_is_mutated(#[case] model: &str) {
+ let upstream = upstream([pages_response()]).await;
+ let mut request = ocr_request("mistral/model-a", &upstream.uri(), json!({}));
+ request.model = model.into();
+
+ perform(request).await.unwrap();
+
+ assert_eq!(only_request(&upstream).await.json()["model"], json!(model));
+}
+
#[rstest::rstest]
#[tokio::test]
async fn a_blocking_before_send_prevents_the_call_and_emits_one_failure() {