litellm/tests/unit/llms/cohere/embed/test_transformation.py
zhengqiuyang ad24ca9f31
fix(cohere): honor COHERE_API_BASE for embeddings (#50249)
* fix(cohere): honor COHERE_API_BASE for embeddings

The cohere embedding branch in the dispatch passed the caller's api_base
straight through with no env fallback, so COHERE_API_BASE was silently
ignored for embeddings — the request went to the hardcoded
api.cohere.ai/v2/embed host. The rerank path (rerank_api/main.py) already
reads the same variable, and the databricks/hosted_vllm/openrouter
embedding branches follow the same convention; this branch was the
asymmetric one (same family as voyage's #49411).

Adds two respx regression tests: the env-routed gateway URL is used when
the variable is set, and the hardcoded default still applies when it is
not.

Signed-off-by: 郑润泽 <506166760@qq.com>

* fix(cohere): route COHERE_API_BASE through ensure_api_route and pin the url semantics

Review follow-up on #50249: COHERE_API_BASE means different things across
cohere's own paths (chat reads it as the full /v2/chat endpoint, rerank as
a base URL) and the PR initially used the verbatim reading — which breaks
a bare-host gateway silently (the request would land on the gateway root).

get_complete_url now runs whichever value it receives through
ensure_api_route(..., "v2/embed"): a bare host joins the route, a full
/v2/embed endpoint passes verbatim, and the no-env default is unchanged.
The default domain (api.cohere.ai vs the api.cohere.com the siblings use)
is left alone on purpose — flagging it here for a maintainer call instead
of bundling a behavior change into this fix.

Tests: three get_complete_url unit pins (bare host joins, full endpoint
verbatim, default unchanged) plus the env-routed respx test reshaped to
the bare-host form. 76 passed in tests/unit/llms/cohere/embed/.

Signed-off-by: 郑润泽 <506166760@qq.com>

* fix(cohere): fail fast when COHERE_API_BASE is a chat endpoint; pin verbatim-path semantics

Review of #50249 surfaced two gaps:

1. Chat reads COHERE_API_BASE as a complete URL (the value may end in
   /v2/chat or /v1/chat), while embeddings now treat it as a base to join
   /v2/embed onto. A chat-configured deployment upgrading would get
   embeddings at <chat-url>/v2/embed and 404. get_complete_url now fails
   fast with an actionable error when the value is a chat endpoint, so
   the user configures embeddings separately instead of silently losing
   them on upgrade.

2. The added tests only covered a bare gateway host — the one shape
   where join and verbatim agree. Adds a /v1/embed verbatim pin (the
   issue's original shape) and a chat-endpoint rejection test.

The query-string corruption in ensure_api_route (pre-existing, locked by
test_url_utils.py) is real but out of scope here — it predates this PR
and needs its own change plus a decision on the locked assertion.

Release-note-worthy: chat-only deployments that set COHERE_API_BASE and
then configure embeddings will now see the fail-fast error instead of a
silent 404.

Signed-off-by: 郑润泽 <506166760@qq.com>

* fix(cohere): resolve the embed api base without rebinding the parameter

AGENTS.md asks for no variable mutation and no comments that restate the code. The base is now a Final local next to cohere_key, and the three-line comment is gone. py_compile passes; the local pytest run is blocked by an unreleased native symbol (NativeRedisClient), so CI verifies the suite.

* fix(cohere): keep an explicit embedding endpoint verbatim

The route was appended to any path that did not already end in /v2/embed, so a gateway exposing /v1/embed or /embeddings received /v1/embed/v2/embed. An explicit embedding endpoint is now used as given, and a chat endpoint still fails fast.

* fix(cohere): keep the configured URL out of the chat-endpoint error

The message reaches proxy error responses, and a server-configured URL can carry credentials in its userinfo or query string.

* fix(cohere): raise BadRequestError for a chat-endpoint base and fix the verbatim test

Review on #50249: aembedding wrapped the guard ValueError into APIConnectionError, so the proxy answered a network error instead of 400. Raise litellm.BadRequestError and assert it. The explicit-endpoint test compared against api_base.rstrip(/) while the code returns the base untouched; compare against api_base. Also drop a corrupted character in the message.

Signed-off-by: 郑润泽 <506166760@qq.com>

* fix(cohere): send embeddings for a chat-endpoint COHERE_API_BASE to the same host's embed route

* fix(cohere): keep an explicit embed api_base as is and derive COHERE_API_BASE safely

An explicit api_base is the full request URL again, as before this PR.
Only COHERE_API_BASE is turned into an embed URL: a trailing /vN,
/vN/chat or /vN/rerank is dropped, /v2/embed is joined on the path so a
query string survives, and only a path ending in /embed is used as is.
litellm.api_base is no longer consulted for Cohere embeddings.

* test(cohere): drop an extra blank line in the embed URL tests

* fix(cohere): read COHERE_API_BASE for embeddings from the environment only

A proxy with a secret manager no longer makes an extra lookup on every
Cohere embedding call, and a bare /chat or /rerank path is now covered
by tests.

---------

Signed-off-by: 郑润泽 <506166760@qq.com>
Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
2026-11-14 04:30:11 -05:00

545 lines
21 KiB
Python

import dataclasses
import datetime
import json
from collections.abc import Iterator, Mapping
from typing import Final
import httpx
import pytest
import respx
from pydantic import ValidationError
import litellm
from litellm.caching.llm_caching_handler import LLMClientCache
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.llms.cohere.embed.transformation import CohereEmbeddingConfig
from litellm.types.secret_managers.main import KeyManagementSettings, KeyManagementSystem
from litellm.types.utils import EmbeddingResponse
FLOAT_VECTORS = [[0.1, 0.2], [0.3, 0.4]]
INT8_VECTORS = [[1, -2], [3, 4]]
def _transform(payload: object) -> EmbeddingResponse:
logging_obj = Logging(
model="embed-english-v3.0",
messages=[],
stream=False,
call_type="embedding",
start_time=datetime.datetime(2025, 1, 1, tzinfo=datetime.timezone.utc),
litellm_call_id="call-id",
function_id="function-id",
)
logging_obj.model_call_details["input"] = ["hello", "world"]
return CohereEmbeddingConfig().transform_embedding_response(
model="embed-english-v3.0",
raw_response=httpx.Response(200, json=payload),
model_response=EmbeddingResponse(),
logging_obj=logging_obj,
api_key="sk-test",
request_data={"model": "embed-english-v3.0", "texts": ["hello", "world"]},
optional_params={},
litellm_params={},
)
def _token_counts(response: EmbeddingResponse) -> tuple[int, int, int]:
assert response.usage is not None
return (response.usage.prompt_tokens, response.usage.completion_tokens, response.usage.total_tokens)
def test_cohere_embedding_response_lists_every_embedding_type_in_provider_order():
response = _transform(
{
"id": "embed-id",
"embeddings": {"float": FLOAT_VECTORS, "int8": INT8_VECTORS},
"meta": {"billed_units": {"input_tokens": 5}},
}
)
assert response.object == "list"
assert response.model == "embed-english-v3.0"
assert response.data == [
{"object": "embedding", "index": 0, "embedding": [0.1, 0.2]},
{"object": "embedding", "index": 1, "embedding": [0.3, 0.4]},
{"object": "embedding", "index": 0, "embedding": [1, -2]},
{"object": "embedding", "index": 1, "embedding": [3, 4]},
]
assert _token_counts(response) == (5, 0, 5)
@pytest.mark.parametrize(
("meta", "expected_counts", "expected_details"),
[
({"billed_units": {"input_tokens": 5}}, (5, 0, 5), (5, None)),
({"billed_units": {"input_tokens": 5, "image_tokens": 0}}, (5, 0, 5), (5, None)),
({"billed_units": {"images": 3}}, (3, 0, 3), (None, 3)),
({"billed_units": {"input_tokens": 5, "images": 3}}, (8, 0, 8), (5, 3)),
({"billed_units": {"input_tokens": 0, "image_tokens": 6}}, (6, 0, 6), (0, 6)),
({"billed_units": {"input_tokens": 3, "image_tokens": 6}}, (9, 0, 9), (3, 6)),
({"billed_units": {"input_tokens": 0}}, (0, 0, 0), (0, None)),
(
{"api_version": {"version": "2"}, "billed_units": {"input_tokens": 2, "output_tokens": 9}},
(2, 0, 2),
(2, None),
),
],
)
def test_cohere_embedding_usage_comes_from_billed_units(
meta: Mapping[str, object],
expected_counts: tuple[int, int, int],
expected_details: tuple[int | None, int | None],
) -> None:
response: Final = _transform({"embeddings": {"float": FLOAT_VECTORS}, "meta": meta})
assert response.usage is not None
details: Final = response.usage.prompt_tokens_details
assert details is not None
assert _token_counts(response) == expected_counts
assert (details.text_tokens, details.image_tokens) == expected_details
@pytest.mark.parametrize(
"payload",
[
{"embeddings": {"float": FLOAT_VECTORS}},
{"embeddings": {"float": FLOAT_VECTORS}, "meta": {}},
{"embeddings": {"float": FLOAT_VECTORS}, "meta": {"billed_units": {}}},
{"embeddings": {"float": FLOAT_VECTORS}, "meta": {"billed_units": {"input_tokens": None, "images": None}}},
],
)
def test_cohere_embedding_usage_counts_input_tokens_when_billed_units_are_absent(payload):
response = _transform(payload)
assert response.usage is not None
assert response.usage.prompt_tokens_details is None
assert _token_counts(response) == (2, 0, 2)
@pytest.mark.parametrize(
("embeddings", "expected_vectors"),
[
({}, []),
({"float": []}, []),
({"float": [], "int8": INT8_VECTORS}, INT8_VECTORS),
({"base64": ["AAAA", "BBBB"]}, ["AAAA", "BBBB"]),
({"float": [[0.1], "x", None, 3]}, [[0.1], "x", None, 3]),
],
)
def test_cohere_embedding_rows_pass_through_whatever_each_type_lists(embeddings, expected_vectors):
response = _transform({"embeddings": embeddings, "meta": {"billed_units": {"input_tokens": 1}}})
assert [row["embedding"] for row in response.data] == expected_vectors
@pytest.mark.parametrize("vectors", [FLOAT_VECTORS, []])
def test_cohere_v1_float_embeddings_list_one_row_per_vector(vectors: list[list[float]]) -> None:
response: Final = _transform(
{"embeddings": vectors, "meta": {"billed_units": {"input_tokens": 1}}, "response_type": "embeddings_floats"}
)
assert response.data == [
{"object": "embedding", "index": index, "embedding": vector} for index, vector in enumerate(vectors)
]
assert _token_counts(response) == (1, 0, 1)
@pytest.mark.parametrize("embeddings", [None, "vectors", 3])
def test_cohere_embeddings_that_are_neither_keyed_by_type_nor_a_list_are_rejected(embeddings: object) -> None:
with pytest.raises(ValidationError):
_transform({"embeddings": embeddings, "meta": {"billed_units": {"input_tokens": 1}}})
@pytest.mark.parametrize("vectors", [None, 3, False, 1.5])
def test_cohere_embedding_type_without_a_list_of_vectors_is_rejected(vectors):
with pytest.raises(ValidationError):
_transform({"embeddings": {"float": vectors}, "meta": {"billed_units": {"input_tokens": 1}}})
@pytest.mark.parametrize("meta", [None, [], "meta", 3])
def test_cohere_embedding_meta_that_is_not_an_object_is_rejected(meta):
with pytest.raises(ValidationError):
_transform({"embeddings": {"float": FLOAT_VECTORS}, "meta": meta})
@pytest.mark.parametrize("payload", [[1], "text", 3, True])
def test_cohere_embedding_body_that_is_not_an_object_is_rejected(payload):
with pytest.raises(ValidationError):
_transform(payload)
def test_cohere_embedding_body_without_embeddings_is_rejected() -> None:
with pytest.raises(ValidationError):
_transform({"meta": {"billed_units": {"input_tokens": 1}}})
COHERE_V2_EMBED_URL: Final = "https://api.cohere.ai/v2/embed"
ONE_PIXEL_PNG: Final = (
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC"
)
@pytest.fixture
def _cohere_httpx_transport(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
client_cache: Final = LLMClientCache()
monkeypatch.setattr(litellm, "in_memory_llm_clients_cache", client_cache)
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
monkeypatch.setattr(litellm, "force_ipv4", False)
yield
client_cache.flush_cache()
def _cohere_v2_embed_response(vectors: list[list[float]], texts: list[str]) -> dict[str, object]:
return {
"id": "da6e531f-83f4-4bcb-8e9a-f1a2c6e7a1b3",
"embeddings": {"float": vectors},
"texts": texts,
"meta": {"api_version": {"version": "2"}, "billed_units": {"input_tokens": 9}},
"response_type": "embeddings_by_type",
}
async def _embed(sync_mode: bool, **kwargs: object) -> EmbeddingResponse:
if sync_mode:
return litellm.embedding(model="cohere/embed-v4.0", api_key="cohere-test-key", **kwargs)
return await litellm.aembedding(model="cohere/embed-v4.0", api_key="cohere-test-key", **kwargs)
def _cohere_embedding_logging_obj() -> Logging:
return Logging(
model="embed-v4.0",
messages=["first", "second"],
stream=False,
call_type="embedding",
start_time=datetime.datetime(2025, 1, 1, tzinfo=datetime.timezone.utc),
litellm_call_id="cohere-embedding-test-call",
function_id="cohere-embedding-test-function",
)
def test_cohere_embed_v4_request_maps_input_options() -> None:
config: Final = CohereEmbeddingConfig()
request: Final = config.transform_embedding_request(
model="embed-v4.0",
input=["first", "second"],
optional_params={
"input_type": "search_document",
"embedding_types": ["float"],
"output_dimension": 256,
},
headers={},
)
assert request == {
"model": "embed-v4.0",
"texts": ["first", "second"],
"input_type": "search_document",
"embedding_types": ["float"],
"output_dimension": 256,
}
def test_cohere_embed_v4_request_routes_base64_images() -> None:
config: Final = CohereEmbeddingConfig()
request: Final = config.transform_embedding_request(
model="embed-v4.0",
input=["data:image/png;base64,aGVsbG8="],
optional_params={"input_type": "search_document"},
headers={},
)
assert request == {
"model": "embed-v4.0",
"images": ["data:image/png;base64,aGVsbG8="],
"input_type": "search_document",
}
def test_cohere_embed_v4_response_parses_multiple_embeddings() -> None:
config: Final = CohereEmbeddingConfig()
model_response: Final = EmbeddingResponse()
raw_response: Final = httpx.Response(
200,
json={
"embeddings": {
"float": [[0.1, 0.2], [0.3, 0.4]],
"int8": [[1, 2], [3, 4]],
},
"meta": {"billed_units": {"input_tokens": 6}},
},
)
response: Final = config.transform_embedding_response(
model="embed-v4.0",
raw_response=raw_response,
model_response=model_response,
logging_obj=_cohere_embedding_logging_obj(),
api_key="test-api-key",
request_data={"texts": ["first", "second"]},
optional_params={"embedding_types": ["float", "int8"]},
litellm_params={},
)
assert response.object == "list"
assert response.model == "embed-v4.0"
assert [item["embedding"] for item in response.data] == [
[0.1, 0.2],
[0.3, 0.4],
[1, 2],
[3, 4],
]
assert [item["index"] for item in response.data] == [0, 1, 0, 1]
assert response.usage.prompt_tokens == 6
assert response.usage.total_tokens == 6
@pytest.mark.usefixtures("_cohere_httpx_transport")
@pytest.mark.respx(assert_all_called=True)
@pytest.mark.parametrize("sync_mode", [True, False])
async def test_cohere_embed_v4_multiple_texts(respx_mock: respx.MockRouter, sync_mode: bool) -> None:
texts: Final = [
"The quick brown fox jumps over the lazy dog",
"Machine learning is transforming the world",
"Python is a versatile programming language",
"Natural language processing enables human-computer interaction",
]
vectors: Final = [[0.011, -0.022], [0.033, -0.044], [0.055, -0.066], [0.077, -0.088]]
route: Final = respx_mock.post(COHERE_V2_EMBED_URL).mock(
return_value=httpx.Response(200, json=_cohere_v2_embed_response(vectors, texts))
)
response: Final = await _embed(sync_mode, input=texts, input_type="search_document")
assert json.loads(route.calls.last.request.content) == {
"model": "embed-v4.0",
"texts": texts,
"input_type": "search_document",
}
assert response.model == "embed-v4.0"
assert response.data == [
{"object": "embedding", "index": index, "embedding": vector} for index, vector in enumerate(vectors)
]
assert response.usage.prompt_tokens == 9
@pytest.mark.usefixtures("_cohere_httpx_transport")
@pytest.mark.respx(assert_all_called=True)
@pytest.mark.parametrize("input_type", ["search_document", "search_query", "classification", "clustering"])
async def test_cohere_embed_v4_input_types(respx_mock: respx.MockRouter, input_type: str) -> None:
text: Final = f"Test text for {input_type}"
route: Final = respx_mock.post(COHERE_V2_EMBED_URL).mock(
return_value=httpx.Response(200, json=_cohere_v2_embed_response([[0.5, -0.5]], [text]))
)
await _embed(False, input=[text], input_type=input_type)
assert json.loads(route.calls.last.request.content) == {
"model": "embed-v4.0",
"texts": [text],
"input_type": input_type,
}
@pytest.mark.usefixtures("_cohere_httpx_transport")
@pytest.mark.respx(assert_all_called=True)
async def test_cohere_embed_v4_encoding_format(respx_mock: respx.MockRouter) -> None:
route: Final = respx_mock.post(COHERE_V2_EMBED_URL).mock(
return_value=httpx.Response(200, json=_cohere_v2_embed_response([[0.25, -0.75, 0.5]], ["Test encoding format"]))
)
response: Final = await _embed(True, input=["Test encoding format"], encoding_format="float")
assert json.loads(route.calls.last.request.content) == {
"model": "embed-v4.0",
"texts": ["Test encoding format"],
"input_type": "search_document",
"embedding_types": ["float"],
}
assert response.data == [{"object": "embedding", "index": 0, "embedding": [0.25, -0.75, 0.5]}]
@pytest.mark.usefixtures("_cohere_httpx_transport")
@pytest.mark.respx(assert_all_called=True)
async def test_cohere_embed_v4_with_optional_params(respx_mock: respx.MockRouter) -> None:
vector: Final = [round(index * 0.001, 3) for index in range(256)]
route: Final = respx_mock.post(COHERE_V2_EMBED_URL).mock(
return_value=httpx.Response(200, json=_cohere_v2_embed_response([vector], ["Test with optional parameters"]))
)
response: Final = await _embed(
True,
input=["Test with optional parameters"],
input_type="search_query",
dimensions=256,
encoding_format="float",
)
assert json.loads(route.calls.last.request.content) == {
"model": "embed-v4.0",
"texts": ["Test with optional parameters"],
"input_type": "search_query",
"embedding_types": ["float"],
"output_dimension": 256,
}
assert response.data == [{"object": "embedding", "index": 0, "embedding": vector}]
@pytest.mark.usefixtures("_cohere_httpx_transport")
@pytest.mark.respx(assert_all_called=True)
@pytest.mark.parametrize(("input_tokens", "image_tokens"), [(0, 6), (3, 6)])
async def test_cohere_embed_v4_image_tokens_are_billed_apart_from_input_tokens(
respx_mock: respx.MockRouter, input_tokens: int, image_tokens: int
) -> None:
respx_mock.post(COHERE_V2_EMBED_URL).mock(
return_value=httpx.Response(
200,
json={
"id": "5807ee2e-0cda-445a-9ec8-864c60a06606",
"embeddings": {"float": [[0.125, -0.375]]},
"texts": [],
"images": [{"width": 1, "height": 1, "format": "image/png", "bit_depth": 8}],
"meta": {
"api_version": {"version": "2"},
"billed_units": {"input_tokens": input_tokens, "image_tokens": image_tokens},
},
"response_type": "embeddings_by_type",
},
)
)
model_info: Final = litellm.get_model_info("cohere/embed-v4.0")
response: Final = await _embed(True, input=[ONE_PIXEL_PNG], input_type="image")
assert model_info["input_cost_per_image_token"] > 0
assert response._hidden_params["response_cost"] == pytest.approx(
input_tokens * model_info["input_cost_per_token"] + image_tokens * model_info["input_cost_per_image_token"]
)
@pytest.mark.usefixtures("_cohere_httpx_transport")
@pytest.mark.respx(assert_all_called=True)
@pytest.mark.parametrize("sync_mode", [True, False])
async def test_cohere_embed_v4_image_embedding(respx_mock: respx.MockRouter, sync_mode: bool) -> None:
image: Final = ONE_PIXEL_PNG
route: Final = respx_mock.post(COHERE_V2_EMBED_URL).mock(
return_value=httpx.Response(
200,
json={
"id": "5807ee2e-0cda-445a-9ec8-864c60a06606",
"embeddings": {"float": [[0.125, -0.375]]},
"texts": [],
"images": [{"width": 1, "height": 1, "format": "image/png", "bit_depth": 8}],
"meta": {"api_version": {"version": "2"}, "billed_units": {"images": 1}},
"response_type": "embeddings_by_type",
},
)
)
response: Final = await _embed(sync_mode, input=[image], input_type="image")
assert json.loads(route.calls.last.request.content) == {
"model": "embed-v4.0",
"images": [image],
"input_type": "image",
}
assert response.data == [{"object": "embedding", "index": 0, "embedding": [0.125, -0.375]}]
@pytest.mark.parametrize(
("cohere_api_base", "expected_url"),
[
(None, "https://api.cohere.ai/v2/embed"),
("https://gateway.example.com", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/cohere", "https://gateway.example.com/cohere/v2/embed"),
("https://gateway.example.com/cohere-embed", "https://gateway.example.com/cohere-embed/v2/embed"),
("https://gateway.example.com/cohere/v2", "https://gateway.example.com/cohere/v2/embed"),
("https://gateway.example.com/v2/embed", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/v1/embed", "https://gateway.example.com/v1/embed"),
("https://gateway.example.com/cohere/v1/embed/", "https://gateway.example.com/cohere/v1/embed/"),
("https://gateway.example.com/v2/chat", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/v1/chat/", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/cohere/v2/chat", "https://gateway.example.com/cohere/v2/embed"),
("https://gateway.example.com/v2/rerank", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/cohere/v1/rerank", "https://gateway.example.com/cohere/v2/embed"),
("https://gateway.example.com/cohere/chat", "https://gateway.example.com/cohere/v2/embed"),
("https://gateway.example.com/rerank", "https://gateway.example.com/v2/embed"),
("https://gateway.example.com/cohere?tenant=a", "https://gateway.example.com/cohere/v2/embed?tenant=a"),
("https://gateway.example.com/v2/chat?tenant=a", "https://gateway.example.com/v2/embed?tenant=a"),
("https://gateway.example.com/v2/embed?tenant=a", "https://gateway.example.com/v2/embed?tenant=a"),
],
)
def test_get_complete_url_resolves_the_embed_endpoint_from_cohere_api_base(
monkeypatch: pytest.MonkeyPatch, cohere_api_base: str | None, expected_url: str
) -> None:
if cohere_api_base is None:
monkeypatch.delenv("COHERE_API_BASE", raising=False)
else:
monkeypatch.setenv("COHERE_API_BASE", cohere_api_base)
url: Final = CohereEmbeddingConfig().get_complete_url(
api_base=None,
api_key=None,
model="embed-english-v3.0",
optional_params={},
litellm_params={},
)
assert url == expected_url
@pytest.mark.parametrize(
"api_base",
[
"https://gateway.example.com/gw/cohere-route",
"https://gateway.example.com/api/cohere?code=abc",
"https://gateway.example.com/cohere/v2/chat",
],
)
def test_get_complete_url_sends_an_explicit_api_base_as_is(monkeypatch: pytest.MonkeyPatch, api_base: str) -> None:
monkeypatch.setenv("COHERE_API_BASE", "https://env-gateway.example.com")
url: Final = CohereEmbeddingConfig().get_complete_url(
api_base=api_base,
api_key=None,
model="embed-english-v3.0",
optional_params={},
litellm_params={},
)
assert url == api_base
@dataclasses.dataclass(frozen=True, slots=True)
class _VaultSecret:
value: str
class _VaultAnsweringEveryName:
def get_secret(self, secret_name: str) -> _VaultSecret:
return _VaultSecret(value=f"https://vault-gateway.example.com/{secret_name}")
@pytest.mark.parametrize(
("env_cohere_api_base", "expected_url"),
[
(None, "https://api.cohere.ai/v2/embed"),
("https://env-gateway.example.com", "https://env-gateway.example.com/v2/embed"),
],
)
def test_get_complete_url_reads_cohere_api_base_from_the_environment_not_the_secret_manager(
monkeypatch: pytest.MonkeyPatch, env_cohere_api_base: str | None, expected_url: str
) -> None:
monkeypatch.setattr(litellm, "secret_manager_client", _VaultAnsweringEveryName())
monkeypatch.setattr(litellm, "_key_management_system", KeyManagementSystem.AZURE_KEY_VAULT)
monkeypatch.setattr(litellm, "_key_management_settings", KeyManagementSettings())
if env_cohere_api_base is None:
monkeypatch.delenv("COHERE_API_BASE", raising=False)
else:
monkeypatch.setenv("COHERE_API_BASE", env_cohere_api_base)
url: Final = CohereEmbeddingConfig().get_complete_url(
api_base=None,
api_key=None,
model="embed-english-v3.0",
optional_params={},
litellm_params={},
)
assert url == expected_url