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]

merge: resolve conflicts with main for anthropic layout rename

Yujong Lee766f45e0eb89
diff --cc litellm-rust/crates/core/src/chat_completions/mod.rs
index b5c231eb42d,2a391f942aa..5f7448bf73a
--- a/litellm-rust/crates/core/src/chat_completions/mod.rs
+++ b/litellm-rust/crates/core/src/chat_completions/mod.rs
@@@ -14,11 -14,14 +14,12 @@@ pub mod conversation
pub(crate) mod handler;
mod prepare;
pub mod response_utils;
+ pub mod streaming;
-pub mod transformation;
pub mod types;
-use serde_json::{Map, Value};
-
use handler::execute_chat_completions_provider_call;
use prepare::{parse_messages, resolve_provider_config, resolve_request};
+use serde_json::{Map, Value};
use types::{ChatCompletionsRequest, ChatCompletionsResponse};
pub async fn chat_completions(
diff --cc litellm-rust/crates/core/src/llms/anthropic/chat/streaming.rs
index 00000000000,c373b666abd..ec44f2c5808
mode 000000,100644..100644
--- a/litellm-rust/crates/core/src/llms/anthropic/chat/streaming.rs
+++ b/litellm-rust/crates/core/src/llms/anthropic/chat/streaming.rs
@@@ -1,0 -1,164 +1,164 @@@
+ use std::collections::HashMap;
+
+ use serde_json::Value;
+
+ use crate::chat_completions::Error;
+ use crate::chat_completions::streaming::StreamTransformer;
+ use crate::chat_completions::types::{
+ ChatCompletionChunk, ChatCompletionThinkingBlock, ChatCompletionToolCallChunk,
+ ChatCompletionsUsage,
+ };
-use crate::providers::anthropic::messages::streaming::{
++use crate::llms::anthropic::experimental_pass_through::messages::streaming::{
+ AnthropicContentBlock, AnthropicContentBlockDelta, AnthropicMessagesStreamEvent,
+ AnthropicStreamUsage,
+ };
+
+ #[derive(Clone, Copy, Debug, Eq, PartialEq)]
+ pub enum AnthropicJsonChunkType {
+ ValidJson,
+ AccumulatedJson,
+ }
+
+ #[derive(Clone, Debug, Eq, PartialEq)]
+ pub enum AnthropicContentBlockType {
+ Text,
+ ToolUse,
+ ServerToolUse,
+ Thinking,
+ RedactedThinking,
+ Compaction,
+ ToolResult(String),
+ Other(String),
+ }
+
+ #[derive(Clone, Debug, PartialEq)]
+ pub struct AnthropicContentBlockDeltaEvent {
+ pub index: u64,
+ pub delta: AnthropicContentBlockDelta,
+ }
+
+ pub struct AnthropicChatCompletionsStreamTransformer {
+ pub content_blocks: Vec<AnthropicContentBlockDeltaEvent>,
+ pub tool_index: i64,
+ pub json_mode: bool,
+ pub speed: Option<String>,
+ pub tool_name_reverse_map: HashMap<String, String>,
+ pub response_id: String,
+ pub served_model: Option<String>,
+ pub is_response_format_tool: bool,
+ pub converted_response_format_tool: bool,
+ pub accumulated_json: String,
+ pub chunk_type: AnthropicJsonChunkType,
+ pub current_content_block_type: Option<AnthropicContentBlockType>,
+ pub web_search_results: Vec<Value>,
+ pub web_search_calls: HashMap<String, Value>,
+ pub compaction_blocks: Vec<Value>,
+ pub reasoning_content_chunks: Vec<String>,
+ pub server_tool_inputs: HashMap<String, Value>,
+ pub tool_results: Vec<Value>,
+ pub current_server_tool_id: Option<String>,
+ pub container_id: Option<String>,
+ }
+
+ impl AnthropicChatCompletionsStreamTransformer {
+ pub fn new(
+ _json_mode: bool,
+ _speed: Option<String>,
+ _tool_name_reverse_map: HashMap<String, String>,
+ ) -> Self {
+ todo!()
+ }
+
+ pub fn check_empty_tool_call_args(&self) -> bool {
+ todo!()
+ }
+
+ pub fn handle_usage(&mut self, _usage: AnthropicStreamUsage) -> ChatCompletionsUsage {
+ todo!()
+ }
+
+ pub fn handle_content_block_delta(
+ &mut self,
+ _index: u64,
+ _delta: AnthropicContentBlockDelta,
+ ) -> (
+ String,
+ Option<ChatCompletionToolCallChunk>,
+ Vec<ChatCompletionThinkingBlock>,
+ Option<Value>,
+ Option<String>,
+ ) {
+ todo!()
+ }
+
+ pub fn handle_content_block_start(
+ &mut self,
+ _index: u64,
+ _content_block: AnthropicContentBlock,
+ ) -> Result<ChatCompletionChunk, Error> {
+ todo!()
+ }
+
+ pub fn handle_json_mode_chunk(
+ &mut self,
+ _text: String,
+ _tool_use: Option<ChatCompletionToolCallChunk>,
+ ) -> (String, Option<ChatCompletionToolCallChunk>) {
+ todo!()
+ }
+
+ pub fn handle_accumulated_json_chunk(
+ &mut self,
+ _data: &str,
+ _is_final: bool,
+ ) -> Result<Option<ChatCompletionChunk>, Error> {
+ todo!()
+ }
+
+ pub fn handle_redacted_thinking_content(
+ &mut self,
+ _content_block: &AnthropicContentBlock,
+ ) -> Vec<ChatCompletionThinkingBlock> {
+ todo!()
+ }
+
+ pub fn web_search_call_snapshot(&self) -> HashMap<String, Value> {
+ todo!()
+ }
+
+ pub fn complete_web_search_call(&mut self, _result: Value) {
+ todo!()
+ }
+
+ pub fn build_code_interpreter_results(&self) -> Vec<Value> {
+ todo!()
+ }
+
+ pub fn handle_message_delta(
+ &mut self,
+ _event: AnthropicMessagesStreamEvent,
+ ) -> (Option<String>, Option<ChatCompletionsUsage>, Option<Value>) {
+ todo!()
+ }
+
+ pub fn chunk_parser(
+ &mut self,
+ _event: AnthropicMessagesStreamEvent,
+ ) -> Result<ChatCompletionChunk, Error> {
+ todo!()
+ }
+ }
+
+ impl StreamTransformer for AnthropicChatCompletionsStreamTransformer {
+ type Input = AnthropicMessagesStreamEvent;
+ type Output = ChatCompletionChunk;
+ type Error = Error;
+
+ fn transform(&mut self, _input: Self::Input) -> Result<Vec<Self::Output>, Self::Error> {
+ todo!()
+ }
+
+ fn finish(&mut self) -> Result<Vec<Self::Output>, Self::Error> {
+ todo!()
+ }
+ }
diff --cc litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/batches.rs
index 00000000000,fcd4a3445c2..762e699acba
mode 000000,100644..100644
--- a/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/batches.rs
+++ b/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/batches.rs
@@@ -1,0 -1,338 +1,338 @@@
+ use serde::{Deserialize, Serialize};
+ use serde_json::Value;
+ use time::OffsetDateTime;
+ use url::Url;
+
++use crate::llms::anthropic::experimental_pass_through::messages::transformation::resolve_anthropic_api_base;
+ use crate::messages::Error;
+ use crate::messages::types::AnthropicMessagesResponse;
-use crate::providers::anthropic::messages::transformation::resolve_anthropic_api_base;
+
+ const BATCHES_PATH_SUFFIX: &str = "/v1/messages/batches";
+
+ #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+ pub struct AnthropicBatchRequestCounts {
+ #[serde(default)]
+ pub processing: u64,
+ #[serde(default)]
+ pub succeeded: u64,
+ #[serde(default)]
+ pub errored: u64,
+ #[serde(default)]
+ pub canceled: u64,
+ #[serde(default)]
+ pub expired: u64,
+ }
+
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ pub struct AnthropicMessageBatch {
+ #[serde(default)]
+ pub id: String,
+ #[serde(default = "default_processing_status")]
+ pub processing_status: String,
+ pub created_at: Option<String>,
+ pub ended_at: Option<String>,
+ pub expires_at: Option<String>,
+ pub cancel_initiated_at: Option<String>,
+ pub archived_at: Option<String>,
+ #[serde(default)]
+ pub request_counts: AnthropicBatchRequestCounts,
+ }
+
+ #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ #[serde(rename_all = "snake_case")]
+ pub enum BatchStatus {
+ InProgress,
+ Cancelling,
+ Completed,
+ }
+
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ pub struct BatchRequestCounts {
+ pub total: u64,
+ pub completed: u64,
+ pub failed: u64,
+ }
+
+ #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+ pub struct LiteLlmMessageBatch {
+ pub id: String,
+ pub object: String,
+ pub endpoint: String,
+ pub input_file_id: String,
+ pub completion_window: String,
+ pub status: BatchStatus,
+ pub output_file_id: String,
+ pub created_at: i64,
+ pub in_progress_at: Option<i64>,
+ pub expires_at: Option<i64>,
+ pub completed_at: Option<i64>,
+ pub expired_at: Option<i64>,
+ pub cancelling_at: Option<i64>,
+ pub cancelled_at: Option<i64>,
+ pub request_counts: BatchRequestCounts,
+ }
+
+ pub trait AnthropicBatchesConfig {
+ fn create_batch_url(
+ &self,
+ api_base: Option<&str>,
+ env_lookup: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<String, Error>;
+
+ fn transform_create_batch_request(&self) -> Result<Value, Error>;
+
+ fn transform_create_batch_response(
+ &self,
+ response: AnthropicMessageBatch,
+ now: i64,
+ ) -> Result<LiteLlmMessageBatch, Error>;
+
+ fn retrieve_batch_url(
+ &self,
+ api_base: Option<&str>,
+ batch_id: &str,
+ env_lookup: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<String, Error>;
+
+ fn transform_retrieve_batch_request(&self) -> Value;
+
+ fn transform_retrieve_batch_response(
+ &self,
+ response: AnthropicMessageBatch,
+ now: i64,
+ ) -> LiteLlmMessageBatch;
+
+ fn transform_batch_results(&self, body: &str) -> Result<Vec<AnthropicMessagesResponse>, Error>;
+ }
+
+ pub struct AnthropicBatchesTransformation;
+
+ pub const ANTHROPIC_BATCHES_TRANSFORMATION: AnthropicBatchesTransformation =
+ AnthropicBatchesTransformation;
+
+ fn default_processing_status() -> String {
+ "in_progress".into()
+ }
+
+ fn timestamp(value: Option<&str>) -> Option<i64> {
+ value
+ .and_then(|value| {
+ OffsetDateTime::parse(value, &time::format_description::well_known::Rfc3339).ok()
+ })
+ .map(OffsetDateTime::unix_timestamp)
+ }
+
+ fn batches_base_url(
+ api_base: Option<&str>,
+ env_lookup: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<Url, Error> {
+ let api_base = resolve_anthropic_api_base(api_base, env_lookup);
+ let api_base = api_base.trim_end_matches('/');
+ let complete_url = if api_base.ends_with(BATCHES_PATH_SUFFIX) {
+ api_base.to_string()
+ } else if let Some(base) = api_base.strip_suffix("/v1/messages") {
+ format!("{base}{BATCHES_PATH_SUFFIX}")
+ } else {
+ format!("{api_base}{BATCHES_PATH_SUFFIX}")
+ };
+ Url::parse(&complete_url)
+ .map_err(|error| Error::InvalidRequest(format!("invalid Anthropic API base: {error}")))
+ }
+
+ impl AnthropicBatchesConfig for AnthropicBatchesTransformation {
+ fn create_batch_url(
+ &self,
+ api_base: Option<&str>,
+ env_lookup: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<String, Error> {
+ Ok(batches_base_url(api_base, env_lookup)?.into())
+ }
+
+ fn transform_create_batch_request(&self) -> Result<Value, Error> {
+ Err(Error::Unsupported("Anthropic message batch creation"))
+ }
+
+ fn transform_create_batch_response(
+ &self,
+ _response: AnthropicMessageBatch,
+ _now: i64,
+ ) -> Result<LiteLlmMessageBatch, Error> {
+ Err(Error::Unsupported("Anthropic message batch creation"))
+ }
+
+ fn retrieve_batch_url(
+ &self,
+ api_base: Option<&str>,
+ batch_id: &str,
+ env_lookup: &dyn Fn(&str) -> Option<String>,
+ ) -> Result<String, Error> {
+ if batch_id.is_empty() {
+ return Err(Error::MissingField("batch_id"));
+ }
+ let mut url = batches_base_url(api_base, env_lookup)?;
+ url.path_segments_mut()
+ .map_err(|_| Error::InvalidRequest("Anthropic API base cannot be a base URL".into()))?
+ .push(batch_id);
+ Ok(url.into())
+ }
+
+ fn transform_retrieve_batch_request(&self) -> Value {
+ Value::Object(Default::default())
+ }
+
+ fn transform_retrieve_batch_response(
+ &self,
+ response: AnthropicMessageBatch,
+ now: i64,
+ ) -> LiteLlmMessageBatch {
+ let created_at = timestamp(response.created_at.as_deref());
+ let ended_at = timestamp(response.ended_at.as_deref());
+ let expires_at = timestamp(response.expires_at.as_deref());
+ let cancel_initiated_at = timestamp(response.cancel_initiated_at.as_deref());
+ let archived_at = timestamp(response.archived_at.as_deref());
+ let status = match response.processing_status.as_str() {
+ "canceling" => BatchStatus::Cancelling,
+ "ended" => BatchStatus::Completed,
+ _ => BatchStatus::InProgress,
+ };
+ let request_counts = BatchRequestCounts {
+ total: response.request_counts.processing
+ + response.request_counts.succeeded
+ + response.request_counts.errored
+ + response.request_counts.canceled
+ + response.request_counts.expired,
+ completed: response.request_counts.succeeded,
+ failed: response.request_counts.errored,
+ };
+
+ LiteLlmMessageBatch {
+ id: response.id.clone(),
+ object: "batch".into(),
+ endpoint: "/v1/messages".into(),
+ input_file_id: "None".into(),
+ completion_window: "24h".into(),
+ status,
+ output_file_id: response.id,
+ created_at: created_at.unwrap_or(now),
+ in_progress_at: (response.processing_status == "in_progress")
+ .then_some(created_at)
+ .flatten(),
+ expires_at,
+ completed_at: (response.processing_status == "ended")
+ .then_some(ended_at)
+ .flatten(),
+ expired_at: archived_at,
+ cancelling_at: (response.processing_status == "canceling")
+ .then_some(cancel_initiated_at)
+ .flatten(),
+ cancelled_at: (response.processing_status == "canceling")
+ .then_some(ended_at)
+ .flatten(),
+ request_counts,
+ }
+ }
+
+ fn transform_batch_results(&self, body: &str) -> Result<Vec<AnthropicMessagesResponse>, Error> {
+ body.lines()
+ .filter(|line| !line.trim().is_empty())
+ .filter_map(|line| serde_json::from_str::<Value>(line.trim()).ok())
+ .map(|record| {
+ serde_json::from_value(record["result"]["message"].clone()).map_err(|error| {
+ Error::InvalidResponse(format!("invalid Anthropic batch result: {error}"))
+ })
+ })
+ .collect()
+ }
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use serde_json::json;
+
+ use super::*;
+
+ #[test]
+ fn builds_and_encodes_message_batch_urls() {
+ assert_eq!(
+ ANTHROPIC_BATCHES_TRANSFORMATION
+ .create_batch_url(None, &|_| None)
+ .unwrap(),
+ "https://api.anthropic.com/v1/messages/batches"
+ );
+ assert_eq!(
+ ANTHROPIC_BATCHES_TRANSFORMATION
+ .create_batch_url(Some("https://proxy.test/v1/messages/batches"), &|_| None)
+ .unwrap(),
+ "https://proxy.test/v1/messages/batches"
+ );
+ assert_eq!(
+ ANTHROPIC_BATCHES_TRANSFORMATION
+ .retrieve_batch_url(Some("https://proxy.test"), "batch/id ?", &|_| None)
+ .unwrap(),
+ "https://proxy.test/v1/messages/batches/batch%2Fid%20%3F"
+ );
+ assert_eq!(
+ ANTHROPIC_BATCHES_TRANSFORMATION.transform_retrieve_batch_request(),
+ json!({})
+ );
+ }
+
+ #[test]
+ fn maps_retrieved_batch_status_counts_and_timestamps_like_python() {
+ let response: AnthropicMessageBatch = serde_json::from_value(json!({
+ "id": "msgbatch_1",
+ "processing_status": "ended",
+ "created_at": "2025-01-01T00:00:00Z",
+ "ended_at": "2025-01-01T00:01:00Z",
+ "expires_at": "not-a-timestamp",
+ "request_counts": {
+ "processing": 1,
+ "succeeded": 2,
+ "errored": 3,
+ "canceled": 4,
+ "expired": 5
+ }
+ }))
+ .unwrap();
+
+ let batch = ANTHROPIC_BATCHES_TRANSFORMATION.transform_retrieve_batch_response(response, 7);
+ assert_eq!(batch.status, BatchStatus::Completed);
+ assert_eq!(batch.created_at, 1_735_689_600);
+ assert_eq!(batch.completed_at, Some(1_735_689_660));
+ assert_eq!(batch.expires_at, None);
+ assert_eq!(
+ batch.request_counts,
+ BatchRequestCounts {
+ total: 15,
+ completed: 2,
+ failed: 3
+ }
+ );
+ }
+
+ #[test]
+ fn extracts_message_responses_from_ndjson_and_skips_non_json_lines() {
+ let body = r#"not-json
+ {"result":{"message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-test","content":[],"stop_reason":"end_turn","stop_sequence":null}}}
+ "#;
+ let messages = ANTHROPIC_BATCHES_TRANSFORMATION
+ .transform_batch_results(body)
+ .unwrap();
+
+ assert_eq!(messages.len(), 1);
+ assert_eq!(messages[0].id, "msg_1");
+ }
+
+ #[test]
+ fn preserves_python_placeholder_for_batch_creation() {
+ assert!(matches!(
+ ANTHROPIC_BATCHES_TRANSFORMATION.transform_create_batch_request(),
+ Err(Error::Unsupported("Anthropic message batch creation"))
+ ));
+ let response: AnthropicMessageBatch = serde_json::from_value(json!({})).unwrap();
+ assert!(matches!(
+ ANTHROPIC_BATCHES_TRANSFORMATION.transform_create_batch_response(response, 0),
+ Err(Error::Unsupported("Anthropic message batch creation"))
+ ));
+ }
+ }
diff --cc litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/count_tokens.rs
index 00000000000,8ad96e2ead5..8ad96e2ead5
mode 000000,100644..100644
--- a/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/count_tokens.rs
+++ b/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/count_tokens.rs
diff --cc litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/streaming.rs
index 00000000000,ab087e50805..ab087e50805
mode 000000,100644..100644
--- a/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/streaming.rs
+++ b/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/streaming.rs
diff --cc litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/transformation.rs
index a4dc7d2aaa3,0f1294a412c..6a1a1613ffc
--- a/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/transformation.rs
+++ b/litellm-rust/crates/core/src/llms/anthropic/experimental_pass_through/messages/transformation.rs
@@@ -62,6 -40,39 +59,16 @@@ pub fn complete_anthropic_url
format!("{api_base}{MESSAGES_PATH_SUFFIX}")
}
+ pub fn resolve_anthropic_api_base(
+ api_base: Option<&str>,
+ env_lookup: &dyn Fn(&str) -> Option<String>,
+ ) -> String {
+ non_empty(api_base)
+ .map(str::to_string)
+ .or_else(|| env_lookup(ANTHROPIC_API_BASE_ENV).filter(|value| !value.trim().is_empty()))
+ .unwrap_or_else(|| DEFAULT_ANTHROPIC_API_BASE.to_string())
+ }
+
-impl AnthropicMessagesProviderConfig for AnthropicMessagesConfig {
- fn complete_url(
- &self,
- api_base: Option<&str>,
- _model: &str,
- env_lookup: &dyn Fn(&str) -> Option<String>,
- ) -> Result<String, Error> {
- Ok(complete_anthropic_url(api_base, env_lookup))
- }
-
- fn resolve_api_key(
- &self,
- api_key: Option<&str>,
- env_lookup: &dyn Fn(&str) -> Option<String>,
- ) -> Result<String, Error> {
- resolve_anthropic_api_key(api_key, env_lookup).map_err(Error::from)
- }
-
- fn auth_strategy(&self) -> MessagesAuthStrategy {
- MessagesAuthStrategy::Header("x-api-key")
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --cc litellm-rust/crates/python-bridge/src/errors.rs
index d54b2755e89,3b67280ae46..93b68dd952f
--- a/litellm-rust/crates/python-bridge/src/errors.rs
+++ b/litellm-rust/crates/python-bridge/src/errors.rs
@@@ -35,23 -35,18 +35,20 @@@ pub(crate) fn responses_error_to_pyerr(
pub(crate) fn core_error_to_pyerr(error: Error) -> PyErr {
let value_error = match &error {
- Error::Ocr(error) => matches!(
- error,
- ocr::Error::Auth(_)
- | ocr::Error::InvalidProvider(_)
- | ocr::Error::InvalidRequest(_)
- | ocr::Error::InvalidType { .. }
- | ocr::Error::MissingField(_)
- | ocr::Error::MissingDocumentUrl
- ),
+ Error::Ocr(error) => {
+ error.is_request()
+ || matches!(
+ error,
+ ocr::Error::Auth(_)
+ | ocr::Error::InvalidProvider(_)
+ | ocr::Error::InvalidRequest(_)
+ | ocr::Error::MissingField(_)
+ | ocr::Error::MissingDocumentUrl
+ )
+ }
Error::Messages(error) => match error {
messages::Error::Auth(source) => auth_is_value_error(source),
- messages::Error::InvalidProvider(_)
- | messages::Error::InvalidRequest(_)
- | messages::Error::Headers(_) => true,
- _ => false,
+ _ => error.is_request(),
},
Error::AudioTranscription(error) => match error {
audio_transcription::Error::Auth(source) => auth_is_value_error(source),