Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 26 additions & 9 deletions litellm/llms/cohere/embed/v1_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,35 @@ def _transform_response(
additional_args={"complete_input_dict": data},
original_response=response_json,
)
return self._populate_embedding_response(
response_json=response_json,
model_response=model_response,
model=model,
encoding=encoding,
input=input,
)

def _populate_embedding_response(
self,
response_json: dict,
model_response: EmbeddingResponse,
model: str,
encoding: Any,
input: list,
) -> EmbeddingResponse:
"""
response
Parse a Cohere embed response body into an OpenAI-style EmbeddingResponse.

Split out from `_transform_response` so callers that already log
`post_call` themselves (e.g. SageMaker's embedding handler) can reuse
the parsing without triggering a second `post_call`.

Response shape:
{
'object': "list",
'data': [

]
'model',
'usage'
'data': [...],
'model',
'usage',
}
"""
embeddings = response_json["embeddings"]
Expand Down Expand Up @@ -149,9 +169,6 @@ def _transform_response(
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,
Expand Down
2 changes: 1 addition & 1 deletion litellm/llms/sagemaker/completion/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,7 @@ def embedding(
logger_fn=None,
):
"""
Supports both Huggingface Jumpstart embeddings and Voyage models
Supports Hugging Face (TGI), Voyage, and Cohere embedding endpoints
"""
### BOTO3 INIT
import boto3
Expand Down
141 changes: 141 additions & 0 deletions litellm/llms/sagemaker/embedding/cohere_transformation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
"""
Translate from OpenAI's `/v1/embeddings` to Sagemaker's `/invoke`

In the native Cohere embed format for self-hosted Cohere endpoints
(AWS Marketplace / JumpStart). Cohere containers expect
`{"texts": [...], "input_type": "..."}` and reject the HuggingFace TGI shape
`{"inputs": [...]}` with `422 EmbedReqV2.inputs is of type string but should
be of type Object`.

Reference: https://docs.cohere.com/v2/reference/embed
"""

from typing import TYPE_CHECKING, Any, List, Optional, Union, cast

if TYPE_CHECKING:
from litellm.types.llms.openai import AllEmbeddingInputValues

from httpx._models import Headers, Response

import litellm
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
from litellm.llms.bedrock.embed.cohere_transformation import (
BedrockCohereEmbeddingConfig,
)
from litellm.llms.cohere.embed.v1_transformation import CohereEmbeddingConfig
from litellm.types.utils import EmbeddingResponse

from ..common_utils import SagemakerError


class SagemakerCohereEmbeddingConfig(BaseEmbeddingConfig):
"""
SageMaker invoke payload for self-hosted Cohere embed models.
"""

def __init__(self) -> None:
pass

def get_supported_openai_params(self, model: str) -> List[str]:
return ["encoding_format", "dimensions", "input_type"]

def map_openai_params(
self,
non_default_params: dict,
optional_params: dict,
model: str,
drop_params: bool,
) -> dict:
optional_params = BedrockCohereEmbeddingConfig().map_openai_params(
non_default_params=non_default_params,
optional_params=optional_params,
)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if "input_type" in non_default_params:
optional_params["input_type"] = non_default_params["input_type"]
return optional_params

def get_error_class(
self, error_message: str, status_code: int, headers: Union[dict, Headers]
) -> BaseLLMException:
return SagemakerError(
message=error_message, status_code=status_code, headers=headers
)

def transform_embedding_request(
self,
model: str,
input: "AllEmbeddingInputValues",
optional_params: dict,
headers: dict,
) -> dict:
"""
Transform embedding request for Cohere models on SageMaker
"""
if isinstance(input, str):
input_list: List[str] = [input]
elif isinstance(input, list):
if input and (isinstance(input[0], list) or isinstance(input[0], int)):
raise ValueError("Input must be a list of strings")
input_list = cast(List[str], input)
else:
input_list = [str(input)]

return dict(
BedrockCohereEmbeddingConfig()._transform_request(
model=model,
input=input_list,
inference_params=optional_params,
)
)

def transform_embedding_response(
self,
model: str,
raw_response: Response,
model_response: "EmbeddingResponse",
logging_obj: Any,
api_key: Optional[str] = None,
request_data: dict = {},
optional_params: dict = {},
litellm_params: dict = {},
) -> "EmbeddingResponse":
"""
Transform embedding response for Cohere models on SageMaker.

Uses `CohereEmbeddingConfig._populate_embedding_response` (not
`_transform_response`) so we do not log `post_call` a second time
— the SageMaker embedding handler already logs `post_call` before
invoking this transform.
"""
input_value = (
logging_obj.model_call_details.get("input")
or request_data.get("texts")
or request_data.get("images")
or []
)
if isinstance(input_value, str):
input_value = [input_value]

return CohereEmbeddingConfig()._populate_embedding_response(
response_json=raw_response.json(),
model_response=model_response,
model=model,
encoding=litellm.encoding,
input=input_value,
)

def validate_environment(
self,
headers: dict,
model: str,
messages: List[Any],
optional_params: dict,
litellm_params: dict,
api_key: Optional[str] = None,
api_base: Optional[str] = None,
) -> dict:
"""
Validate environment for SageMaker Cohere embeddings
"""
return {"Content-Type": "application/json"}
22 changes: 13 additions & 9 deletions litellm/llms/sagemaker/embedding/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@

from httpx._models import Headers, Response

from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.types.utils import Usage, EmbeddingResponse
from litellm.llms.base_llm.embedding.transformation import BaseEmbeddingConfig
from litellm.llms.voyage.embedding.transformation import VoyageEmbeddingConfig
from litellm.types.utils import EmbeddingResponse, Usage

from ..common_utils import SagemakerError
from .cohere_transformation import SagemakerCohereEmbeddingConfig


class SagemakerEmbeddingConfig(BaseEmbeddingConfig):
Expand All @@ -38,17 +39,20 @@ def get_model_config(cls, model: str) -> "BaseEmbeddingConfig":
Returns:
Appropriate embedding config instance
"""
if "voyage" in model.lower():
model_lower = model.lower()
if "voyage" in model_lower:
return VoyageEmbeddingConfig()
else:
return cls()
if "cohere" in model_lower:
return SagemakerCohereEmbeddingConfig()
return cls()

def get_supported_openai_params(self, model: str) -> List[str]:
# Check if this is an embedding model
if "voyage" in model.lower():
model_lower = model.lower()
if "voyage" in model_lower:
return VoyageEmbeddingConfig().get_supported_openai_params(model)
else:
return []
if "cohere" in model_lower:
return SagemakerCohereEmbeddingConfig().get_supported_openai_params(model)
return []

def map_openai_params(
self,
Expand Down
15 changes: 15 additions & 0 deletions litellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3343,6 +3343,21 @@ def _check_valid_arg(supported_params: Optional[list]):
model=model,
drop_params=drop_params if drop_params is not None else False,
)
# Provider-only params (e.g. Cohere input_type) are not in
# OPENAI_EMBEDDING_PARAMS, so embedding_pre_process drops them from
# non_default_params before map_openai_params. Restore only those extras
# from passed_params — skip OPENAI_EMBEDDING_PARAMS to avoid duplicating
# values already mapped (e.g. dimensions -> output_dimension).
if supported_params:
for param in supported_params:
if param in OPENAI_EMBEDDING_PARAMS:
continue
if (
param in passed_params
and passed_params[param] is not None
and param not in optional_params
):
optional_params[param] = passed_params[param]
## raise exception if non-default value passed for non-openai/azure embedding calls
elif custom_llm_provider == "openai":
# 'dimensions` is only supported in `text-embedding-3` and later models
Expand Down
Loading
Loading