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

Ishaan Jaffer9b4b846af9b2
diff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.py
index f045cba5701..10597d6e713 100644
--- a/litellm/integrations/arize/_utils.py
+++ b/litellm/integrations/arize/_utils.py
@@ -88,17 +88,123 @@ class ArizeOTELAttributes(BaseLLMObsOTELAttributes):
)
+def _set_tool_attributes(span: "Span", optional_params: dict):
+ """Helper to set tool and function call attributes on span."""
+ from litellm.integrations._types.open_inference import (
+ MessageAttributes,
+ SpanAttributes,
+ ToolCallAttributes,
+ )
+
+ tools = optional_params.get("tools")
+ if tools:
+ for idx, tool in enumerate(tools):
+ function = tool.get("function")
+ if not function:
+ continue
+ prefix = f"{SpanAttributes.LLM_TOOLS}.{idx}"
+ safe_set_attribute(
+ span, f"{prefix}.{SpanAttributes.TOOL_NAME}", function.get("name")
+ )
+ safe_set_attribute(
+ span,
+ f"{prefix}.{SpanAttributes.TOOL_DESCRIPTION}",
+ function.get("description"),
+ )
+ safe_set_attribute(
+ span,
+ f"{prefix}.{SpanAttributes.TOOL_PARAMETERS}",
+ json.dumps(function.get("parameters")),
+ )
+
+ functions = optional_params.get("functions")
+ if functions:
+ for idx, function in enumerate(functions):
+ prefix = f"{MessageAttributes.MESSAGE_TOOL_CALLS}.{idx}"
+ safe_set_attribute(
+ span,
+ f"{prefix}.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}",
+ function.get("name"),
+ )
+
+
+def _set_response_attributes(span: "Span", response_obj):
+ """Helper to set response output and token usage attributes on span."""
+ from litellm.integrations._types.open_inference import (
+ MessageAttributes,
+ SpanAttributes,
+ )
+
+ if not hasattr(response_obj, "get"):
+ return
+
+ for idx, choice in enumerate(response_obj.get("choices", [])):
+ response_message = choice.get("message", {})
+ safe_set_attribute(
+ span,
+ SpanAttributes.OUTPUT_VALUE,
+ response_message.get("content", ""),
+ )
+ prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{idx}"
+ safe_set_attribute(
+ span,
+ f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",
+ response_message.get("role"),
+ )
+ safe_set_attribute(
+ span,
+ f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",
+ response_message.get("content", ""),
+ )
+
+ output_items = response_obj.get("output", [])
+ if output_items:
+ for i, item in enumerate(output_items):
+ prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{i}"
+ if hasattr(item, "type"):
+ item_type = item.type
+ if item_type == "reasoning" and hasattr(item, "summary"):
+ for summary in item.summary:
+ if hasattr(summary, "text"):
+ safe_set_attribute(
+ span,
+ f"{prefix}.{MessageAttributes.MESSAGE_REASONING_SUMMARY}",
+ summary.text,
+ )
+ elif item_type == "message" and hasattr(item, "content"):
+ message_content = ""
+ content_list = item.content
+ if content_list and len(content_list) > 0:
+ first_content = content_list[0]
+ message_content = getattr(first_content, "text", "")
+ message_role = getattr(item, "role", "assistant")
+ safe_set_attribute(span, SpanAttributes.OUTPUT_VALUE, message_content)
+ safe_set_attribute(span, f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}", message_content)
+ safe_set_attribute(span, f"{prefix}.{MessageAttributes.MESSAGE_ROLE}", message_role)
+
+ usage = response_obj and response_obj.get("usage")
+ if usage:
+ safe_set_attribute(span, SpanAttributes.LLM_TOKEN_COUNT_TOTAL, usage.get("total_tokens"))
+ completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens")
+ if completion_tokens:
+ safe_set_attribute(span, SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, completion_tokens)
+ prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens")
+ if prompt_tokens:
+ safe_set_attribute(span, SpanAttributes.LLM_TOKEN_COUNT_PROMPT, prompt_tokens)
+ reasoning_tokens = usage.get("output_tokens_details", {}).get("reasoning_tokens")
+ if reasoning_tokens:
+ safe_set_attribute(span, SpanAttributes.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING, reasoning_tokens)
+
+
def set_attributes(
span: "Span", kwargs, response_obj, attributes: Type[BaseLLMObsOTELAttributes]
-): # noqa: PLR0915
+):
"""
Populates span with OpenInference-compliant LLM attributes for Arize and Phoenix tracing.
"""
from litellm.integrations._types.open_inference import (
- MessageAttributes,
OpenInferenceSpanKindValues,
SpanAttributes,
- ToolCallAttributes,
)
try:
@@ -110,11 +216,6 @@ def set_attributes(
if standard_logging_payload is None:
raise ValueError("standard_logging_object not found in kwargs")
- #############################################
- ############ LLM CALL METADATA ##############
- #############################################
-
- # Set custom metadata for observability and trace enrichment.
metadata = (
standard_logging_payload.get("metadata")
if standard_logging_payload
@@ -123,253 +224,47 @@ def set_attributes(
if metadata is not None:
safe_set_attribute(span, SpanAttributes.METADATA, safe_dumps(metadata))
- #############################################
- ########## LLM Request Attributes ###########
- #############################################
-
- # The name of the LLM a request is being made to.
if kwargs.get("model"):
- safe_set_attribute(
- span,
- SpanAttributes.LLM_MODEL_NAME,
- kwargs.get("model"),
- )
-
- # The LLM request type.
- safe_set_attribute(
- span,
- "llm.request.type",
- standard_logging_payload["call_type"],
- )
+ safe_set_attribute(span, SpanAttributes.LLM_MODEL_NAME, kwargs.get("model"))
- # The Generative AI Provider: Azure, OpenAI, etc.
- safe_set_attribute(
- span,
- SpanAttributes.LLM_PROVIDER,
- litellm_params.get("custom_llm_provider", "Unknown"),
- )
+ safe_set_attribute(span, "llm.request.type", standard_logging_payload["call_type"])
+ safe_set_attribute(span, SpanAttributes.LLM_PROVIDER, litellm_params.get("custom_llm_provider", "Unknown"))
- # The maximum number of tokens the LLM generates for a request.
if optional_params.get("max_tokens"):
- safe_set_attribute(
- span,
- "llm.request.max_tokens",
- optional_params.get("max_tokens"),
- )
-
- # The temperature setting for the LLM request.
+ safe_set_attribute(span, "llm.request.max_tokens", optional_params.get("max_tokens"))
if optional_params.get("temperature"):
- safe_set_attribute(
- span,
- "llm.request.temperature",
- optional_params.get("temperature"),
- )
-
- # The top_p sampling setting for the LLM request.
+ safe_set_attribute(span, "llm.request.temperature", optional_params.get("temperature"))
if optional_params.get("top_p"):
- safe_set_attribute(
- span,
- "llm.request.top_p",
- optional_params.get("top_p"),
- )
+ safe_set_attribute(span, "llm.request.top_p", optional_params.get("top_p"))
- # Indicates whether response is streamed.
- safe_set_attribute(
- span,
- "llm.is_streaming",
- str(optional_params.get("stream", False)),
- )
+ safe_set_attribute(span, "llm.is_streaming", str(optional_params.get("stream", False)))
- # Logs the user ID if present.
if optional_params.get("user"):
- safe_set_attribute(
- span,
- "llm.user",
- optional_params.get("user"),
- )
+ safe_set_attribute(span, "llm.user", optional_params.get("user"))
- # The unique identifier for the completion.
if response_obj and response_obj.get("id"):
safe_set_attribute(span, "llm.response.id", response_obj.get("id"))
-
- # The model used to generate the response.
if response_obj and response_obj.get("model"):
- safe_set_attribute(
- span,
- "llm.response.model",
- response_obj.get("model"),
- )
+ safe_set_attribute(span, "llm.response.model", response_obj.get("model"))
- # Required by OpenInference to mark span as LLM kind.
- safe_set_attribute(
- span,
- SpanAttributes.OPENINFERENCE_SPAN_KIND,
- OpenInferenceSpanKindValues.LLM.value,
- )
+ safe_set_attribute(span, SpanAttributes.OPENINFERENCE_SPAN_KIND, OpenInferenceSpanKindValues.LLM.value)
attributes.set_messages(span, kwargs)
- # Capture tools (function definitions) used in the LLM call.
- tools = optional_params.get("tools")
- if tools:
- for idx, tool in enumerate(tools):
- function = tool.get("function")
- if not function:
- continue
- prefix = f"{SpanAttributes.LLM_TOOLS}.{idx}"
- safe_set_attribute(
- span, f"{prefix}.{SpanAttributes.TOOL_NAME}", function.get("name")
- )
- safe_set_attribute(
- span,
- f"{prefix}.{SpanAttributes.TOOL_DESCRIPTION}",
- function.get("description"),
- )
- safe_set_attribute(
- span,
- f"{prefix}.{SpanAttributes.TOOL_PARAMETERS}",
- json.dumps(function.get("parameters")),
- )
+ _set_tool_attributes(span=span, optional_params=optional_params)
- # Capture tool calls made during function-calling LLM flows.
- functions = optional_params.get("functions")
- if functions:
- for idx, function in enumerate(functions):
- prefix = f"{MessageAttributes.MESSAGE_TOOL_CALLS}.{idx}"
- safe_set_attribute(
- span,
- f"{prefix}.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}",
- function.get("name"),
- )
-
- # Capture invocation parameters and user ID if available.
model_params = (
standard_logging_payload.get("model_parameters")
if standard_logging_payload
else None
)
if model_params:
- # The Generative AI Provider: Azure, OpenAI, etc.
- safe_set_attribute(
- span,
- SpanAttributes.LLM_INVOCATION_PARAMETERS,
- safe_dumps(model_params),
- )
-
+ safe_set_attribute(span, SpanAttributes.LLM_INVOCATION_PARAMETERS, safe_dumps(model_params))
if model_params.get("user"):
user_id = model_params.get("user")
if user_id is not None:
safe_set_attribute(span, SpanAttributes.USER_ID, user_id)
- #############################################
- ########## LLM Response Attributes ##########
- #############################################
-
- # Captures response tokens, message, and content.
- if hasattr(response_obj, "get"):
- # Handle chat completions API (choices field)
- for idx, choice in enumerate(response_obj.get("choices", [])):
- response_message = choice.get("message", {})
- safe_set_attribute(
- span,
- SpanAttributes.OUTPUT_VALUE,
- response_message.get("content", ""),
- )
-
- # This shows up under `output_messages` tab on the span page.
- prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{idx}"
- safe_set_attribute(
- span,
- f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",
- response_message.get("role"),
- )
- safe_set_attribute(
- span,
- f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",
- response_message.get("content", ""),
- )
-
- # Handle responses API (output field)
- output_items = response_obj.get("output", [])
- if output_items:
- for i, item in enumerate(output_items):
- prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{i}"
-
- if hasattr(item, "type"):
- item_type = item.type
-
- # Extract reasoning summary
- if item_type == "reasoning" and hasattr(item, "summary"):
- for summary in item.summary:
- if hasattr(summary, "text"):
- safe_set_attribute(
- span,
- f"{prefix}.{MessageAttributes.MESSAGE_REASONING_SUMMARY}",
- summary.text,
- )
-
- # Extract message content
- elif item_type == "message" and hasattr(item, "content"):
- message_content = ""
-
- content_list = item.content
- if content_list and len(content_list) > 0:
- first_content = content_list[0]
- message_content = getattr(first_content, "text", "")
- message_role = getattr(item, "role", "assistant")
-
- safe_set_attribute(
- span,
- SpanAttributes.OUTPUT_VALUE,
- message_content,
- )
- safe_set_attribute(
- span,
- f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}",
- message_content,
- )
- safe_set_attribute(
- span,
- f"{prefix}.{MessageAttributes.MESSAGE_ROLE}",
- message_role,
- )
-
- # Token usage info.
- usage = response_obj and response_obj.get("usage")
- if usage:
- safe_set_attribute(
- span,
- SpanAttributes.LLM_TOKEN_COUNT_TOTAL,
- usage.get("total_tokens"),
- )
-
- # The number of tokens used in the LLM response (completion).
- # Responses API uses "output_tokens", chat completions uses "completion_tokens"
- completion_tokens = usage.get("completion_tokens") or usage.get("output_tokens")
- if completion_tokens:
- safe_set_attribute(
- span,
- SpanAttributes.LLM_TOKEN_COUNT_COMPLETION,
- completion_tokens,
- )
-
- # The number of tokens used in the LLM prompt.
- # Responses API uses "input_tokens", chat completions uses "prompt_tokens"
- prompt_tokens = usage.get("prompt_tokens") or usage.get("input_tokens")
- if prompt_tokens:
- safe_set_attribute(
- span,
- SpanAttributes.LLM_TOKEN_COUNT_PROMPT,
- prompt_tokens,
- )
-
- # The number of reasoning tokens in the output, if available.
- reasoning_tokens = usage.get("output_tokens_details", {}).get("reasoning_tokens")
- if reasoning_tokens:
- safe_set_attribute(
- span,
- SpanAttributes.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING,
- reasoning_tokens,
- )
+ _set_response_attributes(span=span, response_obj=response_obj)
except Exception as e:
verbose_logger.error(
diff --git a/litellm/integrations/langfuse/langfuse_otel.py b/litellm/integrations/langfuse/langfuse_otel.py
index fc010928101..0ca430e1334 100644
--- a/litellm/integrations/langfuse/langfuse_otel.py
+++ b/litellm/integrations/langfuse/langfuse_otel.py
@@ -87,31 +87,10 @@ class LangfuseOtelLogger(OpenTelemetry):
return metadata
@staticmethod
- def _set_langfuse_specific_attributes(span: Span, kwargs, response_obj):
- """
- Sets Langfuse specific metadata attributes onto the OTEL span.
-
- All keys supported by the vanilla Langfuse integration are mapped to
- OTEL-safe attribute names defined in LangfuseSpanAttributes. Complex
- values (lists/dicts) are serialised to JSON strings for OTEL
- compatibility.
- """
+ def _set_metadata_attributes(span: Span, metadata: dict):
+ """Helper to set metadata attributes from mapping."""
from litellm.integrations.arize._utils import safe_set_attribute
- from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
-
- # 1) Environment variable override
- langfuse_environment = os.environ.get("LANGFUSE_TRACING_ENVIRONMENT")
- if langfuse_environment:
- safe_set_attribute(
- span,
- LangfuseSpanAttributes.LANGFUSE_ENVIRONMENT.value,
- langfuse_environment,
- )
-
- # 2) Dynamic metadata from kwargs / headers
- metadata = LangfuseOtelLogger._extract_langfuse_metadata(kwargs)
- # Mapping from metadata key -> OTEL attribute enum
mapping = {
"generation_name": LangfuseSpanAttributes.GENERATION_NAME,
"generation_id": LangfuseSpanAttributes.GENERATION_ID,
@@ -135,7 +114,6 @@ class LangfuseOtelLogger(OpenTelemetry):
for key, enum_attr in mapping.items():
if key in metadata and metadata[key] is not None:
value = metadata[key]
- # Lists / dicts must be stringified for OTEL
if isinstance(value, (list, dict)):
try:
value = json.dumps(value)
@@ -143,117 +121,105 @@ class LangfuseOtelLogger(OpenTelemetry):
value = str(value)
safe_set_attribute(span, enum_attr.value, value)
- # 3) Set observation input/output for better UI display
- #
- # These Langfuse-specific attributes provide better UI display,
- # especially for tool calls and function calling.
- # Set observation input (messages)
- messages = kwargs.get("messages")
- if messages:
- safe_set_attribute(
- span,
- LangfuseSpanAttributes.OBSERVATION_INPUT.value,
- safe_dumps(messages),
- )
+ @staticmethod
+ def _set_observation_output(span: Span, response_obj):
+ """Helper to set observation output attributes."""
+ from litellm.integrations.arize._utils import safe_set_attribute
+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
- # Set observation output (response with tool_calls if present)
- if response_obj and hasattr(response_obj, "get"):
- # Handle chat completions API (choices field)
- choices = response_obj.get("choices", [])
- if choices:
- # Extract the first choice's message
- first_choice = choices[0]
- message = first_choice.get("message", {})
-
- # Check if there are tool_calls
- tool_calls = message.get("tool_calls")
- if tool_calls:
- # Transform tool_calls to Langfuse-expected format
- transformed_tool_calls = []
- for tool_call in tool_calls:
- function = tool_call.get("function", {})
- arguments_str = function.get("arguments", "{}")
-
- # Parse arguments from JSON string to object
- try:
- arguments_obj = (
- json.loads(arguments_str)
- if isinstance(arguments_str, str)
- else arguments_str
- )
- except json.JSONDecodeError:
- arguments_obj = {}
-
- # Create Langfuse-compatible tool call object
+ if not response_obj or not hasattr(response_obj, "get"):
+ return
+
+ choices = response_obj.get("choices", [])
+ if choices:
+ first_choice = choices[0]
+ message = first_choice.get("message", {})
+ tool_calls = message.get("tool_calls")
+ if tool_calls:
+ transformed_tool_calls = []
+ for tool_call in tool_calls:
+ function = tool_call.get("function", {})
+ arguments_str = function.get("arguments", "{}")
+ try:
+ arguments_obj = (
+ json.loads(arguments_str)
+ if isinstance(arguments_str, str)
+ else arguments_str
+ )
+ except json.JSONDecodeError:
+ arguments_obj = {}
+ langfuse_tool_call = {
+ "id": response_obj.get("id", ""),
+ "name": function.get("name", ""),
+ "call_id": tool_call.get("id", ""),
+ "type": "function_call",
+ "arguments": arguments_obj,
+ }
+ transformed_tool_calls.append(langfuse_tool_call)
+ safe_set_attribute(span, LangfuseSpanAttributes.OBSERVATION_OUTPUT.value, safe_dumps(transformed_tool_calls))
+ else:
+ output_data = {}
+ if message.get("role"):
+ output_data["role"] = message.get("role")
+ if message.get("content") is not None:
+ output_data["content"] = message.get("content")
+ if output_data:
+ safe_set_attribute(span, LangfuseSpanAttributes.OBSERVATION_OUTPUT.value, safe_dumps(output_data))
+
+ output = response_obj.get("output", [])
+ if output:
+ output_data = []
+ for item in output:
+ if hasattr(item, "type"):
+ item_type = item.type
+ if item_type == "reasoning" and hasattr(item, "summary"):
+ for summary in item.summary:
+ if hasattr(summary, "text"):
+ output_data.append({"role": "reasoning_summary", "content": summary.text})
+ elif item_type == "message":
+ output_data.append({
+ "role": getattr(item, "role", "assistant"),
+ "content": getattr(getattr(item, "content", [{}])[0], "text", "")
+ })
+ elif item_type == "function_call":
+ arguments_str = getattr(item, "arguments", "{}")
+ arguments_obj = json.loads(arguments_str) if isinstance(arguments_str, str) else arguments_str
langfuse_tool_call = {
- "id": response_obj.get("id", ""),
- "name": function.get("name", ""),
- "call_id": tool_call.get("id", ""),
+ "id": getattr(item, "id", ""),
+ "name": getattr(item, "name", ""),
+ "call_id": getattr(item, "call_id", ""),
"type": "function_call",
"arguments": arguments_obj,
}
- transformed_tool_calls.append(langfuse_tool_call)
-
- # Set the observation output with transformed tool_calls
- safe_set_attribute(
- span,
- LangfuseSpanAttributes.OBSERVATION_OUTPUT.value,
- safe_dumps(transformed_tool_calls),
- )
- else:
- # No tool_calls, use regular content-based output
- output_data = {}
-
- if message.get("role"):
- output_data["role"] = message.get("role")
-
- if message.get("content") is not None:
- output_data["content"] = message.get("content")
-
- if output_data:
- safe_set_attribute(
- span,
- LangfuseSpanAttributes.OBSERVATION_OUTPUT.value,
- safe_dumps(output_data),
- )
+ output_data.append(langfuse_tool_call)
+ if output_data:
+ safe_set_attribute(span, LangfuseSpanAttributes.OBSERVATION_OUTPUT.value, safe_dumps(output_data))
- # Handle responses API (output field)
- output = response_obj.get("output", [])
- if output:
- output_data = []
- for item in output:
- if hasattr(item, "type"):
- item_type = item.type
-
- if item_type == "reasoning" and hasattr(item, "summary"):
- for summary in item.summary:
- if hasattr(summary, "text"):
- output_data.append({
- "role": "reasoning_summary",
- "content": summary.text
- })
- elif item_type == "message":
- output_data.append({
- "role": getattr(item, "role", "assistant"),
- "content": getattr(getattr(item, "content", [{}])[0], "text", "")
- })
- elif item_type == "function_call":
- arguments_str = getattr(item, "arguments", "{}")
- arguments_obj = json.loads(arguments_str) if isinstance(arguments_str, str) else arguments_str
- langfuse_tool_call = {
- "id": getattr(item, "id", ""),
- "name": getattr(item, "name", ""),
- "call_id": getattr(item, "call_id", ""),
- "type": "function_call",
- "arguments": arguments_obj,
- }
- output_data.append(langfuse_tool_call)
- if output_data:
- safe_set_attribute(
- span,
- LangfuseSpanAttributes.OBSERVATION_OUTPUT.value,
- safe_dumps(output_data),
- )
+ @staticmethod
+ def _set_langfuse_specific_attributes(span: Span, kwargs, response_obj):
+ """
+ Sets Langfuse specific metadata attributes onto the OTEL span.
+
+ All keys supported by the vanilla Langfuse integration are mapped to
+ OTEL-safe attribute names defined in LangfuseSpanAttributes. Complex
+ values (lists/dicts) are serialised to JSON strings for OTEL
+ compatibility.
+ """
+ from litellm.integrations.arize._utils import safe_set_attribute
+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+
+ langfuse_environment = os.environ.get("LANGFUSE_TRACING_ENVIRONMENT")
+ if langfuse_environment:
+ safe_set_attribute(span, LangfuseSpanAttributes.LANGFUSE_ENVIRONMENT.value, langfuse_environment)
+
+ metadata = LangfuseOtelLogger._extract_langfuse_metadata(kwargs)
+ LangfuseOtelLogger._set_metadata_attributes(span=span, metadata=metadata)
+
+ messages = kwargs.get("messages")
+ if messages:
+ safe_set_attribute(span, LangfuseSpanAttributes.OBSERVATION_INPUT.value, safe_dumps(messages))
+
+ LangfuseOtelLogger._set_observation_output(span=span, response_obj=response_obj)
@staticmethod
def _get_langfuse_otel_host() -> Optional[str]:
diff --git a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
index a1386c1a378..b1ccfc36d0d 100644
--- a/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
+++ b/litellm/llms/azure_ai/ocr/document_intelligence/transformation.py
@@ -29,7 +29,6 @@ from litellm.llms.base_llm.ocr.transformation import (
OCRResponse,
OCRUsageInfo,
)
-from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.secret_managers.main import get_secret_str
diff --git a/litellm/llms/vertex_ai/ocr/transformation.py b/litellm/llms/vertex_ai/ocr/transformation.py
index 520b9a09393..f4482939851 100644
--- a/litellm/llms/vertex_ai/ocr/transformation.py
+++ b/litellm/llms/vertex_ai/ocr/transformation.py
@@ -11,7 +11,6 @@ from litellm.litellm_core_utils.prompt_templates.image_handling import (
from litellm.llms.base_llm.ocr.transformation import DocumentType, OCRRequestData
from litellm.llms.mistral.ocr.transformation import MistralOCRConfig
from litellm.llms.vertex_ai.vertex_llm_base import VertexBase
-from litellm.types.llms.vertex_ai import VERTEX_CREDENTIALS_TYPES
class VertexAIOCRConfig(MistralOCRConfig):
diff --git a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
index 5b596b4ef9a..7073a4341fb 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/noma/noma.py
@@ -9,7 +9,7 @@ import asyncio
import copy
import os
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Dict, Final, List, Literal, Optional, Type, Union
+from typing import TYPE_CHECKING, Any, Dict, Final, Literal, Optional, Type, Union
from urllib.parse import urljoin
from fastapi import HTTPException
@@ -23,7 +23,7 @@ from litellm.llms.custom_httpx.http_handler import (
httpxSpecialProvider,
)
from litellm.proxy._types import UserAPIKeyAuth
-from litellm.types.guardrails import GuardrailEventHooks, PiiEntityType
+from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.utils import EmbeddingResponse, GuardrailStatus, ImageResponse
# Constants
diff --git a/litellm/router.py b/litellm/router.py
index 28ac39ecf28..1489de86488 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -772,142 +772,68 @@ class Router:
self.aget_messages = self.factory_function(litellm.aget_messages)
self.arun_thread = self.factory_function(litellm.arun_thread)
- def initialize_router_endpoints(self):
- self.amoderation = self.factory_function(
- litellm.amoderation, call_type="moderation"
- )
- self.aanthropic_messages = self.factory_function(
- litellm.anthropic_messages, call_type="anthropic_messages"
- )
- self.agenerate_content = self.factory_function(
- litellm.agenerate_content, call_type="agenerate_content"
- )
-
- self.aadapter_generate_content = self.factory_function(
- litellm.aadapter_generate_content, call_type="aadapter_generate_content"
- )
-
- self.aresponses = self.factory_function(
- litellm.aresponses, call_type="aresponses"
- )
- self.afile_delete = self.factory_function(
- litellm.afile_delete, call_type="afile_delete"
- )
-
- self.afile_content = self.factory_function(
- litellm.afile_content, call_type="afile_content"
- )
+ def _initialize_core_endpoints(self):
+ """Helper to initialize core router endpoints."""
+ self.amoderation = self.factory_function(litellm.amoderation, call_type="moderation")
+ self.aanthropic_messages = self.factory_function(litellm.anthropic_messages, call_type="anthropic_messages")
+ self.agenerate_content = self.factory_function(litellm.agenerate_content, call_type="agenerate_content")
+ self.aadapter_generate_content = self.factory_function(litellm.aadapter_generate_content, call_type="aadapter_generate_content")
+ self.aresponses = self.factory_function(litellm.aresponses, call_type="aresponses")
+ self.afile_delete = self.factory_function(litellm.afile_delete, call_type="afile_delete")
+ self.afile_content = self.factory_function(litellm.afile_content, call_type="afile_content")
self.responses = self.factory_function(litellm.responses, call_type="responses")
- self.aget_responses = self.factory_function(
- litellm.aget_responses, call_type="aget_responses"
- )
- self.acancel_responses = self.factory_function(
- litellm.acancel_responses, call_type="acancel_responses"
- )
- self.adelete_responses = self.factory_function(
- litellm.adelete_responses, call_type="adelete_responses"
- )
- self.alist_input_items = self.factory_function(
- litellm.alist_input_items, call_type="alist_input_items"
- )
- self._arealtime = self.factory_function(
- litellm._arealtime, call_type="_arealtime"
- )
- self.acreate_fine_tuning_job = self.factory_function(
- litellm.acreate_fine_tuning_job, call_type="acreate_fine_tuning_job"
- )
- self.acancel_fine_tuning_job = self.factory_function(
- litellm.acancel_fine_tuning_job, call_type="acancel_fine_tuning_job"
- )
- self.alist_fine_tuning_jobs = self.factory_function(
- litellm.alist_fine_tuning_jobs, call_type="alist_fine_tuning_jobs"
- )
- self.aretrieve_fine_tuning_job = self.factory_function(
- litellm.aretrieve_fine_tuning_job, call_type="aretrieve_fine_tuning_job"
- )
- self.afile_list = self.factory_function(
- litellm.afile_list, call_type="alist_files"
- )
- self.aimage_edit = self.factory_function(
- litellm.aimage_edit, call_type="aimage_edit"
- )
- self.allm_passthrough_route = self.factory_function(
- litellm.allm_passthrough_route, call_type="allm_passthrough_route"
- )
-
- #########################################################
- # Vector Store routes
- #########################################################
+ self.aget_responses = self.factory_function(litellm.aget_responses, call_type="aget_responses")
+ self.acancel_responses = self.factory_function(litellm.acancel_responses, call_type="acancel_responses")
+ self.adelete_responses = self.factory_function(litellm.adelete_responses, call_type="adelete_responses")
+ self.alist_input_items = self.factory_function(litellm.alist_input_items, call_type="alist_input_items")
+ self._arealtime = self.factory_function(litellm._arealtime, call_type="_arealtime")
+ self.acreate_fine_tuning_job = self.factory_function(litellm.acreate_fine_tuning_job, call_type="acreate_fine_tuning_job")
+ self.acancel_fine_tuning_job = self.factory_function(litellm.acancel_fine_tuning_job, call_type="acancel_fine_tuning_job")
+ self.alist_fine_tuning_jobs = self.factory_function(litellm.alist_fine_tuning_jobs, call_type="alist_fine_tuning_jobs")
+ self.aretrieve_fine_tuning_job = self.factory_function(litellm.aretrieve_fine_tuning_job, call_type="aretrieve_fine_tuning_job")
+ self.afile_list = self.factory_function(litellm.afile_list, call_type="alist_files")
+ self.aimage_edit = self.factory_function(litellm.aimage_edit, call_type="aimage_edit")
+ self.allm_passthrough_route = self.factory_function(litellm.allm_passthrough_route, call_type="allm_passthrough_route")
+
+ def _initialize_specialized_endpoints(self):
+ """Helper to initialize specialized router endpoints (vector store, OCR, search, video, container)."""
from litellm.vector_stores.main import acreate, asearch, create, search
+ self.avector_store_search = self.factory_function(asearch, call_type="avector_store_search")
+ self.avector_store_create = self.factory_function(acreate, call_type="avector_store_create")
+ self.vector_store_search = self.factory_function(search, call_type="vector_store_search")
+ self.vector_store_create = self.factory_function(create, call_type="vector_store_create")
- # async routes
- self.avector_store_search = self.factory_function(
- asearch, call_type="avector_store_search"
- )
- self.avector_store_create = self.factory_function(
- acreate, call_type="avector_store_create"
- )
- # sync routes
- self.vector_store_search = self.factory_function(
- search, call_type="vector_store_search"
- )
- self.vector_store_create = self.factory_function(
- create, call_type="vector_store_create"
- )
-
- #########################################################
- # Gemini Native routes
- #########################################################
from litellm.google_genai import (
agenerate_content,
agenerate_content_stream,
generate_content,
generate_content_stream,
)
+ self.agenerate_content = self.factory_function(agenerate_content, call_type="agenerate_content")
+ self.generate_content = self.factory_function(generate_content, call_type="generate_content")
+ self.agenerate_content_stream = self.factory_function(agenerate_content_stream, call_type="agenerate_content_stream")
+ self.generate_content_stream = self.factory_function(generate_content_stream, call_type="generate_content_stream")
- self.agenerate_content = self.factory_function(
- agenerate_content, call_type="agenerate_content"
- )
- self.generate_content = self.factory_function(
- generate_content, call_type="generate_content"
- )
- self.agenerate_content_stream = self.factory_function(
- agenerate_content_stream, call_type="agenerate_content_stream"
- )
- self.generate_content_stream = self.factory_function(
- generate_content_stream, call_type="generate_content_stream"
- )
-
- #########################################################
- # OCR routes
- #########################################################
from litellm.ocr import aocr, ocr
-
self.aocr = self.factory_function(aocr, call_type="aocr")
self.ocr = self.factory_function(ocr, call_type="ocr")
- # Search routes
- #########################################################
from litellm.search import asearch, search
-
self.asearch = self.factory_function(asearch, call_type="asearch")
self.search = self.factory_function(search, call_type="search")
- # Video routes
- #########################################################
from litellm.videos import (
+ avideo_content,
avideo_generation,
- video_generation,
avideo_list,
- video_list,
+ avideo_remix,
avideo_status,
- video_status,
- avideo_content,
video_content,
- avideo_remix,
+ video_generation,
+ video_list,
video_remix,
+ video_status,
)
-
self.avideo_generation = self.factory_function(avideo_generation, call_type="avideo_generation")
self.video_generation = self.factory_function(video_generation, call_type="video_generation")
self.avideo_list = self.factory_function(avideo_list, call_type="avideo_list")
@@ -919,19 +845,16 @@ class Router:
self.avideo_remix = self.factory_function(avideo_remix, call_type="avideo_remix")
self.video_remix = self.factory_function(video_remix, call_type="video_remix")
- # Container routes
- #########################################################
from litellm.containers import (
acreate_container,
- create_container,
+ adelete_container,
alist_containers,
- list_containers,
aretrieve_container,
- retrieve_container,
- adelete_container,
+ create_container,
delete_container,
+ list_containers,
+ retrieve_container,
)
-
self.acreate_container = self.factory_function(acreate_container, call_type="acreate_container")
self.create_container = self.factory_function(create_container, call_type="create_container")
self.alist_containers = self.factory_function(alist_containers, call_type="alist_containers")
@@ -941,6 +864,10 @@ class Router:
self.adelete_container = self.factory_function(adelete_container, call_type="adelete_container")
self.delete_container = self.factory_function(delete_container, call_type="delete_container")
+ def initialize_router_endpoints(self):
+ self._initialize_core_endpoints()
+ self._initialize_specialized_endpoints()
+
def validate_fallbacks(self, fallback_param: Optional[List]):
"""
Validate the fallbacks parameter.