Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
61d725d
fix(proxy): apply team model aliases on the JWT auth path
ryan-crabbe-berri Sep 22, 2026
44b7b48
feat(auto-router): allow opted-in team members to manage their routers
tin-berri Sep 22, 2026
d400ee2
feat(router): add classifier circuit breaker
moe-berri Sep 23, 2026
8bf252b
feat(router): add TypeSafe Jev as a complexity router classifier
mateo-berri Sep 23, 2026
ded7f60
fix(proxy): forward every method on the typesafe pass-through route
yuneng-berri Sep 23, 2026
d1bf609
feat(guardrails): add TypeSafe Jev relevance-based compaction guardrail
yassin-berriai Sep 23, 2026
4fa1e08
fix(proxy): enforce virtual key budgets for JEV test routing
moe-berri Sep 23, 2026
73e50a0
feat(auto-router): add JEV classifier alongside LLM classifier
moe-berri Sep 23, 2026
c3c466a
fix(ui): adapt the jev dashboard pieces to stable/1.102.x
mateo-berri Sep 23, 2026
12ef369
chore(backport): regenerate the openapi snapshot and dashboard api ty…
devin-ai-integration[bot] Sep 23, 2026
746686c
feat(openrouter): price typesafe/jev-1.13 and add an openrouter decis…
devin-ai-integration[bot] Sep 22, 2026
8e4c26f
fix(ui): adapt the jev dashboard pieces to stable/1.100.x
devin-ai-integration[bot] Sep 23, 2026
46f81ba
fix: place lint suppressions on the flagged annotation lines
devin-ai-integration[bot] Sep 23, 2026
a392f7b
fix(typing): clear the basedpyright errors the picks introduced
devin-ai-integration[bot] Sep 23, 2026
54b42e3
fix(proxy): port the member auto-router write path and grant plumbing…
devin-ai-integration[bot] Sep 23, 2026
4864227
test(proxy): restore the member-scope parametrization and cover team …
devin-ai-integration[bot] Sep 23, 2026
77915d4
fix(proxy): port append_team_models for member auto-router create on …
devin-ai-integration[bot] Sep 23, 2026
e39e1c8
fix(proxy): take the write-slot advisory lock before member name checks
devin-ai-integration[bot] Sep 23, 2026
55d1597
revert(proxy): drop the member auto-router write-path port from stabl…
devin-ai-integration[bot] Sep 23, 2026
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
1 change: 1 addition & 0 deletions gateway/routes/allowlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
"/vllm/",
"/mistral/",
"/typesafe/",
"/openrouter/",
"/groq/",
"/voyage/",
"/cursor/",
Expand Down
15 changes: 15 additions & 0 deletions litellm/litellm_core_utils/internal_call_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@
from __future__ import annotations

from collections.abc import Mapping
from types import MappingProxyType
from typing import Final

from litellm.constants import INTERNAL_CALL_ORIGIN_METADATA_KEY, NON_INFERENCE_CALL_TYPES
from litellm.litellm_core_utils.initialize_dynamic_callback_params import initialize_standard_callback_dynamic_params
from litellm.types.utils import BACKGROUND_RESPONSE_COST_POLL_CALL_ORIGIN, InternalCallOrigin

BUDGET_RESERVATION_METADATA_KEYS: Final = frozenset({"user_api_key_budget_reservation"})
Expand Down Expand Up @@ -153,3 +155,16 @@ def sanitized_forwardable_call_metadata(
"""
identity: Final = {k: v for k, v in parent_metadata.items() if k in FORWARDABLE_IDENTITY_METADATA_KEYS}
return _sanitized(identity) | {INTERNAL_CALL_ORIGIN_METADATA_KEY: call_origin} # mutable-ok: SDK metadata kwarg


def parent_session_kwargs(request_kwargs: Mapping[str, object] | None) -> Mapping[str, str]:
kwargs: Final = request_kwargs or MappingProxyType({})
return MappingProxyType(
{k: kwargs[k] for k in ("litellm_session_id", "litellm_trace_id") if isinstance(kwargs.get(k), str)}
)


def effective_turn_off_message_logging(request_kwargs: Mapping[str, object] | None) -> bool | None:
return initialize_standard_callback_dynamic_params(
dict(request_kwargs) if request_kwargs else None # mutable-ok: callback params take a mutable dict copy
).get("turn_off_message_logging")
10 changes: 10 additions & 0 deletions litellm/model_prices_and_context_window_backup.json
Original file line number Diff line number Diff line change
Expand Up @@ -55036,6 +55036,16 @@
"mode": "embedding",
"source": "https://docs.fireworks.ai/serverless/pricing"
},
"openrouter/typesafe/jev-1.13": {
"input_cost_per_token": 4.2e-08,
"litellm_provider": "openrouter",
"max_input_tokens": 32000,
"max_output_tokens": 28800,
"max_tokens": 28800,
"mode": "evaluation",
"output_cost_per_token": 0.0,
"source": "https://openrouter.ai/typesafe/jev-1.13"
},
"typesafe/jev-1.13.0": {
"input_cost_per_token": 4.2e-08,
"litellm_provider": "typesafe",
Expand Down
2 changes: 1 addition & 1 deletion litellm/proxy/_lazy_openapi_snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -9752,7 +9752,7 @@
},
"unreachable_fallback": {
"default": "fail_closed",
"description": "Behavior when a guardrail endpoint is unreachable due to network errors. Implemented by guardrail='generic_guardrail_api', 'akto', 'vigil_guard', 'repelloai', 'headroom', and 'compresr'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed.",
"description": "Behavior when a guardrail endpoint is unreachable due to network errors. Implemented by guardrail='generic_guardrail_api', 'agent_365', 'akto', 'vigil_guard', 'repelloai', 'headroom', 'compresr', and 'typesafe'. 'fail_closed' raises an error (default). 'fail_open' logs a critical error and allows the request to proceed.",
"enum": [
"fail_closed",
"fail_open"
Expand Down
3 changes: 3 additions & 0 deletions litellm/proxy/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ class KeyManagementRoutes(str, enum.Enum):
# team's `team_member_permissions`, non-admin members of that team may set
# `access_group_ids` on keys they create/update. Default-deny.
KEY_ACCESS_GROUP_ASSIGNMENT = "/key/access_group_assignment"
AUTO_ROUTER_MANAGE = "/auto_router/manage"

# info and health routes
KEY_INFO = "/key/info"
Expand Down Expand Up @@ -471,6 +472,7 @@ class LiteLLMRoutes(enum.Enum):
"/vllm",
"/mistral",
"/typesafe",
"/openrouter",
"/milvus",
"/watsonx",
]
Expand Down Expand Up @@ -637,6 +639,7 @@ class LiteLLMRoutes(enum.Enum):
KeyManagementRoutes.KEY_RESET_SPEND.value,
KeyManagementRoutes.KEY_ALIASES.value,
KeyManagementRoutes.KEY_ACCESS_GROUP_ASSIGNMENT.value,
KeyManagementRoutes.AUTO_ROUTER_MANAGE.value,
]

management_routes = (
Expand Down
34 changes: 22 additions & 12 deletions litellm/proxy/auth/auth_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
from litellm.repositories.budget_repository import BudgetRepository
from litellm.repositories.object_permission_repository import ObjectPermissionRepository
from litellm.repositories.organization_repository import OrganizationRepository
from litellm.repositories.prisma_protocols import RowT_co
from litellm.repositories.prisma_protocols import DatabaseClient, RowT_co
from litellm.repositories.project_repository import ProjectRepository
from litellm.repositories.table_repositories import (
AccessGroupRepository,
Expand Down Expand Up @@ -4237,6 +4237,7 @@ async def can_key_call_model(
llm_model_list: list | None,
valid_token: UserAPIKeyAuth,
llm_router: litellm.Router | None,
prisma_client: DatabaseClient | None = None,
) -> Literal[True]:
"""
Checks if token can call a given model
Expand Down Expand Up @@ -4266,6 +4267,7 @@ async def can_key_call_model(
if key_access_group_ids:
models_from_groups: Final = await _get_models_from_access_groups(
access_group_ids=key_access_group_ids,
prisma_client=prisma_client, # pyright: ignore[reportArgumentType] # DatabaseClient is the protocol this file passes everywhere
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
)
if models_from_groups:
return _can_object_call_model(
Expand Down Expand Up @@ -4394,6 +4396,7 @@ async def can_team_access_model(
team_object: LiteLLM_TeamTable | None,
llm_router: Router | None,
team_model_aliases: dict[str, str] | None = None,
prisma_client: DatabaseClient | None = None,
) -> Literal[True]:
"""
Returns True if the team can access a specific model.
Expand All @@ -4416,6 +4419,7 @@ async def can_team_access_model(
if team_access_group_ids:
models_from_groups: Final = await _get_models_from_access_groups(
access_group_ids=team_access_group_ids,
prisma_client=prisma_client, # pyright: ignore[reportArgumentType] # DatabaseClient is the protocol this file passes everywhere
)
if models_from_groups:
return _can_object_call_model(
Expand Down Expand Up @@ -5083,6 +5087,8 @@ async def _check_team_member_model_access(
prisma_client: Optional["PrismaClient"],
user_api_key_cache: UserApiKeyCache,
proxy_logging_obj: ProxyLogging,
team_membership: LiteLLM_TeamMembership | None = None,
team_membership_loaded: bool = False,
) -> None:
"""
Check if a team member's per-member model scope allows access to the requested model.
Expand All @@ -5093,22 +5099,26 @@ async def _check_team_member_model_access(
if valid_token.user_id is None or team_object.team_id is None:
return

team_membership: Final = await get_team_membership(
user_id=valid_token.user_id,
team_id=team_object.team_id,
prisma_client=prisma_client,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)
if not team_membership_loaded:
team_membership = await get_team_membership(
user_id=valid_token.user_id,
team_id=team_object.team_id,
prisma_client=prisma_client,
user_api_key_cache=user_api_key_cache,
proxy_logging_obj=proxy_logging_obj,
)
loaded_membership = team_membership

if (
team_membership is None
or team_membership.litellm_budget_table is None
or not team_membership.litellm_budget_table.allowed_models
loaded_membership is None
or loaded_membership.litellm_budget_table is None
or not loaded_membership.litellm_budget_table.allowed_models
):
return # no per-member restriction — inherit team-level check

member_allowed_models: Final[list[str]] = team_membership.litellm_budget_table.allowed_models
member_allowed_models: Final[list[str]] = ( # mutable-ok: allowed_models is a prisma model list consumed read-only
loaded_membership.litellm_budget_table.allowed_models
)
try:
_can_object_call_model(
model=model,
Expand Down
126 changes: 126 additions & 0 deletions litellm/proxy/auth/team_grants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""Project a team row (plus the caller's membership in it) onto the ``team_*`` fields of ``UserAPIKeyAuth``.

The virtual-key path gets these fields for free from the combined-view SQL join. Every other auth path
starts from a ``LiteLLM_TeamTable`` object instead and has to copy them over by hand, which is how JWT
callers kept losing grants (aliases, permissions, limits) one field at a time. Build the badge through
``team_grants`` and the two paths cannot drift.
"""

from collections.abc import Mapping, Sequence
from types import MappingProxyType
from typing import Annotated, Final

from pydantic import BaseModel, BeforeValidator, ConfigDict, TypeAdapter, ValidationError
from pydantic.main import IncEx
from typing_extensions import ReadOnly, TypedDict

from litellm.proxy._types import (
LiteLLM_ObjectPermissionTable,
LiteLLM_TeamMembership,
LiteLLM_TeamTable,
Member,
)

_MODEL_ALIASES_ADAPTER: Final = TypeAdapter(dict[str, str])
_JSON_COLUMNS: Final[Mapping[str, IncEx | bool]] = MappingProxyType(
{"metadata": True, "litellm_model_table": MappingProxyType({"model_aliases": True})}
)


def _decode_model_aliases(value: object) -> object:
"""``LiteLLM_ModelTable.model_aliases`` is typed ``str | dict``; writers hand Prisma ``json.dumps(...)``, so take both."""
if not isinstance(value, str):
return value
try:
return _MODEL_ALIASES_ADAPTER.validate_json(value)
except ValidationError:
return None


class TeamModelAliasTable(BaseModel):
model_config = ConfigDict(protected_namespaces=())

model_aliases: Annotated[Mapping[str, str] | None, BeforeValidator(_decode_model_aliases)] = None


class _TeamJsonColumns(BaseModel):
"""The two loosely typed columns on ``LiteLLM_TeamTable``, re-read with the shape the badge needs."""

metadata: Mapping[str, object] | None = None
litellm_model_table: TeamModelAliasTable | None = None


class TeamGrants(TypedDict, total=False):
"""Keyword arguments for ``UserAPIKeyAuth``. Empty when the caller has no team, so the model's own defaults apply."""

team_alias: ReadOnly[str | None]
team_tpm_limit: ReadOnly[int | None]
team_rpm_limit: ReadOnly[int | None]
team_tpd_limit: ReadOnly[int | None]
team_max_budget: ReadOnly[float | None]
team_soft_budget: ReadOnly[float | None]
team_model_max_budget: ReadOnly[dict[str, object] | None] # mutable-ok: prisma table field typed loosely
team_spend: ReadOnly[float | None]
team_models: ReadOnly[Sequence[str]]
team_blocked: ReadOnly[bool]
team_metadata: ReadOnly[Mapping[str, object] | None]
team_model_aliases: ReadOnly[Mapping[str, str] | None]
team_object_permission_id: ReadOnly[str | None]
team_object_permission: ReadOnly[LiteLLM_ObjectPermissionTable | None]
team_member: ReadOnly[Member | None]
team_member_spend: ReadOnly[float | None]
team_member_tpm_limit: ReadOnly[int | None]
team_member_rpm_limit: ReadOnly[int | None]


def _json_columns(team_object: LiteLLM_TeamTable) -> _TeamJsonColumns:
try:
return _TeamJsonColumns.model_validate(team_object.model_dump(include=_JSON_COLUMNS))
except ValidationError:
return _TeamJsonColumns()


def team_model_aliases(team_object: LiteLLM_TeamTable | None) -> Mapping[str, str] | None:
if team_object is None:
return None
alias_table: Final = _json_columns(team_object).litellm_model_table
return alias_table.model_aliases if alias_table is not None else None


def team_grants(
team_object: LiteLLM_TeamTable | None,
team_membership: LiteLLM_TeamMembership | None,
user_id: str | None,
) -> TeamGrants:
if team_object is None:
return TeamGrants()
json_columns: Final = _json_columns(team_object)
return TeamGrants(
team_alias=team_object.team_alias,
team_tpm_limit=team_object.tpm_limit,
team_rpm_limit=team_object.rpm_limit,
team_tpd_limit=team_object.tpd_limit,
team_max_budget=team_object.max_budget,
team_soft_budget=team_object.soft_budget,
team_model_max_budget=team_object.model_max_budget,
team_spend=team_object.spend,
team_models=tuple(team_object.models),
team_blocked=team_object.blocked,
team_metadata=json_columns.metadata,
team_model_aliases=(
json_columns.litellm_model_table.model_aliases if json_columns.litellm_model_table is not None else None
),
team_object_permission_id=team_object.object_permission_id,
team_object_permission=team_object.object_permission,
team_member=next(
(m for m in team_object.members_with_roles if user_id is not None and m.user_id == user_id),
None,
),
team_member_spend=team_membership.spend if team_membership is not None else None,
team_member_tpm_limit=(
team_membership.safe_get_team_member_tpm_limit() if team_membership is not None else None
),
team_member_rpm_limit=(
team_membership.safe_get_team_member_rpm_limit() if team_membership is not None else None
),
)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
74 changes: 74 additions & 0 deletions litellm/proxy/guardrails/guardrail_hooks/typesafe/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Final

from pydantic import BaseModel

from litellm.types.guardrails import (
GuardrailEventHooks,
Mode,
SupportedGuardrailIntegrations,
)
from litellm.types.proxy.guardrails.guardrail_hooks.typesafe import (
TypeSafeGuardrailOptionalParams,
)

from .typesafe import TypeSafeGuardrail

if TYPE_CHECKING:
from litellm.types.guardrails import Guardrail, LitellmParams


def _coerce_event_hook(
mode: str | list[str] | Mode, # mutable-ok: event hook unions accept an ordered list
) -> GuardrailEventHooks | list[GuardrailEventHooks] | Mode: # mutable-ok: event hook unions accept an ordered list
if isinstance(mode, Mode):
return mode
if isinstance(mode, list):
return [ # mutable-ok: CustomGuardrail event_hook contract wants a list
GuardrailEventHooks(item) for item in mode
]
return GuardrailEventHooks(mode)


def _optional_params(litellm_params: LitellmParams) -> TypeSafeGuardrailOptionalParams:
value: Final = litellm_params.optional_params
if isinstance(value, TypeSafeGuardrailOptionalParams):
return value
if isinstance(value, BaseModel):
return TypeSafeGuardrailOptionalParams.model_validate(value.model_dump())
return TypeSafeGuardrailOptionalParams()


def initialize_guardrail(litellm_params: LitellmParams, guardrail: Guardrail) -> TypeSafeGuardrail:
import litellm

optional_params: Final = _optional_params(litellm_params)

_callback: Final = TypeSafeGuardrail(
api_base=litellm_params.api_base,
api_key=litellm_params.api_key,
model=litellm_params.model,
relevance_threshold=optional_params.relevance_threshold,
min_chars_to_evaluate=optional_params.min_chars_to_evaluate,
max_result_chars_in_state=optional_params.max_result_chars_in_state,
guardrail_name=guardrail["guardrail_name"],
event_hook=_coerce_event_hook(litellm_params.mode),
default_on=litellm_params.default_on or False,
unreachable_fallback=(
litellm_params.unreachable_fallback if "unreachable_fallback" in litellm_params.model_fields_set else None
),
)
litellm.logging_callback_manager.add_litellm_callback( # pyright: ignore[reportUnknownMemberType] # callback manager is untyped
_callback
)
return _callback


guardrail_initializer_registry: Final = { # mutable-ok: guardrail_registry discovery checks isinstance(registry, dict)
SupportedGuardrailIntegrations.TYPESAFE.value: initialize_guardrail,
}

guardrail_class_registry: Final = { # mutable-ok: guardrail_registry discovery checks isinstance(registry, dict)
SupportedGuardrailIntegrations.TYPESAFE.value: TypeSafeGuardrail,
}
Loading
Loading