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]

[Bug Fix] Invite links email should contain the correct invite id (#12130)

Ishaan Jaffcfc07f361ba9
diff --git a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py
index b4b128b6249..a7c127cffff 100644
--- a/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py
+++ b/enterprise/litellm_enterprise/enterprise_callbacks/send_emails/base_email.py
@@ -22,7 +22,7 @@ from litellm.integrations.email_templates.key_created_email import (
from litellm.integrations.email_templates.user_invitation_email import (
USER_INVITATION_EMAIL_TEMPLATE,
)
-from litellm.proxy._types import WebhookEvent
+from litellm.proxy._types import InvitationNew, UserAPIKeyAuth, WebhookEvent
from litellm.types.integrations.slack_alerting import LITELLM_LOGO_URL
@@ -166,39 +166,81 @@ class BaseEmailLogger(CustomLogger):
"""
Get invitation link for the user
"""
- import asyncio
+ # Early validation
+ if not user_id:
+ verbose_proxy_logger.debug("No user_id provided for invitation link")
+ return base_url
+
+ if not await self._is_prisma_client_available():
+ return base_url
+
+ # Wait for any concurrent invitation creation to complete
+ await self._wait_for_invitation_creation()
+
+ # Get or create invitation
+ invitation = await self._get_or_create_invitation(user_id)
+ if not invitation:
+ verbose_proxy_logger.warning(f"Failed to get/create invitation for user_id: {user_id}")
+ return base_url
+
+ return self._construct_invitation_link(invitation.id, base_url)
+ async def _is_prisma_client_available(self) -> bool:
+ """Check if Prisma client is available"""
from litellm.proxy.proxy_server import prisma_client
+
+ if prisma_client is None:
+ verbose_proxy_logger.debug("Prisma client not found. Unable to lookup invitation")
+ return False
+ return True
- ################################################################################
- ########## Sleep for 10 seconds to wait for the invitation link to be created ###
- ################################################################################
- # The UI, calls /invitation/new to generate the invitation link
- # We wait 10 seconds to ensure the link is created
- ################################################################################
+ async def _wait_for_invitation_creation(self) -> None:
+ """
+ Wait for any concurrent invitation creation to complete.
+
+ The UI calls /invitation/new to generate the invitation link.
+ We wait to ensure any pending invitation creation is completed.
+ """
+ import asyncio
await asyncio.sleep(10)
+ async def _get_or_create_invitation(self, user_id: str):
+ """
+ Get existing invitation or create a new one for the user
+
+ Returns:
+ Invitation object with id attribute, or None if failed
+ """
+ from litellm.proxy.management_helpers.user_invitation import (
+ create_invitation_for_user,
+ )
+ from litellm.proxy.proxy_server import prisma_client
+
if prisma_client is None:
- verbose_proxy_logger.debug(
- f"Prisma client not found. Unable to lookup user email for user_id: {user_id}"
+ verbose_proxy_logger.error("Prisma client is None in _get_or_create_invitation")
+ return None
+
+ try:
+ # Try to get existing invitation
+ existing_invitations = await prisma_client.db.litellm_invitationlink.find_many(
+ where={"user_id": user_id},
+ order={"created_at": "desc"},
)
- return base_url
-
- if user_id is None:
- return base_url
-
- # get the latest invitation link for the user
- invitation_rows = await prisma_client.db.litellm_invitationlink.find_many(
- where={"user_id": user_id},
- order={"created_at": "desc"},
- )
- if len(invitation_rows) > 0:
- invitation_row = invitation_rows[0]
- return self._construct_invitation_link(
- invitation_id=invitation_row.id, base_url=base_url
+
+ if existing_invitations and len(existing_invitations) > 0:
+ verbose_proxy_logger.debug(f"Found existing invitation for user_id: {user_id}")
+ return existing_invitations[0]
+
+ # Create new invitation if none exists
+ verbose_proxy_logger.debug(f"Creating new invitation for user_id: {user_id}")
+ return await create_invitation_for_user(
+ data=InvitationNew(user_id=user_id),
+ user_api_key_dict=UserAPIKeyAuth(user_id=user_id),
)
-
- return base_url
+
+ except Exception as e:
+ verbose_proxy_logger.error(f"Error getting/creating invitation for user_id {user_id}: {e}")
+ return None
def _construct_invitation_link(self, invitation_id: str, base_url: str) -> str:
"""
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 94962e81b9b..ddbbce96462 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -152,7 +152,6 @@ from .initialize_dynamic_callback_params import (
from .specialty_caches.dynamic_logging_cache import DynamicLoggingCache
if TYPE_CHECKING:
- from litellm.llms.base_llm.files.transformation import BaseFileEndpoints
from litellm.llms.base_llm.passthrough.transformation import BasePassthroughConfig
try:
from litellm_enterprise.enterprise_callbacks.callback_controls import (
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index e6eb3372956..b69d9984f62 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -23,6 +23,12 @@
"search_context_size_medium": 0.0,
"search_context_size_high": 0.0
},
+ "file_search_cost_per_1k_calls": 0.0,
+ "file_search_cost_per_gb_per_day": 0.0,
+ "vector_store_cost_per_gb_per_day": 0.0,
+ "computer_use_input_cost_per_1k_tokens": 0.0,
+ "computer_use_output_cost_per_1k_tokens": 0.0,
+ "code_interpreter_cost_per_session": 0.0,
"supported_regions": [
"global",
"us-west-2",
@@ -4575,6 +4581,37 @@
"supports_tool_choice": true,
"supports_prompt_caching": true
},
+ "deepseek/deepseek-r1": {
+ "max_tokens": 8192,
+ "max_input_tokens": 65536,
+ "max_output_tokens": 8192,
+ "input_cost_per_token": 5.5e-07,
+ "input_cost_per_token_cache_hit": 1.4e-07,
+ "output_cost_per_token": 2.19e-06,
+ "litellm_provider": "deepseek",
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_assistant_prefill": true,
+ "supports_tool_choice": true,
+ "supports_reasoning": true,
+ "supports_prompt_caching": true
+ },
+ "deepseek/deepseek-v3": {
+ "max_tokens": 8192,
+ "max_input_tokens": 65536,
+ "max_output_tokens": 8192,
+ "input_cost_per_token": 2.7e-07,
+ "input_cost_per_token_cache_hit": 7e-08,
+ "cache_read_input_token_cost": 7e-08,
+ "cache_creation_input_token_cost": 0.0,
+ "output_cost_per_token": 1.1e-06,
+ "litellm_provider": "deepseek",
+ "mode": "chat",
+ "supports_function_calling": true,
+ "supports_assistant_prefill": true,
+ "supports_tool_choice": true,
+ "supports_prompt_caching": true
+ },
"codestral/codestral-latest": {
"max_tokens": 8191,
"max_input_tokens": 32000,
@@ -15735,4 +15772,4 @@
"notes": "ElevenLabs Scribe v1 experimental - enhanced version of the main Scribe model"
}
}
-}
\ No newline at end of file
+}
diff --git a/litellm/proxy/management_helpers/user_invitation.py b/litellm/proxy/management_helpers/user_invitation.py
new file mode 100644
index 00000000000..80f57fef2a9
--- /dev/null
+++ b/litellm/proxy/management_helpers/user_invitation.py
@@ -0,0 +1,47 @@
+from datetime import timedelta
+
+from fastapi import HTTPException
+
+import litellm
+from litellm.proxy._types import CommonProxyErrors, InvitationNew, UserAPIKeyAuth
+
+
+async def create_invitation_for_user(
+ data: InvitationNew,
+ user_api_key_dict: UserAPIKeyAuth,
+):
+ """
+ Create an invitation for the user to onboard to LiteLLM Admin UI.
+ """
+ from litellm.proxy.proxy_server import litellm_proxy_admin_name, prisma_client
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
+
+ current_time = litellm.utils.get_utc_datetime()
+ expires_at = current_time + timedelta(days=7)
+
+ try:
+ response = await prisma_client.db.litellm_invitationlink.create(
+ data={
+ "user_id": data.user_id,
+ "created_at": current_time,
+ "expires_at": expires_at,
+ "created_by": user_api_key_dict.user_id or litellm_proxy_admin_name,
+ "updated_at": current_time,
+ "updated_by": user_api_key_dict.user_id or litellm_proxy_admin_name,
+ } # type: ignore
+ )
+ return response
+ except Exception as e:
+ if "Foreign key constraint failed on the field" in str(e):
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": "User id does not exist in 'LiteLLM_UserTable'. Fix this by creating user via `/user/new`."
+ },
+ )
+ raise HTTPException(status_code=500, detail={"error": str(e)})
\ No newline at end of file
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index e2476a2e684..1aa914585e8 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -323,6 +323,7 @@ from litellm.proxy.utils import (
get_custom_url,
get_error_message_str,
get_server_root_path,
+ handle_exception_on_proxy,
hash_token,
update_spend,
)
@@ -7510,49 +7511,37 @@ async def new_invitation(
}'
```
"""
- global prisma_client
-
- if prisma_client is None:
- raise HTTPException(
- status_code=400,
- detail={"error": CommonProxyErrors.db_not_connected_error.value},
- )
-
- if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:
- raise HTTPException(
- status_code=400,
- detail={
- "error": "{}, your role={}".format(
- CommonProxyErrors.not_allowed_access.value,
- user_api_key_dict.user_role,
- )
- },
+ try:
+ from litellm.proxy.management_helpers.user_invitation import (
+ create_invitation_for_user,
)
+ global prisma_client
- current_time = litellm.utils.get_utc_datetime()
- expires_at = current_time + timedelta(days=7)
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=400,
+ detail={"error": CommonProxyErrors.db_not_connected_error.value},
+ )
- try:
- response = await prisma_client.db.litellm_invitationlink.create(
- data={
- "user_id": data.user_id,
- "created_at": current_time,
- "expires_at": expires_at,
- "created_by": user_api_key_dict.user_id or litellm_proxy_admin_name,
- "updated_at": current_time,
- "updated_by": user_api_key_dict.user_id or litellm_proxy_admin_name,
- } # type: ignore
- )
- return response
- except Exception as e:
- if "Foreign key constraint failed on the field" in str(e):
+ if user_api_key_dict.user_role != LitellmUserRoles.PROXY_ADMIN:
raise HTTPException(
status_code=400,
detail={
- "error": "User id does not exist in 'LiteLLM_UserTable'. Fix this by creating user via `/user/new`."
+ "error": "{}, your role={}".format(
+ CommonProxyErrors.not_allowed_access.value,
+ user_api_key_dict.user_role,
+ )
},
)
- raise HTTPException(status_code=500, detail={"error": str(e)})
+
+ response = await create_invitation_for_user(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ )
+ return response
+ except Exception as e:
+ raise handle_exception_on_proxy(e)
+
@router.get(
diff --git a/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py b/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py
index 71608065c88..651254b754c 100644
--- a/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py
+++ b/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_base_email.py
@@ -248,6 +248,109 @@ def test_construct_invitation_link(base_email_logger):
assert result == "http://test.com/ui?invitation_id=test-id-123"
+async def test_get_invitation_link_creates_new_when_none_exist(base_email_logger):
+ """Test that _get_invitation_link creates a new invitation when none exist"""
+ # Mock prisma client with no existing invitation rows
+ mock_prisma = mock.MagicMock()
+
+ # Mock find_many to return empty list (no existing invitations)
+ async def mock_find_many_empty(*args, **kwargs):
+ return []
+
+ mock_prisma.db.litellm_invitationlink.find_many = mock_find_many_empty
+
+ # Mock the create_invitation_for_user function
+ mock_created_invitation = mock.MagicMock()
+ mock_created_invitation.id = "new-invitation-id"
+
+ with mock.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):
+ with mock.patch(
+ "litellm.proxy.management_helpers.user_invitation.create_invitation_for_user",
+ return_value=mock_created_invitation
+ ) as mock_create_invitation:
+ # Execute
+ result = await base_email_logger._get_invitation_link(
+ user_id="test-user", base_url="http://test.com"
+ )
+
+ # Verify that create_invitation_for_user was called
+ mock_create_invitation.assert_called_once()
+ call_args = mock_create_invitation.call_args[1]
+ assert call_args["data"].user_id == "test-user"
+ assert call_args["user_api_key_dict"].user_id == "test-user"
+
+ # Verify the returned link uses the new invitation ID
+ assert result == "http://test.com/ui?invitation_id=new-invitation-id"
+
+
+async def test_get_invitation_link_uses_existing_when_available(base_email_logger):
+ """Test that _get_invitation_link uses existing invitation when available"""
+ # Mock prisma client with existing invitation row
+ mock_invitation_row = mock.MagicMock()
+ mock_invitation_row.id = "existing-invitation-id"
+
+ mock_prisma = mock.MagicMock()
+
+ # Mock find_many to return existing invitation
+ async def mock_find_many_existing(*args, **kwargs):
+ return [mock_invitation_row]
+
+ mock_prisma.db.litellm_invitationlink.find_many = mock_find_many_existing
+
+ with mock.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):
+ with mock.patch(
+ "litellm.proxy.management_helpers.user_invitation.create_invitation_for_user"
+ ) as mock_create_invitation:
+ # Execute
+ result = await base_email_logger._get_invitation_link(
+ user_id="test-user", base_url="http://test.com"
+ )
+
+ # Verify that create_invitation_for_user was NOT called
+ mock_create_invitation.assert_not_called()
+
+ # Verify the returned link uses the existing invitation ID
+ assert result == "http://test.com/ui?invitation_id=existing-invitation-id"
+
+
+async def test_get_invitation_link_creates_new_when_list_is_none(base_email_logger):
+ """Test that _get_invitation_link creates a new invitation when invitation_rows is None"""
+ # Mock prisma client to return None
+ mock_prisma = mock.MagicMock()
+
+ # Mock find_many to return None
+ async def mock_find_many_none(*args, **kwargs):
+ return None
+
+ mock_prisma.db.litellm_invitationlink.find_many = mock_find_many_none
+
+ # Mock the create_invitation_for_user function
+ mock_created_invitation = mock.MagicMock()
+ mock_created_invitation.id = "new-invitation-from-none"
+
+ with mock.patch("litellm.proxy.proxy_server.prisma_client", mock_prisma):
+ with mock.patch(
+ "litellm.proxy.management_helpers.user_invitation.create_invitation_for_user",
+ return_value=mock_created_invitation
+ ) as mock_create_invitation:
+ # Execute
+ result = await base_email_logger._get_invitation_link(
+ user_id="test-user", base_url="http://test.com"
+ )
+
+ # Verify that create_invitation_for_user was called
+ mock_create_invitation.assert_called_once()
+ call_args = mock_create_invitation.call_args[1]
+ assert call_args["data"].user_id == "test-user"
+ assert call_args["user_api_key_dict"].user_id == "test-user"
+
+ # Verify the returned link uses the new invitation ID
+ assert result == "http://test.com/ui?invitation_id=new-invitation-from-none"
+
+
@pytest.mark.asyncio
async def test_get_email_params_user_invitation(
base_email_logger, mock_lookup_user_email