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]

fix(decisions): bill unpriced returned TypeSafe versions at the requested model and name a missing answers field (#47508)

Mateo Wang81d8c9af38b9
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py
index e8ca60e00af..51f6a65307d 100644
--- a/litellm/cost_calculator.py
+++ b/litellm/cost_calculator.py
@@ -906,11 +906,15 @@ def _bedrock_pricing_info(
return model_info_with_pricing_overrides(profile, registration[1])
-def _declares_rates(model_info: ModelInfo | None) -> bool:
- entry: Final = _raw_cost_map_entry(model_info["key"]) if model_info is not None else None
+def cost_map_key_prices_anything(key: str) -> bool:
+ entry: Final = _raw_cost_map_entry(key)
return entry is not None and _cost_map_entry_prices_anything(entry)
+def _declares_rates(model_info: ModelInfo | None) -> bool:
+ return model_info is not None and cost_map_key_prices_anything(model_info["key"])
+
+
def _base_model_pricing_provider(base_model: str, custom_llm_provider: str | None) -> str | None:
"""The provider to price an explicit base_model under, when the deployment's own provider has
no rates for it (e.g. chatgpt/ subscription rows) but the base model's own row does"""
diff --git a/litellm/decisions/call.py b/litellm/decisions/call.py
index b94b3380ad5..abbeccc10b3 100644
--- a/litellm/decisions/call.py
+++ b/litellm/decisions/call.py
@@ -11,6 +11,7 @@ from pydantic_core import to_jsonable_python
from typing_extensions import assert_never
import litellm
+from litellm.cost_calculator import cost_map_key_prices_anything
from litellm.litellm_core_utils.core_helpers import RESPONSE_COST_HEADER, normalize_drop_params
from litellm.litellm_core_utils.get_provider_specific_headers import ProviderSpecificHeaderUtils
from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj
@@ -21,6 +22,7 @@ from litellm.litellm_core_utils.prompt_templates.image_handling import (
from litellm.llms.base_llm.chat.transformation import BaseLLMException
from litellm.llms.base_llm.decisions.transformation import (
BaseDecisionsConfig,
+ DecisionsResponseValidationError,
image_media_type,
image_param,
input_images,
@@ -687,6 +689,13 @@ def _request_body(call: DecisionsCall) -> Mapping[str, object]:
return body
+def _pricing_model(response: DecisionsIRResponse, call: DecisionsCall) -> str:
+ returned: Final = get_model_cost_key(f"{call.custom_llm_provider}/{response.model}")
+ if returned is not None and cost_map_key_prices_anything(returned):
+ return returned
+ return f"{call.custom_llm_provider}/{call.model}"
+
+
def _format_response(response: DecisionsIRResponse, call: DecisionsCall) -> DecisionsResponse | OpenAIDecisionResponse:
formatted: Final = _formatted_response(response, call)
provider_cost: Final = call.provider_config.provider_reported_cost(response)
@@ -694,10 +703,7 @@ def _format_response(response: DecisionsIRResponse, call: DecisionsCall) -> Deci
{
"model": f"{call.custom_llm_provider}/{call.model}",
"custom_llm_provider": call.custom_llm_provider,
- "provider_response_model": (
- get_model_cost_key(f"{call.custom_llm_provider}/{response.model}")
- or f"{call.custom_llm_provider}/{call.model}"
- ),
+ "provider_response_model": _pricing_model(response, call),
**({"additional_headers": {RESPONSE_COST_HEADER: provider_cost}} if provider_cost is not None else {}),
}
)
@@ -727,18 +733,21 @@ def _formatted_response(
def _map_upstream_exception(error: Exception, call: DecisionsCall) -> Exception:
- if isinstance(error, BaseLLMException) and error.status_code_is_synthesized:
- provider_label: Final = f"{call.custom_llm_provider[0].upper()}{call.custom_llm_provider[1:]}Exception"
- return litellm.APIConnectionError(
- message=f"{provider_label} - {error.message}",
- llm_provider=call.custom_llm_provider,
- model=f"{call.custom_llm_provider}/{call.model}",
- )
- return litellm.exception_type(
- model=f"{call.custom_llm_provider}/{call.model}",
- custom_llm_provider=call.custom_llm_provider,
- original_exception=error,
- )
+ provider_label: Final = f"{call.custom_llm_provider[0].upper()}{call.custom_llm_provider[1:]}Exception"
+ model: Final = f"{call.custom_llm_provider}/{call.model}"
+ match error:
+ case DecisionsResponseValidationError():
+ return litellm.InternalServerError(
+ message=f"{provider_label} - {error.message}", llm_provider=call.custom_llm_provider, model=model
+ )
+ case BaseLLMException(status_code_is_synthesized=True):
+ return litellm.APIConnectionError(
+ message=f"{provider_label} - {error.message}", llm_provider=call.custom_llm_provider, model=model
+ )
+ case _:
+ return litellm.exception_type(
+ model=model, custom_llm_provider=call.custom_llm_provider, original_exception=error
+ )
async def asend(call: DecisionsCall) -> DecisionsResponse | OpenAIDecisionResponse:
diff --git a/litellm/llms/base_llm/decisions/transformation.py b/litellm/llms/base_llm/decisions/transformation.py
index 3af023df378..d74257a4a9d 100644
--- a/litellm/llms/base_llm/decisions/transformation.py
+++ b/litellm/llms/base_llm/decisions/transformation.py
@@ -8,6 +8,7 @@ from typing import Final
import httpx
from pydantic import TypeAdapter, ValidationError
+from pydantic_core import ErrorDetails
from typing_extensions import assert_never
import litellm
@@ -394,7 +395,9 @@ _MAPPING: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, ob
_LABELS: Final[TypeAdapter[tuple[str, ...]]] = TypeAdapter(tuple[str, ...])
-def _normalize_answer(value: object) -> Mapping[str, object]:
+def _normalize_answer(value: object) -> object:
+ if not isinstance(value, Mapping):
+ return value
answer: Final = _MAPPING.validate_python(value)
legend: Final = answer.get("legend")
if answer.get("type") != "score" or not isinstance(legend, list):
@@ -403,11 +406,36 @@ def _normalize_answer(value: object) -> Mapping[str, object]:
return {**answer, "legend": {str(index): label for index, label in enumerate(labels)}}
-def parse_systemone_response(payload: object, request: DecisionsIRRequest) -> DecisionsIRResponse:
+def _normalize_systemone_response(payload: object) -> object:
+ if not isinstance(payload, Mapping):
+ return payload
response: Final = _MAPPING.validate_python(payload)
- answers: Final = _MAPPING.validate_python(response.get("answers"))
- normalized: Final = {**response, "answers": {name: _normalize_answer(answer) for name, answer in answers.items()}}
- return systemone_response_to_ir(_SYSTEMONE_RESPONSE_ADAPTER.validate_python(normalized), request)
+ answers: Final = response.get("answers")
+ if not isinstance(answers, Mapping):
+ return response
+ return {
+ **response,
+ "answers": {name: _normalize_answer(answer) for name, answer in _MAPPING.validate_python(answers).items()},
+ }
+
+
+def _validation_detail(detail: ErrorDetails) -> str:
+ location: Final = ".".join(str(part) for part in detail["loc"])
+ return f"{location}: {detail['msg']}" if location else detail["msg"]
+
+
+def _validation_summary(error: ValidationError) -> str:
+ return "; ".join(_validation_detail(detail) for detail in error.errors(include_url=False, include_input=False))
+
+
+class DecisionsResponseValidationError(BaseLLMException):
+ pass
+
+
+def parse_systemone_response(payload: object, request: DecisionsIRRequest) -> DecisionsIRResponse:
+ return systemone_response_to_ir(
+ _SYSTEMONE_RESPONSE_ADAPTER.validate_python(_normalize_systemone_response(payload)), request
+ )
def _systemone_answer(answer: DecisionsIRAnswer) -> DecisionAnswer | None:
@@ -627,9 +655,10 @@ class BaseDecisionsConfig(ABC):
try:
return self.parse_response(payload, request)
except ValidationError as error:
- raise BaseLLMException(
+ raise DecisionsResponseValidationError(
status_code=500,
- message=f"Decisions provider '{custom_llm_provider}' returned an unexpected response: {error}",
+ message=f"Decisions provider '{custom_llm_provider}' returned an unexpected response: "
+ f"{error.title} {_validation_summary(error)}",
) from error
def get_error_class(
diff --git a/tests/integration/observability/test_arize_otel_v2_openinference_family.py b/tests/integration/observability/test_arize_otel_v2_openinference_family.py
index 0b0c077cbee..f638a7360be 100644
--- a/tests/integration/observability/test_arize_otel_v2_openinference_family.py
+++ b/tests/integration/observability/test_arize_otel_v2_openinference_family.py
@@ -299,6 +299,7 @@ def test_arize_otel_v2_b3_non_openinference_callback_family(callback: str, gatew
assert _json_object(response.content) == _chat_caller_response(_chat_response(marker), rig.model), response.text
attributes: Final = _matching_genai_marker_span(rig.destination, marker)
assert frozenset(attributes) == _B3_ATTRIBUTE_KEYS[callback], attributes
+ assert attributes["litellm.cache_hit"] == "False", attributes
assert "metadata" not in attributes, attributes
assert not any(".tool_calls." in key for key in attributes), attributes
baggage: Final = tuple(
diff --git a/tests/integration/observability/test_arize_otel_v2_openinference_spans.py b/tests/integration/observability/test_arize_otel_v2_openinference_spans.py
index ab79e81289e..6a7d6d99a84 100644
--- a/tests/integration/observability/test_arize_otel_v2_openinference_spans.py
+++ b/tests/integration/observability/test_arize_otel_v2_openinference_spans.py
@@ -921,7 +921,16 @@ def test_arize_otel_v2_a_cache(surface: str, gateway: Gateway, tmp_path: Path) -
)
assert len(sentinel_spans) == 1, spans
_assert_tool_span_for_marker(sentinel_spans[0], sentinel)
- assert not any(attributes.get("litellm.metadata.trace_marker") == marker for attributes in spans), spans
+ cache_hit_spans: Final = tuple(
+ attributes
+ for attributes in spans
+ if (
+ attributes.get("litellm.metadata.trace_marker") == marker
+ and attributes.get("litellm.cache_hit") == "True"
+ )
+ )
+ assert len(cache_hit_spans) == 1, spans
+ assert cache_hit_spans[0]["litellm.cost.total"] == "0.0", cache_hit_spans
def test_arize_otel_v2_cache_hit_exports_llm_span(gateway: Gateway, tmp_path: Path) -> None:
@@ -960,4 +969,9 @@ def test_arize_otel_v2_cache_hit_exports_llm_span(gateway: Gateway, tmp_path: Pa
attributes for attributes in spans if attributes.get("litellm.metadata.trace_marker") == marker
)
assert len(marker_spans) == 2, spans
- _assert_tool_span_for_marker(marker_spans[1], marker)
+ cache_hit_spans: Final = tuple(
+ attributes for attributes in marker_spans if attributes.get("litellm.cache_hit") == "True"
+ )
+ assert len(cache_hit_spans) == 1, marker_spans
+ _assert_tool_span_for_marker(cache_hit_spans[0], marker)
+ assert cache_hit_spans[0]["litellm.cost.total"] == "0.0", marker_spans
diff --git a/tests/unit/decisions/test_main.py b/tests/unit/decisions/test_main.py
index 20af774278f..84e7a970195 100644
--- a/tests/unit/decisions/test_main.py
+++ b/tests/unit/decisions/test_main.py
@@ -612,13 +612,35 @@ async def test_oss_classifier_rejects_unknown_models_and_ambiguous_bases_before_
assert len(respx_mock.calls) == 0
+_PPLX_USAGE: Final = {"model": "pplx-decider-v1-27b", "usage": {"input_tokens": 10, "output_tokens": 0}}
+
+
@pytest.mark.asyncio
-async def test_upstream_reply_without_answers_is_a_server_error(respx_mock: respx.MockRouter) -> None:
- respx_mock.post("https://api.perplexity.ai/v1/decisions").respond(
- json={"model": "pplx-decider-v1-27b", "usage": {"input_tokens": 10, "output_tokens": 0}}
- )
+ ("reply", "detail"),
+ (
+ pytest.param(_PPLX_USAGE, "DecisionsResponse answers: Field required", id="usage"),
+ pytest.param({"error": "Rate limit reached"}, "DecisionsResponse answers: Field required", id="rate_limit_text"),
+ pytest.param({"error": "Request timed out"}, "DecisionsResponse answers: Field required", id="timeout_text"),
+ pytest.param(
+ {**_PPLX_USAGE, "answers": {"rate_limit": None}},
+ "DecisionsResponse answers.rate_limit: Input should be a valid dictionary",
+ id="null_answer_named_rate_limit",
+ ),
+ pytest.param(
+ {**_PPLX_USAGE, "answers": {"is_defect": {"type": "Request timed out"}}},
+ "DecisionsResponse answers.is_defect",
+ id="answer_type_timeout_text",
+ ),
+ pytest.param(["Rate limit reached"], "DecisionsResponse Input should be a valid dictionary", id="not_an_object"),
+ ),
+)
+async def test_a_malformed_upstream_reply_is_a_server_error_whatever_its_text(
+ reply: object, detail: str, respx_mock: respx.MockRouter
+) -> None:
+ respx_mock.post("https://api.perplexity.ai/v1/decisions").respond(json=reply)
- with pytest.raises(litellm.InternalServerError, match="unexpected response"):
+ with pytest.raises(litellm.InternalServerError, match=re.escape(f"unexpected response: {detail}")):
await litellm.asystemone(
model="perplexity/pplx-decider-v1-27b",
state="review",
@@ -3690,6 +3712,39 @@ async def test_decision_hosts_preserve_drex_model_routing_credentials_and_return
}
+ "unpriced_row",
+ (
+ pytest.param({}, id="empty"),
+ pytest.param(
+ {"litellm_provider": "typesafe", "mode": "evaluation", "input_cost_per_token": None},
+ id="metadata_and_null_rate",
+ ),
+ ),
+)
+async def test_a_returned_model_registered_without_prices_is_billed_at_the_requested_model(
+ unpriced_row: dict[str, object], monkeypatch: pytest.MonkeyPatch, respx_mock: respx.MockRouter
+) -> None:
+ monkeypatch.setenv("TYPESAFE_API_KEY", "typesafe-test-key")
+ monkeypatch.setitem(
+ litellm.model_cost,
+ "typesafe/jev-test-alias",
+ {"litellm_provider": "typesafe", "mode": "evaluation", "input_cost_per_token": 0.001, "output_cost_per_token": 0},
+ )
+ monkeypatch.setitem(litellm.model_cost, "typesafe/jev-test-unpriced", unpriced_row)
+ respx_mock.post("https://api.typesafe.ai/v1/systemone").respond(json={**_RESPONSE, "model": "jev-test-unpriced"})
+
+ response: Final = await litellm.asystemone(
+ model="typesafe/jev-test-alias",
+ state="damaged order",
+ questions={"is_defect": {"type": "noul", "instructions": "Is this a defect?"}},
+ )
+
+ assert litellm.completion_cost(completion_response=response, call_type="asystemone") == pytest.approx(
+ _INPUT_TOKENS * 0.001
+ )
+
+
@pytest.mark.parametrize("base_env", ("NACE_API_BASE", "NACE_BASE_URL"))
def test_nace_sync_call_uses_environment_base_and_explicit_credentials(
base_env: str,
diff --git a/tests/unit/llms/base_llm/decisions/test_base_decisions_transformation.py b/tests/unit/llms/base_llm/decisions/test_base_decisions_transformation.py
index 924b192a00e..3aebf56ee73 100644
--- a/tests/unit/llms/base_llm/decisions/test_base_decisions_transformation.py
+++ b/tests/unit/llms/base_llm/decisions/test_base_decisions_transformation.py
@@ -197,6 +197,28 @@ def test_missing_or_mismatched_systemone_answers_are_refusals_left_out_of_the_re
assert tuple(ir_to_systemone_response(parsed, ir).answers) == ("damaged",)
+ ("payload", "field"),
+ [
+ ({"model": "jev-latest", "usage": {"input_tokens": 10, "output_tokens": 1}}, ("answers",)),
+ (
+ {"model": "jev-latest", "answers": {"damaged": None}, "usage": {"input_tokens": 10, "output_tokens": 1}},
+ ("answers", "damaged"),
+ ),
+ ],
+ ids=["missing_answers", "null_answer"],
+)
+def test_a_malformed_systemone_response_names_the_field_at_fault(
+ payload: Mapping[str, object], field: tuple[str, ...]
+) -> None:
+ ir: Final = systemone_request_to_ir(_SYSTEMONE_BODY.validate_python(_SYSTEMONE_REQUEST))
+
+ with pytest.raises(ValidationError) as error:
+ parse_systemone_response(payload, ir)
+
+ assert [item["loc"] for item in error.value.errors()] == [field]
+
+
def test_each_media_kind_is_gated_by_its_own_support_flag() -> None:
audio: Final = ["data:audio/wav;base64,YQ=="]
videos: Final = ["data:video/mp4;base64,YQ=="]