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]

Migrate cohere to `/v2/embed` - adds support for output_dimensions param (#10809)

Krish Dholakia340a0453d33d
diff --git a/litellm/litellm_core_utils/llm_response_utils/get_api_base.py b/litellm/litellm_core_utils/llm_response_utils/get_api_base.py
index ddac7ac3244..6f9fa36591f 100644
--- a/litellm/litellm_core_utils/llm_response_utils/get_api_base.py
+++ b/litellm/litellm_core_utils/llm_response_utils/get_api_base.py
@@ -37,8 +37,7 @@ def get_api_base(
_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)))
+ except Exception:
return None
# get llm provider
diff --git a/litellm/llms/cohere/embed/handler.py b/litellm/llms/cohere/embed/handler.py
index 7a25bf7e541..41b81279723 100644
--- a/litellm/llms/cohere/embed/handler.py
+++ b/litellm/llms/cohere/embed/handler.py
@@ -1,3 +1,7 @@
+"""
+Legacy /v1/embedding handler for Bedrock Cohere.
+"""
+
import json
from typing import Any, Callable, Optional, Union
@@ -13,7 +17,7 @@ from litellm.llms.custom_httpx.http_handler import (
from litellm.types.llms.bedrock import CohereEmbeddingRequest
from litellm.types.utils import EmbeddingResponse
-from .transformation import CohereEmbeddingConfig
+from .v1_transformation import CohereEmbeddingConfig
def validate_environment(api_key, headers: dict):
diff --git a/litellm/llms/cohere/embed/transformation.py b/litellm/llms/cohere/embed/transformation.py
index 837dd5e006e..03d7edd1262 100644
--- a/litellm/llms/cohere/embed/transformation.py
+++ b/litellm/llms/cohere/embed/transformation.py
@@ -10,21 +10,27 @@ Convers
Docs - https://docs.cohere.com/v2/reference/embed
"""
-from typing import Any, List, Optional, Union
+from typing import Any, List, Optional, Union, cast
import httpx
+import litellm
from litellm import COHERE_DEFAULT_EMBEDDING_INPUT_TYPE
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.llms.base_llm import BaseEmbeddingConfig
+from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.types.llms.bedrock import (
CohereEmbeddingRequest,
CohereEmbeddingRequestWithModel,
)
+from litellm.types.llms.openai import AllEmbeddingInputValues, AllMessageValues
from litellm.types.utils import EmbeddingResponse, PromptTokensDetailsWrapper, Usage
from litellm.utils import is_base64_encoded
+from ..common_utils import CohereError
-class CohereEmbeddingConfig:
+
+class CohereEmbeddingConfig(BaseEmbeddingConfig):
"""
Reference: https://docs.cohere.com/v2/reference/embed
"""
@@ -32,20 +38,55 @@ class CohereEmbeddingConfig:
def __init__(self) -> None:
pass
- def get_supported_openai_params(self) -> List[str]:
- return ["encoding_format"]
+ def get_supported_openai_params(self, model: str) -> List[str]:
+ return ["encoding_format", "dimensions"]
def map_openai_params(
- self, non_default_params: dict, optional_params: dict
+ self,
+ non_default_params: dict,
+ optional_params: dict,
+ model: str,
+ drop_params: bool = False,
) -> dict:
for k, v in non_default_params.items():
if k == "encoding_format":
optional_params["embedding_types"] = v
+ elif k == "dimensions":
+ optional_params["output_dimension"] = v
return optional_params
+ def validate_environment(
+ self,
+ headers: dict,
+ model: str,
+ messages: List[AllMessageValues],
+ optional_params: dict,
+ litellm_params: dict,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
+ ) -> dict:
+ default_headers = {
+ "Content-Type": "application/json",
+ }
+ if api_key:
+ default_headers["Authorization"] = f"Bearer {api_key}"
+ headers = {**default_headers, **headers}
+ return headers
+
def _is_v3_model(self, model: str) -> bool:
return "3" in model
+ def get_complete_url(
+ self,
+ api_base: Optional[str],
+ api_key: Optional[str],
+ model: str,
+ optional_params: dict,
+ litellm_params: dict,
+ stream: Optional[bool] = None,
+ ) -> str:
+ return api_base or "https://api.cohere.ai/v2/embed"
+
def _transform_request(
self, model: str, input: List[str], inference_params: dict
) -> CohereEmbeddingRequestWithModel:
@@ -71,6 +112,26 @@ class CohereEmbeddingConfig:
return transformed_request
+ def transform_embedding_request(
+ self,
+ model: str,
+ input: AllEmbeddingInputValues,
+ optional_params: dict,
+ headers: dict,
+ ) -> dict:
+ if isinstance(input, list) and (
+ isinstance(input[0], list) or isinstance(input[0], int)
+ ):
+ raise ValueError("Input must be a list of strings")
+ return cast(
+ dict,
+ self._transform_request(
+ model=model,
+ input=cast(List[str], input) if isinstance(input, List) else [input],
+ inference_params=optional_params,
+ ),
+ )
+
def _calculate_usage(self, input: List[str], encoding: Any, meta: dict) -> Usage:
input_tokens = 0
@@ -131,10 +192,11 @@ class CohereEmbeddingConfig:
"""
embeddings = response_json["embeddings"]
output_data = []
- for idx, embedding in enumerate(embeddings):
- output_data.append(
- {"object": "embedding", "index": idx, "embedding": embedding}
- )
+ for k, embedding_list in embeddings.items():
+ for idx, embedding in enumerate(embedding_list):
+ output_data.append(
+ {"object": "embedding", "index": idx, "embedding": embedding}
+ )
model_response.object = "list"
model_response.data = output_data
model_response.model = model
@@ -149,3 +211,33 @@ class CohereEmbeddingConfig:
)
return model_response
+
+ def transform_embedding_response(
+ self,
+ model: str,
+ raw_response: httpx.Response,
+ model_response: EmbeddingResponse,
+ logging_obj: LiteLLMLoggingObj,
+ api_key: Optional[str],
+ request_data: dict,
+ optional_params: dict,
+ litellm_params: dict,
+ ) -> EmbeddingResponse:
+ return self._transform_response(
+ response=raw_response,
+ api_key=api_key,
+ logging_obj=logging_obj,
+ data=request_data,
+ model_response=model_response,
+ model=model,
+ encoding=litellm.encoding,
+ input=logging_obj.model_call_details["input"],
+ )
+
+ def get_error_class(
+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]
+ ) -> BaseLLMException:
+ return CohereError(
+ status_code=status_code,
+ message=error_message,
+ )
diff --git a/litellm/llms/cohere/embed/v1_transformation.py b/litellm/llms/cohere/embed/v1_transformation.py
new file mode 100644
index 00000000000..e55899a4afa
--- /dev/null
+++ b/litellm/llms/cohere/embed/v1_transformation.py
@@ -0,0 +1,143 @@
+"""
+Legacy /v1/embedding transformation logic for Bedrock Cohere.
+"""
+
+from typing import Any, List, Optional, Union
+
+import httpx
+
+from litellm import COHERE_DEFAULT_EMBEDDING_INPUT_TYPE
+from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
+from litellm.types.llms.bedrock import (
+ CohereEmbeddingRequest,
+ CohereEmbeddingRequestWithModel,
+)
+from litellm.types.utils import EmbeddingResponse, PromptTokensDetailsWrapper, Usage
+from litellm.utils import is_base64_encoded
+
+
+class CohereEmbeddingConfig:
+ """
+ Reference: https://docs.cohere.com/v2/reference/embed
+ """
+
+ def __init__(self) -> None:
+ pass
+
+ def get_supported_openai_params(self) -> List[str]:
+ return ["encoding_format"]
+
+ def map_openai_params(
+ self, non_default_params: dict, optional_params: dict
+ ) -> dict:
+ for k, v in non_default_params.items():
+ if k == "encoding_format":
+ optional_params["embedding_types"] = v
+ return optional_params
+
+ def _is_v3_model(self, model: str) -> bool:
+ return "3" in model
+
+ def _transform_request(
+ self, model: str, input: List[str], inference_params: dict
+ ) -> CohereEmbeddingRequestWithModel:
+ is_encoded = False
+ for input_str in input:
+ is_encoded = is_base64_encoded(input_str)
+
+ if is_encoded: # check if string is b64 encoded image or not
+ transformed_request = CohereEmbeddingRequestWithModel(
+ model=model,
+ images=input,
+ input_type="image",
+ )
+ else:
+ transformed_request = CohereEmbeddingRequestWithModel(
+ model=model,
+ texts=input,
+ input_type=COHERE_DEFAULT_EMBEDDING_INPUT_TYPE,
+ )
+
+ for k, v in inference_params.items():
+ transformed_request[k] = v # type: ignore
+
+ return transformed_request
+
+ def _calculate_usage(self, input: List[str], encoding: Any, meta: dict) -> Usage:
+ input_tokens = 0
+
+ text_tokens: Optional[int] = meta.get("billed_units", {}).get("input_tokens")
+
+ image_tokens: Optional[int] = meta.get("billed_units", {}).get("images")
+
+ prompt_tokens_details: Optional[PromptTokensDetailsWrapper] = None
+ if image_tokens is None and text_tokens is None:
+ for text in input:
+ input_tokens += len(encoding.encode(text))
+ else:
+ prompt_tokens_details = PromptTokensDetailsWrapper(
+ image_tokens=image_tokens,
+ text_tokens=text_tokens,
+ )
+ if image_tokens:
+ input_tokens += image_tokens
+ if text_tokens:
+ input_tokens += text_tokens
+
+ return Usage(
+ prompt_tokens=input_tokens,
+ completion_tokens=0,
+ total_tokens=input_tokens,
+ prompt_tokens_details=prompt_tokens_details,
+ )
+
+ def _transform_response(
+ self,
+ response: httpx.Response,
+ api_key: Optional[str],
+ logging_obj: LiteLLMLoggingObj,
+ data: Union[dict, CohereEmbeddingRequest],
+ model_response: EmbeddingResponse,
+ model: str,
+ encoding: Any,
+ input: list,
+ ) -> EmbeddingResponse:
+ response_json = response.json()
+ ## LOGGING
+ logging_obj.post_call(
+ input=input,
+ api_key=api_key,
+ additional_args={"complete_input_dict": data},
+ original_response=response_json,
+ )
+ """
+ response
+ {
+ 'object': "list",
+ 'data': [
+
+ ]
+ 'model',
+ 'usage'
+ }
+ """
+ embeddings = response_json["embeddings"]
+ output_data = []
+ for idx, embedding in enumerate(embeddings):
+ output_data.append(
+ {"object": "embedding", "index": idx, "embedding": embedding}
+ )
+ model_response.object = "list"
+ model_response.data = output_data
+ model_response.model = model
+ input_tokens = 0
+ for text in input:
+ input_tokens += len(encoding.encode(text))
+
+ setattr(
+ model_response,
+ "usage",
+ self._calculate_usage(input, encoding, response_json.get("meta", {})),
+ )
+
+ return model_response
diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py
index 7e7fc12d78c..fb22a2f4ea1 100644
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@ -711,6 +711,10 @@ class BaseLLMHTTPHandler:
provider_config = ProviderConfigManager.get_provider_embedding_config(
model=model, provider=litellm.LlmProviders(custom_llm_provider)
)
+ if provider_config is None:
+ raise ValueError(
+ f"Provider {custom_llm_provider} does not support embedding"
+ )
# get config from model, custom llm provider
headers = provider_config.validate_environment(
api_key=api_key,
@@ -2016,7 +2020,11 @@ class BaseLLMHTTPHandler:
):
status_code = getattr(e, "status_code", 500)
error_headers = getattr(e, "headers", None)
- error_text = getattr(e, "text", str(e))
+ if isinstance(e, httpx.HTTPStatusError):
+ error_text = e.response.text
+ status_code = e.response.status_code
+ else:
+ error_text = getattr(e, "text", str(e))
error_response = getattr(e, "response", None)
if error_headers is None and error_response:
error_headers = getattr(error_response, "headers", None)
@@ -2026,6 +2034,7 @@ class BaseLLMHTTPHandler:
error_headers = dict(error_headers)
else:
error_headers = {}
+
raise provider_config.get_error_class(
error_message=error_text,
status_code=status_code,
diff --git a/litellm/main.py b/litellm/main.py
index 6a503ff3b6c..6be26ac239d 100644
--- a/litellm/main.py
+++ b/litellm/main.py
@@ -2726,9 +2726,9 @@ def completion( # type: ignore # noqa: PLR0915
"aws_region_name" not in optional_params
or optional_params["aws_region_name"] is None
):
- optional_params["aws_region_name"] = (
- aws_bedrock_client.meta.region_name
- )
+ optional_params[
+ "aws_region_name"
+ ] = aws_bedrock_client.meta.region_name
bedrock_route = BedrockModelInfo.get_bedrock_route(model)
if bedrock_route == "converse":
@@ -3649,8 +3649,8 @@ def embedding( # noqa: PLR0915
cohere_key = (
api_key
or litellm.cohere_key
- or get_secret("COHERE_API_KEY")
- or get_secret("CO_API_KEY")
+ or get_secret_str("COHERE_API_KEY")
+ or get_secret_str("CO_API_KEY")
or litellm.api_key
)
@@ -3658,18 +3658,21 @@ def embedding( # noqa: PLR0915
headers = extra_headers
else:
headers = {}
- response = cohere_embed.embedding(
+
+ response = base_llm_http_handler.embedding(
model=model,
input=input,
- optional_params=optional_params,
- encoding=encoding,
- api_key=cohere_key, # type: ignore
- headers=headers,
+ custom_llm_provider=custom_llm_provider,
+ api_base=api_base,
+ api_key=cohere_key,
logging_obj=logging,
- model_response=EmbeddingResponse(),
- aembedding=aembedding,
timeout=timeout,
+ model_response=EmbeddingResponse(),
+ optional_params=optional_params,
client=client,
+ aembedding=aembedding,
+ litellm_params=litellm_params_dict,
+ headers=headers,
)
elif custom_llm_provider == "huggingface":
api_key = (
@@ -4451,9 +4454,9 @@ def adapter_completion(
new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs)
response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore
- translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = (
- None
- )
+ translated_response: Optional[
+ Union[BaseModel, AdapterCompletionStreamWrapper]
+ ] = None
if isinstance(response, ModelResponse):
translated_response = translation_obj.translate_completion_output_params(
response=response
@@ -5921,9 +5924,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(content_chunks) > 0:
- response["choices"][0]["message"]["content"] = (
- processor.get_combined_content(content_chunks)
- )
+ response["choices"][0]["message"][
+ "content"
+ ] = processor.get_combined_content(content_chunks)
reasoning_chunks = [
chunk
@@ -5934,9 +5937,9 @@ def stream_chunk_builder( # noqa: PLR0915
]
if len(reasoning_chunks) > 0:
- response["choices"][0]["message"]["reasoning_content"] = (
- processor.get_combined_reasoning_content(reasoning_chunks)
- )
+ response["choices"][0]["message"][
+ "reasoning_content"
+ ] = processor.get_combined_reasoning_content(reasoning_chunks)
audio_chunks = [
chunk
diff --git a/litellm/utils.py b/litellm/utils.py
index 0eba5ed3151..ec8ad82b4a4 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -2369,8 +2369,33 @@ def get_optional_params_embeddings( # noqa: PLR0915
default_params=default_params,
additional_drop_params=additional_drop_params,
)
+
+ provider_config: Optional[BaseEmbeddingConfig] = None
+
+ if (
+ custom_llm_provider is not None
+ and custom_llm_provider in LlmProviders._member_map_.values()
+ ):
+ provider_config = ProviderConfigManager.get_provider_embedding_config(
+ model=model,
+ provider=LlmProviders(custom_llm_provider),
+ )
+
+ if provider_config is not None:
+ supported_params: Optional[list] = provider_config.get_supported_openai_params(
+ model=model
+ )
+ _check_valid_arg(supported_params=supported_params)
+ optional_params = provider_config.map_openai_params(
+ non_default_params=non_default_params,
+ optional_params={},
+ model=model,
+ drop_params=drop_params if drop_params is not None else False,
+ )
+ final_params = {**optional_params, **kwargs}
+ return final_params
## raise exception if non-default value passed for non-openai/azure embedding calls
- if custom_llm_provider == "openai":
+ elif custom_llm_provider == "openai":
# 'dimensions` is only supported in `text-embedding-3` and later models
if (
@@ -2552,7 +2577,9 @@ def get_optional_params_embeddings( # noqa: PLR0915
status_code=500,
message=f"Setting {non_default_params} is not supported by {custom_llm_provider}. To drop it from the call, set `litellm.drop_params = True`.",
)
+
final_params = {**non_default_params, **kwargs}
+
return final_params
@@ -6425,7 +6452,7 @@ class ProviderConfigManager:
def get_provider_embedding_config(
model: str,
provider: LlmProviders,
- ) -> BaseEmbeddingConfig:
+ ) -> Optional[BaseEmbeddingConfig]:
if litellm.LlmProviders.VOYAGE == provider:
return litellm.VoyageEmbeddingConfig()
elif litellm.LlmProviders.TRITON == provider:
@@ -6434,7 +6461,14 @@ class ProviderConfigManager:
return litellm.IBMWatsonXEmbeddingConfig()
elif litellm.LlmProviders.INFINITY == provider:
return litellm.InfinityEmbeddingConfig()
- raise ValueError(f"Provider {provider.value} does not support embedding config")
+ elif (
+ litellm.LlmProviders.COHERE == provider
+ or litellm.LlmProviders.COHERE_CHAT == provider
+ ):
+ from litellm.llms.cohere.embed.transformation import CohereEmbeddingConfig
+
+ return CohereEmbeddingConfig()
+ return None
@staticmethod
def get_provider_rerank_config(
diff --git a/tests/litellm/test_utils.py b/tests/litellm/test_utils.py
index 590f235f6da..36da4162a8e 100644
--- a/tests/litellm/test_utils.py
+++ b/tests/litellm/test_utils.py
@@ -306,3 +306,16 @@ def test_anthropic_web_search_in_model_info():
assert (
model_info["search_context_cost_per_query"] is not None
), f"Model {model} should have a search context cost per query"
+
+
+def test_cohere_embedding_optional_params():
+ from litellm import get_optional_params_embeddings
+
+ optional_params = get_optional_params_embeddings(
+ model="embed-v4.0",
+ custom_llm_provider="cohere",
+ input="Hello, world!",
+ input_type="search_query",
+ dimensions=512,
+ )
+ assert optional_params is not None
diff --git a/tests/llm_translation/test_cohere.py b/tests/llm_translation/test_cohere.py
index 6b4d3a2045b..dd1bde93a2d 100644
--- a/tests/llm_translation/test_cohere.py
+++ b/tests/llm_translation/test_cohere.py
@@ -281,3 +281,10 @@ async def test_cohere_request_body_with_allowed_params():
assert "allowed_openai_params" not in request_data
assert request_data["response_format"] == test_response_format
assert request_data["reasoning_effort"] == test_reasoning_effort
+
+
+def test_cohere_embedding_outout_dimensions():
+ litellm._turn_on_debug()
+ response = embedding(model="cohere/embed-v4.0", input="Hello, world!", dimensions=512)
+ print(f"response: {response}\n")
+ assert len(response.data[0]["embedding"]) == 512
\ No newline at end of file