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]

mistral alignment

Yujong Lee27ccf7326bf0
diff --git a/litellm-rust/crates/core/AGENTS.md b/litellm-rust/crates/core/AGENTS.md
index 9ba7bfb5323..d591d241512 100644
--- a/litellm-rust/crates/core/AGENTS.md
+++ b/litellm-rust/crates/core/AGENTS.md
@@ -1,7 +1,23 @@
litellm-core is the LiteLLM SDK in Rust — it makes the LLM call. Each top-level call is a module under `src/<route>/` exposing a public entrypoint named after the route (`messages::messages()`, the Rust equivalent of `litellm.messages()`): you call it and get a typed non-streaming response back.
-A route module owns everything the call needs: types, the provider template trait, provider transforms (under `providers/`), provider/auth/URL resolution, and the handler that performs the HTTP call. Handlers belong here, never in a host crate.
+A route module owns the call entrypoint, runtime types, provider/auth/URL resolution, and the handler that performs the HTTP call. OCR provider transforms and the base provider trait live under `src/llms/`, mirroring their Python source paths. Other routes still use `src/providers/` and route-local traits. Handlers belong in core, never in a host crate
Not here: serving HTTP (axum routes, extractors), config file reading, rollout state, databases, or host-specific callback execution. Core owns lifecycle sequencing and callback payload construction; hosts execute the selected integrations. Env reads are limited to credential fallback in a route's `prepare.rs`.
Routes (messages, ocr, realtime) and providers (anthropic, mistral, openai) are modules, not crates.
+
+## Python/Rust transformation pairs
+
+Use the base OCR and Mistral OCR pairs as the reference when aligning transformations. Derive `src/<relative_path>.rs` from `litellm/<relative_path>.py`, preserving meaningful basenames such as `messages_transformation`
+
+Keep corresponding operation names and parameter names when their responsibilities match. Rust types retain the Python semantic name with Rust acronym casing (`BaseOCRConfig` / `BaseOcrConfig`, `MistralOCRConfig` / `MistralOcrConfig`). Private Python helpers can drop their leading underscore. Give Rust adapter helpers distinct responsibility names rather than duplicating trait method names
+
+Order OCR config methods as supported parameters, credential metadata and connection resolution, health-check input, parameter mapping, environment validation, URL construction, request transformation, async request transformation, response transformation, async response transformation, and error conversion. Put constants and data types before the config, private helpers after it in operation order, and tests last. Rust-only trait hooks follow the corresponding Python methods
+
+Use trait defaults for unchanged inherited behavior and explicit delegation for shared provider behavior. Keep typed inputs, ownership, `Result`, and async I/O idiomatic. A matching path or symbol identifies the counterpart, not a claim of full behavioral parity
+
+Use named `#[rstest]` cases for independent input/output scenarios instead of loops or repeated calls in one test. Inject reusable setup with `#[fixture]` arguments and use `#[with(...)]` for fixture overrides. Keep assertions about the same result together
+
+For base OCR, Python response models correspond to `src/ocr/types.rs`; Rust context/environment types support the runtime. `BaseOcrConfig::prepare_request` corresponds to Python's HTTP-handler preparation rather than a `BaseOCRConfig` method, and `validate_request_body` is a Rust-only hook
+
+For Mistral, `async_transform_ocr_request` uses the base default in both languages. `resolve_headers` and `build_ocr_url` implement the respective environment and URL operations, and `normalize_response` implements the typed part of response transformation. Existing auth key/header handling and top-level response-extra preservation differ between languages; layout refactors must preserve those behaviors and verify them with the existing tests
diff --git a/litellm-rust/crates/core/src/llms/azure_ai/ocr/transformation.rs b/litellm-rust/crates/core/src/llms/azure_ai/ocr/transformation.rs
index 1a909abc2d6..122f1dbce53 100644
--- a/litellm-rust/crates/core/src/llms/azure_ai/ocr/transformation.rs
+++ b/litellm-rust/crates/core/src/llms/azure_ai/ocr/transformation.rs
@@ -5,7 +5,7 @@ use serde_json::Value;
use crate::call_arguments::CallArguments;
use crate::constants::AZURE_AI_OCR_PATH;
use crate::llms::base_llm::ocr::transformation::{BaseOcrConfig, OcrRequestContext};
-use crate::llms::mistral::ocr::transformation::{MistralOCRConfig, MistralOcrRequest};
+use crate::llms::mistral::ocr::transformation::{MistralOcrConfig, MistralOcrRequest};
use crate::ocr::OcrClient;
use crate::ocr::document::{inline_remote_document, validate_inline_document};
use crate::ocr::prepare::credential_env;
@@ -60,11 +60,11 @@ impl BaseOcrConfig for AzureAIOCRConfig {
params: &OpaqueParams,
headers: &[(String, String)],
) -> Result<MistralOcrRequest, crate::ocr::Error> {
- MistralOCRConfig.transform_ocr_request(model, document, params, headers)
+ MistralOcrConfig.transform_ocr_request(model, document, params, headers)
}
fn get_supported_ocr_params(&self, model: &str) -> &'static [&'static str] {
- MistralOCRConfig.get_supported_ocr_params(model)
+ MistralOcrConfig.get_supported_ocr_params(model)
}
fn map_ocr_params(
@@ -72,7 +72,7 @@ impl BaseOcrConfig for AzureAIOCRConfig {
arguments: &CallArguments,
model: &str,
) -> Result<OpaqueParams, crate::ocr::Error> {
- MistralOCRConfig.map_ocr_params(arguments, model)
+ MistralOcrConfig.map_ocr_params(arguments, model)
}
async fn async_transform_ocr_request(
@@ -98,7 +98,7 @@ impl BaseOcrConfig for AzureAIOCRConfig {
raw_response: &[u8],
request_format: crate::ocr::types::OcrResponseFormat,
) -> Result<LiteLLMOcrResponse, crate::ocr::Error> {
- MistralOCRConfig.transform_ocr_response(model, raw_response, request_format)
+ MistralOcrConfig.transform_ocr_response(model, raw_response, request_format)
}
fn validate_request_body(&self, body: &Value) -> Result<(), crate::ocr::Error> {
diff --git a/litellm-rust/crates/core/src/llms/base_llm/ocr/transformation.rs b/litellm-rust/crates/core/src/llms/base_llm/ocr/transformation.rs
index 8af304b7d8d..4c4b7a066ef 100644
--- a/litellm-rust/crates/core/src/llms/base_llm/ocr/transformation.rs
+++ b/litellm-rust/crates/core/src/llms/base_llm/ocr/transformation.rs
@@ -13,6 +13,8 @@ use crate::ocr::types::{
PreparedOcrRequest, ResolvedOcrCredentials,
};
+const HEALTH_CHECK_PDF_DATA_URI: &str = "data:application/pdf;base64,JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL01lZGlhQm94IFswIDAgNjEyIDc5Ml0KL0NvbnRlbnRzIDQgMCBSCi9SZXNvdXJjZXMgPDwvRm9udCA8PC9GMSAyIDAgUj4+Pj4+PgplbmRvYmoKNCAwIG9iago8PC9MZW5ndGggNDQ+PgpzdHJlYW0KQlQKL0YxIDI0IFRmCjEwMCA3MDAgVGQKKHRlc3QpIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKMiAwIG9iago8PC9UeXBlIC9Gb250Ci9TdWJ0eXBlIC9UeXBlMQovQmFzZUZvbnQgL0hlbHZldGljYT4+CmVuZG9iagoxIDAgb2JqCjw8L1R5cGUgL1BhZ2VzCi9LaWRzIFszIDAgUl0KL0NvdW50IDE+PgplbmRvYmoKNSAwIG9iago8PC9UeXBlIC9DYXRhbG9nCi9QYWdlcyAxIDAgUj4+CmVuZG9iagp0cmFpbGVyCjw8L1NpemUgNgovUm9vdCA1IDAgUj4+CnN0YXJ0eHJlZgozMjQKJSVFT0Y=";
+
/// Output of `validate_environment`: whatever a provider resolves up front
/// (headers at minimum; Vertex also carries the project id).
pub(crate) trait OcrEnvironment: Send + Sync {
@@ -25,13 +27,31 @@ impl OcrEnvironment for Vec<(String, String)> {
}
}
-const HEALTH_CHECK_PDF_DATA_URI: &str = "data:application/pdf;base64,JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlIC9QYWdlCi9QYXJlbnQgMSAwIFIKL01lZGlhQm94IFswIDAgNjEyIDc5Ml0KL0NvbnRlbnRzIDQgMCBSCi9SZXNvdXJjZXMgPDwvRm9udCA8PC9GMSAyIDAgUj4+Pj4+PgplbmRvYmoKNCAwIG9iago8PC9MZW5ndGggNDQ+PgpzdHJlYW0KQlQKL0YxIDI0IFRmCjEwMCA3MDAgVGQKKHRlc3QpIFRqCkVUCmVuZHN0cmVhbQplbmRvYmoKMiAwIG9iago8PC9UeXBlIC9Gb250Ci9TdWJ0eXBlIC9UeXBlMQovQmFzZUZvbnQgL0hlbHZldGljYT4+CmVuZG9iagoxIDAgb2JqCjw8L1R5cGUgL1BhZ2VzCi9LaWRzIFszIDAgUl0KL0NvdW50IDE+PgplbmRvYmoKNSAwIG9iago8PC9UeXBlIC9DYXRhbG9nCi9QYWdlcyAxIDAgUj4+CmVuZG9iagp0cmFpbGVyCjw8L1NpemUgNgovUm9vdCA1IDAgUj4+CnN0YXJ0eHJlZgozMjQKJSVFT0Y=";
+#[derive(Clone, Copy)]
+pub(crate) struct OcrRequestContext<'a> {
+ pub client: &'a OcrClient,
+ pub connection: &'a OcrConnection,
+}
+
+#[derive(Clone, Copy)]
+pub(crate) struct OcrResponseContext<'a> {
+ pub client: &'a OcrClient,
+ pub connection: &'a OcrConnection,
+ pub hooks: &'a Arc<dyn OcrHooks>,
+ pub request_format: OcrResponseFormat,
+ pub url: &'a str,
+ pub headers: &'a [(String, String)],
+}
pub(crate) trait BaseOcrConfig: Send + Sync + Sized + 'static {
type OcrParams: Send + Sync;
type ProviderRequest: Serialize + Send;
type Environment: OcrEnvironment;
+ fn get_supported_ocr_params(&self, _model: &str) -> &'static [&'static str] {
+ &[]
+ }
+
fn get_api_key_env_var(&self) -> Option<&'static str> {
None
}
@@ -56,6 +76,12 @@ pub(crate) trait BaseOcrConfig: Send + Sync + Sized + 'static {
}
}
+ fn map_ocr_params(
+ &self,
+ non_default_params: &CallArguments,
+ model: &str,
+ ) -> Result<Self::OcrParams, crate::ocr::Error>;
+
fn validate_environment(
&self,
request: &PreparedOcrRequest,
@@ -69,16 +95,6 @@ pub(crate) trait BaseOcrConfig: Send + Sync + Sized + 'static {
environment: &Self::Environment,
) -> Result<String, crate::ocr::Error>;
- fn get_supported_ocr_params(&self, _model: &str) -> &'static [&'static str] {
- &[]
- }
-
- fn map_ocr_params(
- &self,
- arguments: &CallArguments,
- model: &str,
- ) -> Result<Self::OcrParams, crate::ocr::Error>;
-
fn transform_ocr_request(
&self,
model: &str,
@@ -193,19 +209,3 @@ pub(crate) fn decode_and_normalize_response<T: DeserializeOwned>(
..normalize(model, decoded.data)?
})
}
-
-#[derive(Clone, Copy)]
-pub(crate) struct OcrRequestContext<'a> {
- pub client: &'a OcrClient,
- pub connection: &'a OcrConnection,
-}
-
-#[derive(Clone, Copy)]
-pub(crate) struct OcrResponseContext<'a> {
- pub client: &'a OcrClient,
- pub connection: &'a OcrConnection,
- pub hooks: &'a Arc<dyn OcrHooks>,
- pub request_format: OcrResponseFormat,
- pub url: &'a str,
- pub headers: &'a [(String, String)],
-}
diff --git a/litellm-rust/crates/core/src/llms/mistral/ocr/transformation.rs b/litellm-rust/crates/core/src/llms/mistral/ocr/transformation.rs
index 0f982e5e88a..71dcf88cd0f 100644
--- a/litellm-rust/crates/core/src/llms/mistral/ocr/transformation.rs
+++ b/litellm-rust/crates/core/src/llms/mistral/ocr/transformation.rs
@@ -3,16 +3,17 @@ use serde_json::Value;
use crate::call_arguments::CallArguments;
use crate::constants::MISTRAL_OCR_API_BASE;
-use crate::llms::base_llm::ocr::transformation::{BaseOcrConfig, OcrRequestContext};
+use crate::llms::base_llm::ocr::transformation::{BaseOcrConfig, decode_and_normalize_response};
use crate::ocr::OcrClient;
use crate::ocr::prepare::credential_env;
use crate::ocr::types::{
- LiteLLMOcrResponse, OcrConnection, OcrDocument, OcrPage, OcrUsageInfo, PreparedOcrRequest,
+ LiteLLMOcrResponse, OcrConnection, OcrDocument, OcrPage, OcrResponseFormat, OcrUsageInfo,
+ PreparedOcrRequest,
};
use crate::params::OpaqueParams;
use crate::url_utils::ApiUrl;
-const MISTRAL_API_KEY_ENV: &str = "MISTRAL_API_KEY";
+const MISTRAL_OCR_API_KEY_ENV_VAR: &str = "MISTRAL_API_KEY";
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(crate) struct MistralOcrRequest {
@@ -24,8 +25,6 @@ pub(crate) struct MistralOcrRequest {
#[derive(Clone, Debug, Default, Deserialize)]
pub(crate) struct MistralOcrResponse {
- #[serde(flatten)]
- pub extra_fields: serde_json::Map<String, Value>,
#[serde(default)]
pub pages: Vec<OcrPage>,
#[serde(
@@ -35,51 +34,19 @@ pub(crate) struct MistralOcrResponse {
pub model: Option<Option<String>>,
pub document_annotation: Option<Value>,
pub usage_info: Option<OcrUsageInfo>,
+
+ #[serde(flatten)]
+ pub extra_fields: serde_json::Map<String, Value>,
}
#[derive(Clone, Debug, Default)]
-pub(crate) struct MistralOCRConfig;
+pub(crate) struct MistralOcrConfig;
-impl BaseOcrConfig for MistralOCRConfig {
+impl BaseOcrConfig for MistralOcrConfig {
type OcrParams = OpaqueParams;
type ProviderRequest = MistralOcrRequest;
type Environment = Vec<(String, String)>;
- fn get_api_key_env_var(&self) -> Option<&'static str> {
- Some(MISTRAL_API_KEY_ENV)
- }
-
- async fn validate_environment(
- &self,
- request: &PreparedOcrRequest,
- _client: &OcrClient,
- ) -> Result<Self::Environment, crate::ocr::Error> {
- self.validate_environment(&request.connection, &credential_env)
- }
-
- fn get_complete_url(
- &self,
- request: &PreparedOcrRequest,
- _params: &Self::OcrParams,
- _environment: &Self::Environment,
- ) -> Result<String, crate::ocr::Error> {
- self.get_complete_url(request.connection.api_base.as_deref())
- }
-
- fn transform_ocr_request(
- &self,
- model: &str,
- document: OcrDocument,
- optional_params: &OpaqueParams,
- _headers: &[(String, String)],
- ) -> Result<MistralOcrRequest, crate::ocr::Error> {
- Ok(MistralOcrRequest {
- model: model.to_string(),
- document,
- params: optional_params.clone(),
- })
- }
-
fn get_supported_ocr_params(&self, _model: &str) -> &'static [&'static str] {
&[
"pages",
@@ -98,78 +65,63 @@ impl BaseOcrConfig for MistralOCRConfig {
]
}
+ fn get_api_key_env_var(&self) -> Option<&'static str> {
+ Some(MISTRAL_OCR_API_KEY_ENV_VAR)
+ }
+
fn map_ocr_params(
&self,
- arguments: &CallArguments,
+ non_default_params: &CallArguments,
model: &str,
) -> Result<OpaqueParams, crate::ocr::Error> {
- Ok(arguments
+ Ok(non_default_params
.select(self.get_supported_ocr_params(model))
.into())
}
- async fn async_transform_ocr_request(
+ async fn validate_environment(
+ &self,
+ request: &PreparedOcrRequest,
+ _client: &OcrClient,
+ ) -> Result<Self::Environment, crate::ocr::Error> {
+ self.resolve_headers(&request.connection, &credential_env)
+ }
+
+ fn get_complete_url(
+ &self,
+ request: &PreparedOcrRequest,
+ _optional_params: &Self::OcrParams,
+ _environment: &Self::Environment,
+ ) -> Result<String, crate::ocr::Error> {
+ self.build_ocr_url(request.connection.api_base.as_deref())
+ }
+
+ fn transform_ocr_request(
&self,
model: &str,
document: OcrDocument,
optional_params: &OpaqueParams,
- headers: &[(String, String)],
- _context: OcrRequestContext<'_>,
+ _headers: &[(String, String)],
) -> Result<MistralOcrRequest, crate::ocr::Error> {
- self.transform_ocr_request(model, document, optional_params, headers)
+ Ok(MistralOcrRequest {
+ model: model.to_string(),
+ document,
+ params: optional_params.clone(),
+ })
}
fn transform_ocr_response(
&self,
model: &str,
raw_response: &[u8],
- request_format: crate::ocr::types::OcrResponseFormat,
+ request_format: OcrResponseFormat,
) -> Result<LiteLLMOcrResponse, crate::ocr::Error> {
- crate::llms::base_llm::ocr::transformation::decode_and_normalize_response(
- model,
- raw_response,
- request_format,
- normalize_response,
- )
+ decode_and_normalize_response(model, raw_response, request_format, normalize_response)
}
}
-pub(crate) fn normalize_response(
- model: &str,
- response: MistralOcrResponse,
-) -> Result<LiteLLMOcrResponse, crate::ocr::Error> {
- let model = match response.model {
- Some(Some(model)) => model,
- Some(None) => {
- return Err(crate::ocr::Error::ResponseField {
- path: "model".into(),
- });
- }
- None => model.to_string(),
- };
- Ok(LiteLLMOcrResponse {
- extra_fields: response.extra_fields,
- document_annotation: response.document_annotation,
- usage_info: response.usage_info,
- ..LiteLLMOcrResponse::new(model, response.pages)
- })
-}
-
-impl MistralOCRConfig {
- fn get_complete_url(&self, api_base: Option<&str>) -> Result<String, crate::ocr::Error> {
- let base = api_base
- .map(str::trim)
- .filter(|base| !base.is_empty())
- .unwrap_or(MISTRAL_OCR_API_BASE);
- ApiUrl::parse(base)
- .and_then(|url| url.complete_path(&["v1", "ocr"]))
- .map(|url| url.into_string())
- .map_err(|_| crate::ocr::Error::RequestField {
- path: "api_base".into(),
- })
- }
-
- fn validate_environment(
+impl MistralOcrConfig {
+ fn resolve_headers(
&self,
connection: &OcrConnection,
env_lookup: &(dyn Fn(&str) -> Option<String> + Sync),
@@ -190,7 +142,7 @@ impl MistralOCRConfig {
})
.ok_or(litellm_auth::Error::MissingApiKey {
provider: "Mistral",
- environment_variable: MISTRAL_API_KEY_ENV,
+ environment_variable: MISTRAL_OCR_API_KEY_ENV_VAR,
})?;
Ok(
std::iter::once(("Authorization".into(), format!("Bearer {api_key}")))
@@ -198,15 +150,69 @@ impl MistralOCRConfig {
.collect(),
)
}
+
+ fn build_ocr_url(&self, api_base: Option<&str>) -> Result<String, crate::ocr::Error> {
+ let base = api_base
+ .map(str::trim)
+ .filter(|base| !base.is_empty())
+ .unwrap_or(MISTRAL_OCR_API_BASE);
+ ApiUrl::parse(base)
+ .and_then(|url| url.complete_path(&["v1", "ocr"]))
+ .map(|url| url.into_string())
+ .map_err(|_| crate::ocr::Error::RequestField {
+ path: "api_base".into(),
+ })
+ }
+}
+
+pub(crate) fn normalize_response(
+ model: &str,
+ response: MistralOcrResponse,
+) -> Result<LiteLLMOcrResponse, crate::ocr::Error> {
+ let model = match response.model {
+ Some(Some(model)) => model,
+ Some(None) => {
+ return Err(crate::ocr::Error::ResponseField {
+ path: "model".into(),
+ });
+ }
+ None => model.to_string(),
+ };
+ Ok(LiteLLMOcrResponse {
+ extra_fields: response.extra_fields,
+ document_annotation: response.document_annotation,
+ usage_info: response.usage_info,
+ ..LiteLLMOcrResponse::new(model, response.pages)
+ })
}
#[cfg(test)]
mod tests {
- use rstest::rstest;
+ use rstest::{fixture, rstest};
use serde_json::{Value, json};
use super::*;
+ #[fixture]
+ fn document() -> OcrDocument {
+ serde_json::from_value(
+ json!({"type":"document_url","document_url":"https://example.com/a.pdf"}),
+ )
+ .unwrap()
+ }
+
+ #[fixture]
+ fn connection(
+ #[default(None)] api_key: Option<&str>,
+ #[default(vec![])] extra_headers: Vec<(String, String)>,
+ ) -> OcrConnection {
+ OcrConnection {
+ api_key: api_key.map(str::to_string),
+ extra_headers,
+ ..OcrConnection::default()
+ }
+ }
+
#[test]
fn explicit_null_model_does_not_use_the_missing_model_default() {
let response = serde_json::from_value(json!({"model":null})).unwrap();
@@ -216,38 +222,38 @@ mod tests {
));
}
- #[test]
- fn response_validates_normalized_shapes_at_the_provider_boundary() {
- for (payload, path) in [
- (json!({"pages":[42]}), "pages[0]"),
- (json!({"pages":[{"index":0}]}), "pages[0]"),
- (
- json!({"pages":[{"index":0,"markdown":42}]}),
- "pages[0].markdown",
- ),
- (
- json!({"pages":[{"index":0,"markdown":"","images":[42]}]}),
- "pages[0].images[0]",
- ),
- (
- json!({"pages":[{"index":0,"markdown":"","dimensions":{"width":1.5}}]}),
- "pages[0].dimensions.width",
- ),
- (
- json!({"usage_info":{"pages_processed":"bad"}}),
- "usage_info.pages_processed",
- ),
- ] {
- let error = crate::ocr::json::decode_response::<MistralOcrResponse>(
- &serde_json::to_vec(&payload).unwrap(),
- false,
- )
- .unwrap_err();
- assert!(matches!(
- error,
- crate::ocr::Error::ResponseField { path: actual } if actual == path
- ));
- }
+ #[rstest]
+ #[case::non_object_page(json!({"pages":[42]}), "pages[0]")]
+ #[case::missing_markdown(json!({"pages":[{"index":0}]}), "pages[0]")]
+ #[case::non_string_markdown(
+ json!({"pages":[{"index":0,"markdown":42}]}),
+ "pages[0].markdown"
+ )]
+ #[case::non_object_image(
+ json!({"pages":[{"index":0,"markdown":"","images":[42]}]}),
+ "pages[0].images[0]"
+ )]
+ #[case::fractional_width(
+ json!({"pages":[{"index":0,"markdown":"","dimensions":{"width":1.5}}]}),
+ "pages[0].dimensions.width"
+ )]
+ #[case::invalid_page_count(
+ json!({"usage_info":{"pages_processed":"bad"}}),
+ "usage_info.pages_processed"
+ )]
+ fn response_validates_normalized_shapes_at_the_provider_boundary(
+ #[case] payload: Value,
+ #[case] path: &str,
+ ) {
+ let error = crate::ocr::json::decode_response::<MistralOcrResponse>(
+ &serde_json::to_vec(&payload).unwrap(),
+ false,
+ )
+ .unwrap_err();
+ assert!(matches!(
+ error,
+ crate::ocr::Error::ResponseField { path: actual } if actual == path
+ ));
}
#[test]
@@ -283,7 +289,7 @@ mod tests {
let input =
serde_json::from_value(json!({"pages":null,"extract_header":false,"unknown":true}))
.unwrap();
- let params = MistralOCRConfig.map_ocr_params(&input, "model").unwrap();
+ let params = MistralOcrConfig.map_ocr_params(&input, "model").unwrap();
assert_eq!(
serde_json::to_value(params).unwrap(),
json!({"pages":null,"extract_header":false})
@@ -292,11 +298,11 @@ mod tests {
assert_eq!(input.get("pages"), Some(&Value::Null));
}
- #[test]
- fn request_transform_uses_already_mapped_params_without_filtering_again() {
+ #[rstest]
+ fn request_transform_uses_already_mapped_params_without_filtering_again(document: OcrDocument) {
let params = serde_json::from_value(json!({"extension":{"nested":null}})).unwrap();
- let body = MistralOCRConfig
- .transform_ocr_request("model", document(), &params, &[])
+ let body = MistralOcrConfig
+ .transform_ocr_request("model", document, &params, &[])
.unwrap();
assert_eq!(
serde_json::to_value(body).unwrap()["extension"],
@@ -307,7 +313,7 @@ mod tests {
#[test]
fn raw_response_transform_keeps_native_payload_separate_from_typed_normalization() {
let raw = br#"{"pages":[{"index":"2","markdown":"text"}],"provider_extension":false}"#;
- let response = MistralOCRConfig
+ let response = MistralOcrConfig
.transform_ocr_response("model", raw, crate::ocr::types::OcrResponseFormat::Native)
.unwrap();
assert_eq!(response.pages[0].index, 2);
@@ -315,27 +321,23 @@ mod tests {
assert_eq!(native["pages"][0]["index"], "2");
assert_eq!(native["provider_extension"], false);
assert_eq!(response.extra_fields["provider_extension"], false);
+ }
+
+ #[rstest]
+ fn raw_response_transform_rejects_invalid_page(
+ #[values(OcrResponseFormat::Litellm, OcrResponseFormat::Native)]
+ request_format: OcrResponseFormat,
+ ) {
assert!(
- MistralOCRConfig
- .transform_ocr_response(
- "model",
- br#"{"pages":[{"index":0}]}"#,
- crate::ocr::types::OcrResponseFormat::Litellm
- )
+ MistralOcrConfig
+ .transform_ocr_response("model", br#"{"pages":[{"index":0}]}"#, request_format)
.is_err()
);
}
fn mapped_params(value: Value) -> Value {
let params = serde_json::from_value(value).unwrap();
- serde_json::to_value(MistralOCRConfig.map_ocr_params(&params, "model").unwrap()).unwrap()
- }
-
- fn document() -> OcrDocument {
- serde_json::from_value(
- json!({"type":"document_url","document_url":"https://example.com/a.pdf"}),
- )
- .unwrap()
+ serde_json::to_value(MistralOcrConfig.map_ocr_params(&params, "model").unwrap()).unwrap()
}
#[rstest]
@@ -456,20 +458,24 @@ mod tests {
#[case("include_blocks", json!(true))]
#[case("include_blocks", json!(false))]
#[case("id", json!("req-123"))]
- fn request_mapping_preserves_supplied_options(#[case] name: &str, #[case] value: Value) {
+ fn request_mapping_preserves_supplied_options(
+ document: OcrDocument,
+ #[case] name: &str,
+ #[case] value: Value,
+ ) {
let arguments = serde_json::from_value(json!({name: value.clone()})).unwrap();
- let params = MistralOCRConfig
+ let params = MistralOcrConfig
.map_ocr_params(&arguments, "model")
.unwrap();
let result = serde_json::to_value(
- MistralOCRConfig
- .transform_ocr_request("model", document(), &params, &[])
+ MistralOcrConfig
+ .transform_ocr_request("model", document.clone(), &params, &[])
.unwrap(),
)
.unwrap();
assert_eq!(
result,
- json!({"model":"model", "document":document(), name:value})
+ json!({"model":"model", "document":document, name:value})
);
}
@@ -482,13 +488,14 @@ mod tests {
#[case("include_blocks", json!(true))]
#[case("pages", json!([0,1]))]
fn transform_ocr_request_includes_each_optional_param(
+ document: OcrDocument,
#[case] name: &str,
#[case] value: Value,
) {
let params: OpaqueParams = serde_json::from_value(json!({name:value.clone()})).unwrap();
let result = serde_json::to_value(
- MistralOCRConfig
- .transform_ocr_request("mistral-ocr-latest", document(), &params, &[])
+ MistralOcrConfig
+ .transform_ocr_request("mistral-ocr-latest", document, &params, &[])
.unwrap(),
)
.unwrap();
@@ -497,7 +504,7 @@ mod tests {
}
#[rstest]
- fn transform_ocr_request_includes_multiple_new_params() {
+ fn transform_ocr_request_includes_multiple_new_params(document: OcrDocument) {
let params: OpaqueParams = serde_json::from_value(json!({
"table_format":"html",
"confidence_scores_granularity":"page",
@@ -505,8 +512,8 @@ mod tests {
}))
.unwrap();
let result = serde_json::to_value(
- MistralOCRConfig
- .transform_ocr_request("mistral-ocr-latest", document(), &params, &[])
+ MistralOcrConfig
+ .transform_ocr_request("mistral-ocr-latest", document, &params, &[])
.unwrap(),
)
.unwrap();
@@ -565,69 +572,60 @@ mod tests {
assert!(result["pages"][0]["dimensions"].is_null());
}
- #[test]
- fn complete_url_defaults_and_dedupes_v1() {
- assert_eq!(
- MistralOCRConfig.get_complete_url(None).unwrap(),
- "https://api.mistral.ai/v1/ocr"
- );
- assert_eq!(
- MistralOCRConfig
- .get_complete_url(Some("https://example.com/v1?tenant=a"))
- .unwrap(),
- "https://example.com/v1/ocr?tenant=a"
- );
- assert_eq!(
- MistralOCRConfig
- .get_complete_url(Some("https://example.com/v1/ocr?tenant=a"))
- .unwrap(),
- "https://example.com/v1/ocr?tenant=a"
- );
+ #[rstest]
+ #[case::default_base(None, "https://api.mistral.ai/v1/ocr")]
+ #[case::versioned_base(
+ Some("https://example.com/v1?tenant=a"),
+ "https://example.com/v1/ocr?tenant=a"
+ )]
+ #[case::complete_endpoint(
+ Some("https://example.com/v1/ocr?tenant=a"),
+ "https://example.com/v1/ocr?tenant=a"
+ )]
+ fn complete_url_defaults_and_dedupes_v1(
+ #[case] api_base: Option<&str>,
+ #[case] expected: &str,
+ ) {
+ assert_eq!(MistralOcrConfig.build_ocr_url(api_base).unwrap(), expected);
}
- #[test]
- fn environment_prefers_explicit_key_then_environment() {
- let explicit = OcrConnection {
- api_key: Some("explicit".into()),
- ..OcrConnection::default()
- };
- assert_eq!(
- MistralOCRConfig
- .validate_environment(&explicit, &|_| Some("environment".into()))
- .unwrap()[0],
- ("Authorization".into(), "Bearer explicit".into())
- );
-
+ #[rstest]
+ #[case::explicit_key(Some("explicit"), "Bearer explicit")]
+ #[case::environment_fallback(None, "Bearer environment")]
+ fn environment_prefers_explicit_key_then_environment(
+ #[case] _api_key: Option<&str>,
+ #[case] expected: &str,
+ #[with(_api_key)] connection: OcrConnection,
+ ) {
assert_eq!(
- MistralOCRConfig
- .validate_environment(&OcrConnection::default(), &|_| Some("environment".into()))
+ MistralOcrConfig
+ .resolve_headers(&connection, &|_| Some("environment".into()))
.unwrap()[0],
- ("Authorization".into(), "Bearer environment".into())
+ ("Authorization".into(), expected.into())
);
}
- #[test]
- fn environment_preserves_forwarded_authorization() {
- let connection = OcrConnection {
- extra_headers: vec![("authorization".into(), "Bearer forwarded".into())],
- ..OcrConnection::default()
- };
+ #[rstest]
+ fn environment_preserves_forwarded_authorization(
+ #[with(None, vec![("authorization".into(), "Bearer forwarded".into())])]
+ connection: OcrConnection,
+ ) {
assert_eq!(
- MistralOCRConfig
- .validate_environment(&connection, &|_| None)
+ MistralOcrConfig
+ .resolve_headers(&connection, &|_| None)
.unwrap(),
connection.extra_headers
);
}
- #[test]
- fn environment_rejects_missing_key() {
+ #[rstest]
+ fn environment_rejects_missing_key(connection: OcrConnection) {
assert!(matches!(
- MistralOCRConfig.validate_environment(&OcrConnection::default(), &|_| None),
+ MistralOcrConfig.resolve_headers(&connection, &|_| None),
Err(crate::ocr::Error::Auth(
litellm_auth::Error::MissingApiKey {
provider: "Mistral",
- environment_variable: MISTRAL_API_KEY_ENV,
+ environment_variable: MISTRAL_OCR_API_KEY_ENV_VAR,
}
))
));
diff --git a/litellm-rust/crates/core/src/llms/vertex_ai/ocr/transformation.rs b/litellm-rust/crates/core/src/llms/vertex_ai/ocr/transformation.rs
index 337fa76cfe2..1183043e9ee 100644
--- a/litellm-rust/crates/core/src/llms/vertex_ai/ocr/transformation.rs
+++ b/litellm-rust/crates/core/src/llms/vertex_ai/ocr/transformation.rs
@@ -6,7 +6,7 @@ use crate::call_arguments::CallArguments;
use crate::llms::base_llm::ocr::transformation::{
BaseOcrConfig, OcrEnvironment, OcrRequestContext,
};
-use crate::llms::mistral::ocr::transformation::{MistralOCRConfig, MistralOcrRequest};
+use crate::llms::mistral::ocr::transformation::{MistralOcrConfig, MistralOcrRequest};
use crate::ocr::OcrClient;
use crate::ocr::document::{inline_remote_document, validate_inline_document};
use crate::ocr::prepare::credential_env;
@@ -68,11 +68,11 @@ impl BaseOcrConfig for VertexAIOCRConfig {
params: &OpaqueParams,
headers: &[(String, String)],
) -> Result<MistralOcrRequest, crate::ocr::Error> {
- MistralOCRConfig.transform_ocr_request(model, document, params, headers)
+ MistralOcrConfig.transform_ocr_request(model, document, params, headers)
}
fn get_supported_ocr_params(&self, model: &str) -> &'static [&'static str] {
- MistralOCRConfig.get_supported_ocr_params(model)
+ MistralOcrConfig.get_supported_ocr_params(model)
}
fn map_ocr_params(
@@ -80,7 +80,7 @@ impl BaseOcrConfig for VertexAIOCRConfig {
arguments: &CallArguments,
model: &str,
) -> Result<OpaqueParams, crate::ocr::Error> {
- MistralOCRConfig.map_ocr_params(arguments, model)
+ MistralOcrConfig.map_ocr_params(arguments, model)
}
async fn async_transform_ocr_request(
@@ -106,7 +106,7 @@ impl BaseOcrConfig for VertexAIOCRConfig {
raw_response: &[u8],
request_format: crate::ocr::types::OcrResponseFormat,
) -> Result<LiteLLMOcrResponse, crate::ocr::Error> {
- MistralOCRConfig.transform_ocr_response(model, raw_response, request_format)
+ MistralOcrConfig.transform_ocr_response(model, raw_response, request_format)
}
fn validate_request_body(&self, body: &Value) -> Result<(), crate::ocr::Error> {
@@ -320,7 +320,7 @@ mod tests {
use std::time::Duration;
use crate::llms::base_llm::ocr::transformation::BaseOcrConfig;
- use crate::llms::mistral::ocr::transformation::MistralOCRConfig;
+ use crate::llms::mistral::ocr::transformation::MistralOcrConfig;
use crate::llms::vertex_ai::ocr::transformation::VertexAIOCRConfig;
use crate::ocr::test_support::ocr_client;
@@ -344,7 +344,7 @@ mod tests {
let vertex = crate::ocr::prepare::prepare_request(
crate::ocr::test_support::resolved_request(vertex),
);
- let direct_http = MistralOCRConfig
+ let direct_http = MistralOcrConfig
.prepare_request(&direct, &client)
.await
.unwrap();
@@ -379,7 +379,7 @@ mod tests {
&json!({"pages": [{"index": 0, "markdown": "hello"}], "extra": "preserved"}),
)
.unwrap();
- let direct_response = MistralOCRConfig
+ let direct_response = MistralOcrConfig
.transform_ocr_response(&direct.model, &payload, Default::default())
.unwrap()
.into_json();
diff --git a/litellm-rust/crates/core/src/ocr/provider_config.rs b/litellm-rust/crates/core/src/ocr/provider_config.rs
index 37cc924fcc0..fcbea54779f 100644
--- a/litellm-rust/crates/core/src/ocr/provider_config.rs
+++ b/litellm-rust/crates/core/src/ocr/provider_config.rs
@@ -10,7 +10,7 @@ use crate::llms::azure_ai::ocr::document_intelligence::transformation::AzureDocu
use crate::llms::azure_ai::ocr::transformation::AzureAIOCRConfig;
use crate::llms::base_llm::ocr::transformation::{BaseOcrConfig, OcrResponseContext};
use crate::llms::cohere::ocr::transformation::CohereParseConfig;
-use crate::llms::mistral::ocr::transformation::MistralOCRConfig;
+use crate::llms::mistral::ocr::transformation::MistralOcrConfig;
use crate::llms::reducto::ocr::transformation::{ReductoParseLegacyConfig, ReductoParseV3Config};
use crate::llms::vertex_ai::ocr::deepseek_transformation::VertexAIDeepSeekOCRConfig;
use crate::llms::vertex_ai::ocr::transformation::VertexAIOCRConfig;
@@ -26,7 +26,7 @@ macro_rules! dispatch_config {
(@arms $config:expr, $method:ident($($argument:expr),*), $($suffix:tt)*) => {
match $config {
OcrConfigKind::Cohere => CohereParseConfig.$method($($argument),*)$($suffix)*,
- OcrConfigKind::Mistral => MistralOCRConfig.$method($($argument),*)$($suffix)*,
+ OcrConfigKind::Mistral => MistralOcrConfig.$method($($argument),*)$($suffix)*,
OcrConfigKind::AzureAi => AzureAIOCRConfig.$method($($argument),*)$($suffix)*,
OcrConfigKind::AzureCohere => AzureAICohereParseConfig.$method($($argument),*)$($suffix)*,
OcrConfigKind::AzureDocumentIntelligence => AzureDocumentIntelligenceOCRConfig.$method($($argument),*)$($suffix)*,
diff --git a/litellm-rust/crates/core/tests/vertex_ai_ocr.rs b/litellm-rust/crates/core/tests/vertex_ai_ocr.rs
index ebee4046e23..1908c7aa347 100644
--- a/litellm-rust/crates/core/tests/vertex_ai_ocr.rs
+++ b/litellm-rust/crates/core/tests/vertex_ai_ocr.rs
@@ -103,7 +103,7 @@ async fn adapters_build_complete_requests_and_share_mistral_normalization() {
use std::time::Duration;
use crate::llms::base_llm::ocr::transformation::BaseOcrConfig;
- use crate::llms::mistral::ocr::transformation::MistralOCRConfig;
+ use crate::llms::mistral::ocr::transformation::MistralOcrConfig;
use crate::llms::vertex_ai::ocr::transformation::VertexAIOCRConfig;
use crate::ocr::test_support::ocr_client;
@@ -125,7 +125,7 @@ async fn adapters_build_complete_requests_and_share_mistral_normalization() {
crate::ocr::prepare::prepare_request(super::test_support::resolved_request(direct));
let vertex =
crate::ocr::prepare::prepare_request(super::test_support::resolved_request(vertex));
- let direct_http = MistralOCRConfig
+ let direct_http = MistralOcrConfig
.prepare_request(&direct, &client)
.await
.unwrap();
@@ -157,7 +157,7 @@ async fn adapters_build_complete_requests_and_share_mistral_normalization() {
}
let payload = json!({"pages": [{"index": 0, "markdown": "hello"}], "extra": "preserved"});
let raw = serde_json::to_vec(&payload).unwrap();
- let direct_response = MistralOCRConfig
+ let direct_response = MistralOcrConfig
.transform_ocr_response(
&direct.model,
&raw,