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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Update the logic to work with GET request
Sameer Kankute0543ab5e77b4
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex f847a2b41ad..7abfe7a96bc 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -412,7 +412,6 @@ class LiteLLMRoutes(enum.Enum):agent_routes = ["/v1/agents","/agents",-"/a2a/{agent_id}","/a2a/{agent_id}/message/send","/a2a/{agent_id}/message/stream",@@ -830,9 +829,9 @@ class GenerateRequestBase(LiteLLMPydanticObjectBase):allowed_cache_controls: Optional[list] = []config: Optional[dict] = {}permissions: Optional[dict] = {}- model_max_budget: Optional[dict] = (- {}- ) # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}+ model_max_budget: Optional[+ dict+ ] = {} # {"gpt-4": 5.0, "gpt-3.5-turbo": 5.0}, defaults to {}model_config = ConfigDict(protected_namespaces=())model_rpm_limit: Optional[dict] = None@@ -843,15 +842,6 @@ class GenerateRequestBase(LiteLLMPydanticObjectBase):aliases: Optional[dict] = {}object_permission: Optional[LiteLLM_ObjectPermissionBase] = None- @model_validator(mode="after")- def validate_budget_values(self) -> "GenerateRequestBase":- """Validate that budget values are not negative"""- if self.max_budget is not None and self.max_budget < 0:- raise ValueError(- f"max_budget cannot be negative. Received: {self.max_budget}"- )- return self-class AllowedVectorStoreIndexItem(LiteLLMPydanticObjectBase):index_name: str@@ -901,15 +891,6 @@ class GenerateKeyRequest(KeyRequestBase):)organization_id: Optional[str] = None- @model_validator(mode="after")- def validate_soft_budget(self) -> "GenerateKeyRequest":- """Validate that soft_budget is not negative"""- if self.soft_budget is not None and self.soft_budget < 0:- raise ValueError(- f"soft_budget cannot be negative. Received: {self.soft_budget}"- )- return self-class GenerateKeyResponse(KeyRequestBase):key: str # type: ignore@@ -1053,6 +1034,9 @@ class NewMCPServerRequest(LiteLLMPydanticObjectBase):command: Optional[str] = Noneargs: List[str] = Field(default_factory=list)env: Dict[str, str] = Field(default_factory=dict)+ authorization_url: Optional[str] = None+ token_url: Optional[str] = None+ registration_url: Optional[str] = None@model_validator(mode="before")@classmethod@@ -1110,6 +1094,9 @@ class UpdateMCPServerRequest(LiteLLMPydanticObjectBase):command: Optional[str] = Noneargs: List[str] = Field(default_factory=list)env: Dict[str, str] = Field(default_factory=dict)+ authorization_url: Optional[str] = None+ token_url: Optional[str] = None+ registration_url: Optional[str] = None@model_validator(mode="before")@classmethod@@ -1159,6 +1146,9 @@ class LiteLLM_MCPServerTable(LiteLLMPydanticObjectBase):command: Optional[str] = Noneargs: List[str] = Field(default_factory=list)env: Dict[str, str] = Field(default_factory=dict)+ authorization_url: Optional[str] = None+ token_url: Optional[str] = None+ registration_url: Optional[str] = Noneclass MakeMCPServersPublicRequest(LiteLLMPydanticObjectBase):@@ -1178,6 +1168,9 @@ class NewSkillRequest(LiteLLMPydanticObjectBase):file_name: Optional[str] = None # Original filenamefile_type: Optional[str] = None # MIME type (e.g., "application/zip")metadata: Optional[Dict[str, Any]] = None+ authorization_url: Optional[str] = None+ token_url: Optional[str] = None+ registration_url: Optional[str] = Noneclass UpdateSkillRequest(LiteLLMPydanticObjectBase):@@ -1224,15 +1217,6 @@ class NewUserRequestTeam(LiteLLMPydanticObjectBase):max_budget_in_team: Optional[float] = Noneuser_role: Literal["user", "admin"] = "user"- @model_validator(mode="after")- def validate_budget_values(self) -> "NewUserRequestTeam":- """Validate that budget values are not negative"""- if self.max_budget_in_team is not None and self.max_budget_in_team < 0:- raise ValueError(- f"max_budget_in_team cannot be negative. Received: {self.max_budget_in_team}"- )- return self-class NewUserRequest(GenerateRequestBase):max_budget: Optional[float] = None@@ -1344,19 +1328,6 @@ class BudgetNewRequest(LiteLLMPydanticObjectBase):description="Datetime when the budget is reset",)- @model_validator(mode="after")- def validate_budget_values(self) -> "BudgetNewRequest":- """Validate that budget values are not negative"""- if self.max_budget is not None and self.max_budget < 0:- raise ValueError(- f"max_budget cannot be negative. Received: {self.max_budget}"- )- if self.soft_budget is not None and self.soft_budget < 0:- raise ValueError(- f"soft_budget cannot be negative. Received: {self.soft_budget}"- )- return self-class BudgetRequest(LiteLLMPydanticObjectBase):budgets: List[str]@@ -1387,12 +1358,12 @@ class NewCustomerRequest(BudgetNewRequest):blocked: bool = False # allow/disallow requests for this end-userbudget_id: Optional[str] = None # give either a budget_id or max_budgetspend: Optional[float] = None- allowed_model_region: Optional[AllowedModelRegion] = (- None # require all user requests to use models in this specific region- )- default_model: Optional[str] = (- None # if no equivalent model in allowed region - default all requests to this model- )+ allowed_model_region: Optional[+ AllowedModelRegion+ ] = None # require all user requests to use models in this specific region+ default_model: Optional[+ str+ ] = None # if no equivalent model in allowed region - default all requests to this model@model_validator(mode="before")@classmethod@@ -1414,12 +1385,12 @@ class UpdateCustomerRequest(LiteLLMPydanticObjectBase):blocked: bool = False # allow/disallow requests for this end-usermax_budget: Optional[float] = Nonebudget_id: Optional[str] = None # give either a budget_id or max_budget- allowed_model_region: Optional[AllowedModelRegion] = (- None # require all user requests to use models in this specific region- )- default_model: Optional[str] = (- None # if no equivalent model in allowed region - default all requests to this model- )+ allowed_model_region: Optional[+ AllowedModelRegion+ ] = None # require all user requests to use models in this specific region+ default_model: Optional[+ str+ ] = None # if no equivalent model in allowed region - default all requests to this modelclass DeleteCustomerRequest(LiteLLMPydanticObjectBase):@@ -1486,15 +1457,6 @@ class TeamBase(LiteLLMPydanticObjectBase):models: list = []blocked: bool = False- @model_validator(mode="after")- def validate_budget_values(self) -> "TeamBase":- """Validate that budget values are not negative"""- if self.max_budget is not None and self.max_budget < 0:- raise ValueError(- f"max_budget cannot be negative. Received: {self.max_budget}"- )- return self-class NewTeamRequest(TeamBase):model_aliases: Optional[dict] = None@@ -1513,29 +1475,20 @@ class NewTeamRequest(TeamBase):] = None # raise an error if 'guaranteed_throughput' is set and we're overallocating tpmmodel_tpm_limit: Optional[Dict[str, int]] = None- team_member_budget: Optional[float] = (- None # allow user to set a budget for all team members- )- team_member_rpm_limit: Optional[int] = (- None # allow user to set RPM limit for all team members- )- team_member_tpm_limit: Optional[int] = (- None # allow user to set TPM limit for all team members- )+ team_member_budget: Optional[+ float+ ] = None # allow user to set a budget for all team members+ team_member_rpm_limit: Optional[+ int+ ] = None # allow user to set RPM limit for all team members+ team_member_tpm_limit: Optional[+ int+ ] = None # allow user to set TPM limit for all team membersteam_member_key_duration: Optional[str] = None # e.g. "1d", "1w", "1m"allowed_vector_store_indexes: Optional[List[AllowedVectorStoreIndexItem]] = Nonemodel_config = ConfigDict(protected_namespaces=())- @model_validator(mode="after")- def validate_team_member_budget(self) -> "NewTeamRequest":- """Validate that team_member_budget is not negative"""- if self.team_member_budget is not None and self.team_member_budget < 0:- raise ValueError(- f"team_member_budget cannot be negative. Received: {self.team_member_budget}"- )- return self-class GlobalEndUsersSpend(LiteLLMPydanticObjectBase):api_key: Optional[str] = None@@ -1585,19 +1538,6 @@ class UpdateTeamRequest(LiteLLMPydanticObjectBase):model_tpm_limit: Optional[Dict[str, int]] = Noneallowed_vector_store_indexes: Optional[List[AllowedVectorStoreIndexItem]] = None- @model_validator(mode="after")- def validate_budget_values(self) -> "UpdateTeamRequest":- """Validate that budget values are not negative"""- if self.max_budget is not None and self.max_budget < 0:- raise ValueError(- f"max_budget cannot be negative. Received: {self.max_budget}"- )- if self.team_member_budget is not None and self.team_member_budget < 0:- raise ValueError(- f"team_member_budget cannot be negative. Received: {self.team_member_budget}"- )- return self-class ResetTeamBudgetRequest(LiteLLMPydanticObjectBase):"""@@ -1629,9 +1569,9 @@ class BlockKeyRequest(LiteLLMPydanticObjectBase):class AddTeamCallback(LiteLLMPydanticObjectBase):callback_name: str- callback_type: Optional[Literal["success", "failure", "success_and_failure"]] = (- "success_and_failure"- )+ callback_type: Optional[+ Literal["success", "failure", "success_and_failure"]+ ] = "success_and_failure"callback_vars: Dict[str, str]@model_validator(mode="before")@@ -1783,19 +1723,6 @@ class LiteLLM_BudgetTable(LiteLLMPydanticObjectBase):model_config = ConfigDict(protected_namespaces=())- @model_validator(mode="after")- def validate_budget_values(self) -> "LiteLLM_BudgetTable":- """Validate that budget values are not negative"""- if self.max_budget is not None and self.max_budget < 0:- raise ValueError(- f"max_budget cannot be negative. Received: {self.max_budget}"- )- if self.soft_budget is not None and self.soft_budget < 0:- raise ValueError(- f"soft_budget cannot be negative. Received: {self.soft_budget}"- )- return self-class LiteLLM_BudgetTableFull(LiteLLM_BudgetTable):"""Represents all params for a LiteLLM_BudgetTable record"""@@ -1872,9 +1799,10 @@ class DynamoDBArgs(LiteLLMPydanticObjectBase):class PassThroughGuardrailSettings(LiteLLMPydanticObjectBase):"""Settings for a specific guardrail on a passthrough endpoint.-+Allows field-level targeting for guardrail execution."""+request_fields: Optional[List[str]] = Field(default=None,description="JSONPath expressions for input field targeting (pre_call). Examples: 'query', 'documents[*].text', 'messages[*].content'. If not specified, guardrail runs on entire request payload.",@@ -1955,9 +1883,9 @@ class ConfigList(LiteLLMPydanticObjectBase):stored_in_db: Optional[bool]field_default_value: Anypremium_field: bool = False- nested_fields: Optional[List[FieldDetail]] = (- None # For nested dictionary or Pydantic fields- )+ nested_fields: Optional[+ List[FieldDetail]+ ] = None # For nested dictionary or Pydantic fieldsclass UserHeaderMapping(LiteLLMPydanticObjectBase):@@ -2343,9 +2271,9 @@ class LiteLLM_OrganizationMembershipTable(LiteLLMPydanticObjectBase):budget_id: Optional[str] = Nonecreated_at: datetimeupdated_at: datetime- user: Optional[Any] = (- None # You might want to replace 'Any' with a more specific type if available- )+ user: Optional[+ Any+ ] = None # You might want to replace 'Any' with a more specific type if availablelitellm_budget_table: Optional[LiteLLM_BudgetTable] = Nonemodel_config = ConfigDict(protected_namespaces=())@@ -2787,7 +2715,7 @@ class AllCallbacks(LiteLLMPydanticObjectBase):"TRACELOOP_API_KEY",],ui_callback_name="Traceloop",- )+ )class SpendLogsMetadata(TypedDict):@@ -2821,9 +2749,7 @@ class SpendLogsMetadata(TypedDict):cold_storage_object_key: Optional[str] # S3/GCS object key for cold storage retrieval- litellm_overhead_time_ms: Optional[- float- ] # LiteLLM overhead time in milliseconds+ litellm_overhead_time_ms: Optional[float] # LiteLLM overhead time in millisecondscost_breakdown: Optional[CostBreakdown] # Detailed cost breakdown (input_cost, output_cost, margin, discount, etc.)@@ -3307,9 +3233,9 @@ class TeamModelDeleteRequest(BaseModel):# Organization Member Requestsclass OrganizationMemberAddRequest(OrgMemberAddRequest):organization_id: str- max_budget_in_organization: Optional[float] = (- None # Users max budget within the organization- )+ max_budget_in_organization: Optional[+ float+ ] = None # Users max budget within the organizationclass OrganizationMemberDeleteRequest(MemberDeleteRequest):@@ -3524,9 +3450,9 @@ class ProviderBudgetResponse(LiteLLMPydanticObjectBase):Maps provider names to their budget configs."""- providers: Dict[str, ProviderBudgetResponseObject] = (- {}- ) # Dictionary mapping provider names to their budget configurations+ providers: Dict[+ str, ProviderBudgetResponseObject+ ] = {} # Dictionary mapping provider names to their budget configurationsclass ProxyStateVariables(TypedDict):@@ -3645,8 +3571,16 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):default=None,description="If no team_id given, default permissions/spend-tracking to this team.s",)+ team_alias_jwt_field: Optional[str] = Field(+ default=None,+ description="The field in the JWT token that stores the team name/alias. Will be resolved to team_id via database lookup.",+ )org_id_jwt_field: Optional[str] = None+ org_alias_jwt_field: Optional[str] = Field(+ default=None,+ description="The field in the JWT token that stores the organization name/alias. Will be resolved to org_id via database lookup.",+ )user_id_jwt_field: Optional[str] = Noneuser_email_jwt_field: Optional[str] = Noneuser_allowed_email_domain: Optional[str] = None@@ -3661,9 +3595,9 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):enforce_rbac: bool = Falseroles_jwt_field: Optional[str] = None # v2 on role mappingsrole_mappings: Optional[List[RoleMapping]] = None- object_id_jwt_field: Optional[str] = (- None # can be either user / team, inferred from the role mapping- )+ object_id_jwt_field: Optional[+ str+ ] = None # can be either user / team, inferred from the role mappingscope_mappings: Optional[List[ScopeMapping]] = Noneenforce_scope_based_access: bool = Falseenforce_team_based_model_access: bool = False@@ -3814,13 +3748,16 @@ class DailyOrganizationSpendTransaction(BaseDailySpendTransaction):class DailyUserSpendTransaction(BaseDailySpendTransaction):user_id: str+class DailyEndUserSpendTransaction(BaseDailySpendTransaction):end_user_id: str+class DailyTagSpendTransaction(BaseDailySpendTransaction):request_id: Optional[str]tag: str+class DailyAgentSpendTransaction(BaseDailySpendTransaction):agent_id: str@@ -3852,8 +3789,8 @@ class LiteLLM_ManagedFileTable(LiteLLMPydanticObjectBase):flat_model_file_ids: List[str]created_by: Optional[str]updated_by: Optional[str]- storage_backend: Optional[str] = None- storage_url: Optional[str] = None+ storage_backend: Optional[str] = None+ storage_url: Optional[str] = Noneclass LiteLLM_ManagedObjectTable(LiteLLMPydanticObjectBase):@@ -3884,4 +3821,4 @@ class LiteLLM_ManagedVectorStoresTable(LiteLLMPydanticObjectBase):class ResponseLiteLLM_ManagedVectorStore(TypedDict, total=False):- vector_store: LiteLLM_ManagedVectorStoresTable+ vector_store: LiteLLM_ManagedVectorStoresTable\ No newline at end of filediff --git a/litellm/proxy/management_endpoints/budget_management_endpoints.py b/litellm/proxy/management_endpoints/budget_management_endpoints.pyindex 2d86f74a41c..e43da32565a 100644--- a/litellm/proxy/management_endpoints/budget_management_endpoints.py+++ b/litellm/proxy/management_endpoints/budget_management_endpoints.py@@ -55,6 +55,18 @@ async def new_budget(detail={"error": CommonProxyErrors.db_not_connected_error.value},)+ # Validate budget values are not negative+ if budget_obj.max_budget is not None and budget_obj.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {budget_obj.max_budget}"}+ )+ if budget_obj.soft_budget is not None and budget_obj.soft_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"soft_budget cannot be negative. Received: {budget_obj.soft_budget}"}+ )+# if no budget_reset_at date is set, but a budget_duration is given, then set budget_reset_at initially to the first completed duration interval in futureif budget_obj.budget_reset_at is None and budget_obj.budget_duration is not None:budget_obj.budget_reset_at = datetime.utcnow() + timedelta(@@ -107,6 +119,18 @@ async def update_budget(if budget_obj.budget_id is None:raise HTTPException(status_code=400, detail={"error": "budget_id is required"})+ # Validate budget values are not negative+ if budget_obj.max_budget is not None and budget_obj.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {budget_obj.max_budget}"}+ )+ if budget_obj.soft_budget is not None and budget_obj.soft_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"soft_budget cannot be negative. Received: {budget_obj.soft_budget}"}+ )+response = await prisma_client.db.litellm_budgettable.update(where={"budget_id": budget_obj.budget_id},data={diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.pyindex 4f9534521c3..4d72bc86257 100644--- a/litellm/proxy/management_endpoints/key_management_endpoints.py+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py@@ -1069,6 +1069,18 @@ async def generate_key_fn(verbose_proxy_logger.debug("entered /key/generate")+ # Validate budget values are not negative+ if data.max_budget is not None and data.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ )+ if data.soft_budget is not None and data.soft_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"soft_budget cannot be negative. Received: {data.soft_budget}"}+ )+if user_custom_key_generate is not None:if asyncio.iscoroutinefunction(user_custom_key_generate):result = await user_custom_key_generate(data) # type: ignore@@ -1502,6 +1514,13 @@ async def update_key_fn()try:+ # Validate budget values are not negative+ if data.max_budget is not None and data.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ )+data_json: dict = data.model_dump(exclude_unset=True, exclude_none=True)key = data_json.pop("key")diff --git a/litellm/proxy/management_endpoints/organization_endpoints.py b/litellm/proxy/management_endpoints/organization_endpoints.pyindex 99b37c765a8..228b4963ea2 100644--- a/litellm/proxy/management_endpoints/organization_endpoints.py+++ b/litellm/proxy/management_endpoints/organization_endpoints.py@@ -168,6 +168,18 @@ async def new_organization(status_code=500, detail={"error": CommonProxyErrors.no_llm_router.value})+ # Validate budget values are not negative+ if data.max_budget is not None and data.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ )+ if data.soft_budget is not None and data.soft_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"soft_budget cannot be negative. Received: {data.soft_budget}"}+ )+user_object_correct_type: Optional[LiteLLM_UserTable] = Noneif user_api_key_dict.user_id is not None:@@ -414,6 +426,18 @@ async def update_organization(# Create validated data modeldata = LiteLLM_OrganizationTableUpdate(**raw_data_with_flat_budget_fields)+ # Validate budget values are not negative+ if data.max_budget is not None and data.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ )+ if data.soft_budget is not None and data.soft_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"soft_budget cannot be negative. Received: {data.soft_budget}"}+ )+if data.updated_by is None:data.updated_by = user_api_key_dict.user_iddiff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex c6fab9a73f0..6dfba9edfdc 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -732,6 +732,18 @@ async def new_team( # noqa: PLR0915if prisma_client is None:raise HTTPException(status_code=500, detail={"error": "No db connected"})+ # Validate budget values are not negative+ if data.max_budget is not None and data.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ )+ if data.team_member_budget is not None and data.team_member_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"team_member_budget cannot be negative. Received: {data.team_member_budget}"}+ )+# Check if license is over limittotal_teams = await prisma_client.db.litellm_teamtable.count()if total_teams and _license_check.is_team_count_over_limit(@@ -1254,6 +1266,18 @@ async def update_team(raise HTTPException(status_code=400, detail={"error": "No team id passed in"})verbose_proxy_logger.debug("/team/update - %s", data)+ # Validate budget values are not negative+ if data.max_budget is not None and data.max_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"max_budget cannot be negative. Received: {data.max_budget}"}+ )+ if data.team_member_budget is not None and data.team_member_budget < 0:+ raise HTTPException(+ status_code=400,+ detail={"error": f"team_member_budget cannot be negative. Received: {data.team_member_budget}"}+ )+existing_team_row = await prisma_client.db.litellm_teamtable.find_unique(where={"team_id": data.team_id})