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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
LiteLLM Minor Fixes & Improvements (12/16/2024) - p1 (#7263)
Krish Dholakia179d2f56b7f5
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex 0df1011398a..6f176e12c38 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -199,9 +199,6 @@ def cost_per_token( # noqa: PLR0915model = model_without_prefix# see this https://learn.microsoft.com/en-us/azure/ai-services/openai/concepts/models- print_verbose(- f"Looking up model={model} in model_cost_map, custom_llm_provider={custom_llm_provider}, call_type={call_type}"- )if call_type == "speech" or call_type == "aspeech":if prompt_characters is None:raise ValueError(@@ -346,37 +343,84 @@ def has_hidden_params(obj: Any) -> bool:return hasattr(obj, "_hidden_params")+def _get_provider_for_cost_calc(+ model: Optional[str],+ custom_llm_provider: Optional[str] = None,+) -> Optional[str]:+ if custom_llm_provider is not None:+ return custom_llm_provider+ if model is None:+ return None+ try:+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model)+ except Exception as e:+ verbose_logger.debug(+ f"litellm.cost_calculator.py::_get_provider_for_cost_calc() - Error inferring custom_llm_provider - {str(e)}"+ )+ return None++ return custom_llm_provider++def _select_model_name_for_cost_calc(model: Optional[str],- completion_response: Union[BaseModel, dict, str],+ completion_response: Optional[Any],base_model: Optional[str] = None,custom_pricing: Optional[bool] = None,+ custom_llm_provider: Optional[str] = None,) -> Optional[str]:"""1. If custom pricing is true, return received model name2. If base_model is set (e.g. for azure models), return that3. If completion response has model set return that+ 4. Check if compl4. If model is passed in return that"""+ return_model: Optional[str] = None+ region_name: Optional[str] = None+ custom_llm_provider = _get_provider_for_cost_calc(+ model=model, custom_llm_provider=custom_llm_provider+ )+if custom_pricing is True:- return model+ return_model = modelif base_model is not None:- return base_model- return_model = model- if isinstance(completion_response, str):- return return_model-- elif return_model is None and hasattr(completion_response, "get"):- return_model = completion_response.get("model", "") # type: ignore- hidden_params = getattr(completion_response, "_hidden_params", None)+ return_model = base_model- if hidden_params is not None:+ completion_response_model: Optional[str] = None+ if completion_response is not None and isinstance(completion_response, BaseModel):+ completion_response_model = getattr(completion_response, "model", None)+ hidden_params = getattr(completion_response, "_hidden_params", None)+ if completion_response_model is None and hidden_params is not None:+ if (+ hidden_params.get("model", None) is not None+ and len(hidden_params["model"]) > 0+ ):+ return_model = hidden_params.get("model", model)if (- hidden_params.get("model", None) is not None- and len(hidden_params["model"]) > 0+ hidden_params is not None+ and hidden_params.get("region_name", None) is not None):- return_model = hidden_params.get("model", model)+ region_name = hidden_params.get("region_name", None)+ elif completion_response is not None and isinstance(completion_response, dict):+ completion_response_model = completion_response.get("model", None)++ if return_model is None and completion_response_model is not None:+ return_model = completion_response_model++ if return_model is None and model is not None:+ return_model = model++ if (+ return_model is not None+ and custom_llm_provider is not None+ and not return_model.startswith(custom_llm_provider)+ ): # add provider prefix if not already present, to match model_cost+ if region_name is not None:+ return_model = f"{custom_llm_provider}/{region_name}/{return_model}"+ else:+ return_model = f"{custom_llm_provider}/{return_model}"return return_model@@ -439,6 +483,8 @@ def completion_cost( # noqa: PLR0915custom_cost_per_token: Optional[CostPerToken] = None,custom_cost_per_second: Optional[float] = None,optional_params: Optional[dict] = None,+ custom_pricing: Optional[bool] = None,+ base_model: Optional[str] = None,) -> float:"""Calculate the cost of a given completion call fot GPT-3.5-turbo, llama2, any litellm supported llm.@@ -489,11 +535,17 @@ def completion_cost( # noqa: PLR0915cost_per_token_usage_object: Optional[Usage] = _get_usage_object(completion_response=completion_response)+ model = _select_model_name_for_cost_calc(+ model=model,+ completion_response=completion_response,+ custom_llm_provider=custom_llm_provider,+ custom_pricing=custom_pricing,+ base_model=base_model,+ )if completion_response is not None and (isinstance(completion_response, BaseModel)or isinstance(completion_response, dict)): # tts returns a custom class-usage_obj: Optional[Union[dict, Usage]] = completion_response.get( # type: ignore"usage", {})@@ -528,10 +580,7 @@ def completion_cost( # noqa: PLR0915verbose_logger.debug(f"completion_response response ms: {getattr(completion_response, '_response_ms', None)} ")- model = _select_model_name_for_cost_calc(- model=model,- completion_response=completion_response,- )+hidden_params = getattr(completion_response, "_hidden_params", None)if hidden_params is not None:custom_llm_provider = hidden_params.get(@@ -562,15 +611,16 @@ def completion_cost( # noqa: PLR0915f"Model is None and does not exist in passed completion_response. Passed completion_response={completion_response}, model={model}")- if custom_llm_provider is None:- try:- _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model)- except Exception as e:- verbose_logger.debug(- "litellm.cost_calculator.py::completion_cost() - Error inferring custom_llm_provider - {}".format(- str(e)- )+ try:+ model, custom_llm_provider, _, _ = litellm.get_llm_provider(+ model=model+ ) # strip the llm provider from the model name -> for image gen cost calculation+ except Exception as e:+ verbose_logger.debug(+ "litellm.cost_calculator.py::completion_cost() - Error inferring custom_llm_provider - {}".format(+ str(e))+ )if (call_type == CallTypes.image_generation.valueor call_type == CallTypes.aimage_generation.value@@ -760,6 +810,7 @@ def response_cost_calculator(cache_hit: Optional[bool] = None,base_model: Optional[str] = None,custom_pricing: Optional[bool] = None,+ prompt: str = "",) -> Optional[float]:"""Returns@@ -772,26 +823,16 @@ def response_cost_calculator(else:if isinstance(response_object, BaseModel):response_object._hidden_params["optional_params"] = optional_params- if isinstance(response_object, ImageResponse):- if base_model is not None:- model = base_model- response_cost = completion_cost(- completion_response=response_object,- model=model,- call_type=call_type,- custom_llm_provider=custom_llm_provider,- optional_params=optional_params,- )- else:- if custom_pricing is True: # override defaults if custom pricing is set- base_model = model- # base_model defaults to None if not set on model_info- response_cost = completion_cost(- completion_response=response_object,- call_type=call_type,- model=base_model,- custom_llm_provider=custom_llm_provider,- )+ response_cost = completion_cost(+ completion_response=response_object,+ model=model,+ call_type=call_type,+ custom_llm_provider=custom_llm_provider,+ optional_params=optional_params,+ custom_pricing=custom_pricing,+ base_model=base_model,+ prompt=prompt,+ )return response_costexcept Exception as e:raise ediff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex f14307219e3..3fca34aa394 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -94,6 +94,7 @@ from ..integrations.supabase import Supabasefrom ..integrations.traceloop import TraceloopLoggerfrom ..integrations.weights_biases import WeightsBiasesLoggerfrom .exception_mapping_utils import _get_response_headers+from .llm_response_utils.get_formatted_prompt import get_formatted_promptfrom .logging_utils import _assemble_complete_response_from_streaming_chunkstry:@@ -225,6 +226,7 @@ class Logging(LiteLLMLoggingBaseClass):] = None,kwargs: Optional[Dict] = None,):+ _input: Optional[str] = messages # save original value of messagesif messages is not None:if isinstance(messages, str):messages = [@@ -251,7 +253,6 @@ class Logging(LiteLLMLoggingBaseClass):self.sync_streaming_chunks: List[Any] = ([]) # for generating complete stream response- self.model_call_details: Dict[Any, Any] = {}# Initialize dynamic callbacksself.dynamic_input_callbacks: Optional[@@ -282,9 +283,10 @@ class Logging(LiteLLMLoggingBaseClass):self.completion_start_time: Optional[datetime.datetime] = Noneself._llm_caching_handler: Optional[LLMCachingHandler] = None- self.model_call_details = {+ self.model_call_details: Dict[str, Any] = {"litellm_trace_id": litellm_trace_id,"litellm_call_id": litellm_call_id,+ "input": _input,}def process_dynamic_callbacks(self):@@ -734,6 +736,11 @@ class Logging(LiteLLMLoggingBaseClass):))+ prompt = "" # use for tts cost calc+ _input = self.model_call_details.get("input", None)+ if _input is not None and isinstance(_input, str):+ prompt = _input+if cache_hit is None:cache_hit = self.model_call_details.get("cache_hit", False)@@ -751,6 +758,7 @@ class Logging(LiteLLMLoggingBaseClass):"call_type": self.call_type,"optional_params": self.optional_params,"custom_pricing": custom_pricing,+ "prompt": prompt,}except Exception as e: # error creating kwargs for cost calculationself.model_call_details["response_cost_failure_debug_information"] = (@@ -765,7 +773,6 @@ class Logging(LiteLLMLoggingBaseClass):response_cost = litellm.response_cost_calculator(**response_cost_calculator_kwargs)-return response_costexcept Exception as e: # error calculating costself.model_call_details["response_cost_failure_debug_information"] = (diff --git a/litellm/litellm_core_utils/llm_cost_calc/utils.py b/litellm/litellm_core_utils/llm_cost_calc/utils.pyindex b97e2f4f0a1..631682a9846 100644--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py@@ -34,7 +34,6 @@ def _generic_cost_per_character(Raises:Exception if 'input_cost_per_character' or 'output_cost_per_character' is missing from model_info"""- args = locals()## GET MODEL INFOmodel_info = litellm.get_model_info(model=model, custom_llm_provider=custom_llm_providerdiff --git a/litellm/litellm_core_utils/llm_response_utils/get_api_base.py b/litellm/litellm_core_utils/llm_response_utils/get_api_base.pynew file mode 100644index 00000000000..ddac7ac3244--- /dev/null+++ b/litellm/litellm_core_utils/llm_response_utils/get_api_base.py@@ -0,0 +1,122 @@+from typing import Optional, Union++import litellm+from litellm import verbose_logger++from ...litellm_core_utils.get_llm_provider_logic import get_llm_provider+from ...types.router import LiteLLM_Params+++def get_api_base(+ model: str, optional_params: Union[dict, LiteLLM_Params]+) -> Optional[str]:+ """+ Returns the api base used for calling the model.++ Parameters:+ - model: str - the model passed to litellm.completion()+ - optional_params - the 'litellm_params' in router.completion *OR* additional params passed to litellm.completion - eg. api_base, api_key, etc. See `LiteLLM_Params` - https://github.com/BerriAI/litellm/blob/f09e6ba98d65e035a79f73bc069145002ceafd36/litellm/router.py#L67++ Returns:+ - string (api_base) or None++ Example:+ ```+ from litellm import get_api_base++ get_api_base(model="gemini/gemini-pro")+ ```+ """++ try:+ if isinstance(optional_params, LiteLLM_Params):+ _optional_params = optional_params+ elif "model" in optional_params:+ _optional_params = LiteLLM_Params(**optional_params)+ else: # prevent needing to copy and pop the dict+ _optional_params = LiteLLM_Params(+ model=model, **optional_params+ ) # convert to pydantic object+ except Exception as e:+ verbose_logger.debug("Error occurred in getting api base - {}".format(str(e)))+ return None+ # get llm provider++ if _optional_params.api_base is not None:+ return _optional_params.api_base++ if litellm.model_alias_map and model in litellm.model_alias_map:+ model = litellm.model_alias_map[model]+ try:+ (+ model,+ custom_llm_provider,+ dynamic_api_key,+ dynamic_api_base,+ ) = get_llm_provider(+ model=model,+ custom_llm_provider=_optional_params.custom_llm_provider,+ api_base=_optional_params.api_base,+ api_key=_optional_params.api_key,+ )+ except Exception as e:+ verbose_logger.debug("Error occurred in getting api base - {}".format(str(e)))+ custom_llm_provider = None+ dynamic_api_base = None++ if dynamic_api_base is not None:+ return dynamic_api_base++ stream: bool = getattr(optional_params, "stream", False)++ if (+ _optional_params.vertex_location is not None+ and _optional_params.vertex_project is not None+ ):+ from litellm.llms.vertex_ai.vertex_ai_partner_models.main import (+ VertexPartnerProvider,+ create_vertex_url,+ )++ if "claude" in model:+ _api_base = create_vertex_url(+ vertex_location=_optional_params.vertex_location,+ vertex_project=_optional_params.vertex_project,+ model=model,+ stream=stream,+ partner=VertexPartnerProvider.claude,+ )+ else:+ if stream:+ _api_base = "{}-aiplatform.googleapis.com/v1/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent".format(+ _optional_params.vertex_location,+ _optional_params.vertex_project,+ _optional_params.vertex_location,+ model,+ )+ else:+ _api_base = "{}-aiplatform.googleapis.com/v1/projects/{}/locations/{}/publishers/google/models/{}:generateContent".format(+ _optional_params.vertex_location,+ _optional_params.vertex_project,+ _optional_params.vertex_location,+ model,+ )+ return _api_base++ if custom_llm_provider is None:+ return None++ if custom_llm_provider == "gemini":+ if stream:+ _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:streamGenerateContent".format(+ model+ )+ else:+ _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent".format(+ model+ )+ return _api_base+ elif custom_llm_provider == "openai":+ _api_base = "https://api.openai.com"+ return _api_base+ return Nonediff --git a/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py b/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.pynew file mode 100644index 00000000000..fffaad79b9e--- /dev/null+++ b/litellm/litellm_core_utils/llm_response_utils/get_formatted_prompt.py@@ -0,0 +1,49 @@+from typing import List, Literal+++def get_formatted_prompt(+ data: dict,+ call_type: Literal[+ "completion",+ "embedding",+ "image_generation",+ "audio_transcription",+ "moderation",+ "text_completion",+ ],+) -> str:+ """+ Extracts the prompt from the input data based on the call type.++ Returns a string.+ """+ prompt = ""+ if call_type == "completion":+ for message in data["messages"]:+ if message.get("content", None) is not None:+ content = message.get("content")+ if isinstance(content, str):+ prompt += message["content"]+ elif isinstance(content, List):+ for c in content:+ if c["type"] == "text":+ prompt += c["text"]+ if "tool_calls" in message:+ for tool_call in message["tool_calls"]:+ if "function" in tool_call:+ function_arguments = tool_call["function"]["arguments"]+ prompt += function_arguments+ elif call_type == "text_completion":+ prompt = data["prompt"]+ elif call_type == "embedding" or call_type == "moderation":+ if isinstance(data["input"], str):+ prompt = data["input"]+ elif isinstance(data["input"], list):+ for m in data["input"]:+ prompt += m+ elif call_type == "image_generation":+ prompt = data["prompt"]+ elif call_type == "audio_transcription":+ if "prompt" in data:+ prompt = data["prompt"]+ return promptdiff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.pyindex 79933a462ec..0b5bd48bb8d 100644--- a/litellm/litellm_core_utils/prompt_templates/factory.py+++ b/litellm/litellm_core_utils/prompt_templates/factory.py@@ -5,7 +5,17 @@ import tracebackimport uuidimport xml.etree.ElementTree as ETfrom enum import Enum-from typing import Any, List, Mapping, MutableMapping, Optional, Sequence, Tuple, cast+from typing import (+ Any,+ List,+ Mapping,+ MutableMapping,+ Optional,+ Sequence,+ Tuple,+ cast,+ overload,+)from jinja2 import BaseLoader, Template, exceptions, metafrom jinja2.sandbox import ImmutableSandboxedEnvironment@@ -2459,7 +2469,7 @@ def get_user_message_block_or_continue_message(if content_block is None or (user_continue_message is None and litellm.modify_params is False):- return message+ return skip_empty_text_blocks(message=message)# Handle string caseif isinstance(content_block, str):@@ -2525,9 +2535,40 @@ def return_assistant_continue_message(return DEFAULT_ASSISTANT_CONTINUE_MESSAGE+def _skip_empty_dict_blocks(blocks: List[dict]) -> List[dict]:+ """+ Filter out empty text blocks from a list of dictionaries.++ Args:+ blocks: List of dictionaries representing message content blocks++ Returns:+ Filtered list of non-empty text blocks+ """+ return [+ item+ for item in blocks+ if not (item.get("type") == "text" and not item.get("text", "").strip())+ ]+++@overloaddef skip_empty_text_blocks(message: ChatCompletionAssistantMessage,) -> ChatCompletionAssistantMessage:+ pass+++@overload+def skip_empty_text_blocks(+ message: ChatCompletionUserMessage,+) -> ChatCompletionUserMessage:+ pass+++def skip_empty_text_blocks(+ message: Union[ChatCompletionAssistantMessage, ChatCompletionUserMessage],+) -> Union[ChatCompletionAssistantMessage, ChatCompletionUserMessage]:"""Skips empty text blocks in message content text blocks.@@ -2540,19 +2581,36 @@ def skip_empty_text_blocks(isinstance(content_block, str)and not content_block.strip()and is_non_content_values_set(message)+ and message["role"] == "assistant"):modified_message = message.copy()- modified_message["content"] = None+ modified_message["content"] = None # user message content cannot be Nonereturn modified_messageelif isinstance(content_block, list):- modified_content_block = [- item- for item in content_block- if not (item["type"] == "text" and not item["text"].strip())- ]- modified_message = message.copy()- modified_message["content"] = modified_content_block- return modified_message+ modified_content_block = _skip_empty_dict_blocks(+ cast(List[dict], content_block)+ )++ # If no content remains and it's an assistant message, set content to None+ if not modified_content_block and message["role"] == "assistant":+ modified_message = message.copy()+ modified_message["content"] = None+ return modified_message++ modified_message_alt = message.copy()++ # Type-specific casting based on message role+ if message["role"] == "assistant":+ modified_message_alt["content"] = cast( # type: ignore+ Optional[List[OpenAIMessageContentListBlock]],+ modified_content_block or None,+ )+ elif message["role"] == "user" and modified_content_block is not None:+ modified_message_alt["content"] = cast( # type: ignore+ Optional[List[ChatCompletionTextObject]], modified_content_block+ )++ return modified_message_altreturn messagediff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex b8d428100e6..b4fe4cbee5c 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -29,6 +29,7 @@ from ..exceptions import OpenAIErrorfrom .core_helpers import map_finish_reason, process_response_headersfrom .default_encoding import encodingfrom .exception_mapping_utils import exception_type+from .llm_response_utils.get_api_base import get_api_basefrom .rules import RulesMAX_THREADS = 100@@ -86,8 +87,17 @@ class CustomStreamWrapper:)or {})++ _api_base = get_api_base(+ model=model or "",+ optional_params=self.logging_obj.model_call_details.get(+ "litellm_params", {}+ ),+ )+self._hidden_params = {"model_id": (_model_info.get("id", None)),+ "api_base": _api_base,} # returned as x-litellm-model-id response header in proxyself._hidden_params["additional_headers"] = process_response_headers(diff --git a/litellm/llms/openai/cost_calculation.py b/litellm/llms/openai/cost_calculation.pyindex b0096f1d6b8..0c26fd74488 100644--- a/litellm/llms/openai/cost_calculation.py+++ b/litellm/llms/openai/cost_calculation.py@@ -30,7 +30,6 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]:"""## GET MODEL INFOmodel_info = get_model_info(model=model, custom_llm_provider="openai")-## CALCULATE INPUT COST### Non-cached text tokensnon_cached_text_tokens = usage.prompt_tokensdiff --git a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.pyindex d438dea2fae..8c534a4fa79 100644--- a/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py+++ b/litellm/llms/vertex_ai/gemini/vertex_and_google_ai_studio_gemini.py@@ -394,6 +394,7 @@ class VertexGeminiConfig(BaseConfig):def _map_function(self, value: List[dict]) -> List[Tools]:gtool_func_declarations = []+ googleSearch: Optional[dict] = NonegoogleSearchRetrieval: Optional[dict] = Nonecode_execution: Optional[dict] = None# remove 'additionalProperties' from tools@@ -424,7 +425,9 @@ class VertexGeminiConfig(BaseConfig):openai_function_object = ChatCompletionToolParamFunctionChunk(**tool) # type: ignore# check if grounding- if tool.get("googleSearchRetrieval", None) is not None:+ if tool.get("googleSearch", None) is not None:+ googleSearch = tool["googleSearch"]+ elif tool.get("googleSearchRetrieval", None) is not None:googleSearchRetrieval = tool["googleSearchRetrieval"]elif tool.get("code_execution", None) is not None:code_execution = tool["code_execution"]@@ -448,6 +451,8 @@ class VertexGeminiConfig(BaseConfig):_tools = Tools(function_declarations=gtool_func_declarations,)+ if googleSearch is not None:+ _tools["googleSearch"] = googleSearchif googleSearchRetrieval is not None:_tools["googleSearchRetrieval"] = googleSearchRetrievalif code_execution is not None:diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yamlindex da3644a63af..86946a65dac 100644--- a/litellm/proxy/_new_secret_config.yaml+++ b/litellm/proxy/_new_secret_config.yaml@@ -10,6 +10,12 @@ model_list:model: openai/gpt-4oapi_key: os.environ/OPENAI_API_KEYnum_retries: 3+ - model_name: azure-tts+ litellm_params:+ model: azure/tts-1+ api_key: "6a4ULQtTSBZi5TONpzGP2GkKDUSSReHFQYwjMpZaywNxY03FsplGJQQJ99ALACHrzpqXJ3w3AAAAACOGUsjy"+ api_base: "https://krris-m4rve6fd-northcentralus.cognitiveservices.azure.com/openai/deployments/tts"+ api_version: "2024-05-01-preview"litellm_settings:success_callback: ["langsmith"]diff --git a/litellm/types/llms/vertex_ai.py b/litellm/types/llms/vertex_ai.pyindex c1a3bb464f3..0eca1c05454 100644--- a/litellm/types/llms/vertex_ai.py+++ b/litellm/types/llms/vertex_ai.py@@ -164,6 +164,7 @@ class GenerationConfig(TypedDict, total=False):class Tools(TypedDict, total=False):function_declarations: List[FunctionDeclaration]+ googleSearch: dictgoogleSearchRetrieval: dictcode_execution: dictretrieval: Retrievaldiff --git a/litellm/utils.py b/litellm/utils.pyindex 093b4844dce..256329fabbf 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -85,6 +85,10 @@ from litellm.litellm_core_utils.llm_response_utils.convert_dict_to_response impoconvert_to_streaming_response,convert_to_streaming_response_async,)+from litellm.litellm_core_utils.llm_response_utils.get_api_base import get_api_base+from litellm.litellm_core_utils.llm_response_utils.get_formatted_prompt import (+ get_formatted_prompt,+)from litellm.litellm_core_utils.llm_response_utils.get_headers import (get_response_headers,)@@ -3904,121 +3908,6 @@ def get_model_region(return None-def get_api_base(- model: str, optional_params: Union[dict, LiteLLM_Params]-) -> Optional[str]:- """- Returns the api base used for calling the model.-- Parameters:- - model: str - the model passed to litellm.completion()- - optional_params - the 'litellm_params' in router.completion *OR* additional params passed to litellm.completion - eg. api_base, api_key, etc. See `LiteLLM_Params` - https://github.com/BerriAI/litellm/blob/f09e6ba98d65e035a79f73bc069145002ceafd36/litellm/router.py#L67-- Returns:- - string (api_base) or None-- Example:- ```- from litellm import get_api_base-- get_api_base(model="gemini/gemini-pro")- ```- """-- try:- if isinstance(optional_params, LiteLLM_Params):- _optional_params = optional_params- elif "model" in optional_params:- _optional_params = LiteLLM_Params(**optional_params)- else: # prevent needing to copy and pop the dict- _optional_params = LiteLLM_Params(- model=model, **optional_params- ) # convert to pydantic object- except Exception as e:- verbose_logger.debug("Error occurred in getting api base - {}".format(str(e)))- return None- # get llm provider-- if _optional_params.api_base is not None:- return _optional_params.api_base-- if litellm.model_alias_map and model in litellm.model_alias_map:- model = litellm.model_alias_map[model]- try:- (- model,- custom_llm_provider,- dynamic_api_key,- dynamic_api_base,- ) = get_llm_provider(- model=model,- custom_llm_provider=_optional_params.custom_llm_provider,- api_base=_optional_params.api_base,- api_key=_optional_params.api_key,- )- except Exception as e:- verbose_logger.debug("Error occurred in getting api base - {}".format(str(e)))- custom_llm_provider = None- dynamic_api_base = None-- if dynamic_api_base is not None:- return dynamic_api_base-- stream: bool = getattr(optional_params, "stream", False)-- if (- _optional_params.vertex_location is not None- and _optional_params.vertex_project is not None- ):- from litellm.llms.vertex_ai.vertex_ai_partner_models.main import (- VertexPartnerProvider,- create_vertex_url,- )-- if "claude" in model:- _api_base = create_vertex_url(- vertex_location=_optional_params.vertex_location,- vertex_project=_optional_params.vertex_project,- model=model,- stream=stream,- partner=VertexPartnerProvider.claude,- )- else:- if stream:- _api_base = "{}-aiplatform.googleapis.com/v1/projects/{}/locations/{}/publishers/google/models/{}:streamGenerateContent".format(- _optional_params.vertex_location,- _optional_params.vertex_project,- _optional_params.vertex_location,- model,- )- else:- _api_base = "{}-aiplatform.googleapis.com/v1/projects/{}/locations/{}/publishers/google/models/{}:generateContent".format(- _optional_params.vertex_location,- _optional_params.vertex_project,- _optional_params.vertex_location,- model,- )- return _api_base-- if custom_llm_provider is None:- return None-- if custom_llm_provider == "gemini":- if stream:- _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:streamGenerateContent".format(- model- )- else:- _api_base = "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent".format(- model- )- return _api_base- elif custom_llm_provider == "openai":- _api_base = "https://api.openai.com"- return _api_base- return None--def get_first_chars_messages(kwargs: dict) -> str:try:_messages = kwargs.get("messages")@@ -4034,54 +3923,6 @@ def _count_characters(text: str) -> int:return len(filtered_text)-def get_formatted_prompt(- data: dict,- call_type: Literal[- "completion",- "embedding",- "image_generation",- "audio_transcription",- "moderation",- "text_completion",- ],-) -> str:- """- Extracts the prompt from the input data based on the call type.-- Returns a string.- """- prompt = ""- if call_type == "completion":- for message in data["messages"]:- if message.get("content", None) is not None:- content = message.get("content")- if isinstance(content, str):- prompt += message["content"]- elif isinstance(content, List):- for c in content:- if c["type"] == "text":- prompt += c["text"]- if "tool_calls" in message:- for tool_call in message["tool_calls"]:- if "function" in tool_call:- function_arguments = tool_call["function"]["arguments"]- prompt += function_arguments- elif call_type == "text_completion":- prompt = data["prompt"]- elif call_type == "embedding" or call_type == "moderation":- if isinstance(data["input"], str):- prompt = data["input"]- elif isinstance(data["input"], list):- for m in data["input"]:- prompt += m- elif call_type == "image_generation":- prompt = data["prompt"]- elif call_type == "audio_transcription":- if "prompt" in data:- prompt = data["prompt"]- return prompt--def get_response_string(response_obj: ModelResponse) -> str:_choices: List[Union[Choices, StreamingChoices]] = response_obj.choices@@ -4283,6 +4124,62 @@ def _check_provider_match(model_info: dict, custom_llm_provider: Optional[str])return True+from typing import TypedDict+++class PotentialModelNamesAndCustomLLMProvider(TypedDict):+ split_model: str+ combined_model_name: str+ stripped_model_name: str+ combined_stripped_model_name: str+ custom_llm_provider: str+++def _get_potential_model_names(+ model: str, custom_llm_provider: Optional[str]+) -> PotentialModelNamesAndCustomLLMProvider:+ if custom_llm_provider is None:+ # Get custom_llm_provider+ try:+ split_model, custom_llm_provider, _, _ = get_llm_provider(model=model)+ except Exception:+ split_model = model+ combined_model_name = model+ stripped_model_name = _strip_model_name(+ model=model, custom_llm_provider=custom_llm_provider+ )+ combined_stripped_model_name = stripped_model_name+ elif custom_llm_provider and model.startswith(+ custom_llm_provider + "/"+ ): # handle case where custom_llm_provider is provided and model starts with custom_llm_provider+ split_model = model.split("/")[1]+ combined_model_name = model+ stripped_model_name = _strip_model_name(+ model=split_model, custom_llm_provider=custom_llm_provider+ )+ combined_stripped_model_name = "{}/{}".format(+ custom_llm_provider, stripped_model_name+ )+ else:+ split_model = model+ combined_model_name = "{}/{}".format(custom_llm_provider, model)+ stripped_model_name = _strip_model_name(+ model=model, custom_llm_provider=custom_llm_provider+ )+ combined_stripped_model_name = "{}/{}".format(+ custom_llm_provider,+ _strip_model_name(model=model, custom_llm_provider=custom_llm_provider),+ )++ return PotentialModelNamesAndCustomLLMProvider(+ split_model=split_model,+ combined_model_name=combined_model_name,+ stripped_model_name=stripped_model_name,+ combined_stripped_model_name=combined_stripped_model_name,+ custom_llm_provider=cast(str, custom_llm_provider),+ )++def get_model_info( # noqa: PLR0915model: str, custom_llm_provider: Optional[str] = None) -> ModelInfo:@@ -4390,28 +4287,16 @@ def get_model_info( # noqa: PLR0915elif model + "@latest" in litellm.vertex_ai_ai21_models:model = model + "@latest"##########################- if custom_llm_provider is None:- # Get custom_llm_provider- try:- split_model, custom_llm_provider, _, _ = get_llm_provider(model=model)- except Exception:- split_model = model- combined_model_name = model- stripped_model_name = _strip_model_name(- model=model, custom_llm_provider=custom_llm_provider- )- combined_stripped_model_name = stripped_model_name- else:- split_model = model- combined_model_name = "{}/{}".format(custom_llm_provider, model)- stripped_model_name = _strip_model_name(- model=model, custom_llm_provider=custom_llm_provider- )- combined_stripped_model_name = "{}/{}".format(- custom_llm_provider,- _strip_model_name(model=model, custom_llm_provider=custom_llm_provider),- )-+ potential_model_names = _get_potential_model_names(+ model=model, custom_llm_provider=custom_llm_provider+ )+ combined_model_name = potential_model_names["combined_model_name"]+ stripped_model_name = potential_model_names["stripped_model_name"]+ combined_stripped_model_name = potential_model_names[+ "combined_stripped_model_name"+ ]+ split_model = potential_model_names["split_model"]+ custom_llm_provider = potential_model_names["custom_llm_provider"]#########################supported_openai_params = litellm.get_supported_openai_params(model=model, custom_llm_provider=custom_llm_provider@@ -5956,8 +5841,10 @@ def _get_base_model_from_metadata(model_call_details=None):if model_call_details is None:return Nonelitellm_params = model_call_details.get("litellm_params", {})-if litellm_params is not None:+ _base_model = litellm_params.get("base_model", None)+ if _base_model is not None:+ return _base_modelmetadata = litellm_params.get("metadata", {})return _get_base_model_from_litellm_call_metadata(metadata=metadata)diff --git a/tests/llm_translation/test_bedrock_completion.py b/tests/llm_translation/test_bedrock_completion.pyindex d466a13553e..5aa23e2dfa2 100644--- a/tests/llm_translation/test_bedrock_completion.py+++ b/tests/llm_translation/test_bedrock_completion.py@@ -2232,6 +2232,24 @@ def test_bedrock_nova_topk(top_k_param):assert 'inferenceConfig' in captured_data['additionalModelRequestFields']assert captured_data['additionalModelRequestFields']['inferenceConfig']['topK'] == 10+def test_bedrock_empty_content_real_call():+ completion(+ model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0",+ messages=[+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": "",+ },+ {"type": "text", "text": "Hey, how's it going?"},+ ],+ }+ ],+ )++def test_bedrock_process_empty_text_blocks():from litellm.litellm_core_utils.prompt_templates.factory import (process_empty_text_blocks,diff --git a/tests/llm_translation/test_vertex.py b/tests/llm_translation/test_vertex.pyindex aa1fdc7d049..ee820e99e14 100644--- a/tests/llm_translation/test_vertex.py+++ b/tests/llm_translation/test_vertex.py@@ -125,6 +125,7 @@ def test_build_vertex_schema():@pytest.mark.parametrize("tools, key",[+ ([{"googleSearch": {}}], "googleSearch"),([{"googleSearchRetrieval": {}}], "googleSearchRetrieval"),([{"code_execution": {}}], "code_execution"),],diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.pyindex 38dc3439223..8c01a6889db 100644--- a/tests/local_testing/test_amazing_vertex_completion.py+++ b/tests/local_testing/test_amazing_vertex_completion.py@@ -60,6 +60,7 @@ VERTEX_MODELS_TO_NOT_TEST = ["gemini-1.5-flash-exp-0827","gemini-pro-flash","gemini-1.5-flash-exp-0827",+ "gemini-2.0-flash-exp"]diff --git a/tests/local_testing/test_audio_speech.py b/tests/local_testing/test_audio_speech.pyindex a51d86e447c..cef9d354d52 100644--- a/tests/local_testing/test_audio_speech.py+++ b/tests/local_testing/test_audio_speech.py@@ -279,3 +279,38 @@ async def test_speech_litellm_vertex_async_with_voice_ssml():"voice": {"languageCode": "en-UK", "name": "en-UK-Studio-O"},"audioConfig": {"audioEncoding": "LINEAR22", "speakingRate": "10"},}+++def test_audio_speech_cost_calc():+ from litellm.integrations.custom_logger import CustomLogger++ model = "azure/azure-tts"+ api_base = os.getenv("AZURE_SWEDEN_API_BASE")+ api_key = os.getenv("AZURE_SWEDEN_API_KEY")++ custom_logger = CustomLogger()+ litellm.set_verbose = True++ with patch.object(custom_logger, "log_success_event") as mock_cost_calc:+ litellm.callbacks = [custom_logger]+ litellm.speech(+ model=model,+ voice="alloy",+ input="the quick brown fox jumped over the lazy dogs",+ api_base=api_base,+ api_key=api_key,+ base_model="azure/tts-1",+ )++ time.sleep(1)++ mock_cost_calc.assert_called_once()++ print(+ f"mock_cost_calc.call_args: {mock_cost_calc.call_args.kwargs['kwargs'].keys()}"+ )+ standard_logging_payload = mock_cost_calc.call_args.kwargs["kwargs"][+ "standard_logging_object"+ ]+ print(f"standard_logging_payload: {standard_logging_payload}")+ assert standard_logging_payload["response_cost"] > 0diff --git a/tests/local_testing/test_completion_cost.py b/tests/local_testing/test_completion_cost.pyindex 57061e6b630..8a0fbff2f8f 100644--- a/tests/local_testing/test_completion_cost.py+++ b/tests/local_testing/test_completion_cost.py@@ -191,6 +191,8 @@ def test_cost_ft_gpt_35():from litellm import Choices, Message, ModelResponsefrom litellm.utils import Usage+ litellm.set_verbose = True+resp = ModelResponse(id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",choices=[@@ -223,6 +225,7 @@ def test_cost_ft_gpt_35():print("\n Excpected cost", expected_cost)assert cost == expected_costexcept Exception as e:+ print(f"Error: {e}")pytest.fail(f"Cost Calc failed for ft:gpt-3.5. Expected {expected_cost}, Calculated cost {cost}")@@ -250,12 +253,12 @@ def test_cost_azure_gpt_35():),)],- model="gpt-35-turbo", # azure always has model written like this+ model="azure/gpt-35-turbo", # azure always has model written like thisusage=Usage(prompt_tokens=21, completion_tokens=17, total_tokens=38),)cost = litellm.completion_cost(- completion_response=resp, model="azure/gpt-35-turbo"+ completion_response=resp, model="azure/chatgpt-deployment-2")print("\n Calculated Cost for azure/gpt-3.5-turbo", cost)input_cost = model_cost["azure/gpt-35-turbo"]["input_cost_per_token"]@@ -1157,7 +1160,7 @@ def test_completion_cost_azure_common_deployment_name():mock_client.assert_called()print(f"mock_client.call_args: {mock_client.call_args.kwargs}")- assert "azure/gpt-4" == mock_client.call_args.kwargs["model"]+ assert "azure/gpt-4" == mock_client.call_args.kwargs["base_model"]def test_completion_cost_anthropic_prompt_caching():@@ -1260,7 +1263,7 @@ def test_completion_cost_anthropic_prompt_caching():"databricks/databricks-meta-llama-3-1-70b-instruct","databricks/databricks-meta-llama-3-70b-instruct","databricks/databricks-dbrx-instruct",- "databricks/databricks-mixtral-8x7b-instruct",+ # "databricks/databricks-mixtral-8x7b-instruct",],)def test_completion_cost_databricks(model):@@ -2636,3 +2639,60 @@ def test_completion_cost_azure_ai_meta():cost = completion_cost(model_response, custom_llm_provider="azure_ai")assert cost > 0+++def test_completion_cost_azure_tts():+ from unittest.mock import MagicMock++ args = {+ "response_object": MagicMock,+ "model": "tts-1",+ "cache_hit": None,+ "custom_llm_provider": "azure",+ "base_model": None,+ "call_type": "aspeech",+ "optional_params": {},+ "custom_pricing": False,+ }+ litellm.response_cost_calculator(**args)+++def test_select_model_name_for_cost_calc():+ from litellm.cost_calculator import _select_model_name_for_cost_calc+ from litellm.types.utils import ModelResponse, Choices, Usage, Message++ args = {+ "model": "Mistral-large-nmefg",+ "completion_response": ModelResponse(+ id="127f24aed4984b4c9a4c5e32ad3752f3",+ created=1734406048,+ model="azure_ai/mistral-large",+ object="chat.completion",+ system_fingerprint=None,+ choices=[+ Choices(+ finish_reason="length",+ index=0,+ message=Message(+ content="I'm an artificial intelligence and do not have an LLM (Master",+ role="assistant",+ tool_calls=None,+ function_call=None,+ ),+ )+ ],+ usage=Usage(+ completion_tokens=15,+ prompt_tokens=8,+ total_tokens=23,+ completion_tokens_details=None,+ prompt_tokens_details=None,+ ),+ service_tier=None,+ ),+ "base_model": None,+ "custom_pricing": None,+ }++ return_model = _select_model_name_for_cost_calc(**args)+ assert return_model == "azure_ai/mistral-large"diff --git a/tests/local_testing/test_gcs_bucket.py b/tests/local_testing/test_gcs_bucket.pyindex 0813596810c..f0b11e6418d 100644--- a/tests/local_testing/test_gcs_bucket.py+++ b/tests/local_testing/test_gcs_bucket.py@@ -532,10 +532,10 @@ async def test_get_gcs_logging_config_without_service_account():"""load_vertex_ai_credentials()_old_gcs_bucket_name = os.environ.get("GCS_BUCKET_NAME")- os.environ.pop("GCS_BUCKET_NAME")+ os.environ.pop("GCS_BUCKET_NAME", None)_old_gcs_service_acct = os.environ.get("GCS_PATH_SERVICE_ACCOUNT")- os.environ.pop("GCS_PATH_SERVICE_ACCOUNT")+ os.environ.pop("GCS_PATH_SERVICE_ACCOUNT", None)# Mock the load_auth function to avoid credential loading issues# Test 1: With standard_callback_dynamic_params (with service account)diff --git a/tests/local_testing/test_get_model_info.py b/tests/local_testing/test_get_model_info.pyindex 9f8e05d9eb0..a5b3b31ec66 100644--- a/tests/local_testing/test_get_model_info.py+++ b/tests/local_testing/test_get_model_info.py@@ -37,7 +37,8 @@ def test_get_model_info_custom_llm_with_same_name_vllm():model = "command-r-plus"provider = "openai" # vllm is openai-compatibletry:- litellm.get_model_info(model, custom_llm_provider=provider)+ model_info = litellm.get_model_info(model, custom_llm_provider=provider)+ print("model_info", model_info)pytest.fail("Expected get model info to fail for an unmapped model/provider")except Exception:pass@@ -94,7 +95,7 @@ def test_get_model_info_ollama_chat():assert info["supports_function_calling"] is Trueinfo = get_model_info("ollama/mistral")-+ print("info", info)assert info["supports_function_calling"] is Truemock_client.assert_called()@@ -147,3 +148,13 @@ def test_get_model_info_bedrock_region():def test_get_model_info_completion_cost_unit_tests(model):info = litellm.get_model_info(model)print("info", info)+++def test_get_model_info_ft_model_with_provider_prefix():+ args = {+ "model": "openai/ft:gpt-3.5-turbo:my-org:custom_suffix:id",+ "custom_llm_provider": "openai",+ }+ info = litellm.get_model_info(**args)+ print("info", info)+ assert info["key"] == "ft:gpt-3.5-turbo"diff --git a/tests/local_testing/test_streaming.py b/tests/local_testing/test_streaming.pyindex 22d043a97be..285b8b298c0 100644--- a/tests/local_testing/test_streaming.py+++ b/tests/local_testing/test_streaming.py@@ -3978,3 +3978,13 @@ def test_streaming_tool_calls_valid_json_str(model):for k, v in tool_call_id_arg_map.items():print("k={}, v={}".format(k, v))json.loads(v) # valid json str+++def test_streaming_api_base():+ litellm.set_verbose = False+ stream = litellm.completion(+ model="gpt-3.5-turbo",+ messages=[{"role": "user", "content": "Hey"}],+ stream=True,+ )+ assert "https://api.openai.com" in stream._hidden_params["api_base"]