Skip to content
Open
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
78 changes: 73 additions & 5 deletions litellm/llms/databricks/decisions/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,71 @@
from types import MappingProxyType
from typing import Final

from pydantic import TypeAdapter, ValidationError

from litellm.llms.base_llm.decisions.transformation import BaseDecisionsConfig
from litellm.types.decisions import DecisionsIRRequest, UnsupportedDecisionsRequest

DATABRICKS_AI_DECIDE_MODEL: Final = "ai_decide"
_AI_DECIDE_PATH: Final = "/api/2.0/ai-functions/ai-decide"
_SERVING_ENDPOINT_NAME: Final = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]*")
_MAPPING_ADAPTER: Final[TypeAdapter[Mapping[str, object]]] = TypeAdapter(Mapping[str, object])


def is_ai_decide_model(model: str) -> bool:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · ai_decide string switch repeated across modules instead of a tagged union

AGENTS.md says "Use tagged unions + match". Instead, is_ai_decide_model(model) is an if on a raw str in four places:

  • validate_databricks_decisions_model
  • get_complete_url
  • transform_decisions_request
  • jev_classifier._excluded_fields

Parsing the model once into an AiDecide | ServingEndpoint union in canonical_model would remove these branches. This is a judgement-level breach (Standards axis).

transformation.py:33, 92, 103 and jev_classifier.py:201 all call is_ai_decide_model

Review by code-review · Reviewed 74174369dd8b

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This backport keeps the code identical to #45722 on main, so a change here would belong there first. It's Low, so I'm tracking it as a follow-up

return model == DATABRICKS_AI_DECIDE_MODEL

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · model string stands for both the ai_decide sentinel and an endpoint name

Possible Primitive Obsession / Repeated Switches (a judgement call). Six call sites in Python and TS branch on is_ai_decide_model. AGENTS.md says "Use tagged unions + match". Parsing the string once into AiDecide | ServingEndpoint would put that branching in one place.

def is_ai_decide_model(model: str) -> bool: return model == DATABRICKS_AI_DECIDE_MODEL

Review by code-review · Reviewed afd6f4512476

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This backport keeps the code identical to #45722 on main, so a change here would belong there first. It's Low, so I'm tracking it as a follow-up



def validate_serving_endpoint_name(name: str) -> str:
if _SERVING_ENDPOINT_NAME.fullmatch(name) is None:
raise ValueError(
f"Databricks serving endpoint name {name!r} must be the bare endpoint name (letters, digits, '-', '_' "
"and '.', with no '/', '?', '#', spaces, or a leading '.'), e.g. databricks-openjev-qwen35-4b"
"Databricks decisions model must be 'ai_decide' (the ai_decide AI Function) or a bare serving endpoint "
"name (letters, digits, '-', '_' and '.', with no '/', '?', '#', spaces, or a leading '.'), e.g. "
"databricks-openjev-qwen35-4b"
)
return name


def validate_databricks_decisions_model(model: str) -> str:
if is_ai_decide_model(model):
return model
return validate_serving_endpoint_name(model)


def databricks_workspace_host(api_base: str) -> str:
return api_base.rstrip("/").removesuffix("/serving-endpoints")


def _mapping(value: object) -> Mapping[str, object] | None:
try:
return _MAPPING_ADAPTER.validate_python(value)
except ValidationError:
return None


def _systemone_answer(answer: object) -> object:
fields: Final = _mapping(answer)
if fields is None or fields.get("type") != "noul" or "probability" not in fields:
return answer
return MappingProxyType(
{**{key: value for key, value in fields.items() if key != "probability"}, "noul": fields["probability"]}
)


def ai_decide_response(payload: Mapping[str, object]) -> Mapping[str, object]:
response: Final = _mapping(payload.get("response"))
answers: Final = None if response is None else _mapping(response.get("answers"))
if response is None or answers is None:
return payload
return MappingProxyType(
{
**{key: value for key, value in payload.items() if key != "response"},
**response,
"answers": MappingProxyType({key: _systemone_answer(answer) for key, answer in answers.items()}),
}
)


@dataclass(frozen=True, slots=True)
class DatabricksDecisionsConnection:
api_base: str
Expand All @@ -35,13 +86,30 @@ def missing_api_base_message(self, custom_llm_provider: str) -> str:
)

def canonical_model(self, model: str) -> str:
return validate_serving_endpoint_name(model)
return validate_databricks_decisions_model(model)

def get_complete_url(self, api_base: str, model: str) -> str:
return f"{api_base.rstrip('/')}/{validate_serving_endpoint_name(model)}/invocations"
if is_ai_decide_model(model):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · Accepted API base forms differ between ai_decide and serving endpoints

ai_decide strips a trailing /serving-endpoints, so tests accept a bare workspace host as DATABRICKS_API_BASE. Serving endpoints append /<name>/invocations to the base unchanged. With a bare-host base, databricks/<endpoint> would post to https://host/<name>/invocations and get a 404.

This predates the PR, and the docs say to use /serving-endpoints. It is still an inconsistency for admins who share one base across both model kinds. Accepting both forms for serving endpoints too, using databricks_workspace_host plus /serving-endpoints, would remove it (Spec axis).

get_complete_url: only the ai_decide branch calls databricks_workspace_host

Review by code-review · Reviewed 74174369dd8b

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This backport keeps the code identical to #45722 on main, so a change here would belong there first. It's Low, so I'm tracking it as a follow-up

return f"{databricks_workspace_host(api_base)}{_AI_DECIDE_PATH}"
return f"{api_base.rstrip('/')}/{validate_databricks_decisions_model(model)}/invocations"

def transform_decisions_request(
self,
model: str,
request: DecisionsIRRequest,
custom_llm_provider: str,
) -> Mapping[str, object] | UnsupportedDecisionsRequest:
body: Final = super().transform_decisions_request(model, request, custom_llm_provider)
if isinstance(body, UnsupportedDecisionsRequest) or not is_ai_decide_model(model):
return body
return MappingProxyType({key: value for key, value in body.items() if key != "model"})

def unwrap_response(self, payload: object) -> object:
fields: Final = _mapping(payload)
return payload if fields is None else ai_decide_response(fields)

def classifier_response(self, body: Mapping[str, object], requested_model: str) -> Mapping[str, object]:
return MappingProxyType({**body, "model": requested_model})
return MappingProxyType({**ai_decide_response(body), "model": requested_model})

def connection(self, api_base: str | None, api_key: str | None) -> DatabricksDecisionsConnection:
base: Final = self.resolve_api_base(api_base)
Expand Down
12 changes: 12 additions & 0 deletions litellm/model_prices_and_context_window_backup.json
Original file line number Diff line number Diff line change
Expand Up @@ -21177,6 +21177,18 @@
"output_cost_per_token": 0.0,
"source": "https://docs.databricks.com/aws/en/machine-learning/foundation-model-apis/supported-models"
},
"databricks/ai_decide": {
"cache_creation_input_token_cost": 0.0,
"cache_read_input_token_cost": 0.0,
"input_cost_per_token": 0.0,
"litellm_provider": "databricks",
"metadata": {
"notes": "The ai_decide AI Function (Beta), called through POST /api/2.0/ai-functions/ai-decide. Its response carries no token usage, so LiteLLM records no spend for it."
},
"mode": "evaluation",
"output_cost_per_token": 0.0,
"source": "https://docs.databricks.com/api/ai-functions/v1/ai-decide"
},
"dataforseo/search": {
"input_cost_per_query": 0.003,
"litellm_provider": "dataforseo",
Expand Down
11 changes: 7 additions & 4 deletions litellm/router_strategy/complexity_router/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -769,14 +769,17 @@ def _keep_the_environment_key_on_the_environment_base(self) -> "OpenSourceClassi
_ = validate_oss_api_base(self.provider, self.api_base)
return self
if self.provider == "databricks":
from litellm.llms.databricks.decisions.transformation import validate_serving_endpoint_name
from litellm.llms.databricks.decisions.transformation import (
DATABRICKS_AI_DECIDE_MODEL,
validate_databricks_decisions_model,
)

if "model" not in self.model_fields_set:
raise ValueError(
"opensource_classifier_config.model is required for provider 'databricks': the serving endpoint "
"name, e.g. databricks-openjev-qwen35-4b"
"opensource_classifier_config.model is required for provider 'databricks': "
f"{DATABRICKS_AI_DECIDE_MODEL!r} or a serving endpoint name, e.g. databricks-openjev-qwen35-4b"
)
_ = validate_serving_endpoint_name(self.model)
_ = validate_databricks_decisions_model(self.model)
if self.api_base is not None and self.api_key is None:
raise ValueError(
"opensource_classifier_config.api_base requires opensource_classifier_config.api_key: "
Expand Down
8 changes: 6 additions & 2 deletions litellm/router_strategy/complexity_router/jev_classifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.llms.databricks.decisions.transformation import DATABRICKS_DECISIONS_CONFIG
from litellm.llms.databricks.decisions.transformation import DATABRICKS_DECISIONS_CONFIG, is_ai_decide_model
from litellm.llms.laya.common_utils import laya_response_model
from litellm.proxy.pass_through_endpoints.llm_provider_handlers.typesafe_passthrough_logging_handler import (
TypeSafePassthroughLoggingHandler,
Expand All @@ -35,6 +35,7 @@
JevProbability: TypeAlias = Annotated[float, Field(ge=0.0, le=1.0)]
ClassifierProvider: TypeAlias = Literal["typesafe", "laya", "bespoke", "databricks"]
DEFAULT_JEV_INSTRUCTIONS: Final = _DEFAULT_JEV_INSTRUCTIONS
_WITHOUT_MODEL: Final = MappingProxyType({"model": True})


class JevChoiceQuestion(LiteLLMBaseModel):
Expand Down Expand Up @@ -183,7 +184,7 @@ async def evaluate(
)
response: Final = await self._http_client.post( # pyright: ignore[reportUnknownMemberType] # AsyncHTTPHandler has a dynamic post signature
self._request_url(request.model),
json=request.model_dump(mode="json"),
json=request.model_dump(mode="json", exclude=self._excluded_fields(request.model)),
headers=MappingProxyType({**authorization, "Content-Type": "application/json"}), # pyright: ignore[reportArgumentType] # HTTP headers are not mutated by AsyncHTTPHandler
timeout=timeout_s,
)
Expand All @@ -196,6 +197,9 @@ async def evaluate(
verbose_router_logger.warning("JEV response logging failed (%s)", type(exc).__name__)
return TypeAdapter(JevSystemOneResponse).validate_python(normalized_body)

def _excluded_fields(self, model: str) -> Mapping[str, bool] | None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · Rule that ai_decide drops model is duplicated across transformation and JEV classifier

Possible Duplicated Code / Shotgun Surgery (a judgement call). _excluded_fields repeats the model stripping that DatabricksDecisionsConfig.transform_decisions_request already does. If the ai_decide body shape changes, both places have to change together.

return _WITHOUT_MODEL if self._provider == "databricks" and is_ai_decide_model(model) else None

return MappingProxyType({key: value for key, value in body.items() if key != "model"})

Review by code-review · Reviewed afd6f4512476

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This backport keeps the code identical to #45722 on main, so a change here would belong there first. It's Low, so I'm tracking it as a follow-up

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · Possible Duplicated Code: classifier repeats the ai_decide model-stripping rule

This is a judgement call, not a hard violation.

_excluded_fields checks self._provider == "databricks" and is_ai_decide_model(model) to drop model from the request. DatabricksDecisionsConfig.transform_decisions_request already encodes the same rule.

The classifier already asks DATABRICKS_DECISIONS_CONFIG for the URL and for response normalization. Asking it for the request body too would keep the rule in one place.

Review by code-review · Reviewed de1fef7c5a3f

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This backport keeps the code identical to #45722 on main, so a change here would belong there first. It's Low, so I'm tracking it as a follow-up

return _WITHOUT_MODEL if self._provider == "databricks" and is_ai_decide_model(model) else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Low · Possible Duplicated Code / Feature Envy: rule to drop model for ai_decide is written twice

The rule that the ai-decide route takes no model in its body is written in two places:

  • the dict comprehension in DatabricksDecisionsConfig.transform_decisions_request
  • _WITHOUT_MODEL / _excluded_fields in the JEV classifier

The classifier also checks Databricks model details that DATABRICKS_DECISIONS_CONFIG should own; it already owns the URL and the response. A single config method that builds the request body would keep the two in sync. This is a baseline smell and a judgement call (Standards axis).

_WITHOUT_MODEL: Final = MappingProxyType({"model": True})

return MappingProxyType({key: value for key, value in body.items() if key != "model"})

Review by code-review · Reviewed 74174369dd8b

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This backport keeps the code identical to #45722 on main, so a change here would belong there first. It's Low, so I'm tracking it as a follow-up


def _request_url(self, model: str) -> str:
if self._provider == "databricks":
return DATABRICKS_DECISIONS_CONFIG.get_complete_url(self._api_base, model)
Expand Down
12 changes: 12 additions & 0 deletions model_prices_and_context_window.json
Original file line number Diff line number Diff line change
Expand Up @@ -21177,6 +21177,18 @@
"output_cost_per_token": 0.0,
"source": "https://docs.databricks.com/aws/en/machine-learning/foundation-model-apis/supported-models"
},
"databricks/ai_decide": {
"cache_creation_input_token_cost": 0.0,
"cache_read_input_token_cost": 0.0,
"input_cost_per_token": 0.0,
"litellm_provider": "databricks",
"metadata": {
"notes": "The ai_decide AI Function (Beta), called through POST /api/2.0/ai-functions/ai-decide. Its response carries no token usage, so LiteLLM records no spend for it."
},
"mode": "evaluation",
"output_cost_per_token": 0.0,
"source": "https://docs.databricks.com/api/ai-functions/v1/ai-decide"
},
"dataforseo/search": {
"input_cost_per_query": 0.003,
"litellm_provider": "dataforseo",
Expand Down
Loading
Loading