From ebfff975d49c7b4fde39820a3710c8cf099a78f5 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Mon, 21 Apr 2025 23:05:53 -0700 Subject: [PATCH 01/40] docs responses routing --- docs/my-website/docs/response_api.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/docs/my-website/docs/response_api.md b/docs/my-website/docs/response_api.md index ce0ffeac48..532f20bc05 100644 --- a/docs/my-website/docs/response_api.md +++ b/docs/my-website/docs/response_api.md @@ -631,10 +631,3 @@ follow_up = client.responses.create( - -#### How It Works - -1. When a user makes an initial request to the Responses API, LiteLLM caches which model deployment that returned the specific response. (Stored in Redis if you connected LiteLLM to Redis) -2. When a subsequent request includes `previous_response_id`, LiteLLM automatically routes it to the same deployment -3. If the original deployment is unavailable, or if the `previous_response_id` isn't found in the cache, LiteLLM falls back to normal routing - From b2955a2bdd360b658ece4686d04f5693377e65fe Mon Sep 17 00:00:00 2001 From: Dwij <96073160+Dwij1704@users.noreply.github.com> Date: Tue, 22 Apr 2025 22:59:01 +0530 Subject: [PATCH 02/40] Add AgentOps Integration to LiteLLM (#9685) * feat(sidebars): add new item for agentops integration in Logging & Observability category * Update agentops_integration.md to enhance title formatting and remove redundant section * Enhance AgentOps integration in documentation and codebase by removing LiteLLMCallbackHandler references, adding environment variable configurations, and updating logging initialization for AgentOps support. * Update AgentOps integration documentation to include instructions for obtaining API keys and clarify environment variable setup. * Add unit tests for AgentOps integration and improve error handling in token fetching * Add unit tests for AgentOps configuration and token fetching functionality * Corrected agentops test directory * Linting fix * chore: add OpenTelemetry dependencies to pyproject.toml * chore: update OpenTelemetry dependencies and add new packages in pyproject.toml and poetry.lock --- .../observability/agentops_integration.md | 83 ++++ docs/my-website/sidebars.js | 1 + litellm/__init__.py | 1 + litellm/integrations/agentops/__init__.py | 3 + litellm/integrations/agentops/agentops.py | 118 ++++++ litellm/litellm_core_utils/litellm_logging.py | 12 +- poetry.lock | 353 ++++++++++++++---- pyproject.toml | 6 + tests/litellm/integrations/test_agentops.py | 98 +++++ 9 files changed, 608 insertions(+), 67 deletions(-) create mode 100644 docs/my-website/docs/observability/agentops_integration.md create mode 100644 litellm/integrations/agentops/__init__.py create mode 100644 litellm/integrations/agentops/agentops.py create mode 100644 tests/litellm/integrations/test_agentops.py diff --git a/docs/my-website/docs/observability/agentops_integration.md b/docs/my-website/docs/observability/agentops_integration.md new file mode 100644 index 0000000000..e0599fab70 --- /dev/null +++ b/docs/my-website/docs/observability/agentops_integration.md @@ -0,0 +1,83 @@ +# 🖇️ AgentOps - LLM Observability Platform + +:::tip + +This is community maintained. Please make an issue if you run into a bug: +https://github.com/BerriAI/litellm + +::: + +[AgentOps](https://docs.agentops.ai) is an observability platform that enables tracing and monitoring of LLM calls, providing detailed insights into your AI operations. + +## Using AgentOps with LiteLLM + +LiteLLM provides `success_callbacks` and `failure_callbacks`, allowing you to easily integrate AgentOps for comprehensive tracing and monitoring of your LLM operations. + +### Integration + +Use just a few lines of code to instantly trace your responses **across all providers** with AgentOps: +Get your AgentOps API Keys from https://app.agentops.ai/ +```python +import litellm + +# Configure LiteLLM to use AgentOps +litellm.success_callback = ["agentops"] + +# Make your LLM calls as usual +response = litellm.completion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello, how are you?"}], +) +``` + +Complete Code: + +```python +import os +from litellm import completion + +# Set env variables +os.environ["OPENAI_API_KEY"] = "your-openai-key" +os.environ["AGENTOPS_API_KEY"] = "your-agentops-api-key" + +# Configure LiteLLM to use AgentOps +litellm.success_callback = ["agentops"] + +# OpenAI call +response = completion( + model="gpt-4", + messages=[{"role": "user", "content": "Hi 👋 - I'm OpenAI"}], +) + +print(response) +``` + +### Configuration Options + +The AgentOps integration can be configured through environment variables: + +- `AGENTOPS_API_KEY` (str, optional): Your AgentOps API key +- `AGENTOPS_ENVIRONMENT` (str, optional): Deployment environment (defaults to "production") +- `AGENTOPS_SERVICE_NAME` (str, optional): Service name for tracing (defaults to "agentops") + +### Advanced Usage + +You can configure additional settings through environment variables: + +```python +import os + +# Configure AgentOps settings +os.environ["AGENTOPS_API_KEY"] = "your-agentops-api-key" +os.environ["AGENTOPS_ENVIRONMENT"] = "staging" +os.environ["AGENTOPS_SERVICE_NAME"] = "my-service" + +# Enable AgentOps tracing +litellm.success_callback = ["agentops"] +``` + +### Support + +For issues or questions, please refer to: +- [AgentOps Documentation](https://docs.agentops.ai) +- [LiteLLM Documentation](https://docs.litellm.ai) \ No newline at end of file diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.js index c21c727b6a..60030a59bb 100644 --- a/docs/my-website/sidebars.js +++ b/docs/my-website/sidebars.js @@ -411,6 +411,7 @@ const sidebars = { type: "category", label: "Logging & Observability", items: [ + "observability/agentops_integration", "observability/langfuse_integration", "observability/lunary_integration", "observability/mlflow", diff --git a/litellm/__init__.py b/litellm/__init__.py index a7b747541a..59c8c78eb9 100644 --- a/litellm/__init__.py +++ b/litellm/__init__.py @@ -113,6 +113,7 @@ _custom_logger_compatible_callbacks_literal = Literal[ "pagerduty", "humanloop", "gcs_pubsub", + "agentops", "anthropic_cache_control_hook", ] logged_real_time_event_types: Optional[Union[List[str], Literal["*"]]] = None diff --git a/litellm/integrations/agentops/__init__.py b/litellm/integrations/agentops/__init__.py new file mode 100644 index 0000000000..6ad02ce0ba --- /dev/null +++ b/litellm/integrations/agentops/__init__.py @@ -0,0 +1,3 @@ +from .agentops import AgentOps + +__all__ = ["AgentOps"] \ No newline at end of file diff --git a/litellm/integrations/agentops/agentops.py b/litellm/integrations/agentops/agentops.py new file mode 100644 index 0000000000..11e76841e9 --- /dev/null +++ b/litellm/integrations/agentops/agentops.py @@ -0,0 +1,118 @@ +""" +AgentOps integration for LiteLLM - Provides OpenTelemetry tracing for LLM calls +""" +import os +from dataclasses import dataclass +from typing import Optional, Dict, Any +from litellm.integrations.opentelemetry import OpenTelemetry, OpenTelemetryConfig +from litellm.llms.custom_httpx.http_handler import _get_httpx_client + +@dataclass +class AgentOpsConfig: + endpoint: str = "https://otlp.agentops.cloud/v1/traces" + api_key: Optional[str] = None + service_name: Optional[str] = None + deployment_environment: Optional[str] = None + auth_endpoint: str = "https://api.agentops.ai/v3/auth/token" + + @classmethod + def from_env(cls): + return cls( + endpoint="https://otlp.agentops.cloud/v1/traces", + api_key=os.getenv("AGENTOPS_API_KEY"), + service_name=os.getenv("AGENTOPS_SERVICE_NAME", "agentops"), + deployment_environment=os.getenv("AGENTOPS_ENVIRONMENT", "production"), + auth_endpoint="https://api.agentops.ai/v3/auth/token" + ) + +class AgentOps(OpenTelemetry): + """ + AgentOps integration - built on top of OpenTelemetry + + Example usage: + ```python + import litellm + + litellm.success_callback = ["agentops"] + + response = litellm.completion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello, how are you?"}], + ) + ``` + """ + def __init__( + self, + config: Optional[AgentOpsConfig] = None, + ): + if config is None: + config = AgentOpsConfig.from_env() + + # Prefetch JWT token for authentication + jwt_token = None + project_id = None + if config.api_key: + try: + response = self._fetch_auth_token(config.api_key, config.auth_endpoint) + jwt_token = response.get("token") + project_id = response.get("project_id") + except Exception: + pass + + headers = f"Authorization=Bearer {jwt_token}" if jwt_token else None + + otel_config = OpenTelemetryConfig( + exporter="otlp_http", + endpoint=config.endpoint, + headers=headers + ) + + # Initialize OpenTelemetry with our config + super().__init__( + config=otel_config, + callback_name="agentops" + ) + + # Set AgentOps-specific resource attributes + resource_attrs = { + "service.name": config.service_name or "litellm", + "deployment.environment": config.deployment_environment or "production", + "telemetry.sdk.name": "agentops", + } + + if project_id: + resource_attrs["project.id"] = project_id + + self.resource_attributes = resource_attrs + + def _fetch_auth_token(self, api_key: str, auth_endpoint: str) -> Dict[str, Any]: + """ + Fetch JWT authentication token from AgentOps API + + Args: + api_key: AgentOps API key + auth_endpoint: Authentication endpoint + + Returns: + Dict containing JWT token and project ID + """ + headers = { + "Content-Type": "application/json", + "Connection": "keep-alive", + } + + client = _get_httpx_client() + try: + response = client.post( + url=auth_endpoint, + headers=headers, + json={"api_key": api_key}, + timeout=10 + ) + + if response.status_code != 200: + raise Exception(f"Failed to fetch auth token: {response.text}") + + return response.json() + finally: + client.close() \ No newline at end of file diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py index 4d0b93f390..77d4fd7d5d 100644 --- a/litellm/litellm_core_utils/litellm_logging.py +++ b/litellm/litellm_core_utils/litellm_logging.py @@ -28,6 +28,7 @@ from litellm._logging import _is_debugging_on, verbose_logger from litellm.batches.batch_utils import _handle_completed_batch from litellm.caching.caching import DualCache, InMemoryCache from litellm.caching.caching_handler import LLMCachingHandler + from litellm.constants import ( DEFAULT_MOCK_RESPONSE_COMPLETION_TOKEN_COUNT, DEFAULT_MOCK_RESPONSE_PROMPT_TOKEN_COUNT, @@ -36,6 +37,7 @@ from litellm.cost_calculator import ( RealtimeAPITokenUsageProcessor, _select_model_name_for_cost_calc, ) +from litellm.integrations.agentops import AgentOps from litellm.integrations.anthropic_cache_control_hook import AnthropicCacheControlHook from litellm.integrations.arize.arize import ArizeLogger from litellm.integrations.custom_guardrail import CustomGuardrail @@ -2685,7 +2687,15 @@ def _init_custom_logger_compatible_class( # noqa: PLR0915 """ try: custom_logger_init_args = custom_logger_init_args or {} - if logging_integration == "lago": + if logging_integration == "agentops": # Add AgentOps initialization + for callback in _in_memory_loggers: + if isinstance(callback, AgentOps): + return callback # type: ignore + + agentops_logger = AgentOps() + _in_memory_loggers.append(agentops_logger) + return agentops_logger # type: ignore + elif logging_integration == "lago": for callback in _in_memory_loggers: if isinstance(callback, LagoLogger): return callback # type: ignore diff --git a/poetry.lock b/poetry.lock index 02ec90cc31..1ad74a07a6 100644 --- a/poetry.lock +++ b/poetry.lock @@ -548,7 +548,7 @@ version = "3.4.1" description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." optional = false python-versions = ">=3.7" -groups = ["main"] +groups = ["main", "dev", "proxy-dev"] files = [ {file = "charset_normalizer-3.4.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:91b36a978b5ae0ee86c394f5a54d6ef44db1de0815eb43de826d41d21e4af3de"}, {file = "charset_normalizer-3.4.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7461baadb4dc00fd9e0acbe254e3d7d2112e7f92ced2adc96e54ef6501c5f176"}, @@ -742,6 +742,24 @@ ssh = ["bcrypt (>=3.1.5)"] test = ["certifi", "cryptography-vectors (==43.0.3)", "pretend", "pytest (>=6.2.0)", "pytest-benchmark", "pytest-cov", "pytest-xdist"] test-randomorder = ["pytest-randomly"] +[[package]] +name = "deprecated" +version = "1.2.18" +description = "Python @deprecated decorator to deprecate old python classes, functions or methods." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,>=2.7" +groups = ["dev", "proxy-dev"] +files = [ + {file = "Deprecated-1.2.18-py2.py3-none-any.whl", hash = "sha256:bd5011788200372a32418f888e326a09ff80d0214bd961147cfed01b5c018eec"}, + {file = "deprecated-1.2.18.tar.gz", hash = "sha256:422b6f6d859da6f2ef57857761bfb392480502a64c3028ca9bbe86085d72115d"}, +] + +[package.dependencies] +wrapt = ">=1.10,<2" + +[package.extras] +dev = ["PyTest", "PyTest-Cov", "bump2version (<1)", "setuptools ; python_version >= \"3.12\"", "tox"] + [[package]] name = "distro" version = "1.9.0" @@ -1116,14 +1134,14 @@ protobuf = ">=3.20.2,<4.21.0 || >4.21.0,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4 name = "googleapis-common-protos" version = "1.70.0" description = "Common protobufs used in Google APIs" -optional = true +optional = false python-versions = ">=3.7" -groups = ["main"] -markers = "extra == \"extra-proxy\"" +groups = ["main", "dev", "proxy-dev"] files = [ {file = "googleapis_common_protos-1.70.0-py3-none-any.whl", hash = "sha256:b8bfcca8c25a2bb253e0e0b0adaf8c00773e5e6af6fd92397576680b807e0fd8"}, {file = "googleapis_common_protos-1.70.0.tar.gz", hash = "sha256:0e1b44e0ea153e6594f9f394fef15193a68aaaea2d843f83e2742717ca753257"}, ] +markers = {main = "extra == \"extra-proxy\""} [package.dependencies] grpcio = {version = ">=1.44.0,<2.0.0", optional = true, markers = "extra == \"grpc\""} @@ -1154,10 +1172,9 @@ protobuf = ">=3.20.2,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4 name = "grpcio" version = "1.70.0" description = "HTTP/2-based RPC framework" -optional = true +optional = false python-versions = ">=3.8" -groups = ["main"] -markers = "python_version < \"3.10\" and extra == \"extra-proxy\"" +groups = ["main", "dev", "proxy-dev"] files = [ {file = "grpcio-1.70.0-cp310-cp310-linux_armv7l.whl", hash = "sha256:95469d1977429f45fe7df441f586521361e235982a0b39e33841549143ae2851"}, {file = "grpcio-1.70.0-cp310-cp310-macosx_12_0_universal2.whl", hash = "sha256:ed9718f17fbdb472e33b869c77a16d0b55e166b100ec57b016dc7de9c8d236bf"}, @@ -1215,6 +1232,7 @@ files = [ {file = "grpcio-1.70.0-cp39-cp39-win_amd64.whl", hash = "sha256:a31d7e3b529c94e930a117b2175b2efd179d96eb3c7a21ccb0289a8ab05b645c"}, {file = "grpcio-1.70.0.tar.gz", hash = "sha256:8d1584a68d5922330025881e63a6c1b54cc8117291d382e4fa69339b6d914c56"}, ] +markers = {main = "python_version < \"3.10\" and extra == \"extra-proxy\"", dev = "python_version < \"3.10\"", proxy-dev = "python_version < \"3.10\""} [package.extras] protobuf = ["grpcio-tools (>=1.70.0)"] @@ -1223,10 +1241,9 @@ protobuf = ["grpcio-tools (>=1.70.0)"] name = "grpcio" version = "1.71.0" description = "HTTP/2-based RPC framework" -optional = true +optional = false python-versions = ">=3.9" -groups = ["main"] -markers = "python_version >= \"3.10\" and extra == \"extra-proxy\"" +groups = ["main", "dev", "proxy-dev"] files = [ {file = "grpcio-1.71.0-cp310-cp310-linux_armv7l.whl", hash = "sha256:c200cb6f2393468142eb50ab19613229dcc7829b5ccee8b658a36005f6669fdd"}, {file = "grpcio-1.71.0-cp310-cp310-macosx_12_0_universal2.whl", hash = "sha256:b2266862c5ad664a380fbbcdbdb8289d71464c42a8c29053820ee78ba0119e5d"}, @@ -1280,45 +1297,28 @@ files = [ {file = "grpcio-1.71.0-cp39-cp39-win_amd64.whl", hash = "sha256:63e41b91032f298b3e973b3fa4093cbbc620c875e2da7b93e249d4728b54559a"}, {file = "grpcio-1.71.0.tar.gz", hash = "sha256:2b85f7820475ad3edec209d3d89a7909ada16caab05d3f2e08a7e8ae3200a55c"}, ] +markers = {main = "python_version >= \"3.10\" and extra == \"extra-proxy\"", dev = "python_version >= \"3.10\"", proxy-dev = "python_version >= \"3.10\""} [package.extras] protobuf = ["grpcio-tools (>=1.71.0)"] [[package]] name = "grpcio-status" -version = "1.70.0" +version = "1.62.3" description = "Status proto mapping for gRPC" optional = true -python-versions = ">=3.8" +python-versions = ">=3.6" groups = ["main"] -markers = "python_version < \"3.10\" and extra == \"extra-proxy\"" +markers = "extra == \"extra-proxy\"" files = [ - {file = "grpcio_status-1.70.0-py3-none-any.whl", hash = "sha256:fc5a2ae2b9b1c1969cc49f3262676e6854aa2398ec69cb5bd6c47cd501904a85"}, - {file = "grpcio_status-1.70.0.tar.gz", hash = "sha256:0e7b42816512433b18b9d764285ff029bde059e9d41f8fe10a60631bd8348101"}, + {file = "grpcio-status-1.62.3.tar.gz", hash = "sha256:289bdd7b2459794a12cf95dc0cb727bd4a1742c37bd823f760236c937e53a485"}, + {file = "grpcio_status-1.62.3-py3-none-any.whl", hash = "sha256:f9049b762ba8de6b1086789d8315846e094edac2c50beaf462338b301a8fd4b8"}, ] [package.dependencies] googleapis-common-protos = ">=1.5.5" -grpcio = ">=1.70.0" -protobuf = ">=5.26.1,<6.0dev" - -[[package]] -name = "grpcio-status" -version = "1.71.0" -description = "Status proto mapping for gRPC" -optional = true -python-versions = ">=3.9" -groups = ["main"] -markers = "extra == \"extra-proxy\" and python_version >= \"3.10\"" -files = [ - {file = "grpcio_status-1.71.0-py3-none-any.whl", hash = "sha256:843934ef8c09e3e858952887467f8256aac3910c55f077a359a65b2b3cde3e68"}, - {file = "grpcio_status-1.71.0.tar.gz", hash = "sha256:11405fed67b68f406b3f3c7c5ae5104a79d2d309666d10d61b152e91d28fb968"}, -] - -[package.dependencies] -googleapis-common-protos = ">=1.5.5" -grpcio = ">=1.71.0" -protobuf = ">=5.26.1,<6.0dev" +grpcio = ">=1.62.3" +protobuf = ">=4.21.6" [[package]] name = "gunicorn" @@ -1550,27 +1550,23 @@ all = ["flake8 (>=7.1.1)", "mypy (>=1.11.2)", "pytest (>=8.3.2)", "ruff (>=0.6.2 [[package]] name = "importlib-metadata" -version = "8.5.0" +version = "7.1.0" description = "Read metadata from Python packages" optional = false python-versions = ">=3.8" -groups = ["main"] +groups = ["main", "dev", "proxy-dev"] files = [ - {file = "importlib_metadata-8.5.0-py3-none-any.whl", hash = "sha256:45e54197d28b7a7f1559e60b95e7c567032b602131fbd588f1497f47880aa68b"}, - {file = "importlib_metadata-8.5.0.tar.gz", hash = "sha256:71522656f0abace1d072b9e5481a48f07c138e00f079c38c8f883823f9c26bd7"}, + {file = "importlib_metadata-7.1.0-py3-none-any.whl", hash = "sha256:30962b96c0c223483ed6cc7280e7f0199feb01a0e40cfae4d4450fc6fab1f570"}, + {file = "importlib_metadata-7.1.0.tar.gz", hash = "sha256:b78938b926ee8d5f020fc4772d487045805a55ddbad2ecf21c6d60938dc7fcd2"}, ] [package.dependencies] -zipp = ">=3.20" +zipp = ">=0.5" [package.extras] -check = ["pytest-checkdocs (>=2.4)", "pytest-ruff (>=0.2.1) ; sys_platform != \"cygwin\""] -cover = ["pytest-cov"] -doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"] -enabler = ["pytest-enabler (>=2.2)"] +docs = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"] perf = ["ipython"] -test = ["flufl.flake8", "importlib-resources (>=1.3) ; python_version < \"3.9\"", "jaraco.test (>=5.4)", "packaging", "pyfakefs", "pytest (>=6,!=8.1.*)", "pytest-perf (>=0.9.2)"] -type = ["pytest-mypy"] +testing = ["flufl.flake8", "importlib-resources (>=1.3) ; python_version < \"3.9\"", "jaraco.test (>=5.4)", "packaging", "pyfakefs", "pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=2.2)", "pytest-mypy ; platform_python_implementation != \"PyPy\"", "pytest-perf (>=0.9.2)", "pytest-ruff (>=0.2.1)"] [[package]] name = "importlib-resources" @@ -2326,6 +2322,142 @@ datalib = ["numpy (>=1)", "pandas (>=1.2.3)", "pandas-stubs (>=1.1.0.11)"] realtime = ["websockets (>=13,<16)"] voice-helpers = ["numpy (>=2.0.2)", "sounddevice (>=0.5.1)"] +[[package]] +name = "opentelemetry-api" +version = "1.25.0" +description = "OpenTelemetry Python API" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_api-1.25.0-py3-none-any.whl", hash = "sha256:757fa1aa020a0f8fa139f8959e53dec2051cc26b832e76fa839a6d76ecefd737"}, + {file = "opentelemetry_api-1.25.0.tar.gz", hash = "sha256:77c4985f62f2614e42ce77ee4c9da5fa5f0bc1e1821085e9a47533a9323ae869"}, +] + +[package.dependencies] +deprecated = ">=1.2.6" +importlib-metadata = ">=6.0,<=7.1" + +[[package]] +name = "opentelemetry-exporter-otlp" +version = "1.25.0" +description = "OpenTelemetry Collector Exporters" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_exporter_otlp-1.25.0-py3-none-any.whl", hash = "sha256:d67a831757014a3bc3174e4cd629ae1493b7ba8d189e8a007003cacb9f1a6b60"}, + {file = "opentelemetry_exporter_otlp-1.25.0.tar.gz", hash = "sha256:ce03199c1680a845f82e12c0a6a8f61036048c07ec7a0bd943142aca8fa6ced0"}, +] + +[package.dependencies] +opentelemetry-exporter-otlp-proto-grpc = "1.25.0" +opentelemetry-exporter-otlp-proto-http = "1.25.0" + +[[package]] +name = "opentelemetry-exporter-otlp-proto-common" +version = "1.25.0" +description = "OpenTelemetry Protobuf encoding" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_exporter_otlp_proto_common-1.25.0-py3-none-any.whl", hash = "sha256:15637b7d580c2675f70246563363775b4e6de947871e01d0f4e3881d1848d693"}, + {file = "opentelemetry_exporter_otlp_proto_common-1.25.0.tar.gz", hash = "sha256:c93f4e30da4eee02bacd1e004eb82ce4da143a2f8e15b987a9f603e0a85407d3"}, +] + +[package.dependencies] +opentelemetry-proto = "1.25.0" + +[[package]] +name = "opentelemetry-exporter-otlp-proto-grpc" +version = "1.25.0" +description = "OpenTelemetry Collector Protobuf over gRPC Exporter" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_exporter_otlp_proto_grpc-1.25.0-py3-none-any.whl", hash = "sha256:3131028f0c0a155a64c430ca600fd658e8e37043cb13209f0109db5c1a3e4eb4"}, + {file = "opentelemetry_exporter_otlp_proto_grpc-1.25.0.tar.gz", hash = "sha256:c0b1661415acec5af87625587efa1ccab68b873745ca0ee96b69bb1042087eac"}, +] + +[package.dependencies] +deprecated = ">=1.2.6" +googleapis-common-protos = ">=1.52,<2.0" +grpcio = ">=1.0.0,<2.0.0" +opentelemetry-api = ">=1.15,<2.0" +opentelemetry-exporter-otlp-proto-common = "1.25.0" +opentelemetry-proto = "1.25.0" +opentelemetry-sdk = ">=1.25.0,<1.26.0" + +[[package]] +name = "opentelemetry-exporter-otlp-proto-http" +version = "1.25.0" +description = "OpenTelemetry Collector Protobuf over HTTP Exporter" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_exporter_otlp_proto_http-1.25.0-py3-none-any.whl", hash = "sha256:2eca686ee11b27acd28198b3ea5e5863a53d1266b91cda47c839d95d5e0541a6"}, + {file = "opentelemetry_exporter_otlp_proto_http-1.25.0.tar.gz", hash = "sha256:9f8723859e37c75183ea7afa73a3542f01d0fd274a5b97487ea24cb683d7d684"}, +] + +[package.dependencies] +deprecated = ">=1.2.6" +googleapis-common-protos = ">=1.52,<2.0" +opentelemetry-api = ">=1.15,<2.0" +opentelemetry-exporter-otlp-proto-common = "1.25.0" +opentelemetry-proto = "1.25.0" +opentelemetry-sdk = ">=1.25.0,<1.26.0" +requests = ">=2.7,<3.0" + +[[package]] +name = "opentelemetry-proto" +version = "1.25.0" +description = "OpenTelemetry Python Proto" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_proto-1.25.0-py3-none-any.whl", hash = "sha256:f07e3341c78d835d9b86665903b199893befa5e98866f63d22b00d0b7ca4972f"}, + {file = "opentelemetry_proto-1.25.0.tar.gz", hash = "sha256:35b6ef9dc4a9f7853ecc5006738ad40443701e52c26099e197895cbda8b815a3"}, +] + +[package.dependencies] +protobuf = ">=3.19,<5.0" + +[[package]] +name = "opentelemetry-sdk" +version = "1.25.0" +description = "OpenTelemetry Python SDK" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_sdk-1.25.0-py3-none-any.whl", hash = "sha256:d97ff7ec4b351692e9d5a15af570c693b8715ad78b8aafbec5c7100fe966b4c9"}, + {file = "opentelemetry_sdk-1.25.0.tar.gz", hash = "sha256:ce7fc319c57707ef5bf8b74fb9f8ebdb8bfafbe11898410e0d2a761d08a98ec7"}, +] + +[package.dependencies] +opentelemetry-api = "1.25.0" +opentelemetry-semantic-conventions = "0.46b0" +typing-extensions = ">=3.7.4" + +[[package]] +name = "opentelemetry-semantic-conventions" +version = "0.46b0" +description = "OpenTelemetry Semantic Conventions" +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "opentelemetry_semantic_conventions-0.46b0-py3-none-any.whl", hash = "sha256:6daef4ef9fa51d51855d9f8e0ccd3a1bd59e0e545abe99ac6203804e36ab3e07"}, + {file = "opentelemetry_semantic_conventions-0.46b0.tar.gz", hash = "sha256:fbc982ecbb6a6e90869b15c1673be90bd18c8a56ff1cffc0864e38e2edffaefa"}, +] + +[package.dependencies] +opentelemetry-api = "1.25.0" + [[package]] name = "orjson" version = "3.10.15" @@ -2668,25 +2800,25 @@ testing = ["google-api-core (>=1.31.5)"] [[package]] name = "protobuf" -version = "5.29.4" +version = "4.25.6" description = "" -optional = true +optional = false python-versions = ">=3.8" -groups = ["main"] -markers = "extra == \"extra-proxy\"" +groups = ["main", "dev", "proxy-dev"] files = [ - {file = "protobuf-5.29.4-cp310-abi3-win32.whl", hash = "sha256:13eb236f8eb9ec34e63fc8b1d6efd2777d062fa6aaa68268fb67cf77f6839ad7"}, - {file = "protobuf-5.29.4-cp310-abi3-win_amd64.whl", hash = "sha256:bcefcdf3976233f8a502d265eb65ea740c989bacc6c30a58290ed0e519eb4b8d"}, - {file = "protobuf-5.29.4-cp38-abi3-macosx_10_9_universal2.whl", hash = "sha256:307ecba1d852ec237e9ba668e087326a67564ef83e45a0189a772ede9e854dd0"}, - {file = "protobuf-5.29.4-cp38-abi3-manylinux2014_aarch64.whl", hash = "sha256:aec4962f9ea93c431d5714ed1be1c93f13e1a8618e70035ba2b0564d9e633f2e"}, - {file = "protobuf-5.29.4-cp38-abi3-manylinux2014_x86_64.whl", hash = "sha256:d7d3f7d1d5a66ed4942d4fefb12ac4b14a29028b209d4bfb25c68ae172059922"}, - {file = "protobuf-5.29.4-cp38-cp38-win32.whl", hash = "sha256:1832f0515b62d12d8e6ffc078d7e9eb06969aa6dc13c13e1036e39d73bebc2de"}, - {file = "protobuf-5.29.4-cp38-cp38-win_amd64.whl", hash = "sha256:476cb7b14914c780605a8cf62e38c2a85f8caff2e28a6a0bad827ec7d6c85d68"}, - {file = "protobuf-5.29.4-cp39-cp39-win32.whl", hash = "sha256:fd32223020cb25a2cc100366f1dedc904e2d71d9322403224cdde5fdced0dabe"}, - {file = "protobuf-5.29.4-cp39-cp39-win_amd64.whl", hash = "sha256:678974e1e3a9b975b8bc2447fca458db5f93a2fb6b0c8db46b6675b5b5346812"}, - {file = "protobuf-5.29.4-py3-none-any.whl", hash = "sha256:3fde11b505e1597f71b875ef2fc52062b6a9740e5f7c8997ce878b6009145862"}, - {file = "protobuf-5.29.4.tar.gz", hash = "sha256:4f1dfcd7997b31ef8f53ec82781ff434a28bf71d9102ddde14d076adcfc78c99"}, + {file = "protobuf-4.25.6-cp310-abi3-win32.whl", hash = "sha256:61df6b5786e2b49fc0055f636c1e8f0aff263808bb724b95b164685ac1bcc13a"}, + {file = "protobuf-4.25.6-cp310-abi3-win_amd64.whl", hash = "sha256:b8f837bfb77513fe0e2f263250f423217a173b6d85135be4d81e96a4653bcd3c"}, + {file = "protobuf-4.25.6-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:6d4381f2417606d7e01750e2729fe6fbcda3f9883aa0c32b51d23012bded6c91"}, + {file = "protobuf-4.25.6-cp37-abi3-manylinux2014_aarch64.whl", hash = "sha256:5dd800da412ba7f6f26d2c08868a5023ce624e1fdb28bccca2dc957191e81fb5"}, + {file = "protobuf-4.25.6-cp37-abi3-manylinux2014_x86_64.whl", hash = "sha256:4434ff8bb5576f9e0c78f47c41cdf3a152c0b44de475784cd3fd170aef16205a"}, + {file = "protobuf-4.25.6-cp38-cp38-win32.whl", hash = "sha256:8bad0f9e8f83c1fbfcc34e573352b17dfce7d0519512df8519994168dc015d7d"}, + {file = "protobuf-4.25.6-cp38-cp38-win_amd64.whl", hash = "sha256:b6905b68cde3b8243a198268bb46fbec42b3455c88b6b02fb2529d2c306d18fc"}, + {file = "protobuf-4.25.6-cp39-cp39-win32.whl", hash = "sha256:3f3b0b39db04b509859361ac9bca65a265fe9342e6b9406eda58029f5b1d10b2"}, + {file = "protobuf-4.25.6-cp39-cp39-win_amd64.whl", hash = "sha256:6ef2045f89d4ad8d95fd43cd84621487832a61d15b49500e4c1350e8a0ef96be"}, + {file = "protobuf-4.25.6-py3-none-any.whl", hash = "sha256:07972021c8e30b870cfc0863409d033af940213e0e7f64e27fe017b929d2c9f7"}, + {file = "protobuf-4.25.6.tar.gz", hash = "sha256:f8cfbae7c5afd0d0eaccbe73267339bff605a2315860bb1ba08eb66670a9a91f"}, ] +markers = {main = "extra == \"extra-proxy\""} [[package]] name = "pyasn1" @@ -3342,7 +3474,7 @@ version = "2.31.0" description = "Python HTTP for Humans." optional = false python-versions = ">=3.7" -groups = ["main"] +groups = ["main", "dev", "proxy-dev"] files = [ {file = "requests-2.31.0-py3-none-any.whl", hash = "sha256:58cd2187c01e70e6e26505bca751777aa9f2ee0b7f4300988b709f44e013003f"}, {file = "requests-2.31.0.tar.gz", hash = "sha256:942c5a758f98d790eaed1a29cb6eefc7ffb0d1cf7af05c3d2791656dbd6ad1e1"}, @@ -4027,7 +4159,7 @@ version = "1.26.20" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,>=2.7" -groups = ["main"] +groups = ["main", "dev", "proxy-dev"] markers = "python_version < \"3.10\"" files = [ {file = "urllib3-1.26.20-py2.py3-none-any.whl", hash = "sha256:0ed14ccfbf1c30a9072c7ca157e4319b70d65f623e91e7b32fadb2853431016e"}, @@ -4045,7 +4177,7 @@ version = "2.2.3" description = "HTTP library with thread-safe connection pooling, file post, and more." optional = false python-versions = ">=3.8" -groups = ["main", "dev"] +groups = ["main", "dev", "proxy-dev"] markers = "python_version >= \"3.10\"" files = [ {file = "urllib3-2.2.3-py3-none-any.whl", hash = "sha256:ca899ca043dcb1bafa3e262d73aa25c465bfb49e0bd9dd5d59f1d0acba2f8fac"}, @@ -4229,6 +4361,95 @@ files = [ {file = "websockets-13.1.tar.gz", hash = "sha256:a3b3366087c1bc0a2795111edcadddb8b3b59509d5db5d7ea3fdd69f954a8878"}, ] +[[package]] +name = "wrapt" +version = "1.17.2" +description = "Module for decorators, wrappers and monkey patching." +optional = false +python-versions = ">=3.8" +groups = ["dev", "proxy-dev"] +files = [ + {file = "wrapt-1.17.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:3d57c572081fed831ad2d26fd430d565b76aa277ed1d30ff4d40670b1c0dd984"}, + {file = "wrapt-1.17.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:b5e251054542ae57ac7f3fba5d10bfff615b6c2fb09abeb37d2f1463f841ae22"}, + {file = "wrapt-1.17.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:80dd7db6a7cb57ffbc279c4394246414ec99537ae81ffd702443335a61dbf3a7"}, + {file = "wrapt-1.17.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0a6e821770cf99cc586d33833b2ff32faebdbe886bd6322395606cf55153246c"}, + {file = "wrapt-1.17.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b60fb58b90c6d63779cb0c0c54eeb38941bae3ecf7a73c764c52c88c2dcb9d72"}, + {file = "wrapt-1.17.2-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b870b5df5b71d8c3359d21be8f0d6c485fa0ebdb6477dda51a1ea54a9b558061"}, + {file = "wrapt-1.17.2-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:4011d137b9955791f9084749cba9a367c68d50ab8d11d64c50ba1688c9b457f2"}, + {file = "wrapt-1.17.2-cp310-cp310-musllinux_1_2_i686.whl", hash = "sha256:1473400e5b2733e58b396a04eb7f35f541e1fb976d0c0724d0223dd607e0f74c"}, + {file = "wrapt-1.17.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:3cedbfa9c940fdad3e6e941db7138e26ce8aad38ab5fe9dcfadfed9db7a54e62"}, + {file = "wrapt-1.17.2-cp310-cp310-win32.whl", hash = "sha256:582530701bff1dec6779efa00c516496968edd851fba224fbd86e46cc6b73563"}, + {file = "wrapt-1.17.2-cp310-cp310-win_amd64.whl", hash = "sha256:58705da316756681ad3c9c73fd15499aa4d8c69f9fd38dc8a35e06c12468582f"}, + {file = "wrapt-1.17.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:ff04ef6eec3eee8a5efef2401495967a916feaa353643defcc03fc74fe213b58"}, + {file = "wrapt-1.17.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4db983e7bca53819efdbd64590ee96c9213894272c776966ca6306b73e4affda"}, + {file = "wrapt-1.17.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:9abc77a4ce4c6f2a3168ff34b1da9b0f311a8f1cfd694ec96b0603dff1c79438"}, + {file = "wrapt-1.17.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0b929ac182f5ace000d459c59c2c9c33047e20e935f8e39371fa6e3b85d56f4a"}, + {file = "wrapt-1.17.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f09b286faeff3c750a879d336fb6d8713206fc97af3adc14def0cdd349df6000"}, + {file = "wrapt-1.17.2-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1a7ed2d9d039bd41e889f6fb9364554052ca21ce823580f6a07c4ec245c1f5d6"}, + {file = "wrapt-1.17.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:129a150f5c445165ff941fc02ee27df65940fcb8a22a61828b1853c98763a64b"}, + {file = "wrapt-1.17.2-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:1fb5699e4464afe5c7e65fa51d4f99e0b2eadcc176e4aa33600a3df7801d6662"}, + {file = "wrapt-1.17.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9a2bce789a5ea90e51a02dfcc39e31b7f1e662bc3317979aa7e5538e3a034f72"}, + {file = "wrapt-1.17.2-cp311-cp311-win32.whl", hash = "sha256:4afd5814270fdf6380616b321fd31435a462019d834f83c8611a0ce7484c7317"}, + {file = "wrapt-1.17.2-cp311-cp311-win_amd64.whl", hash = "sha256:acc130bc0375999da18e3d19e5a86403667ac0c4042a094fefb7eec8ebac7cf3"}, + {file = "wrapt-1.17.2-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d5e2439eecc762cd85e7bd37161d4714aa03a33c5ba884e26c81559817ca0925"}, + {file = "wrapt-1.17.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:3fc7cb4c1c744f8c05cd5f9438a3caa6ab94ce8344e952d7c45a8ed59dd88392"}, + {file = "wrapt-1.17.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:8fdbdb757d5390f7c675e558fd3186d590973244fab0c5fe63d373ade3e99d40"}, + {file = "wrapt-1.17.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5bb1d0dbf99411f3d871deb6faa9aabb9d4e744d67dcaaa05399af89d847a91d"}, + {file = "wrapt-1.17.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:d18a4865f46b8579d44e4fe1e2bcbc6472ad83d98e22a26c963d46e4c125ef0b"}, + {file = "wrapt-1.17.2-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc570b5f14a79734437cb7b0500376b6b791153314986074486e0b0fa8d71d98"}, + {file = "wrapt-1.17.2-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:6d9187b01bebc3875bac9b087948a2bccefe464a7d8f627cf6e48b1bbae30f82"}, + {file = "wrapt-1.17.2-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:9e8659775f1adf02eb1e6f109751268e493c73716ca5761f8acb695e52a756ae"}, + {file = "wrapt-1.17.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e8b2816ebef96d83657b56306152a93909a83f23994f4b30ad4573b00bd11bb9"}, + {file = "wrapt-1.17.2-cp312-cp312-win32.whl", hash = "sha256:468090021f391fe0056ad3e807e3d9034e0fd01adcd3bdfba977b6fdf4213ea9"}, + {file = "wrapt-1.17.2-cp312-cp312-win_amd64.whl", hash = "sha256:ec89ed91f2fa8e3f52ae53cd3cf640d6feff92ba90d62236a81e4e563ac0e991"}, + {file = "wrapt-1.17.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6ed6ffac43aecfe6d86ec5b74b06a5be33d5bb9243d055141e8cabb12aa08125"}, + {file = "wrapt-1.17.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:35621ae4c00e056adb0009f8e86e28eb4a41a4bfa8f9bfa9fca7d343fe94f998"}, + {file = "wrapt-1.17.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:a604bf7a053f8362d27eb9fefd2097f82600b856d5abe996d623babd067b1ab5"}, + {file = "wrapt-1.17.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5cbabee4f083b6b4cd282f5b817a867cf0b1028c54d445b7ec7cfe6505057cf8"}, + {file = "wrapt-1.17.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:49703ce2ddc220df165bd2962f8e03b84c89fee2d65e1c24a7defff6f988f4d6"}, + {file = "wrapt-1.17.2-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8112e52c5822fc4253f3901b676c55ddf288614dc7011634e2719718eaa187dc"}, + {file = "wrapt-1.17.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:9fee687dce376205d9a494e9c121e27183b2a3df18037f89d69bd7b35bcf59e2"}, + {file = "wrapt-1.17.2-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:18983c537e04d11cf027fbb60a1e8dfd5190e2b60cc27bc0808e653e7b218d1b"}, + {file = "wrapt-1.17.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:703919b1633412ab54bcf920ab388735832fdcb9f9a00ae49387f0fe67dad504"}, + {file = "wrapt-1.17.2-cp313-cp313-win32.whl", hash = "sha256:abbb9e76177c35d4e8568e58650aa6926040d6a9f6f03435b7a522bf1c487f9a"}, + {file = "wrapt-1.17.2-cp313-cp313-win_amd64.whl", hash = "sha256:69606d7bb691b50a4240ce6b22ebb319c1cfb164e5f6569835058196e0f3a845"}, + {file = "wrapt-1.17.2-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:4a721d3c943dae44f8e243b380cb645a709ba5bd35d3ad27bc2ed947e9c68192"}, + {file = "wrapt-1.17.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:766d8bbefcb9e00c3ac3b000d9acc51f1b399513f44d77dfe0eb026ad7c9a19b"}, + {file = "wrapt-1.17.2-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:e496a8ce2c256da1eb98bd15803a79bee00fc351f5dfb9ea82594a3f058309e0"}, + {file = "wrapt-1.17.2-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40d615e4fe22f4ad3528448c193b218e077656ca9ccb22ce2cb20db730f8d306"}, + {file = "wrapt-1.17.2-cp313-cp313t-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a5aaeff38654462bc4b09023918b7f21790efb807f54c000a39d41d69cf552cb"}, + {file = "wrapt-1.17.2-cp313-cp313t-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9a7d15bbd2bc99e92e39f49a04653062ee6085c0e18b3b7512a4f2fe91f2d681"}, + {file = "wrapt-1.17.2-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:e3890b508a23299083e065f435a492b5435eba6e304a7114d2f919d400888cc6"}, + {file = "wrapt-1.17.2-cp313-cp313t-musllinux_1_2_i686.whl", hash = "sha256:8c8b293cd65ad716d13d8dd3624e42e5a19cc2a2f1acc74b30c2c13f15cb61a6"}, + {file = "wrapt-1.17.2-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:4c82b8785d98cdd9fed4cac84d765d234ed3251bd6afe34cb7ac523cb93e8b4f"}, + {file = "wrapt-1.17.2-cp313-cp313t-win32.whl", hash = "sha256:13e6afb7fe71fe7485a4550a8844cc9ffbe263c0f1a1eea569bc7091d4898555"}, + {file = "wrapt-1.17.2-cp313-cp313t-win_amd64.whl", hash = "sha256:eaf675418ed6b3b31c7a989fd007fa7c3be66ce14e5c3b27336383604c9da85c"}, + {file = "wrapt-1.17.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:5c803c401ea1c1c18de70a06a6f79fcc9c5acfc79133e9869e730ad7f8ad8ef9"}, + {file = "wrapt-1.17.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:f917c1180fdb8623c2b75a99192f4025e412597c50b2ac870f156de8fb101119"}, + {file = "wrapt-1.17.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ecc840861360ba9d176d413a5489b9a0aff6d6303d7e733e2c4623cfa26904a6"}, + {file = "wrapt-1.17.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bb87745b2e6dc56361bfde481d5a378dc314b252a98d7dd19a651a3fa58f24a9"}, + {file = "wrapt-1.17.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:58455b79ec2661c3600e65c0a716955adc2410f7383755d537584b0de41b1d8a"}, + {file = "wrapt-1.17.2-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b4e42a40a5e164cbfdb7b386c966a588b1047558a990981ace551ed7e12ca9c2"}, + {file = "wrapt-1.17.2-cp38-cp38-musllinux_1_2_aarch64.whl", hash = "sha256:91bd7d1773e64019f9288b7a5101f3ae50d3d8e6b1de7edee9c2ccc1d32f0c0a"}, + {file = "wrapt-1.17.2-cp38-cp38-musllinux_1_2_i686.whl", hash = "sha256:bb90fb8bda722a1b9d48ac1e6c38f923ea757b3baf8ebd0c82e09c5c1a0e7a04"}, + {file = "wrapt-1.17.2-cp38-cp38-musllinux_1_2_x86_64.whl", hash = "sha256:08e7ce672e35efa54c5024936e559469436f8b8096253404faeb54d2a878416f"}, + {file = "wrapt-1.17.2-cp38-cp38-win32.whl", hash = "sha256:410a92fefd2e0e10d26210e1dfb4a876ddaf8439ef60d6434f21ef8d87efc5b7"}, + {file = "wrapt-1.17.2-cp38-cp38-win_amd64.whl", hash = "sha256:95c658736ec15602da0ed73f312d410117723914a5c91a14ee4cdd72f1d790b3"}, + {file = "wrapt-1.17.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99039fa9e6306880572915728d7f6c24a86ec57b0a83f6b2491e1d8ab0235b9a"}, + {file = "wrapt-1.17.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2696993ee1eebd20b8e4ee4356483c4cb696066ddc24bd70bcbb80fa56ff9061"}, + {file = "wrapt-1.17.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:612dff5db80beef9e649c6d803a8d50c409082f1fedc9dbcdfde2983b2025b82"}, + {file = "wrapt-1.17.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62c2caa1585c82b3f7a7ab56afef7b3602021d6da34fbc1cf234ff139fed3cd9"}, + {file = "wrapt-1.17.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c958bcfd59bacc2d0249dcfe575e71da54f9dcf4a8bdf89c4cb9a68a1170d73f"}, + {file = "wrapt-1.17.2-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fc78a84e2dfbc27afe4b2bd7c80c8db9bca75cc5b85df52bfe634596a1da846b"}, + {file = "wrapt-1.17.2-cp39-cp39-musllinux_1_2_aarch64.whl", hash = "sha256:ba0f0eb61ef00ea10e00eb53a9129501f52385c44853dbd6c4ad3f403603083f"}, + {file = "wrapt-1.17.2-cp39-cp39-musllinux_1_2_i686.whl", hash = "sha256:1e1fe0e6ab7775fd842bc39e86f6dcfc4507ab0ffe206093e76d61cde37225c8"}, + {file = "wrapt-1.17.2-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:c86563182421896d73858e08e1db93afdd2b947a70064b813d515d66549e15f9"}, + {file = "wrapt-1.17.2-cp39-cp39-win32.whl", hash = "sha256:f393cda562f79828f38a819f4788641ac7c4085f30f1ce1a68672baa686482bb"}, + {file = "wrapt-1.17.2-cp39-cp39-win_amd64.whl", hash = "sha256:36ccae62f64235cf8ddb682073a60519426fdd4725524ae38874adf72b5f2aeb"}, + {file = "wrapt-1.17.2-py3-none-any.whl", hash = "sha256:b18f2d1533a71f069c7f82d524a52599053d4c7166e9dd374ae2136b7f40f7c8"}, + {file = "wrapt-1.17.2.tar.gz", hash = "sha256:41388e9d4d1522446fe79d3213196bd9e3b301a336965b9e27ca2788ebd122f3"}, +] + [[package]] name = "wsproto" version = "1.2.0" @@ -4363,7 +4584,7 @@ version = "3.20.2" description = "Backport of pathlib-compatible object wrapper for zip files" optional = false python-versions = ">=3.8" -groups = ["main"] +groups = ["main", "dev", "proxy-dev"] files = [ {file = "zipp-3.20.2-py3-none-any.whl", hash = "sha256:a817ac80d6cf4b23bf7f2828b7cabf326f15a001bea8b1f9b49631780ba28350"}, {file = "zipp-3.20.2.tar.gz", hash = "sha256:bc9eb26f4506fda01b81bcde0ca78103b6e62f991b381fec825435c836edbc29"}, @@ -4384,4 +4605,4 @@ proxy = ["PyJWT", "apscheduler", "backoff", "boto3", "cryptography", "fastapi", [metadata] lock-version = "2.1" python-versions = ">=3.8.1,<4.0, !=3.9.7" -content-hash = "40074b2e47aae8ece058be9a42eda3ca0618e27e4fc9d6529793816df7adb6c8" +content-hash = "adefc5c35b625ab156ff674c880256643a22880012451d4ade7fa2ef11f5885d" diff --git a/pyproject.toml b/pyproject.toml index 17ac3744b8..7c5558f7f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -107,11 +107,17 @@ types-requests = "*" types-setuptools = "*" types-redis = "*" types-PyYAML = "*" +opentelemetry-api = "1.25.0" +opentelemetry-sdk = "1.25.0" +opentelemetry-exporter-otlp = "1.25.0" [tool.poetry.group.proxy-dev.dependencies] prisma = "0.11.0" hypercorn = "^0.15.0" prometheus-client = "0.20.0" +opentelemetry-api = "1.25.0" +opentelemetry-sdk = "1.25.0" +opentelemetry-exporter-otlp = "1.25.0" [build-system] requires = ["poetry-core", "wheel"] diff --git a/tests/litellm/integrations/test_agentops.py b/tests/litellm/integrations/test_agentops.py new file mode 100644 index 0000000000..3302736177 --- /dev/null +++ b/tests/litellm/integrations/test_agentops.py @@ -0,0 +1,98 @@ +import os +import sys +import pytest +from unittest.mock import patch, MagicMock + +sys.path.insert(0, os.path.abspath("../..")) # Adds the parent directory to the system-path + +from litellm.integrations.agentops.agentops import AgentOps, AgentOpsConfig + +@pytest.fixture +def mock_auth_response(): + return { + "token": "test_jwt_token", + "project_id": "test_project_id" + } + +@pytest.fixture +def agentops_config(): + return AgentOpsConfig( + endpoint="https://otlp.agentops.cloud/v1/traces", + api_key="test_api_key", + service_name="test_service", + deployment_environment="test_env", + auth_endpoint="https://api.agentops.ai/v3/auth/token" + ) + +def test_agentops_config_from_env(): + """Test that AgentOpsConfig correctly reads from environment variables""" + with patch.dict(os.environ, { + "AGENTOPS_API_KEY": "test_key", + "AGENTOPS_SERVICE_NAME": "test_service", + "AGENTOPS_ENVIRONMENT": "test_env" + }): + config = AgentOpsConfig.from_env() + assert config.api_key == "test_key" + assert config.service_name == "test_service" + assert config.deployment_environment == "test_env" + assert config.endpoint == "https://otlp.agentops.cloud/v1/traces" + assert config.auth_endpoint == "https://api.agentops.ai/v3/auth/token" + +def test_agentops_config_defaults(): + """Test that AgentOpsConfig uses correct default values""" + config = AgentOpsConfig() + assert config.service_name is None + assert config.deployment_environment is None + assert config.api_key is None + assert config.endpoint == "https://otlp.agentops.cloud/v1/traces" + assert config.auth_endpoint == "https://api.agentops.ai/v3/auth/token" + +@patch('litellm.integrations.agentops.agentops.AgentOps._fetch_auth_token') +def test_fetch_auth_token_success(mock_fetch_auth_token, mock_auth_response): + """Test successful JWT token fetch""" + mock_fetch_auth_token.return_value = mock_auth_response + + config = AgentOpsConfig(api_key="test_key") + agentops = AgentOps(config=config) + + mock_fetch_auth_token.assert_called_once_with("test_key", "https://api.agentops.ai/v3/auth/token") + assert agentops.resource_attributes.get("project.id") == mock_auth_response.get("project_id") + +@patch('litellm.integrations.agentops.agentops.AgentOps._fetch_auth_token') +def test_fetch_auth_token_failure(mock_fetch_auth_token): + """Test failed JWT token fetch""" + mock_fetch_auth_token.side_effect = Exception("Failed to fetch auth token: Unauthorized") + + config = AgentOpsConfig(api_key="test_key") + agentops = AgentOps(config=config) + + mock_fetch_auth_token.assert_called_once() + assert "project.id" not in agentops.resource_attributes + +@patch('litellm.integrations.agentops.agentops.AgentOps._fetch_auth_token') +def test_agentops_initialization(mock_fetch_auth_token, agentops_config, mock_auth_response): + """Test AgentOps initialization with config""" + mock_fetch_auth_token.return_value = mock_auth_response + + agentops = AgentOps(config=agentops_config) + + assert agentops.resource_attributes["service.name"] == "test_service" + assert agentops.resource_attributes["deployment.environment"] == "test_env" + assert agentops.resource_attributes["telemetry.sdk.name"] == "agentops" + assert agentops.resource_attributes["project.id"] == "test_project_id" + +def test_agentops_initialization_no_auth(): + """Test AgentOps initialization without authentication""" + test_config = AgentOpsConfig( + endpoint="https://otlp.agentops.cloud/v1/traces", + api_key=None, # No API key + service_name="test_service", + deployment_environment="test_env" + ) + + agentops = AgentOps(config=test_config) + + assert agentops.resource_attributes["service.name"] == "test_service" + assert agentops.resource_attributes["deployment.environment"] == "test_env" + assert agentops.resource_attributes["telemetry.sdk.name"] == "agentops" + assert "project.id" not in agentops.resource_attributes \ No newline at end of file From 66680c421d087a569fea8dbc0d46ceae2044cdaf Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Tue, 22 Apr 2025 13:59:43 -0700 Subject: [PATCH 03/40] Add global filtering to Users tab (#10195) * style(internal_user_endpoints.py): add response model to `/user/list` endpoint make sure we maintain consistent response spec * fix(key_management_endpoints.py): return 'created_at' and 'updated_at' on `/key/generate` Show 'created_at' on UI when key created * test(test_keys.py): add e2e test to ensure created at is always returned * fix(view_users.tsx): support global search by user email allows easier search * test(search_users.spec.ts): add e2e test ensure user search works on admin ui * fix(view_users.tsx): support filtering user by role and user id More powerful filtering on internal users table * fix(view_users.tsx): allow filtering users by team * style(view_users.tsx): cleanup ui to show filters in consistent style * refactor(view_users.tsx): cleanup to just use 1 variable for the data * fix(view_users.tsx): cleanup use effect hooks * fix(internal_user_endpoints.py): fix check to pass testing * test: update tests * test: update tests * Revert "test: update tests" This reverts commit 6553eeb2325f77e302ff67d6c1fc736e67f854bb. * fix(view_userts.tsx): add back in 'previous' and 'next' tabs for pagination --- .../proxy/_experimental/out/onboarding.html | 1 - litellm/proxy/_types.py | 2 + .../internal_user_endpoints.py | 62 ++-- .../key_management_endpoints.py | 3 + .../internal_user_endpoints.py | 18 + test-results/.last-run.json | 4 + .../e2e_ui_tests/search_users.spec.ts | 119 +++++++ .../e2e_ui_tests/view_internal_user.spec.ts | 73 ++-- .../test-results/.last-run.json | 8 + tests/test_keys.py | 12 + .../src/components/networking.tsx | 15 + .../src/components/view_users.tsx | 327 ++++++++++++++++-- 12 files changed, 556 insertions(+), 88 deletions(-) delete mode 100644 litellm/proxy/_experimental/out/onboarding.html create mode 100644 litellm/types/proxy/management_endpoints/internal_user_endpoints.py create mode 100644 test-results/.last-run.json create mode 100644 tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts create mode 100644 tests/proxy_admin_ui_tests/test-results/.last-run.json diff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.html deleted file mode 100644 index bf33fa19ec..0000000000 --- a/litellm/proxy/_experimental/out/onboarding.html +++ /dev/null @@ -1 +0,0 @@ -LiteLLM Dashboard \ No newline at end of file diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py index 150528fd8f..354f6bb54c 100644 --- a/litellm/proxy/_types.py +++ b/litellm/proxy/_types.py @@ -687,6 +687,8 @@ class GenerateKeyResponse(KeyRequestBase): token: Optional[str] = None created_by: Optional[str] = None updated_by: Optional[str] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None @model_validator(mode="before") @classmethod diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py index 42a5dd7e81..0d6c9ee622 100644 --- a/litellm/proxy/management_endpoints/internal_user_endpoints.py +++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py @@ -43,6 +43,9 @@ from litellm.types.proxy.management_endpoints.common_daily_activity import ( SpendAnalyticsPaginatedResponse, SpendMetrics, ) +from litellm.types.proxy.management_endpoints.internal_user_endpoints import ( + UserListResponse, +) router = APIRouter() @@ -899,15 +902,11 @@ async def get_user_key_counts( return result -@router.get( - "/user/get_users", - tags=["Internal User management"], - dependencies=[Depends(user_api_key_auth)], -) @router.get( "/user/list", tags=["Internal User management"], dependencies=[Depends(user_api_key_auth)], + response_model=UserListResponse, ) async def get_users( role: Optional[str] = fastapi.Query( @@ -916,15 +915,19 @@ async def get_users( user_ids: Optional[str] = fastapi.Query( default=None, description="Get list of users by user_ids" ), + user_email: Optional[str] = fastapi.Query( + default=None, description="Filter users by partial email match" + ), + team: Optional[str] = fastapi.Query( + default=None, description="Filter users by team id" + ), page: int = fastapi.Query(default=1, ge=1, description="Page number"), page_size: int = fastapi.Query( default=25, ge=1, le=100, description="Number of items per page" ), ): """ - Get a paginated list of users, optionally filtered by role. - - Used by the UI to populate the user lists. + Get a paginated list of users with filtering options. Parameters: role: Optional[str] @@ -935,17 +938,17 @@ async def get_users( - internal_user_viewer user_ids: Optional[str] Get list of users by user_ids. Comma separated list of user_ids. + user_email: Optional[str] + Filter users by partial email match + team: Optional[str] + Filter users by team id. Will match if user has this team in their teams array. page: int The page number to return page_size: int The number of items per page - Currently - admin-only endpoint. - - Example curl: - ``` - http://0.0.0.0:4000/user/list?user_ids=default_user_id,693c1a4a-1cc0-4c7c-afe8-b5d2c8d52e17 - ``` + Returns: + UserListResponse with filtered and paginated users """ from litellm.proxy.proxy_server import prisma_client @@ -958,25 +961,32 @@ async def get_users( # Calculate skip and take for pagination skip = (page - 1) * page_size - # Prepare the query conditions # Build where conditions based on provided parameters where_conditions: Dict[str, Any] = {} if role: - where_conditions["user_role"] = { - "contains": role, - "mode": "insensitive", # Case-insensitive search - } + where_conditions["user_role"] = role # Exact match instead of contains if user_ids and isinstance(user_ids, str): user_id_list = [uid.strip() for uid in user_ids.split(",") if uid.strip()] where_conditions["user_id"] = { - "in": user_id_list, # Now passing a list of strings as required by Prisma + "in": user_id_list, } - users: Optional[ - List[LiteLLM_UserTable] - ] = await prisma_client.db.litellm_usertable.find_many( + if user_email is not None and isinstance(user_email, str): + where_conditions["user_email"] = { + "contains": user_email, + "mode": "insensitive", # Case-insensitive search + } + + if team is not None and isinstance(team, str): + where_conditions["teams"] = { + "has": team # Array contains for string arrays in Prisma + } + + ## Filter any none fastapi.Query params - e.g. where_conditions: {'user_email': {'contains': Query(None), 'mode': 'insensitive'}, 'teams': {'has': Query(None)}} + where_conditions = {k: v for k, v in where_conditions.items() if v is not None} + users = await prisma_client.db.litellm_usertable.find_many( where=where_conditions, skip=skip, take=page_size, @@ -984,9 +994,7 @@ async def get_users( ) # Get total count of user rows - total_count = await prisma_client.db.litellm_usertable.count( - where=where_conditions # type: ignore - ) + total_count = await prisma_client.db.litellm_usertable.count(where=where_conditions) # Get key count for each user if users is not None: @@ -1009,7 +1017,7 @@ async def get_users( LiteLLM_UserTableWithKeyCount( **user.model_dump(), key_count=user_key_counts.get(user.user_id, 0) ) - ) # Return full key object + ) else: user_list = [] diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 8fd3b555d4..15edab8909 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -1347,10 +1347,13 @@ async def generate_key_helper_fn( # noqa: PLR0915 create_key_response = await prisma_client.insert_data( data=key_data, table_name="key" ) + key_data["token_id"] = getattr(create_key_response, "token", None) key_data["litellm_budget_table"] = getattr( create_key_response, "litellm_budget_table", None ) + key_data["created_at"] = getattr(create_key_response, "created_at", None) + key_data["updated_at"] = getattr(create_key_response, "updated_at", None) except Exception as e: verbose_proxy_logger.error( "litellm.proxy.proxy_server.generate_key_helper_fn(): Exception occured - {}".format( diff --git a/litellm/types/proxy/management_endpoints/internal_user_endpoints.py b/litellm/types/proxy/management_endpoints/internal_user_endpoints.py new file mode 100644 index 0000000000..5c2c5bf371 --- /dev/null +++ b/litellm/types/proxy/management_endpoints/internal_user_endpoints.py @@ -0,0 +1,18 @@ +from typing import Any, Dict, List, Literal, Optional, Union + +from fastapi import HTTPException +from pydantic import BaseModel, EmailStr + +from litellm.proxy._types import LiteLLM_UserTableWithKeyCount + + +class UserListResponse(BaseModel): + """ + Response model for the user list endpoint + """ + + users: List[LiteLLM_UserTableWithKeyCount] + total: int + page: int + page_size: int + total_pages: int diff --git a/test-results/.last-run.json b/test-results/.last-run.json new file mode 100644 index 0000000000..5fca3f84bc --- /dev/null +++ b/test-results/.last-run.json @@ -0,0 +1,4 @@ +{ + "status": "failed", + "failedTests": [] +} \ No newline at end of file diff --git a/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts b/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts new file mode 100644 index 0000000000..ef5dfa6c0c --- /dev/null +++ b/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts @@ -0,0 +1,119 @@ +/* +Search Users in Admin UI +E2E Test for user search functionality + +Tests: +1. Navigate to Internal Users tab +2. Verify search input exists +3. Test search functionality +4. Verify results update +*/ + +import { test, expect } from "@playwright/test"; + +test("user search test", async ({ page }) => { + // Set a longer timeout for the entire test + test.setTimeout(60000); + + // Enable console logging + page.on("console", (msg) => console.log("PAGE LOG:", msg.text())); + + // Login first + await page.goto("http://localhost:4000/ui"); + console.log("Navigated to login page"); + + // Wait for login form to be visible + await page.waitForSelector('input[name="username"]', { timeout: 10000 }); + console.log("Login form is visible"); + + await page.fill('input[name="username"]', "admin"); + await page.fill('input[name="password"]', "gm"); + console.log("Filled login credentials"); + + const loginButton = page.locator('input[type="submit"]'); + await expect(loginButton).toBeEnabled(); + await loginButton.click(); + console.log("Clicked login button"); + + // Wait for navigation to complete and dashboard to load + await page.waitForLoadState("networkidle"); + console.log("Page loaded after login"); + + // Take a screenshot for debugging + await page.screenshot({ path: "after-login.png" }); + console.log("Took screenshot after login"); + + // Try to find the Internal User tab with more debugging + console.log("Looking for Internal User tab..."); + const internalUserTab = page.locator("span.ant-menu-title-content", { + hasText: "Internal User", + }); + + // Wait for the tab to be visible + await internalUserTab.waitFor({ state: "visible", timeout: 10000 }); + console.log("Internal User tab is visible"); + + // Take another screenshot before clicking + await page.screenshot({ path: "before-tab-click.png" }); + console.log("Took screenshot before tab click"); + + await internalUserTab.click(); + console.log("Clicked Internal User tab"); + + // Wait for the page to load and table to be visible + await page.waitForSelector("tbody tr", { timeout: 10000 }); + await page.waitForTimeout(2000); // Additional wait for table to stabilize + console.log("Table is visible"); + + // Take a final screenshot + await page.screenshot({ path: "after-tab-click.png" }); + console.log("Took screenshot after tab click"); + + // Verify search input exists + const searchInput = page.locator('input[placeholder="Search by email..."]'); + await expect(searchInput).toBeVisible(); + console.log("Search input is visible"); + + // Test search functionality + const initialUserCount = await page.locator("tbody tr").count(); + console.log(`Initial user count: ${initialUserCount}`); + + // Perform a search + const testEmail = "test@"; + await searchInput.fill(testEmail); + console.log("Filled search input"); + + // Wait for the debounced search to complete + await page.waitForTimeout(500); + console.log("Waited for debounce"); + + // Wait for the results count to update + await page.waitForFunction((initialCount) => { + const currentCount = document.querySelectorAll("tbody tr").length; + return currentCount !== initialCount; + }, initialUserCount); + console.log("Results updated"); + + const filteredUserCount = await page.locator("tbody tr").count(); + console.log(`Filtered user count: ${filteredUserCount}`); + + expect(filteredUserCount).toBeDefined(); + + // Clear the search + await searchInput.clear(); + console.log("Cleared search"); + + await page.waitForTimeout(500); + console.log("Waited for debounce after clear"); + + await page.waitForFunction((initialCount) => { + const currentCount = document.querySelectorAll("tbody tr").length; + return currentCount === initialCount; + }, initialUserCount); + console.log("Results reset"); + + const resetUserCount = await page.locator("tbody tr").count(); + console.log(`Reset user count: ${resetUserCount}`); + + expect(resetUserCount).toBe(initialUserCount); +}); diff --git a/tests/proxy_admin_ui_tests/e2e_ui_tests/view_internal_user.spec.ts b/tests/proxy_admin_ui_tests/e2e_ui_tests/view_internal_user.spec.ts index 4d27a4a7ce..bb6df91c39 100644 --- a/tests/proxy_admin_ui_tests/e2e_ui_tests/view_internal_user.spec.ts +++ b/tests/proxy_admin_ui_tests/e2e_ui_tests/view_internal_user.spec.ts @@ -2,45 +2,74 @@ Test view internal user page */ -import { test, expect } from '@playwright/test'; +import { test, expect } from "@playwright/test"; -test('view internal user page', async ({ page }) => { +test("view internal user page", async ({ page }) => { // Go to the specified URL - await page.goto('http://localhost:4000/ui'); + await page.goto("http://localhost:4000/ui"); // Enter "admin" in the username input field - await page.fill('input[name="username"]', 'admin'); + await page.fill('input[name="username"]', "admin"); // Enter "gm" in the password input field - await page.fill('input[name="password"]', 'gm'); + await page.fill('input[name="password"]', "gm"); - // Optionally, you can add an assertion to verify the login button is enabled + // Click the login button const loginButton = page.locator('input[type="submit"]'); await expect(loginButton).toBeEnabled(); - - // Optionally, you can click the login button to submit the form await loginButton.click(); - const tabElement = page.locator('span.ant-menu-title-content', { hasText: 'Internal User' }); + // Wait for the Internal User tab and click it + const tabElement = page.locator("span.ant-menu-title-content", { + hasText: "Internal User", + }); await tabElement.click(); - // try to click on button - // - // wait 1-2 seconds - await page.waitForTimeout(10000); + // Wait for the table to load + await page.waitForSelector("tbody tr", { timeout: 10000 }); + await page.waitForTimeout(2000); // Additional wait for table to stabilize - // Test all expected fields are present - // number of keys owned by user - const keysBadges = page.locator('p.tremor-Badge-text.text-sm.whitespace-nowrap', { hasText: 'Keys' }); - const keysCountArray = await keysBadges.evaluateAll(elements => elements.map(el => parseInt(el.textContent.split(' ')[0], 10))); + // Test all expected fields are present + // number of keys owned by user + const keysBadges = page.locator( + "p.tremor-Badge-text.text-sm.whitespace-nowrap", + { hasText: "Keys" } + ); + const keysCountArray = await keysBadges.evaluateAll((elements) => + elements.map((el) => { + const text = el.textContent; + return text ? parseInt(text.split(" ")[0], 10) : 0; + }) + ); - const hasNonZeroKeys = keysCountArray.some(count => count > 0); + const hasNonZeroKeys = keysCountArray.some((count) => count > 0); expect(hasNonZeroKeys).toBe(true); // test pagination - const prevButton = page.locator('button.px-3.py-1.text-sm.border.rounded-md.hover\\:bg-gray-50.disabled\\:opacity-50.disabled\\:cursor-not-allowed', { hasText: 'Previous' }); - await expect(prevButton).toBeDisabled(); + // Wait for pagination controls to be visible + await page.waitForSelector(".flex.justify-between.items-center", { + timeout: 5000, + }); - const nextButton = page.locator('button.px-3.py-1.text-sm.border.rounded-md.hover\\:bg-gray-50.disabled\\:opacity-50.disabled\\:cursor-not-allowed', { hasText: 'Next' }); - await expect(nextButton).toBeEnabled(); + // Check if we're on the first page by looking at the results count + const resultsText = + (await page.locator(".text-sm.text-gray-700").textContent()) || ""; + const isFirstPage = resultsText.includes("1 -"); + + if (isFirstPage) { + // On first page, previous button should be disabled + const prevButton = page.locator("button", { hasText: "Previous" }); + await expect(prevButton).toBeDisabled(); + } + + // Next button should be enabled if there are more pages + const nextButton = page.locator("button", { hasText: "Next" }); + const totalResults = + (await page.locator(".text-sm.text-gray-700").textContent()) || ""; + const hasMorePages = + totalResults.includes("of") && !totalResults.includes("1 - 25 of 25"); + + if (hasMorePages) { + await expect(nextButton).toBeEnabled(); + } }); diff --git a/tests/proxy_admin_ui_tests/test-results/.last-run.json b/tests/proxy_admin_ui_tests/test-results/.last-run.json new file mode 100644 index 0000000000..0c96e15dce --- /dev/null +++ b/tests/proxy_admin_ui_tests/test-results/.last-run.json @@ -0,0 +1,8 @@ +{ + "status": "failed", + "failedTests": [ + "8306bf902634636ae770-183086b993a71bc98dd6", + "1bfc70f64c2dd4741dbb-58cd256736ebe53a2d97", + "ea1c46def20befad7a54-cb6c473c41474485b610" + ] +} \ No newline at end of file diff --git a/tests/test_keys.py b/tests/test_keys.py index eaf9369d89..89b54ba92c 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -109,6 +109,18 @@ async def test_key_gen(): await asyncio.gather(*tasks) +@pytest.mark.asyncio +async def test_simple_key_gen(): + async with aiohttp.ClientSession() as session: + key_data = await generate_key(session, i=0) + key = key_data["key"] + assert key_data["token"] is not None + assert key_data["token"] != key + assert key_data["token_id"] is not None + assert key_data["created_at"] is not None + assert key_data["updated_at"] is not None + + @pytest.mark.asyncio async def test_key_gen_bad_key(): """ diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx index f16aaf30fa..a1fdf7d073 100644 --- a/ui/litellm-dashboard/src/components/networking.tsx +++ b/ui/litellm-dashboard/src/components/networking.tsx @@ -676,6 +676,9 @@ export const userListCall = async ( userIDs: string[] | null = null, page: number | null = null, page_size: number | null = null, + userEmail: string | null = null, + userRole: string | null = null, + team: string | null = null, ) => { /** * Get all available teams on proxy @@ -698,6 +701,18 @@ export const userListCall = async ( if (page_size) { queryParams.append('page_size', page_size.toString()); } + + if (userEmail) { + queryParams.append('user_email', userEmail); + } + + if (userRole) { + queryParams.append('role', userRole); + } + + if (team) { + queryParams.append('team', team); + } const queryString = queryParams.toString(); if (queryString) { diff --git a/ui/litellm-dashboard/src/components/view_users.tsx b/ui/litellm-dashboard/src/components/view_users.tsx index 6052269586..99ae2c979e 100644 --- a/ui/litellm-dashboard/src/components/view_users.tsx +++ b/ui/litellm-dashboard/src/components/view_users.tsx @@ -1,4 +1,4 @@ -import React, { useState, useEffect } from "react"; +import React, { useState, useEffect, useCallback, useRef } from "react"; import { Card, Title, @@ -23,6 +23,7 @@ import { DialogPanel, Icon, TextInput, + NumberInput, } from "@tremor/react"; import { message } from "antd"; @@ -32,6 +33,7 @@ import { userInfoCall, userUpdateUserCall, getPossibleUserRoles, + userListCall, } from "./networking"; import { Badge, BadgeDelta, Button } from "@tremor/react"; import RequestAccess from "./request_model_access"; @@ -50,6 +52,7 @@ import { UserDataTable } from "./view_users/table"; import { UserInfo } from "./view_users/types"; import BulkCreateUsers from "./bulk_create_users_button"; import SSOSettings from "./SSOSettings"; +import debounce from "lodash/debounce"; interface ViewUserDashboardProps { accessToken: string | null; @@ -77,6 +80,16 @@ interface CreateuserProps { onUserCreated: () => Promise; } +interface FilterState { + email: string; + user_id: string; + user_role: string; + team: string; + model: string; + min_spend: number | null; + max_spend: number | null; +} + const isLocal = process.env.NODE_ENV === "development"; const proxyBaseUrl = isLocal ? "http://localhost:4000" : null; if (isLocal != true) { @@ -93,7 +106,6 @@ const ViewUserDashboard: React.FC = ({ setKeys, }) => { const [userListResponse, setUserListResponse] = useState(null); - const [userData, setUserData] = useState(null); const [endUsers, setEndUsers] = useState(null); const [currentPage, setCurrentPage] = useState(1); const [openDialogId, setOpenDialogId] = React.useState(null); @@ -108,6 +120,19 @@ const ViewUserDashboard: React.FC = ({ const defaultPageSize = 25; const [searchTerm, setSearchTerm] = useState(""); const [activeTab, setActiveTab] = useState("users"); + const [filters, setFilters] = useState({ + email: "", + user_id: "", + user_role: "", + team: "", + model: "", + min_spend: null, + max_spend: null + }); + const [showFilters, setShowFilters] = useState(false); + const [showColumnDropdown, setShowColumnDropdown] = useState(false); + const [selectedFilter, setSelectedFilter] = useState("Email"); + const filtersRef = useRef(null); // check if window is not undefined if (typeof window !== "undefined") { @@ -122,15 +147,66 @@ const ViewUserDashboard: React.FC = ({ setIsDeleteModalOpen(true); }; + const handleFilterChange = (key: keyof FilterState, value: string | number | null) => { + const newFilters = { ...filters, [key]: value }; + setFilters(newFilters); + debouncedSearch(newFilters); + }; + + // Create a debounced version of the search function + const debouncedSearch = useCallback( + debounce(async (filters: FilterState) => { + if (!accessToken || !token || !userRole || !userID) { + return; + } + try { + // Make the API call using userListCall with all filter parameters + const data = await userListCall( + accessToken, + filters.user_id ? [filters.user_id] : null, + 1, // Reset to first page when searching + defaultPageSize, + filters.email || null, + filters.user_role || null, + filters.team || null + ); + + if (data) { + setUserListResponse(data); + console.log("called from debouncedSearch"); + } + } catch (error) { + console.error("Error searching users:", error); + } + }, 300), + [accessToken, token, userRole, userID] + ); + + // Cleanup the debounced function on component unmount + useEffect(() => { + return () => { + debouncedSearch.cancel(); + }; + }, [debouncedSearch]); + + const handleSearch = (value: string) => { + setSearchTerm(value); + if (value === "") { + refreshUserData(); // Reset to original data when search is cleared + } else { + debouncedSearch(filters); + } + }; + const confirmDelete = async () => { if (userToDelete && accessToken) { try { await userDeleteCall(accessToken, [userToDelete]); message.success("User deleted successfully"); // Update the user list after deletion - if (userData) { - const updatedUserData = userData.filter(user => user.user_id !== userToDelete); - setUserData(updatedUserData); + if (userListResponse) { + const updatedUserData = userListResponse.users?.filter(user => user.user_id !== userToDelete); + setUserListResponse({ ...userListResponse, users: updatedUserData || [] }); } } catch (error) { console.error("Error deleting user:", error); @@ -164,11 +240,11 @@ const ViewUserDashboard: React.FC = ({ } catch (error) { console.error("There was an error updating the user", error); } - if (userData) { - const updatedUserData = userData.map((user) => + if (userListResponse) { + const updatedUserData = userListResponse.users?.map((user) => user.user_id === editedUser.user_id ? editedUser : user ); - setUserData(updatedUserData); + setUserListResponse({ ...userListResponse, users: updatedUserData || [] }); } setSelectedUser(null); setEditModalVisible(false); @@ -195,14 +271,42 @@ const ViewUserDashboard: React.FC = ({ `userList_${currentPage}`, JSON.stringify(userDataResponse) ); - + console.log("called from refreshUserData"); setUserListResponse(userDataResponse); - setUserData(userDataResponse.users || []); } catch (error) { console.error("Error refreshing user data:", error); } }; + const handlePageChange = async (newPage: number) => { + if (!accessToken || !token || !userRole || !userID) { + return; + } + + try { + const userDataResponse = await userListCall( + accessToken, + filters.user_id ? [filters.user_id] : null, + newPage, + defaultPageSize, + filters.email || null, + filters.user_role || null, + filters.team || null + ); + + // Update session storage with new data + sessionStorage.setItem( + `userList_${newPage}`, + JSON.stringify(userDataResponse) + ); + + setUserListResponse(userDataResponse); + setCurrentPage(newPage); + } catch (error) { + console.error("Error changing page:", error); + } + }; + useEffect(() => { if (!accessToken || !token || !userRole || !userID) { return; @@ -214,16 +318,17 @@ const ViewUserDashboard: React.FC = ({ if (cachedUserData) { const parsedData = JSON.parse(cachedUserData); setUserListResponse(parsedData); - setUserData(parsedData.users || []); + console.log("called from useEffect"); } else { - // Fetch from API if not in cache - const userDataResponse = await userInfoCall( + // Fetch from API using userListCall with current filters + const userDataResponse = await userListCall( accessToken, - null, - userRole, - true, + filters.user_id ? [filters.user_id] : null, currentPage, - defaultPageSize + defaultPageSize, + filters.email || null, + filters.user_role || null, + filters.team || null ); // Store in session storage @@ -233,7 +338,7 @@ const ViewUserDashboard: React.FC = ({ ); setUserListResponse(userDataResponse); - setUserData(userDataResponse.users || []); + console.log("called from useEffect 2"); } // Fetch roles if not cached @@ -254,9 +359,9 @@ const ViewUserDashboard: React.FC = ({ fetchData(); } - }, [accessToken, token, userRole, userID, currentPage]); + }, [accessToken, token, userRole, userID]); - if (!userData) { + if (!userListResponse) { return
Loading...
; } @@ -297,8 +402,150 @@ const ViewUserDashboard: React.FC = ({
-
-
+
+ {/* Search and Filter Controls */} +
+ {/* Email Search */} +
+ handleFilterChange('email', e.target.value)} + /> + + + +
+ + {/* Filter Button */} + + + {/* Reset Filters Button */} + +
+ + {/* Additional Filters */} + {showFilters && ( +
+ {/* User ID Search */} +
+ handleFilterChange('user_id', e.target.value)} + /> + + + +
+ + {/* Role Dropdown */} +
+ +
+ + {/* Team Dropdown */} +
+ +
+
+ )} + + {/* Results Count and Pagination */} +
Showing{" "} {userListResponse && userListResponse.users && userListResponse.users.length > 0 @@ -313,25 +560,28 @@ const ViewUserDashboard: React.FC = ({ : 0}{" "} of {userListResponse ? userListResponse.total : 0} results -
+ + {/* Pagination Buttons */} +
- - Page {userListResponse ? userListResponse.page : "-"} of{" "} - {userListResponse ? userListResponse.total_pages : "-"} - @@ -339,10 +589,11 @@ const ViewUserDashboard: React.FC = ({
+
From 44264ab6d696782f7d372a90c638c07f64cd5e19 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 14:39:50 -0700 Subject: [PATCH 04/40] fix failing agent ops test --- tests/logging_callback_tests/test_unit_tests_init_callbacks.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py index 3ffa97be9f..445c773d99 100644 --- a/tests/logging_callback_tests/test_unit_tests_init_callbacks.py +++ b/tests/logging_callback_tests/test_unit_tests_init_callbacks.py @@ -38,6 +38,7 @@ from litellm.integrations.langfuse.langfuse_prompt_management import ( LangfusePromptManagement, ) from litellm.integrations.azure_storage.azure_storage import AzureBlobStorageLogger +from litellm.integrations.agentops import AgentOps from litellm.integrations.humanloop import HumanloopLogger from litellm.proxy.hooks.dynamic_rate_limiter import _PROXY_DynamicRateLimitHandler from unittest.mock import patch @@ -75,6 +76,7 @@ callback_class_str_to_classType = { "pagerduty": PagerDutyAlerting, "gcs_pubsub": GcsPubSubLogger, "anthropic_cache_control_hook": AnthropicCacheControlHook, + "agentops": AgentOps, } expected_env_vars = { From 2bb51866b1f4a6bed2ba1f0cfbcbbfc2bd7044e4 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 18:21:06 -0700 Subject: [PATCH 05/40] fix azure/computer-use-preview native streaming --- litellm/model_prices_and_context_window_backup.json | 1 - model_prices_and_context_window.json | 1 - 2 files changed, 2 deletions(-) diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 74cb44a460..95543d09c2 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -1490,7 +1490,6 @@ "supports_prompt_caching": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_native_streaming": false, "supports_reasoning": true }, "azure/gpt-4o-audio-preview-2024-12-17": { diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index 74cb44a460..95543d09c2 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -1490,7 +1490,6 @@ "supports_prompt_caching": false, "supports_system_messages": true, "supports_tool_choice": true, - "supports_native_streaming": false, "supports_reasoning": true }, "azure/gpt-4o-audio-preview-2024-12-17": { From 868cdd02269d29c9246e4dc1ec953a1477cd91e8 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 18:27:03 -0700 Subject: [PATCH 06/40] [Feat] Add Support for DELETE /v1/responses/{response_id} on OpenAI, Azure OpenAI (#10205) * add transform_delete_response_api_request to base responses config * add transform_delete_response_api_request * add delete_response_api_handler * fixes for deleting responses, response API * add adelete_responses * add async test_basic_openai_responses_delete_endpoint * test_basic_openai_responses_delete_endpoint * working delete for streaming on responses API * fixes azure transformation * TestAnthropicResponsesAPITest * fix code check * fix linting * fixes for get_complete_url * test_basic_openai_responses_streaming_delete_endpoint * streaming fixes --- .../llms/azure/responses/transformation.py | 54 +++++- .../llms/base_llm/responses/transformation.py | 32 +++- litellm/llms/custom_httpx/http_handler.py | 43 +++++ litellm/llms/custom_httpx/llm_http_handler.py | 177 +++++++++++++++++- .../llms/openai/responses/transformation.py | 41 +++- litellm/responses/main.py | 169 ++++++++++++++++- litellm/responses/streaming_iterator.py | 46 ++++- litellm/responses/utils.py | 66 +++++-- .../responses_api_deployment_check.py | 7 +- litellm/types/responses/main.py | 28 +++ litellm/types/utils.py | 4 +- litellm/utils.py | 40 ++-- .../test_openai_responses_transformation.py | 15 -- .../base_responses_api.py | 84 +++++++++ .../test_anthropic_responses_api.py | 6 + 15 files changed, 729 insertions(+), 83 deletions(-) diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.py index a85ba73bec..499d21cb0e 100644 --- a/litellm/llms/azure/responses/transformation.py +++ b/litellm/llms/azure/responses/transformation.py @@ -1,11 +1,14 @@ -from typing import TYPE_CHECKING, Any, Optional, cast +from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, cast import httpx import litellm +from litellm._logging import verbose_logger from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig from litellm.secret_managers.main import get_secret_str from litellm.types.llms.openai import * +from litellm.types.responses.main import * +from litellm.types.router import GenericLiteLLMParams from litellm.utils import _add_path_to_api_base if TYPE_CHECKING: @@ -41,11 +44,7 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig): def get_complete_url( self, api_base: Optional[str], - api_key: Optional[str], - model: str, - optional_params: dict, litellm_params: dict, - stream: Optional[bool] = None, ) -> str: """ Constructs a complete URL for the API request. @@ -92,3 +91,48 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig): final_url = httpx.URL(new_url).copy_with(params=query_params) return str(final_url) + + ######################################################### + ########## DELETE RESPONSE API TRANSFORMATION ############## + ######################################################### + def transform_delete_response_api_request( + self, + response_id: str, + api_base: str, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[str, Dict]: + """ + Transform the delete response API request into a URL and data + + Azure OpenAI API expects the following request: + - DELETE /openai/responses/{response_id}?api-version=xxx + + This function handles URLs with query parameters by inserting the response_id + at the correct location (before any query parameters). + """ + from urllib.parse import urlparse, urlunparse + + # Parse the URL to separate its components + parsed_url = urlparse(api_base) + + # Insert the response_id at the end of the path component + # Remove trailing slash if present to avoid double slashes + path = parsed_url.path.rstrip("/") + new_path = f"{path}/{response_id}" + + # Reconstruct the URL with all original components but with the modified path + delete_url = urlunparse( + ( + parsed_url.scheme, # http, https + parsed_url.netloc, # domain name, port + new_path, # path with response_id added + parsed_url.params, # parameters + parsed_url.query, # query string + parsed_url.fragment, # fragment + ) + ) + + data: Dict = {} + verbose_logger.debug(f"delete response url={delete_url}") + return delete_url, data diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.py index 649b91226f..15ce8cba3f 100644 --- a/litellm/llms/base_llm/responses/transformation.py +++ b/litellm/llms/base_llm/responses/transformation.py @@ -1,6 +1,6 @@ import types from abc import ABC, abstractmethod -from typing import TYPE_CHECKING, Any, Dict, Optional, Union +from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union import httpx @@ -10,6 +10,7 @@ from litellm.types.llms.openai import ( ResponsesAPIResponse, ResponsesAPIStreamingResponse, ) +from litellm.types.responses.main import * from litellm.types.router import GenericLiteLLMParams if TYPE_CHECKING: @@ -73,11 +74,7 @@ class BaseResponsesAPIConfig(ABC): def get_complete_url( self, api_base: Optional[str], - api_key: Optional[str], - model: str, - optional_params: dict, litellm_params: dict, - stream: Optional[bool] = None, ) -> str: """ OPTIONAL @@ -122,6 +119,31 @@ class BaseResponsesAPIConfig(ABC): """ pass + ######################################################### + ########## DELETE RESPONSE API TRANSFORMATION ############## + ######################################################### + @abstractmethod + def transform_delete_response_api_request( + self, + response_id: str, + api_base: str, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[str, Dict]: + pass + + @abstractmethod + def transform_delete_response_api_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + ) -> DeleteResponseResult: + pass + + ######################################################### + ########## END DELETE RESPONSE API TRANSFORMATION ########## + ######################################################### + def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: diff --git a/litellm/llms/custom_httpx/http_handler.py b/litellm/llms/custom_httpx/http_handler.py index 627dd8c9f9..f99e04ab9d 100644 --- a/litellm/llms/custom_httpx/http_handler.py +++ b/litellm/llms/custom_httpx/http_handler.py @@ -650,6 +650,49 @@ class HTTPHandler: except Exception as e: raise e + def delete( + self, + url: str, + data: Optional[Union[dict, str]] = None, # type: ignore + json: Optional[dict] = None, + params: Optional[dict] = None, + headers: Optional[dict] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + stream: bool = False, + ): + try: + if timeout is not None: + req = self.client.build_request( + "DELETE", url, data=data, json=json, params=params, headers=headers, timeout=timeout # type: ignore + ) + else: + req = self.client.build_request( + "DELETE", url, data=data, json=json, params=params, headers=headers # type: ignore + ) + response = self.client.send(req, stream=stream) + response.raise_for_status() + return response + except httpx.TimeoutException: + raise litellm.Timeout( + message=f"Connection timed out after {timeout} seconds.", + model="default-model-name", + llm_provider="litellm-httpx-handler", + ) + except httpx.HTTPStatusError as e: + if stream is True: + setattr(e, "message", mask_sensitive_info(e.response.read())) + setattr(e, "text", mask_sensitive_info(e.response.read())) + else: + error_text = mask_sensitive_info(e.response.text) + setattr(e, "message", error_text) + setattr(e, "text", error_text) + + setattr(e, "status_code", e.response.status_code) + + raise e + except Exception as e: + raise e + def __del__(self) -> None: try: self.close() diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index c7b18215d0..1958ef0b60 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -36,6 +36,7 @@ from litellm.types.llms.openai import ( ResponsesAPIResponse, ) from litellm.types.rerank import OptionalRerankParams, RerankResponse +from litellm.types.responses.main import DeleteResponseResult from litellm.types.router import GenericLiteLLMParams from litellm.types.utils import EmbeddingResponse, FileTypes, TranscriptionResponse from litellm.utils import CustomStreamWrapper, ModelResponse, ProviderConfigManager @@ -1015,6 +1016,7 @@ class BaseLLMHTTPHandler: client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, _is_async: bool = False, fake_stream: bool = False, + litellm_metadata: Optional[Dict[str, Any]] = None, ) -> Union[ ResponsesAPIResponse, BaseResponsesAPIStreamingIterator, @@ -1041,6 +1043,7 @@ class BaseLLMHTTPHandler: timeout=timeout, client=client if isinstance(client, AsyncHTTPHandler) else None, fake_stream=fake_stream, + litellm_metadata=litellm_metadata, ) if client is None or not isinstance(client, HTTPHandler): @@ -1064,11 +1067,7 @@ class BaseLLMHTTPHandler: api_base = responses_api_provider_config.get_complete_url( api_base=litellm_params.api_base, - api_key=litellm_params.api_key, - model=model, - optional_params=response_api_optional_request_params, litellm_params=dict(litellm_params), - stream=stream, ) data = responses_api_provider_config.transform_responses_api_request( @@ -1113,6 +1112,8 @@ class BaseLLMHTTPHandler: model=model, logging_obj=logging_obj, responses_api_provider_config=responses_api_provider_config, + litellm_metadata=litellm_metadata, + custom_llm_provider=custom_llm_provider, ) return SyncResponsesAPIStreamingIterator( @@ -1120,6 +1121,8 @@ class BaseLLMHTTPHandler: model=model, logging_obj=logging_obj, responses_api_provider_config=responses_api_provider_config, + litellm_metadata=litellm_metadata, + custom_llm_provider=custom_llm_provider, ) else: # For non-streaming requests @@ -1156,6 +1159,7 @@ class BaseLLMHTTPHandler: timeout: Optional[Union[float, httpx.Timeout]] = None, client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, fake_stream: bool = False, + litellm_metadata: Optional[Dict[str, Any]] = None, ) -> Union[ResponsesAPIResponse, BaseResponsesAPIStreamingIterator]: """ Async version of the responses API handler. @@ -1183,11 +1187,7 @@ class BaseLLMHTTPHandler: api_base = responses_api_provider_config.get_complete_url( api_base=litellm_params.api_base, - api_key=litellm_params.api_key, - model=model, - optional_params=response_api_optional_request_params, litellm_params=dict(litellm_params), - stream=stream, ) data = responses_api_provider_config.transform_responses_api_request( @@ -1234,6 +1234,8 @@ class BaseLLMHTTPHandler: model=model, logging_obj=logging_obj, responses_api_provider_config=responses_api_provider_config, + litellm_metadata=litellm_metadata, + custom_llm_provider=custom_llm_provider, ) # Return the streaming iterator @@ -1242,6 +1244,8 @@ class BaseLLMHTTPHandler: model=model, logging_obj=logging_obj, responses_api_provider_config=responses_api_provider_config, + litellm_metadata=litellm_metadata, + custom_llm_provider=custom_llm_provider, ) else: # For non-streaming, proceed as before @@ -1265,6 +1269,163 @@ class BaseLLMHTTPHandler: logging_obj=logging_obj, ) + async def async_delete_response_api_handler( + self, + response_id: str, + responses_api_provider_config: BaseResponsesAPIConfig, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + custom_llm_provider: Optional[str], + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ) -> DeleteResponseResult: + """ + Async version of the delete response API handler. + Uses async HTTP client to make requests. + """ + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders(custom_llm_provider), + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + else: + async_httpx_client = client + + headers = responses_api_provider_config.validate_environment( + api_key=litellm_params.api_key, + headers=extra_headers or {}, + model="None", + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = responses_api_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url, data = responses_api_provider_config.transform_delete_response_api_request( + response_id=response_id, + api_base=api_base, + litellm_params=litellm_params, + headers=headers, + ) + + ## LOGGING + logging_obj.pre_call( + input=input, + api_key="", + additional_args={ + "complete_input_dict": data, + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = await async_httpx_client.delete( + url=url, headers=headers, data=json.dumps(data), timeout=timeout + ) + + except Exception as e: + raise self._handle_error( + e=e, + provider_config=responses_api_provider_config, + ) + + return responses_api_provider_config.transform_delete_response_api_response( + raw_response=response, + logging_obj=logging_obj, + ) + + def delete_response_api_handler( + self, + response_id: str, + responses_api_provider_config: BaseResponsesAPIConfig, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + custom_llm_provider: Optional[str], + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ) -> Union[DeleteResponseResult, Coroutine[Any, Any, DeleteResponseResult]]: + """ + Async version of the responses API handler. + Uses async HTTP client to make requests. + """ + if _is_async: + return self.async_delete_response_api_handler( + response_id=response_id, + responses_api_provider_config=responses_api_provider_config, + litellm_params=litellm_params, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + client=client, + ) + if client is None or not isinstance(client, HTTPHandler): + sync_httpx_client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) + else: + sync_httpx_client = client + + headers = responses_api_provider_config.validate_environment( + api_key=litellm_params.api_key, + headers=extra_headers or {}, + model="None", + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = responses_api_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url, data = responses_api_provider_config.transform_delete_response_api_request( + response_id=response_id, + api_base=api_base, + litellm_params=litellm_params, + headers=headers, + ) + + ## LOGGING + logging_obj.pre_call( + input=input, + api_key="", + additional_args={ + "complete_input_dict": data, + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = sync_httpx_client.delete( + url=url, headers=headers, data=json.dumps(data), timeout=timeout + ) + + except Exception as e: + raise self._handle_error( + e=e, + provider_config=responses_api_provider_config, + ) + + return responses_api_provider_config.transform_delete_response_api_response( + raw_response=response, + logging_obj=logging_obj, + ) + def create_file( self, create_file_data: CreateFileRequest, diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py index 047572657c..d4a443aedb 100644 --- a/litellm/llms/openai/responses/transformation.py +++ b/litellm/llms/openai/responses/transformation.py @@ -7,6 +7,7 @@ from litellm._logging import verbose_logger from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig from litellm.secret_managers.main import get_secret_str from litellm.types.llms.openai import * +from litellm.types.responses.main import * from litellm.types.router import GenericLiteLLMParams from ..common_utils import OpenAIError @@ -110,11 +111,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): def get_complete_url( self, api_base: Optional[str], - api_key: Optional[str], - model: str, - optional_params: dict, litellm_params: dict, - stream: Optional[bool] = None, ) -> str: """ Get the endpoint for OpenAI responses API @@ -217,3 +214,39 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): f"Error getting model info in OpenAIResponsesAPIConfig: {e}" ) return False + + ######################################################### + ########## DELETE RESPONSE API TRANSFORMATION ############## + ######################################################### + def transform_delete_response_api_request( + self, + response_id: str, + api_base: str, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[str, Dict]: + """ + Transform the delete response API request into a URL and data + + OpenAI API expects the following request + - DELETE /v1/responses/{response_id} + """ + url = f"{api_base}/{response_id}" + data: Dict = {} + return url, data + + def transform_delete_response_api_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + ) -> DeleteResponseResult: + """ + Transform the delete response API response into a DeleteResponseResult + """ + try: + raw_response_json = raw_response.json() + except Exception: + raise OpenAIError( + message=raw_response.text, status_code=raw_response.status_code + ) + return DeleteResponseResult(**raw_response_json) diff --git a/litellm/responses/main.py b/litellm/responses/main.py index 2d7426205e..004a19a0ae 100644 --- a/litellm/responses/main.py +++ b/litellm/responses/main.py @@ -1,7 +1,7 @@ import asyncio import contextvars from functools import partial -from typing import Any, Dict, Iterable, List, Literal, Optional, Union +from typing import Any, Coroutine, Dict, Iterable, List, Literal, Optional, Union import httpx @@ -24,6 +24,7 @@ from litellm.types.llms.openai import ( ToolChoice, ToolParam, ) +from litellm.types.responses.main import * from litellm.types.router import GenericLiteLLMParams from litellm.utils import ProviderConfigManager, client @@ -121,7 +122,8 @@ async def aresponses( if isinstance(response, ResponsesAPIResponse): response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id( responses_api_response=response, - kwargs=kwargs, + litellm_metadata=kwargs.get("litellm_metadata", {}), + custom_llm_provider=custom_llm_provider, ) return response except Exception as e: @@ -253,13 +255,15 @@ def responses( fake_stream=responses_api_provider_config.should_fake_stream( model=model, stream=stream, custom_llm_provider=custom_llm_provider ), + litellm_metadata=kwargs.get("litellm_metadata", {}), ) # Update the responses_api_response_id with the model_id if isinstance(response, ResponsesAPIResponse): response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id( responses_api_response=response, - kwargs=kwargs, + litellm_metadata=kwargs.get("litellm_metadata", {}), + custom_llm_provider=custom_llm_provider, ) return response @@ -271,3 +275,162 @@ def responses( completion_kwargs=local_vars, extra_kwargs=kwargs, ) + + +@client +async def adelete_responses( + response_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> DeleteResponseResult: + """ + Async version of the DELETE Responses API + + DELETE /v1/responses/{response_id} endpoint in the responses API + + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["adelete_responses"] = True + + # get custom llm provider from response_id + decoded_response_id: DecodedResponseId = ( + ResponsesAPIRequestUtils._decode_responses_api_response_id( + response_id=response_id, + ) + ) + response_id = decoded_response_id.get("response_id") or response_id + custom_llm_provider = ( + decoded_response_id.get("custom_llm_provider") or custom_llm_provider + ) + + func = partial( + delete_responses, + response_id=response_id, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + + +@client +def delete_responses( + response_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[DeleteResponseResult, Coroutine[Any, Any, DeleteResponseResult]]: + """ + Synchronous version of the DELETE Responses API + + DELETE /v1/responses/{response_id} endpoint in the responses API + + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("adelete_responses", False) is True + + # get llm provider logic + litellm_params = GenericLiteLLMParams(**kwargs) + + # get custom llm provider from response_id + decoded_response_id: DecodedResponseId = ( + ResponsesAPIRequestUtils._decode_responses_api_response_id( + response_id=response_id, + ) + ) + response_id = decoded_response_id.get("response_id") or response_id + custom_llm_provider = ( + decoded_response_id.get("custom_llm_provider") or custom_llm_provider + ) + + if custom_llm_provider is None: + raise ValueError("custom_llm_provider is required but passed as None") + + # get provider config + responses_api_provider_config: Optional[BaseResponsesAPIConfig] = ( + ProviderConfigManager.get_provider_responses_api_config( + model=None, + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if responses_api_provider_config is None: + raise ValueError( + f"DELETE responses is not supported for {custom_llm_provider}" + ) + + local_vars.update(kwargs) + + # Pre Call logging + litellm_logging_obj.update_environment_variables( + model=None, + optional_params={ + "response_id": response_id, + }, + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Call the handler with _is_async flag instead of directly calling the async handler + response = base_llm_http_handler.delete_response_api_handler( + response_id=response_id, + custom_llm_provider=custom_llm_provider, + responses_api_provider_config=responses_api_provider_config, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.py index e050c47080..3e12761ba0 100644 --- a/litellm/responses/streaming_iterator.py +++ b/litellm/responses/streaming_iterator.py @@ -1,7 +1,7 @@ import asyncio import json from datetime import datetime -from typing import Optional +from typing import Any, Dict, Optional import httpx @@ -10,6 +10,7 @@ from litellm.litellm_core_utils.asyncify import run_async_function from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj from litellm.litellm_core_utils.thread_pool_executor import executor from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig +from litellm.responses.utils import ResponsesAPIRequestUtils from litellm.types.llms.openai import ( OutputTextDeltaEvent, ResponseCompletedEvent, @@ -33,6 +34,8 @@ class BaseResponsesAPIStreamingIterator: model: str, responses_api_provider_config: BaseResponsesAPIConfig, logging_obj: LiteLLMLoggingObj, + litellm_metadata: Optional[Dict[str, Any]] = None, + custom_llm_provider: Optional[str] = None, ): self.response = response self.model = model @@ -42,6 +45,10 @@ class BaseResponsesAPIStreamingIterator: self.completed_response: Optional[ResponsesAPIStreamingResponse] = None self.start_time = datetime.now() + # set request kwargs + self.litellm_metadata = litellm_metadata + self.custom_llm_provider = custom_llm_provider + def _process_chunk(self, chunk): """Process a single chunk of data from the stream""" if not chunk: @@ -70,6 +77,17 @@ class BaseResponsesAPIStreamingIterator: logging_obj=self.logging_obj, ) ) + + # if "response" in parsed_chunk, then encode litellm specific information like custom_llm_provider + response_object = getattr(openai_responses_api_chunk, "response", None) + if response_object: + response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id( + responses_api_response=response_object, + litellm_metadata=self.litellm_metadata, + custom_llm_provider=self.custom_llm_provider, + ) + setattr(openai_responses_api_chunk, "response", response) + # Store the completed response if ( openai_responses_api_chunk @@ -102,8 +120,17 @@ class ResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator): model: str, responses_api_provider_config: BaseResponsesAPIConfig, logging_obj: LiteLLMLoggingObj, + litellm_metadata: Optional[Dict[str, Any]] = None, + custom_llm_provider: Optional[str] = None, ): - super().__init__(response, model, responses_api_provider_config, logging_obj) + super().__init__( + response, + model, + responses_api_provider_config, + logging_obj, + litellm_metadata, + custom_llm_provider, + ) self.stream_iterator = response.aiter_lines() def __aiter__(self): @@ -163,8 +190,17 @@ class SyncResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator): model: str, responses_api_provider_config: BaseResponsesAPIConfig, logging_obj: LiteLLMLoggingObj, + litellm_metadata: Optional[Dict[str, Any]] = None, + custom_llm_provider: Optional[str] = None, ): - super().__init__(response, model, responses_api_provider_config, logging_obj) + super().__init__( + response, + model, + responses_api_provider_config, + logging_obj, + litellm_metadata, + custom_llm_provider, + ) self.stream_iterator = response.iter_lines() def __iter__(self): @@ -228,12 +264,16 @@ class MockResponsesAPIStreamingIterator(BaseResponsesAPIStreamingIterator): model: str, responses_api_provider_config: BaseResponsesAPIConfig, logging_obj: LiteLLMLoggingObj, + litellm_metadata: Optional[Dict[str, Any]] = None, + custom_llm_provider: Optional[str] = None, ): super().__init__( response=response, model=model, responses_api_provider_config=responses_api_provider_config, logging_obj=logging_obj, + litellm_metadata=litellm_metadata, + custom_llm_provider=custom_llm_provider, ) # one-time transform diff --git a/litellm/responses/utils.py b/litellm/responses/utils.py index 5e95cbd93a..9fa455de71 100644 --- a/litellm/responses/utils.py +++ b/litellm/responses/utils.py @@ -1,5 +1,5 @@ import base64 -from typing import Any, Dict, Optional, Tuple, Union, cast, get_type_hints +from typing import Any, Dict, Optional, Union, cast, get_type_hints import litellm from litellm._logging import verbose_logger @@ -9,6 +9,7 @@ from litellm.types.llms.openai import ( ResponsesAPIOptionalRequestParams, ResponsesAPIResponse, ) +from litellm.types.responses.main import DecodedResponseId from litellm.types.utils import SpecialEnums, Usage @@ -83,30 +84,36 @@ class ResponsesAPIRequestUtils: @staticmethod def _update_responses_api_response_id_with_model_id( responses_api_response: ResponsesAPIResponse, - kwargs: Dict[str, Any], + custom_llm_provider: Optional[str], + litellm_metadata: Optional[Dict[str, Any]] = None, ) -> ResponsesAPIResponse: - """Update the responses_api_response_id with the model_id""" - litellm_metadata: Dict[str, Any] = kwargs.get("litellm_metadata", {}) or {} + """ + Update the responses_api_response_id with model_id and custom_llm_provider + + This builds a composite ID containing the custom LLM provider, model ID, and original response ID + """ + litellm_metadata = litellm_metadata or {} model_info: Dict[str, Any] = litellm_metadata.get("model_info", {}) or {} model_id = model_info.get("id") updated_id = ResponsesAPIRequestUtils._build_responses_api_response_id( model_id=model_id, + custom_llm_provider=custom_llm_provider, response_id=responses_api_response.id, ) + responses_api_response.id = updated_id return responses_api_response @staticmethod def _build_responses_api_response_id( + custom_llm_provider: Optional[str], model_id: Optional[str], response_id: str, ) -> str: """Build the responses_api_response_id""" - if model_id is None: - return response_id assembled_id: str = str( SpecialEnums.LITELLM_MANAGED_RESPONSE_COMPLETE_STR.value - ).format(model_id, response_id) + ).format(custom_llm_provider, model_id, response_id) base64_encoded_id: str = base64.b64encode(assembled_id.encode("utf-8")).decode( "utf-8" ) @@ -115,12 +122,12 @@ class ResponsesAPIRequestUtils: @staticmethod def _decode_responses_api_response_id( response_id: str, - ) -> Tuple[Optional[str], str]: + ) -> DecodedResponseId: """ Decode the responses_api_response_id Returns: - Tuple of model_id, response_id (from upstream provider) + DecodedResponseId: Structured tuple with custom_llm_provider, model_id, and response_id """ try: # Remove prefix and decode @@ -129,16 +136,45 @@ class ResponsesAPIRequestUtils: # Parse components using known prefixes if ";" not in decoded_id: - return None, response_id + return DecodedResponseId( + custom_llm_provider=None, + model_id=None, + response_id=response_id, + ) - model_part, response_part = decoded_id.split(";", 1) - model_id = model_part.replace("litellm:model_id:", "") - decoded_response_id = response_part.replace("response_id:", "") + parts = decoded_id.split(";") - return model_id, decoded_response_id + # Format: litellm:custom_llm_provider:{};model_id:{};response_id:{} + custom_llm_provider = None + model_id = None + + if ( + len(parts) >= 3 + ): # Full format with custom_llm_provider, model_id, and response_id + custom_llm_provider_part = parts[0] + model_id_part = parts[1] + response_part = parts[2] + + custom_llm_provider = custom_llm_provider_part.replace( + "litellm:custom_llm_provider:", "" + ) + model_id = model_id_part.replace("model_id:", "") + decoded_response_id = response_part.replace("response_id:", "") + else: + decoded_response_id = response_id + + return DecodedResponseId( + custom_llm_provider=custom_llm_provider, + model_id=model_id, + response_id=decoded_response_id, + ) except Exception as e: verbose_logger.debug(f"Error decoding response_id '{response_id}': {e}") - return None, response_id + return DecodedResponseId( + custom_llm_provider=None, + model_id=None, + response_id=response_id, + ) class ResponseAPILoggingUtils: diff --git a/litellm/router_utils/pre_call_checks/responses_api_deployment_check.py b/litellm/router_utils/pre_call_checks/responses_api_deployment_check.py index 445460c237..b030fc28c8 100644 --- a/litellm/router_utils/pre_call_checks/responses_api_deployment_check.py +++ b/litellm/router_utils/pre_call_checks/responses_api_deployment_check.py @@ -31,11 +31,10 @@ class ResponsesApiDeploymentCheck(CustomLogger): if previous_response_id is None: return healthy_deployments - model_id, response_id = ( - ResponsesAPIRequestUtils._decode_responses_api_response_id( - response_id=previous_response_id, - ) + decoded_response = ResponsesAPIRequestUtils._decode_responses_api_response_id( + response_id=previous_response_id, ) + model_id = decoded_response.get("model_id") if model_id is None: return healthy_deployments diff --git a/litellm/types/responses/main.py b/litellm/types/responses/main.py index 63a548bbfd..b85df206bc 100644 --- a/litellm/types/responses/main.py +++ b/litellm/types/responses/main.py @@ -1,5 +1,6 @@ from typing import Literal +from pydantic import PrivateAttr from typing_extensions import Any, List, Optional, TypedDict from litellm.types.llms.base import BaseLiteLLMOpenAIResponseObject @@ -46,3 +47,30 @@ class GenericResponseOutputItem(BaseLiteLLMOpenAIResponseObject): status: str # "completed", "in_progress", etc. role: str # "assistant", "user", etc. content: List[OutputText] + + +class DeleteResponseResult(BaseLiteLLMOpenAIResponseObject): + """ + Result of a delete response request + + { + "id": "resp_6786a1bec27481909a17d673315b29f6", + "object": "response", + "deleted": true + } + """ + + id: Optional[str] + object: Optional[str] + deleted: Optional[bool] + + # Define private attributes using PrivateAttr + _hidden_params: dict = PrivateAttr(default_factory=dict) + + +class DecodedResponseId(TypedDict, total=False): + """Structure representing a decoded response ID""" + + custom_llm_provider: Optional[str] + model_id: Optional[str] + response_id: str diff --git a/litellm/types/utils.py b/litellm/types/utils.py index e9859513b9..532162e60f 100644 --- a/litellm/types/utils.py +++ b/litellm/types/utils.py @@ -2254,7 +2254,9 @@ class SpecialEnums(Enum): LITELM_MANAGED_FILE_ID_PREFIX = "litellm_proxy" LITELLM_MANAGED_FILE_COMPLETE_STR = "litellm_proxy:{};unified_id,{}" - LITELLM_MANAGED_RESPONSE_COMPLETE_STR = "litellm:model_id:{};response_id:{}" + LITELLM_MANAGED_RESPONSE_COMPLETE_STR = ( + "litellm:custom_llm_provider:{};model_id:{};response_id:{}" + ) LLMResponseTypes = Union[ diff --git a/litellm/utils.py b/litellm/utils.py index 38e604943a..0150c4f43f 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -516,9 +516,9 @@ def function_setup( # noqa: PLR0915 function_id: Optional[str] = kwargs["id"] if "id" in kwargs else None ## DYNAMIC CALLBACKS ## - dynamic_callbacks: Optional[ - List[Union[str, Callable, CustomLogger]] - ] = kwargs.pop("callbacks", None) + dynamic_callbacks: Optional[List[Union[str, Callable, CustomLogger]]] = ( + kwargs.pop("callbacks", None) + ) all_callbacks = get_dynamic_callbacks(dynamic_callbacks=dynamic_callbacks) if len(all_callbacks) > 0: @@ -1202,9 +1202,9 @@ def client(original_function): # noqa: PLR0915 exception=e, retry_policy=kwargs.get("retry_policy"), ) - kwargs[ - "retry_policy" - ] = reset_retry_policy() # prevent infinite loops + kwargs["retry_policy"] = ( + reset_retry_policy() + ) # prevent infinite loops litellm.num_retries = ( None # set retries to None to prevent infinite loops ) @@ -3028,16 +3028,16 @@ def get_optional_params( # noqa: PLR0915 True # so that main.py adds the function call to the prompt ) if "tools" in non_default_params: - optional_params[ - "functions_unsupported_model" - ] = non_default_params.pop("tools") + optional_params["functions_unsupported_model"] = ( + non_default_params.pop("tools") + ) non_default_params.pop( "tool_choice", None ) # causes ollama requests to hang elif "functions" in non_default_params: - optional_params[ - "functions_unsupported_model" - ] = non_default_params.pop("functions") + optional_params["functions_unsupported_model"] = ( + non_default_params.pop("functions") + ) elif ( litellm.add_function_to_prompt ): # if user opts to add it to prompt instead @@ -3060,10 +3060,10 @@ def get_optional_params( # noqa: PLR0915 if "response_format" in non_default_params: if provider_config is not None: - non_default_params[ - "response_format" - ] = provider_config.get_json_schema_from_pydantic_object( - response_format=non_default_params["response_format"] + non_default_params["response_format"] = ( + provider_config.get_json_schema_from_pydantic_object( + response_format=non_default_params["response_format"] + ) ) else: non_default_params["response_format"] = type_to_response_format_param( @@ -4079,9 +4079,9 @@ def _count_characters(text: str) -> int: def get_response_string(response_obj: Union[ModelResponse, ModelResponseStream]) -> str: - _choices: Union[ - List[Union[Choices, StreamingChoices]], List[StreamingChoices] - ] = response_obj.choices + _choices: Union[List[Union[Choices, StreamingChoices]], List[StreamingChoices]] = ( + response_obj.choices + ) response_str = "" for choice in _choices: @@ -6625,8 +6625,8 @@ class ProviderConfigManager: @staticmethod def get_provider_responses_api_config( - model: str, provider: LlmProviders, + model: Optional[str] = None, ) -> Optional[BaseResponsesAPIConfig]: if litellm.LlmProviders.OPENAI == provider: return litellm.OpenAIResponsesAPIConfig() diff --git a/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py b/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py index 202d0aea23..3b9ae72da7 100644 --- a/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py +++ b/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py @@ -203,9 +203,6 @@ class TestOpenAIResponsesAPIConfig: result = self.config.get_complete_url( api_base=api_base, - model=self.model, - api_key="test_api_key", - optional_params={}, litellm_params={}, ) @@ -215,9 +212,6 @@ class TestOpenAIResponsesAPIConfig: with patch("litellm.api_base", "https://litellm-api-base.example.com/v1"): result = self.config.get_complete_url( api_base=None, - model=self.model, - api_key="test_api_key", - optional_params={}, litellm_params={}, ) @@ -231,9 +225,6 @@ class TestOpenAIResponsesAPIConfig: ): result = self.config.get_complete_url( api_base=None, - model=self.model, - api_key="test_api_key", - optional_params={}, litellm_params={}, ) @@ -247,9 +238,6 @@ class TestOpenAIResponsesAPIConfig: ): result = self.config.get_complete_url( api_base=None, - model=self.model, - api_key="test_api_key", - optional_params={}, litellm_params={}, ) @@ -260,9 +248,6 @@ class TestOpenAIResponsesAPIConfig: result = self.config.get_complete_url( api_base=api_base, - model=self.model, - api_key="test_api_key", - optional_params={}, litellm_params={}, ) diff --git a/tests/llm_responses_api_testing/base_responses_api.py b/tests/llm_responses_api_testing/base_responses_api.py index fd39c13604..905b9b3219 100644 --- a/tests/llm_responses_api_testing/base_responses_api.py +++ b/tests/llm_responses_api_testing/base_responses_api.py @@ -189,6 +189,90 @@ class BaseResponsesAPITest(ABC): + @pytest.mark.parametrize("sync_mode", [False, True]) + @pytest.mark.asyncio + async def test_basic_openai_responses_delete_endpoint(self, sync_mode): + litellm._turn_on_debug() + litellm.set_verbose = True + base_completion_call_args = self.get_base_completion_call_args() + if sync_mode: + response = litellm.responses( + input="Basic ping", max_output_tokens=20, + **base_completion_call_args + ) + + # delete the response + if isinstance(response, ResponsesAPIResponse): + litellm.delete_responses( + response_id=response.id, + **base_completion_call_args + ) + else: + raise ValueError("response is not a ResponsesAPIResponse") + else: + response = await litellm.aresponses( + input="Basic ping", max_output_tokens=20, + **base_completion_call_args + ) + + # async delete the response + if isinstance(response, ResponsesAPIResponse): + await litellm.adelete_responses( + response_id=response.id, + **base_completion_call_args + ) + else: + raise ValueError("response is not a ResponsesAPIResponse") + + + @pytest.mark.parametrize("sync_mode", [True, False]) + @pytest.mark.asyncio + async def test_basic_openai_responses_streaming_delete_endpoint(self, sync_mode): + #litellm._turn_on_debug() + #litellm.set_verbose = True + base_completion_call_args = self.get_base_completion_call_args() + response_id = None + if sync_mode: + response_id = None + response = litellm.responses( + input="Basic ping", max_output_tokens=20, + stream=True, + **base_completion_call_args + ) + for event in response: + print("litellm response=", json.dumps(event, indent=4, default=str)) + if "response" in event: + response_obj = event.get("response") + if response_obj is not None: + response_id = response_obj.get("id") + print("got response_id=", response_id) + + # delete the response + assert response_id is not None + litellm.delete_responses( + response_id=response_id, + **base_completion_call_args + ) + else: + response = await litellm.aresponses( + input="Basic ping", max_output_tokens=20, + stream=True, + **base_completion_call_args + ) + async for event in response: + print("litellm response=", json.dumps(event, indent=4, default=str)) + if "response" in event: + response_obj = event.get("response") + if response_obj is not None: + response_id = response_obj.get("id") + print("got response_id=", response_id) + + # delete the response + assert response_id is not None + await litellm.adelete_responses( + response_id=response_id, + **base_completion_call_args + ) diff --git a/tests/llm_responses_api_testing/test_anthropic_responses_api.py b/tests/llm_responses_api_testing/test_anthropic_responses_api.py index 0fcb771f73..b02c9b8d11 100644 --- a/tests/llm_responses_api_testing/test_anthropic_responses_api.py +++ b/tests/llm_responses_api_testing/test_anthropic_responses_api.py @@ -29,6 +29,12 @@ class TestAnthropicResponsesAPITest(BaseResponsesAPITest): return { "model": "anthropic/claude-3-5-sonnet-latest", } + + async def test_basic_openai_responses_delete_endpoint(self, sync_mode=False): + pass + + async def test_basic_openai_responses_streaming_delete_endpoint(self, sync_mode=False): + pass def test_multiturn_tool_calls(): From b96d2ea422aaa744314809a83e75b1f51dd25076 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 18:29:56 -0700 Subject: [PATCH 07/40] Bug Fix - Address deprecation of open_text (#10208) * Update utils.py (#10201) * fixes importlib --------- Co-authored-by: Nathan Brake <33383515+njbrake@users.noreply.github.com> --- litellm/utils.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/litellm/utils.py b/litellm/utils.py index 0150c4f43f..98a9c34b47 100644 --- a/litellm/utils.py +++ b/litellm/utils.py @@ -180,10 +180,18 @@ from litellm.types.utils import ( all_litellm_params, ) -with resources.open_text( - "litellm.litellm_core_utils.tokenizers", "anthropic_tokenizer.json" -) as f: - json_data = json.load(f) +try: + # Python 3.9+ + with resources.files("litellm.litellm_core_utils.tokenizers").joinpath( + "anthropic_tokenizer.json" + ).open("r") as f: + json_data = json.load(f) +except (ImportError, AttributeError, TypeError): + with resources.open_text( + "litellm.litellm_core_utils.tokenizers", "anthropic_tokenizer.json" + ) as f: + json_data = json.load(f) + # Convert to str (if necessary) claude_json_str = json.dumps(json_data) import importlib.metadata From 6e4fed59b6fbd14e738eb5574fe337421437fb33 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 18:32:28 -0700 Subject: [PATCH 08/40] docs agent ops logging --- docs/my-website/docs/proxy/config_settings.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.md index bd8e2116c2..1e3c800b03 100644 --- a/docs/my-website/docs/proxy/config_settings.md +++ b/docs/my-website/docs/proxy/config_settings.md @@ -299,6 +299,9 @@ router_settings: |------|-------------| | ACTIONS_ID_TOKEN_REQUEST_TOKEN | Token for requesting ID in GitHub Actions | ACTIONS_ID_TOKEN_REQUEST_URL | URL for requesting ID token in GitHub Actions +| AGENTOPS_ENVIRONMENT | Environment for AgentOps logging integration +| AGENTOPS_API_KEY | API Key for AgentOps logging integration +| AGENTOPS_SERVICE_NAME | Service Name for AgentOps logging integration | AISPEND_ACCOUNT_ID | Account ID for AI Spend | AISPEND_API_KEY | API Key for AI Spend | ALLOWED_EMAIL_DOMAINS | List of email domains allowed for access From 0dba2886f0ceb390c5dbef83858d167ed4459be0 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 18:37:56 -0700 Subject: [PATCH 09/40] fix test --- tests/llm_responses_api_testing/test_openai_responses_api.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/llm_responses_api_testing/test_openai_responses_api.py b/tests/llm_responses_api_testing/test_openai_responses_api.py index b3cd88190b..333f99f9d4 100644 --- a/tests/llm_responses_api_testing/test_openai_responses_api.py +++ b/tests/llm_responses_api_testing/test_openai_responses_api.py @@ -804,7 +804,7 @@ async def test_openai_o1_pro_response_api(sync_mode): print("Response:", json.dumps(response, indent=4, default=str)) # Check that the response has the expected structure - assert response["id"] == mock_response["id"] + assert response["id"] is not None assert response["status"] == "incomplete" assert response["incomplete_details"].reason == "max_output_tokens" assert response["max_output_tokens"] == 20 From 5f98d4d7de0ff0e1d475386e0276059518a2d180 Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Tue, 22 Apr 2025 19:59:53 -0700 Subject: [PATCH 10/40] UI - Users page - Enable global sorting (allows finding users with highest spend) (#10211) * fix(view_users.tsx): add time tracking logic to debounce search - prevent new queries from being overwritten by previous ones * fix(internal_user_endpoints.py): add sort functionality to user list endpoint * feat(internal_user_endpoints.py): support sort by on `/user/list` * fix(view_users.tsx): enable global sorting allows finding user with highest spend * feat(view_users.tsx): support filtering by sso user id * test(search_users.spec.ts): add tests to ensure filtering works * test: add more unit testing --- .../internal_user_endpoints.py | 71 +++++++++++++- .../test_internal_user_endpoints.py | 16 +++ .../e2e_ui_tests/search_users.spec.ts | 97 ++++++++++++++++++- .../src/components/networking.tsx | 15 +++ .../src/components/view_users.tsx | 73 ++++++++++++-- .../src/components/view_users/table.tsx | 32 +++++- 6 files changed, 287 insertions(+), 17 deletions(-) diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py index 0d6c9ee622..2a019f4cb1 100644 --- a/litellm/proxy/management_endpoints/internal_user_endpoints.py +++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py @@ -902,6 +902,42 @@ async def get_user_key_counts( return result +def _validate_sort_params( + sort_by: Optional[str], sort_order: str +) -> Optional[Dict[str, str]]: + order_by: Dict[str, str] = {} + + if sort_by is None: + return None + # Validate sort_by is a valid column + valid_columns = [ + "user_id", + "user_email", + "created_at", + "spend", + "user_alias", + "user_role", + ] + if sort_by not in valid_columns: + raise HTTPException( + status_code=400, + detail={ + "error": f"Invalid sort column. Must be one of: {', '.join(valid_columns)}" + }, + ) + + # Validate sort_order + if sort_order.lower() not in ["asc", "desc"]: + raise HTTPException( + status_code=400, + detail={"error": "Invalid sort order. Must be 'asc' or 'desc'"}, + ) + + order_by[sort_by] = sort_order.lower() + + return order_by + + @router.get( "/user/list", tags=["Internal User management"], @@ -915,6 +951,9 @@ async def get_users( user_ids: Optional[str] = fastapi.Query( default=None, description="Get list of users by user_ids" ), + sso_user_ids: Optional[str] = fastapi.Query( + default=None, description="Get list of users by sso_user_id" + ), user_email: Optional[str] = fastapi.Query( default=None, description="Filter users by partial email match" ), @@ -925,9 +964,16 @@ async def get_users( page_size: int = fastapi.Query( default=25, ge=1, le=100, description="Number of items per page" ), + sort_by: Optional[str] = fastapi.Query( + default=None, + description="Column to sort by (e.g. 'user_id', 'user_email', 'created_at', 'spend')", + ), + sort_order: str = fastapi.Query( + default="asc", description="Sort order ('asc' or 'desc')" + ), ): """ - Get a paginated list of users with filtering options. + Get a paginated list of users with filtering and sorting options. Parameters: role: Optional[str] @@ -938,6 +984,8 @@ async def get_users( - internal_user_viewer user_ids: Optional[str] Get list of users by user_ids. Comma separated list of user_ids. + sso_ids: Optional[str] + Get list of users by sso_ids. Comma separated list of sso_ids. user_email: Optional[str] Filter users by partial email match team: Optional[str] @@ -946,9 +994,10 @@ async def get_users( The page number to return page_size: int The number of items per page - - Returns: - UserListResponse with filtered and paginated users + sort_by: Optional[str] + Column to sort by (e.g. 'user_id', 'user_email', 'created_at', 'spend') + sort_order: Optional[str] + Sort order ('asc' or 'desc') """ from litellm.proxy.proxy_server import prisma_client @@ -984,13 +1033,25 @@ async def get_users( "has": team # Array contains for string arrays in Prisma } + if sso_user_ids is not None and isinstance(sso_user_ids, str): + sso_id_list = [sid.strip() for sid in sso_user_ids.split(",") if sid.strip()] + where_conditions["sso_user_id"] = { + "in": sso_id_list, + } + ## Filter any none fastapi.Query params - e.g. where_conditions: {'user_email': {'contains': Query(None), 'mode': 'insensitive'}, 'teams': {'has': Query(None)}} where_conditions = {k: v for k, v in where_conditions.items() if v is not None} + + # Build order_by conditions + order_by: Optional[Dict[str, str]] = _validate_sort_params(sort_by, sort_order) + users = await prisma_client.db.litellm_usertable.find_many( where=where_conditions, skip=skip, take=page_size, - order={"created_at": "desc"}, + order=order_by + if order_by + else {"created_at": "desc"}, # Default to created_at desc if no sort specified ) # Get total count of user rows diff --git a/tests/litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/litellm/proxy/management_endpoints/test_internal_user_endpoints.py index deef94c15a..360f21f171 100644 --- a/tests/litellm/proxy/management_endpoints/test_internal_user_endpoints.py +++ b/tests/litellm/proxy/management_endpoints/test_internal_user_endpoints.py @@ -153,3 +153,19 @@ async def test_get_users_includes_timestamps(mocker): assert user_response.created_at == mock_user_data["created_at"] assert user_response.updated_at == mock_user_data["updated_at"] assert user_response.key_count == 0 + + +def test_validate_sort_params(): + """ + Test that validate_sort_params returns None if sort_by is None + """ + from litellm.proxy.management_endpoints.internal_user_endpoints import ( + _validate_sort_params, + ) + + assert _validate_sort_params(None, "asc") is None + assert _validate_sort_params(None, "desc") is None + assert _validate_sort_params("user_id", "asc") == {"user_id": "asc"} + assert _validate_sort_params("user_id", "desc") == {"user_id": "desc"} + with pytest.raises(Exception): + _validate_sort_params("user_id", "invalid") diff --git a/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts b/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts index ef5dfa6c0c..7b9da6a27d 100644 --- a/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts +++ b/tests/proxy_admin_ui_tests/e2e_ui_tests/search_users.spec.ts @@ -7,6 +7,7 @@ Tests: 2. Verify search input exists 3. Test search functionality 4. Verify results update +5. Test filtering by email, user ID, and SSO user ID */ import { test, expect } from "@playwright/test"; @@ -61,7 +62,7 @@ test("user search test", async ({ page }) => { console.log("Clicked Internal User tab"); // Wait for the page to load and table to be visible - await page.waitForSelector("tbody tr", { timeout: 10000 }); + await page.waitForSelector("tbody tr", { timeout: 30000 }); await page.waitForTimeout(2000); // Additional wait for table to stabilize console.log("Table is visible"); @@ -117,3 +118,97 @@ test("user search test", async ({ page }) => { expect(resetUserCount).toBe(initialUserCount); }); + +test("user filter test", async ({ page }) => { + // Set a longer timeout for the entire test + test.setTimeout(60000); + + // Enable console logging + page.on("console", (msg) => console.log("PAGE LOG:", msg.text())); + + // Login first + await page.goto("http://localhost:4000/ui"); + console.log("Navigated to login page"); + + // Wait for login form to be visible + await page.waitForSelector('input[name="username"]', { timeout: 10000 }); + console.log("Login form is visible"); + + await page.fill('input[name="username"]', "admin"); + await page.fill('input[name="password"]', "gm"); + console.log("Filled login credentials"); + + const loginButton = page.locator('input[type="submit"]'); + await expect(loginButton).toBeEnabled(); + await loginButton.click(); + console.log("Clicked login button"); + + // Wait for navigation to complete and dashboard to load + await page.waitForLoadState("networkidle"); + console.log("Page loaded after login"); + + // Navigate to Internal Users tab + const internalUserTab = page.locator("span.ant-menu-title-content", { + hasText: "Internal User", + }); + await internalUserTab.waitFor({ state: "visible", timeout: 10000 }); + await internalUserTab.click(); + console.log("Clicked Internal User tab"); + + // Wait for the page to load and table to be visible + await page.waitForSelector("tbody tr", { timeout: 30000 }); + await page.waitForTimeout(2000); // Additional wait for table to stabilize + console.log("Table is visible"); + + // Get initial user count + const initialUserCount = await page.locator("tbody tr").count(); + console.log(`Initial user count: ${initialUserCount}`); + + // Click the filter button to show additional filters + const filterButton = page.getByRole("button", { + name: "Filters", + exact: true, + }); + await filterButton.click(); + console.log("Clicked filter button"); + await page.waitForTimeout(500); // Wait for filters to appear + + // Test user ID filter + const userIdInput = page.locator('input[placeholder="Filter by User ID"]'); + await expect(userIdInput).toBeVisible(); + console.log("User ID filter is visible"); + + await userIdInput.fill("user"); + console.log("Filled user ID filter"); + await page.waitForTimeout(1000); + const userIdFilteredCount = await page.locator("tbody tr").count(); + console.log(`User ID filtered count: ${userIdFilteredCount}`); + expect(userIdFilteredCount).toBeLessThan(initialUserCount); + + // Clear user ID filter + await userIdInput.clear(); + await page.waitForTimeout(1000); + console.log("Cleared user ID filter"); + + // Test SSO user ID filter + const ssoUserIdInput = page.locator('input[placeholder="Filter by SSO ID"]'); + await expect(ssoUserIdInput).toBeVisible(); + console.log("SSO user ID filter is visible"); + + await ssoUserIdInput.fill("sso"); + console.log("Filled SSO user ID filter"); + await page.waitForTimeout(1000); + const ssoUserIdFilteredCount = await page.locator("tbody tr").count(); + console.log(`SSO user ID filtered count: ${ssoUserIdFilteredCount}`); + expect(ssoUserIdFilteredCount).toBeLessThan(initialUserCount); + + // Clear SSO user ID filter + await ssoUserIdInput.clear(); + await page.waitForTimeout(5000); + console.log("Cleared SSO user ID filter"); + + // Verify count returns to initial after clearing all filters + const finalUserCount = await page.locator("tbody tr").count(); + console.log(`Final user count: ${finalUserCount}`); + expect(finalUserCount).toBe(initialUserCount); +}); diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx index a1fdf7d073..8049899179 100644 --- a/ui/litellm-dashboard/src/components/networking.tsx +++ b/ui/litellm-dashboard/src/components/networking.tsx @@ -679,6 +679,9 @@ export const userListCall = async ( userEmail: string | null = null, userRole: string | null = null, team: string | null = null, + sso_user_id: string | null = null, + sortBy: string | null = null, + sortOrder: 'asc' | 'desc' | null = null, ) => { /** * Get all available teams on proxy @@ -713,6 +716,18 @@ export const userListCall = async ( if (team) { queryParams.append('team', team); } + + if (sso_user_id) { + queryParams.append('sso_user_ids', sso_user_id); + } + + if (sortBy) { + queryParams.append('sort_by', sortBy); + } + + if (sortOrder) { + queryParams.append('sort_order', sortOrder); + } const queryString = queryParams.toString(); if (queryString) { diff --git a/ui/litellm-dashboard/src/components/view_users.tsx b/ui/litellm-dashboard/src/components/view_users.tsx index 99ae2c979e..e50aa1d5b1 100644 --- a/ui/litellm-dashboard/src/components/view_users.tsx +++ b/ui/litellm-dashboard/src/components/view_users.tsx @@ -84,10 +84,13 @@ interface FilterState { email: string; user_id: string; user_role: string; + sso_user_id: string; team: string; model: string; min_spend: number | null; max_spend: number | null; + sort_by: string; + sort_order: 'asc' | 'desc'; } const isLocal = process.env.NODE_ENV === "development"; @@ -124,15 +127,19 @@ const ViewUserDashboard: React.FC = ({ email: "", user_id: "", user_role: "", + sso_user_id: "", team: "", model: "", min_spend: null, - max_spend: null + max_spend: null, + sort_by: "created_at", + sort_order: "desc" }); const [showFilters, setShowFilters] = useState(false); const [showColumnDropdown, setShowColumnDropdown] = useState(false); const [selectedFilter, setSelectedFilter] = useState("Email"); const filtersRef = useRef(null); + const lastSearchTimestamp = useRef(0); // check if window is not undefined if (typeof window !== "undefined") { @@ -150,6 +157,17 @@ const ViewUserDashboard: React.FC = ({ const handleFilterChange = (key: keyof FilterState, value: string | number | null) => { const newFilters = { ...filters, [key]: value }; setFilters(newFilters); + console.log("called from handleFilterChange - newFilters:", JSON.stringify(newFilters)); + debouncedSearch(newFilters); + }; + + const handleSortChange = (sortBy: string, sortOrder: 'asc' | 'desc') => { + const newFilters = { + ...filters, + sort_by: sortBy, + sort_order: sortOrder + }; + setFilters(newFilters); debouncedSearch(newFilters); }; @@ -159,6 +177,10 @@ const ViewUserDashboard: React.FC = ({ if (!accessToken || !token || !userRole || !userID) { return; } + + const currentTimestamp = Date.now(); + lastSearchTimestamp.current = currentTimestamp; + try { // Make the API call using userListCall with all filter parameters const data = await userListCall( @@ -168,12 +190,19 @@ const ViewUserDashboard: React.FC = ({ defaultPageSize, filters.email || null, filters.user_role || null, - filters.team || null + filters.team || null, + filters.sso_user_id || null, + filters.sort_by, + filters.sort_order ); - if (data) { - setUserListResponse(data); - console.log("called from debouncedSearch"); + // Only update state if this is the most recent search + if (currentTimestamp === lastSearchTimestamp.current) { + if (data) { + setUserListResponse(data); + console.log("called from debouncedSearch filters:", JSON.stringify(filters)); + console.log("called from debouncedSearch data:", JSON.stringify(data)); + } } } catch (error) { console.error("Error searching users:", error); @@ -252,6 +281,7 @@ const ViewUserDashboard: React.FC = ({ }; const refreshUserData = async () => { + console.log("called from refreshUserData"); if (!accessToken || !token || !userRole || !userID) { return; } @@ -291,7 +321,10 @@ const ViewUserDashboard: React.FC = ({ defaultPageSize, filters.email || null, filters.user_role || null, - filters.team || null + filters.team || null, + filters.sso_user_id || null, + filters.sort_by, + filters.sort_order ); // Update session storage with new data @@ -328,7 +361,10 @@ const ViewUserDashboard: React.FC = ({ defaultPageSize, filters.email || null, filters.user_role || null, - filters.team || null + filters.team || null, + filters.sso_user_id || null, + filters.sort_by, + filters.sort_order ); // Store in session storage @@ -462,9 +498,12 @@ const ViewUserDashboard: React.FC = ({ user_id: "", user_role: "", team: "", + sso_user_id: "", model: "", min_spend: null, - max_spend: null + max_spend: null, + sort_by: "created_at", + sort_order: "desc" }); }} > @@ -541,6 +580,17 @@ const ViewUserDashboard: React.FC = ({ ))}
+ + {/* SSO ID Search */} +
+ handleFilterChange('sso_user_id', e.target.value)} + /> +
)} @@ -591,9 +641,14 @@ const ViewUserDashboard: React.FC = ({
diff --git a/ui/litellm-dashboard/src/components/view_users/table.tsx b/ui/litellm-dashboard/src/components/view_users/table.tsx index c426b42127..e35852e67a 100644 --- a/ui/litellm-dashboard/src/components/view_users/table.tsx +++ b/ui/litellm-dashboard/src/components/view_users/table.tsx @@ -23,15 +23,25 @@ interface UserDataTableProps { data: UserInfo[]; columns: ColumnDef[]; isLoading?: boolean; + onSortChange?: (sortBy: string, sortOrder: 'asc' | 'desc') => void; + currentSort?: { + sortBy: string; + sortOrder: 'asc' | 'desc'; + }; } export function UserDataTable({ data = [], columns, isLoading = false, + onSortChange, + currentSort, }: UserDataTableProps) { const [sorting, setSorting] = React.useState([ - { id: "created_at", desc: true } + { + id: currentSort?.sortBy || "created_at", + desc: currentSort?.sortOrder === "desc" + } ]); const table = useReactTable({ @@ -40,12 +50,30 @@ export function UserDataTable({ state: { sorting, }, - onSortingChange: setSorting, + onSortingChange: (newSorting: any) => { + setSorting(newSorting); + if (newSorting.length > 0) { + const sortState = newSorting[0]; + const sortBy = sortState.id; + const sortOrder = sortState.desc ? 'desc' : 'asc'; + onSortChange?.(sortBy, sortOrder); + } + }, getCoreRowModel: getCoreRowModel(), getSortedRowModel: getSortedRowModel(), enableSorting: true, }); + // Update local sorting state when currentSort prop changes + React.useEffect(() => { + if (currentSort) { + setSorting([{ + id: currentSort.sortBy, + desc: currentSort.sortOrder === 'desc' + }]); + } + }, [currentSort]); + return (
From 96e31d205c710acb20f03ee950290f833fd3c1f6 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 21:34:51 -0700 Subject: [PATCH 11/40] feat: Added Missing Attributes For Arize & Phoenix Integration (#10043) (#10215) * feat: Added Missing Attributes For Arize & Phoenix Integration * chore: Added noqa for PLR0915 to suppress warning * chore: Moved Contributor Test to Correct Location * chore: Removed Redundant Fallback Co-authored-by: Ali Saleh --- litellm/integrations/_types/open_inference.py | 103 +++++++ litellm/integrations/arize/_utils.py | 251 ++++++++++++++---- .../integrations/arize/test_arize_utils.py | 231 ++++++++++++++++ .../test_arize_logging.py | 111 -------- 4 files changed, 540 insertions(+), 156 deletions(-) create mode 100644 tests/litellm/integrations/arize/test_arize_utils.py delete mode 100644 tests/logging_callback_tests/test_arize_logging.py diff --git a/litellm/integrations/_types/open_inference.py b/litellm/integrations/_types/open_inference.py index bcfabe9b7b..65ecadcf37 100644 --- a/litellm/integrations/_types/open_inference.py +++ b/litellm/integrations/_types/open_inference.py @@ -45,6 +45,14 @@ class SpanAttributes: """ The name of the model being used. """ + LLM_PROVIDER = "llm.provider" + """ + The provider of the model, such as OpenAI, Azure, Google, etc. + """ + LLM_SYSTEM = "llm.system" + """ + The AI product as identified by the client or server + """ LLM_PROMPTS = "llm.prompts" """ Prompts provided to a completions API. @@ -65,15 +73,40 @@ class SpanAttributes: """ Number of tokens in the prompt. """ + LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE = "llm.token_count.prompt_details.cache_write" + """ + Number of tokens in the prompt that were written to cache. + """ + LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ = "llm.token_count.prompt_details.cache_read" + """ + Number of tokens in the prompt that were read from cache. + """ + LLM_TOKEN_COUNT_PROMPT_DETAILS_AUDIO = "llm.token_count.prompt_details.audio" + """ + The number of audio input tokens presented in the prompt + """ LLM_TOKEN_COUNT_COMPLETION = "llm.token_count.completion" """ Number of tokens in the completion. """ + LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING = "llm.token_count.completion_details.reasoning" + """ + Number of tokens used for reasoning steps in the completion. + """ + LLM_TOKEN_COUNT_COMPLETION_DETAILS_AUDIO = "llm.token_count.completion_details.audio" + """ + The number of audio input tokens generated by the model + """ LLM_TOKEN_COUNT_TOTAL = "llm.token_count.total" """ Total number of tokens, including both prompt and completion. """ + LLM_TOOLS = "llm.tools" + """ + List of tools that are advertised to the LLM to be able to call + """ + TOOL_NAME = "tool.name" """ Name of the tool being used. @@ -112,6 +145,19 @@ class SpanAttributes: The id of the user """ + PROMPT_VENDOR = "prompt.vendor" + """ + The vendor or origin of the prompt, e.g. a prompt library, a specialized service, etc. + """ + PROMPT_ID = "prompt.id" + """ + A vendor-specific id used to locate the prompt. + """ + PROMPT_URL = "prompt.url" + """ + A vendor-specific url used to locate the prompt. + """ + class MessageAttributes: """ @@ -151,6 +197,10 @@ class MessageAttributes: The JSON string representing the arguments passed to the function during a function call. """ + MESSAGE_TOOL_CALL_ID = "message.tool_call_id" + """ + The id of the tool call. + """ class MessageContentAttributes: @@ -186,6 +236,25 @@ class ImageAttributes: """ +class AudioAttributes: + """ + Attributes for audio + """ + + AUDIO_URL = "audio.url" + """ + The url to an audio file + """ + AUDIO_MIME_TYPE = "audio.mime_type" + """ + The mime type of the audio file + """ + AUDIO_TRANSCRIPT = "audio.transcript" + """ + The transcript of the audio file + """ + + class DocumentAttributes: """ Attributes for a document. @@ -257,6 +326,10 @@ class ToolCallAttributes: Attributes for a tool call """ + TOOL_CALL_ID = "tool_call.id" + """ + The id of the tool call. + """ TOOL_CALL_FUNCTION_NAME = "tool_call.function.name" """ The name of function that is being called during a tool call. @@ -268,6 +341,18 @@ class ToolCallAttributes: """ +class ToolAttributes: + """ + Attributes for a tools + """ + + TOOL_JSON_SCHEMA = "tool.json_schema" + """ + The json schema of a tool input, It is RECOMMENDED that this be in the + OpenAI tool calling format: https://platform.openai.com/docs/assistants/tools + """ + + class OpenInferenceSpanKindValues(Enum): TOOL = "TOOL" CHAIN = "CHAIN" @@ -284,3 +369,21 @@ class OpenInferenceSpanKindValues(Enum): class OpenInferenceMimeTypeValues(Enum): TEXT = "text/plain" JSON = "application/json" + + +class OpenInferenceLLMSystemValues(Enum): + OPENAI = "openai" + ANTHROPIC = "anthropic" + COHERE = "cohere" + MISTRALAI = "mistralai" + VERTEXAI = "vertexai" + + +class OpenInferenceLLMProviderValues(Enum): + OPENAI = "openai" + ANTHROPIC = "anthropic" + COHERE = "cohere" + MISTRALAI = "mistralai" + GOOGLE = "google" + AZURE = "azure" + AWS = "aws" diff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.py index 5a090968b4..e93ef128b4 100644 --- a/litellm/integrations/arize/_utils.py +++ b/litellm/integrations/arize/_utils.py @@ -1,3 +1,4 @@ +import json from typing import TYPE_CHECKING, Any, Optional, Union from litellm._logging import verbose_logger @@ -12,36 +13,141 @@ else: Span = Any -def set_attributes(span: Span, kwargs, response_obj): +def cast_as_primitive_value_type(value) -> Union[str, bool, int, float]: + """ + Converts a value to an OTEL-supported primitive for Arize/Phoenix observability. + """ + if value is None: + return "" + if isinstance(value, (str, bool, int, float)): + return value + try: + return str(value) + except Exception: + return "" + + +def safe_set_attribute(span: Span, key: str, value: Any): + """ + Sets a span attribute safely with OTEL-compliant primitive typing for Arize/Phoenix. + """ + primitive_value = cast_as_primitive_value_type(value) + span.set_attribute(key, primitive_value) + + +def set_attributes(span: Span, kwargs, response_obj): # noqa: PLR0915 + """ + Populates span with OpenInference-compliant LLM attributes for Arize and Phoenix tracing. + """ from litellm.integrations._types.open_inference import ( MessageAttributes, OpenInferenceSpanKindValues, SpanAttributes, + ToolCallAttributes, ) try: + optional_params = kwargs.get("optional_params", {}) + litellm_params = kwargs.get("litellm_params", {}) standard_logging_payload: Optional[StandardLoggingPayload] = kwargs.get( "standard_logging_object" ) + if standard_logging_payload is None: + raise ValueError("standard_logging_object not found in kwargs") ############################################# ############ LLM CALL METADATA ############## ############################################# - if standard_logging_payload and ( - metadata := standard_logging_payload["metadata"] - ): - span.set_attribute(SpanAttributes.METADATA, safe_dumps(metadata)) + # Set custom metadata for observability and trace enrichment. + metadata = ( + standard_logging_payload.get("metadata") + if standard_logging_payload + else None + ) + if metadata is not None: + safe_set_attribute(span, SpanAttributes.METADATA, safe_dumps(metadata)) ############################################# ########## LLM Request Attributes ########### ############################################# - # The name of the LLM a request is being made to + # The name of the LLM a request is being made to. if kwargs.get("model"): - span.set_attribute(SpanAttributes.LLM_MODEL_NAME, kwargs.get("model")) + safe_set_attribute( + span, + SpanAttributes.LLM_MODEL_NAME, + kwargs.get("model"), + ) - span.set_attribute( + # The LLM request type. + safe_set_attribute( + span, + "llm.request.type", + standard_logging_payload["call_type"], + ) + + # The Generative AI Provider: Azure, OpenAI, etc. + safe_set_attribute( + span, + SpanAttributes.LLM_PROVIDER, + litellm_params.get("custom_llm_provider", "Unknown"), + ) + + # The maximum number of tokens the LLM generates for a request. + if optional_params.get("max_tokens"): + safe_set_attribute( + span, + "llm.request.max_tokens", + optional_params.get("max_tokens"), + ) + + # The temperature setting for the LLM request. + if optional_params.get("temperature"): + safe_set_attribute( + span, + "llm.request.temperature", + optional_params.get("temperature"), + ) + + # The top_p sampling setting for the LLM request. + if optional_params.get("top_p"): + safe_set_attribute( + span, + "llm.request.top_p", + optional_params.get("top_p"), + ) + + # Indicates whether response is streamed. + safe_set_attribute( + span, + "llm.is_streaming", + str(optional_params.get("stream", False)), + ) + + # Logs the user ID if present. + if optional_params.get("user"): + safe_set_attribute( + span, + "llm.user", + optional_params.get("user"), + ) + + # The unique identifier for the completion. + if response_obj and response_obj.get("id"): + safe_set_attribute(span, "llm.response.id", response_obj.get("id")) + + # The model used to generate the response. + if response_obj and response_obj.get("model"): + safe_set_attribute( + span, + "llm.response.model", + response_obj.get("model"), + ) + + # Required by OpenInference to mark span as LLM kind. + safe_set_attribute( + span, SpanAttributes.OPENINFERENCE_SPAN_KIND, OpenInferenceSpanKindValues.LLM.value, ) @@ -50,77 +156,132 @@ def set_attributes(span: Span, kwargs, response_obj): # for /chat/completions # https://docs.arize.com/arize/large-language-models/tracing/semantic-conventions if messages: - span.set_attribute( + last_message = messages[-1] + safe_set_attribute( + span, SpanAttributes.INPUT_VALUE, - messages[-1].get("content", ""), # get the last message for input + last_message.get("content", ""), ) - # LLM_INPUT_MESSAGES shows up under `input_messages` tab on the span page + # LLM_INPUT_MESSAGES shows up under `input_messages` tab on the span page. for idx, msg in enumerate(messages): - # Set the role per message - span.set_attribute( - f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}.{MessageAttributes.MESSAGE_ROLE}", - msg["role"], + prefix = f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}" + # Set the role per message. + safe_set_attribute( + span, f"{prefix}.{MessageAttributes.MESSAGE_ROLE}", msg.get("role") ) - # Set the content per message - span.set_attribute( - f"{SpanAttributes.LLM_INPUT_MESSAGES}.{idx}.{MessageAttributes.MESSAGE_CONTENT}", + # Set the content per message. + safe_set_attribute( + span, + f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}", msg.get("content", ""), ) - if standard_logging_payload and ( - model_params := standard_logging_payload["model_parameters"] - ): + # Capture tools (function definitions) used in the LLM call. + tools = optional_params.get("tools") + if tools: + for idx, tool in enumerate(tools): + function = tool.get("function") + if not function: + continue + prefix = f"{SpanAttributes.LLM_TOOLS}.{idx}" + safe_set_attribute( + span, f"{prefix}.{SpanAttributes.TOOL_NAME}", function.get("name") + ) + safe_set_attribute( + span, + f"{prefix}.{SpanAttributes.TOOL_DESCRIPTION}", + function.get("description"), + ) + safe_set_attribute( + span, + f"{prefix}.{SpanAttributes.TOOL_PARAMETERS}", + json.dumps(function.get("parameters")), + ) + + # Capture tool calls made during function-calling LLM flows. + functions = optional_params.get("functions") + if functions: + for idx, function in enumerate(functions): + prefix = f"{MessageAttributes.MESSAGE_TOOL_CALLS}.{idx}" + safe_set_attribute( + span, + f"{prefix}.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}", + function.get("name"), + ) + + # Capture invocation parameters and user ID if available. + model_params = ( + standard_logging_payload.get("model_parameters") + if standard_logging_payload + else None + ) + if model_params: # The Generative AI Provider: Azure, OpenAI, etc. - span.set_attribute( - SpanAttributes.LLM_INVOCATION_PARAMETERS, safe_dumps(model_params) + safe_set_attribute( + span, + SpanAttributes.LLM_INVOCATION_PARAMETERS, + safe_dumps(model_params), ) if model_params.get("user"): user_id = model_params.get("user") if user_id is not None: - span.set_attribute(SpanAttributes.USER_ID, user_id) + safe_set_attribute(span, SpanAttributes.USER_ID, user_id) ############################################# ########## LLM Response Attributes ########## - # https://docs.arize.com/arize/large-language-models/tracing/semantic-conventions ############################################# - if hasattr(response_obj, "get"): - for choice in response_obj.get("choices", []): - response_message = choice.get("message", {}) - span.set_attribute( - SpanAttributes.OUTPUT_VALUE, response_message.get("content", "") - ) - # This shows up under `output_messages` tab on the span page - # This code assumes a single response - span.set_attribute( - f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_ROLE}", - response_message.get("role"), - ) - span.set_attribute( - f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENT}", + # Captures response tokens, message, and content. + if hasattr(response_obj, "get"): + for idx, choice in enumerate(response_obj.get("choices", [])): + response_message = choice.get("message", {}) + safe_set_attribute( + span, + SpanAttributes.OUTPUT_VALUE, response_message.get("content", ""), ) - usage = response_obj.get("usage") + # This shows up under `output_messages` tab on the span page. + prefix = f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{idx}" + safe_set_attribute( + span, + f"{prefix}.{MessageAttributes.MESSAGE_ROLE}", + response_message.get("role"), + ) + safe_set_attribute( + span, + f"{prefix}.{MessageAttributes.MESSAGE_CONTENT}", + response_message.get("content", ""), + ) + + # Token usage info. + usage = response_obj and response_obj.get("usage") if usage: - span.set_attribute( + safe_set_attribute( + span, SpanAttributes.LLM_TOKEN_COUNT_TOTAL, usage.get("total_tokens"), ) # The number of tokens used in the LLM response (completion). - span.set_attribute( + safe_set_attribute( + span, SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, usage.get("completion_tokens"), ) # The number of tokens used in the LLM prompt. - span.set_attribute( + safe_set_attribute( + span, SpanAttributes.LLM_TOKEN_COUNT_PROMPT, usage.get("prompt_tokens"), ) - pass + except Exception as e: - verbose_logger.error(f"Error setting arize attributes: {e}") + verbose_logger.error( + f"[Arize/Phoenix] Failed to set OpenInference span attributes: {e}" + ) + if hasattr(span, "record_exception"): + span.record_exception(e) diff --git a/tests/litellm/integrations/arize/test_arize_utils.py b/tests/litellm/integrations/arize/test_arize_utils.py new file mode 100644 index 0000000000..bea42faaa8 --- /dev/null +++ b/tests/litellm/integrations/arize/test_arize_utils.py @@ -0,0 +1,231 @@ +import json +import os +import sys +from typing import Optional + +# Adds the grandparent directory to sys.path to allow importing project modules +sys.path.insert(0, os.path.abspath("../..")) + +import asyncio +import litellm +import pytest +from litellm.integrations.arize.arize import ArizeLogger +from litellm.integrations.custom_logger import CustomLogger +from litellm.integrations._types.open_inference import ( + SpanAttributes, + MessageAttributes, + ToolCallAttributes, +) +from litellm.types.utils import Choices, StandardCallbackDynamicParams + + +def test_arize_set_attributes(): + """ + Test setting attributes for Arize, including all custom LLM attributes. + Ensures that the correct span attributes are being added during a request. + """ + from unittest.mock import MagicMock + from litellm.types.utils import ModelResponse + + span = MagicMock() # Mocked tracing span to test attribute setting + + # Construct kwargs to simulate a real LLM request scenario + kwargs = { + "model": "gpt-4o", + "messages": [{"role": "user", "content": "Basic Request Content"}], + "standard_logging_object": { + "model_parameters": {"user": "test_user"}, + "metadata": {"key_1": "value_1", "key_2": None}, + "call_type": "completion", + }, + "optional_params": { + "max_tokens": "100", + "temperature": "1", + "top_p": "5", + "stream": False, + "user": "test_user", + "tools": [ + { + "function": { + "name": "get_weather", + "description": "Fetches weather details.", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "City name", + } + }, + "required": ["location"], + }, + } + } + ], + "functions": [{"name": "get_weather"}, {"name": "get_stock_price"}], + }, + "litellm_params": {"custom_llm_provider": "openai"}, + } + + # Simulated LLM response object + response_obj = ModelResponse( + usage={"total_tokens": 100, "completion_tokens": 60, "prompt_tokens": 40}, + choices=[ + Choices(message={"role": "assistant", "content": "Basic Response Content"}) + ], + model="gpt-4o", + id="chatcmpl-ID", + ) + + # Apply attribute setting via ArizeLogger + ArizeLogger.set_arize_attributes(span, kwargs, response_obj) + + # Validate that the expected number of attributes were set + assert span.set_attribute.call_count == 28 + + # Metadata attached to the span + span.set_attribute.assert_any_call( + SpanAttributes.METADATA, json.dumps({"key_1": "value_1", "key_2": None}) + ) + + # Basic LLM information + span.set_attribute.assert_any_call(SpanAttributes.LLM_MODEL_NAME, "gpt-4o") + span.set_attribute.assert_any_call("llm.request.type", "completion") + span.set_attribute.assert_any_call(SpanAttributes.LLM_PROVIDER, "openai") + + # LLM generation parameters + span.set_attribute.assert_any_call("llm.request.max_tokens", "100") + span.set_attribute.assert_any_call("llm.request.temperature", "1") + span.set_attribute.assert_any_call("llm.request.top_p", "5") + + # Streaming and user info + span.set_attribute.assert_any_call("llm.is_streaming", "False") + span.set_attribute.assert_any_call("llm.user", "test_user") + + # Response metadata + span.set_attribute.assert_any_call("llm.response.id", "chatcmpl-ID") + span.set_attribute.assert_any_call("llm.response.model", "gpt-4o") + span.set_attribute.assert_any_call(SpanAttributes.OPENINFERENCE_SPAN_KIND, "LLM") + + # Request message content and metadata + span.set_attribute.assert_any_call( + SpanAttributes.INPUT_VALUE, "Basic Request Content" + ) + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_INPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_ROLE}", + "user", + ) + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_INPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENT}", + "Basic Request Content", + ) + + # Tool call definitions and function names + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_TOOLS}.0.{SpanAttributes.TOOL_NAME}", "get_weather" + ) + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_TOOLS}.0.{SpanAttributes.TOOL_DESCRIPTION}", + "Fetches weather details.", + ) + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_TOOLS}.0.{SpanAttributes.TOOL_PARAMETERS}", + json.dumps( + { + "type": "object", + "properties": { + "location": {"type": "string", "description": "City name"} + }, + "required": ["location"], + } + ), + ) + + # Tool calls captured from optional_params + span.set_attribute.assert_any_call( + f"{MessageAttributes.MESSAGE_TOOL_CALLS}.0.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}", + "get_weather", + ) + span.set_attribute.assert_any_call( + f"{MessageAttributes.MESSAGE_TOOL_CALLS}.1.{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}", + "get_stock_price", + ) + + # Invocation parameters + span.set_attribute.assert_any_call( + SpanAttributes.LLM_INVOCATION_PARAMETERS, '{"user": "test_user"}' + ) + + # User ID + span.set_attribute.assert_any_call(SpanAttributes.USER_ID, "test_user") + + # Output message content + span.set_attribute.assert_any_call( + SpanAttributes.OUTPUT_VALUE, "Basic Response Content" + ) + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_ROLE}", + "assistant", + ) + span.set_attribute.assert_any_call( + f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.0.{MessageAttributes.MESSAGE_CONTENT}", + "Basic Response Content", + ) + + # Token counts + span.set_attribute.assert_any_call(SpanAttributes.LLM_TOKEN_COUNT_TOTAL, 100) + span.set_attribute.assert_any_call(SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, 60) + span.set_attribute.assert_any_call(SpanAttributes.LLM_TOKEN_COUNT_PROMPT, 40) + + +class TestArizeLogger(CustomLogger): + """ + Custom logger implementation to capture standard_callback_dynamic_params. + Used to verify that dynamic config keys are being passed to callbacks. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.standard_callback_dynamic_params: Optional[ + StandardCallbackDynamicParams + ] = None + + async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): + # Capture dynamic params and print them for verification + print("logged kwargs", json.dumps(kwargs, indent=4, default=str)) + self.standard_callback_dynamic_params = kwargs.get( + "standard_callback_dynamic_params" + ) + + +@pytest.mark.asyncio +async def test_arize_dynamic_params(): + """ + Test to ensure that dynamic Arize keys (API key and space key) + are received inside the callback logger at runtime. + """ + test_arize_logger = TestArizeLogger() + litellm.callbacks = [test_arize_logger] + + # Perform a mocked async completion call to trigger logging + await litellm.acompletion( + model="gpt-4o", + messages=[{"role": "user", "content": "Basic Request Content"}], + mock_response="test", + arize_api_key="test_api_key_dynamic", + arize_space_key="test_space_key_dynamic", + ) + + # Allow for async propagation + await asyncio.sleep(2) + + # Assert dynamic parameters were received in the callback + assert test_arize_logger.standard_callback_dynamic_params is not None + assert ( + test_arize_logger.standard_callback_dynamic_params.get("arize_api_key") + == "test_api_key_dynamic" + ) + assert ( + test_arize_logger.standard_callback_dynamic_params.get("arize_space_key") + == "test_space_key_dynamic" + ) diff --git a/tests/logging_callback_tests/test_arize_logging.py b/tests/logging_callback_tests/test_arize_logging.py deleted file mode 100644 index aca3ae9a02..0000000000 --- a/tests/logging_callback_tests/test_arize_logging.py +++ /dev/null @@ -1,111 +0,0 @@ -import os -import sys -import time -from unittest.mock import Mock, patch -import json -import opentelemetry.exporter.otlp.proto.grpc.trace_exporter -from typing import Optional - -sys.path.insert( - 0, os.path.abspath("../..") -) # Adds the parent directory to the system-path -from litellm.integrations._types.open_inference import SpanAttributes -from litellm.integrations.arize.arize import ArizeConfig, ArizeLogger -from litellm.integrations.custom_logger import CustomLogger -from litellm.main import completion -import litellm -from litellm.types.utils import Choices, StandardCallbackDynamicParams -import pytest -import asyncio - - -def test_arize_set_attributes(): - """ - Test setting attributes for Arize - """ - from unittest.mock import MagicMock - from litellm.types.utils import ModelResponse - - span = MagicMock() - kwargs = { - "role": "user", - "content": "simple arize test", - "model": "gpt-4o", - "messages": [{"role": "user", "content": "basic arize test"}], - "standard_logging_object": { - "model_parameters": {"user": "test_user"}, - "metadata": {"key": "value", "key2": None}, - }, - } - response_obj = ModelResponse( - usage={"total_tokens": 100, "completion_tokens": 60, "prompt_tokens": 40}, - choices=[Choices(message={"role": "assistant", "content": "response content"})], - ) - - ArizeLogger.set_arize_attributes(span, kwargs, response_obj) - - assert span.set_attribute.call_count == 14 - span.set_attribute.assert_any_call( - SpanAttributes.METADATA, json.dumps({"key": "value", "key2": None}) - ) - span.set_attribute.assert_any_call(SpanAttributes.LLM_MODEL_NAME, "gpt-4o") - span.set_attribute.assert_any_call(SpanAttributes.OPENINFERENCE_SPAN_KIND, "LLM") - span.set_attribute.assert_any_call(SpanAttributes.INPUT_VALUE, "basic arize test") - span.set_attribute.assert_any_call("llm.input_messages.0.message.role", "user") - span.set_attribute.assert_any_call( - "llm.input_messages.0.message.content", "basic arize test" - ) - span.set_attribute.assert_any_call( - SpanAttributes.LLM_INVOCATION_PARAMETERS, '{"user": "test_user"}' - ) - span.set_attribute.assert_any_call(SpanAttributes.USER_ID, "test_user") - span.set_attribute.assert_any_call(SpanAttributes.OUTPUT_VALUE, "response content") - span.set_attribute.assert_any_call( - "llm.output_messages.0.message.role", "assistant" - ) - span.set_attribute.assert_any_call( - "llm.output_messages.0.message.content", "response content" - ) - span.set_attribute.assert_any_call(SpanAttributes.LLM_TOKEN_COUNT_TOTAL, 100) - span.set_attribute.assert_any_call(SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, 60) - span.set_attribute.assert_any_call(SpanAttributes.LLM_TOKEN_COUNT_PROMPT, 40) - - -class TestArizeLogger(CustomLogger): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.standard_callback_dynamic_params: Optional[ - StandardCallbackDynamicParams - ] = None - - async def async_log_success_event(self, kwargs, response_obj, start_time, end_time): - print("logged kwargs", json.dumps(kwargs, indent=4, default=str)) - self.standard_callback_dynamic_params = kwargs.get( - "standard_callback_dynamic_params" - ) - - -@pytest.mark.asyncio -async def test_arize_dynamic_params(): - """verify arize ai dynamic params are recieved by a callback""" - test_arize_logger = TestArizeLogger() - litellm.callbacks = [test_arize_logger] - await litellm.acompletion( - model="gpt-4o", - messages=[{"role": "user", "content": "basic arize test"}], - mock_response="test", - arize_api_key="test_api_key_dynamic", - arize_space_key="test_space_key_dynamic", - ) - - await asyncio.sleep(2) - - assert test_arize_logger.standard_callback_dynamic_params is not None - assert ( - test_arize_logger.standard_callback_dynamic_params.get("arize_api_key") - == "test_api_key_dynamic" - ) - assert ( - test_arize_logger.standard_callback_dynamic_params.get("arize_space_key") - == "test_space_key_dynamic" - ) From 1e3a1cba2397e6c084f32a261eee5e8d3bcbc2b9 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Tue, 22 Apr 2025 21:35:23 -0700 Subject: [PATCH 12/40] =?UTF-8?q?bump:=20version=201.67.1=20=E2=86=92=201.?= =?UTF-8?q?67.2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 7c5558f7f4..c033ee5f33 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "litellm" -version = "1.67.1" +version = "1.67.2" description = "Library to easily interface with LLM API providers" authors = ["BerriAI"] license = "MIT" @@ -124,7 +124,7 @@ requires = ["poetry-core", "wheel"] build-backend = "poetry.core.masonry.api" [tool.commitizen] -version = "1.67.1" +version = "1.67.2" version_files = [ "pyproject.toml:^version" ] From 31f704a3705ab25ea25d2f06b29f77f850da593d Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Tue, 22 Apr 2025 21:41:13 -0700 Subject: [PATCH 13/40] fix(internal_user_endpoints.py): add check on sortby value --- .../proxy/management_endpoints/internal_user_endpoints.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.py index 2a019f4cb1..589b30d524 100644 --- a/litellm/proxy/management_endpoints/internal_user_endpoints.py +++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py @@ -1043,7 +1043,12 @@ async def get_users( where_conditions = {k: v for k, v in where_conditions.items() if v is not None} # Build order_by conditions - order_by: Optional[Dict[str, str]] = _validate_sort_params(sort_by, sort_order) + + order_by: Optional[Dict[str, str]] = ( + _validate_sort_params(sort_by, sort_order) + if sort_by is not None and isinstance(sort_by, str) + else None + ) users = await prisma_client.db.litellm_usertable.find_many( where=where_conditions, From f670ebeb2ff4d40c59fd6859fd12309cb34f4a49 Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Tue, 22 Apr 2025 21:55:47 -0700 Subject: [PATCH 14/40] Users page - new user info pane (#10213) * feat(user_info_view.tsx): be able to click in and see all teams user is part of makes it easy to see which teams a user belongs to * test(ui/): add unit testing for user info view * fix(user_info_view.tsx): fix linting errors * fix(login.ts): fix login * fix: fix linting error --- .../e2e_ui_tests/view_user_info.spec.ts | 82 +++++ tests/proxy_admin_ui_tests/utils/login.ts | 23 ++ .../src/components/networking.tsx | 6 +- .../src/components/view_users.tsx | 2 + .../src/components/view_users/table.tsx | 34 ++ .../components/view_users/user_info_view.tsx | 297 ++++++++++++++++++ 6 files changed, 442 insertions(+), 2 deletions(-) create mode 100644 tests/proxy_admin_ui_tests/e2e_ui_tests/view_user_info.spec.ts create mode 100644 tests/proxy_admin_ui_tests/utils/login.ts create mode 100644 ui/litellm-dashboard/src/components/view_users/user_info_view.tsx diff --git a/tests/proxy_admin_ui_tests/e2e_ui_tests/view_user_info.spec.ts b/tests/proxy_admin_ui_tests/e2e_ui_tests/view_user_info.spec.ts new file mode 100644 index 0000000000..cc138f0946 --- /dev/null +++ b/tests/proxy_admin_ui_tests/e2e_ui_tests/view_user_info.spec.ts @@ -0,0 +1,82 @@ +import { test, expect } from "@playwright/test"; +import { loginToUI } from "../utils/login"; + +test.describe("User Info View", () => { + test.beforeEach(async ({ page }) => { + await loginToUI(page); + // Navigate to users page + await page.goto("http://localhost:4000/ui?page=users"); + }); + + test("should display user info when clicking on user ID", async ({ + page, + }) => { + // Wait for users table to load + await page.waitForSelector("table"); + + // Get the first user ID cell + const firstUserIdCell = page.locator( + "table tbody tr:first-child td:first-child" + ); + const userId = await firstUserIdCell.textContent(); + console.log("Found user ID:", userId); + + // Click on the user ID + await firstUserIdCell.click(); + + // Wait for user info view to load + await page.waitForSelector('h1:has-text("User")'); + console.log("User info view loaded"); + + // Check for tabs + await expect(page.locator('button:has-text("Overview")')).toBeVisible(); + await expect(page.locator('button:has-text("Details")')).toBeVisible(); + + // Switch to details tab + await page.locator('button:has-text("Details")').click(); + + // Check details section + await expect(page.locator("text=User ID")).toBeVisible(); + await expect(page.locator("text=Email")).toBeVisible(); + + // Go back to users list + await page.locator('button:has-text("Back to Users")').click(); + + // Verify we're back on the users page + await expect(page.locator('h1:has-text("Users")')).toBeVisible(); + }); + + // test("should handle user deletion", async ({ page }) => { + // // Wait for users table to load + // await page.waitForSelector("table"); + + // // Get the first user ID cell + // const firstUserIdCell = page.locator( + // "table tbody tr:first-child td:first-child" + // ); + // const userId = await firstUserIdCell.textContent(); + + // // Click on the user ID + // await firstUserIdCell.click(); + + // // Wait for user info view to load + // await page.waitForSelector('h1:has-text("User")'); + + // // Click delete button + // await page.locator('button:has-text("Delete User")').click(); + + // // Confirm deletion in modal + // await page.locator('button:has-text("Delete")').click(); + + // // Verify success message + // await expect(page.locator("text=User deleted successfully")).toBeVisible(); + + // // Verify we're back on the users page + // await expect(page.locator('h1:has-text("Users")')).toBeVisible(); + + // // Verify user is no longer in the table + // if (userId) { + // await expect(page.locator(`text=${userId}`)).not.toBeVisible(); + // } + // }); +}); diff --git a/tests/proxy_admin_ui_tests/utils/login.ts b/tests/proxy_admin_ui_tests/utils/login.ts new file mode 100644 index 0000000000..e875508997 --- /dev/null +++ b/tests/proxy_admin_ui_tests/utils/login.ts @@ -0,0 +1,23 @@ +import { Page, expect } from "@playwright/test"; + +export async function loginToUI(page: Page) { + // Login first + await page.goto("http://localhost:4000/ui"); + console.log("Navigated to login page"); + + // Wait for login form to be visible + await page.waitForSelector('input[name="username"]', { timeout: 10000 }); + console.log("Login form is visible"); + + await page.fill('input[name="username"]', "admin"); + await page.fill('input[name="password"]', "gm"); + console.log("Filled login credentials"); + + const loginButton = page.locator('input[type="submit"]'); + await expect(loginButton).toBeEnabled(); + await loginButton.click(); + console.log("Clicked login button"); + + // Wait for navigation to complete + await page.waitForURL("**/*"); +} diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx index 8049899179..e518314e64 100644 --- a/ui/litellm-dashboard/src/components/networking.tsx +++ b/ui/litellm-dashboard/src/components/networking.tsx @@ -766,8 +766,10 @@ export const userInfoCall = async ( userRole: String, viewAll: Boolean = false, page: number | null, - page_size: number | null + page_size: number | null, + lookup_user_id: boolean = false ) => { + console.log(`userInfoCall: ${userID}, ${userRole}, ${viewAll}, ${page}, ${page_size}, ${lookup_user_id}`) try { let url: string; @@ -781,7 +783,7 @@ export const userInfoCall = async ( } else { // Use /user/info endpoint for individual user info url = proxyBaseUrl ? `${proxyBaseUrl}/user/info` : `/user/info`; - if (userRole === "Admin" || userRole === "Admin Viewer") { + if ((userRole === "Admin" || userRole === "Admin Viewer") && !lookup_user_id) { // do nothing } else if (userID) { url += `?user_id=${userID}`; diff --git a/ui/litellm-dashboard/src/components/view_users.tsx b/ui/litellm-dashboard/src/components/view_users.tsx index e50aa1d5b1..1fdcbc5a09 100644 --- a/ui/litellm-dashboard/src/components/view_users.tsx +++ b/ui/litellm-dashboard/src/components/view_users.tsx @@ -644,6 +644,8 @@ const ViewUserDashboard: React.FC = ({ data={userListResponse?.users || []} columns={tableColumns} isLoading={!userListResponse} + accessToken={accessToken} + userRole={userRole} onSortChange={handleSortChange} currentSort={{ sortBy: filters.sort_by, diff --git a/ui/litellm-dashboard/src/components/view_users/table.tsx b/ui/litellm-dashboard/src/components/view_users/table.tsx index e35852e67a..7674a6491f 100644 --- a/ui/litellm-dashboard/src/components/view_users/table.tsx +++ b/ui/litellm-dashboard/src/components/view_users/table.tsx @@ -18,6 +18,7 @@ import { } from "@tremor/react"; import { SwitchVerticalIcon, ChevronUpIcon, ChevronDownIcon } from "@heroicons/react/outline"; import { UserInfo } from "./types"; +import UserInfoView from "./user_info_view"; interface UserDataTableProps { data: UserInfo[]; @@ -28,6 +29,8 @@ interface UserDataTableProps { sortBy: string; sortOrder: 'asc' | 'desc'; }; + accessToken: string | null; + userRole: string | null; } export function UserDataTable({ @@ -36,6 +39,8 @@ export function UserDataTable({ isLoading = false, onSortChange, currentSort, + accessToken, + userRole, }: UserDataTableProps) { const [sorting, setSorting] = React.useState([ { @@ -43,6 +48,7 @@ export function UserDataTable({ desc: currentSort?.sortOrder === "desc" } ]); + const [selectedUserId, setSelectedUserId] = React.useState(null); const table = useReactTable({ data, @@ -64,6 +70,14 @@ export function UserDataTable({ enableSorting: true, }); + const handleUserClick = (userId: string) => { + setSelectedUserId(userId); + }; + + const handleCloseUserInfo = () => { + setSelectedUserId(null); + }; + // Update local sorting state when currentSort prop changes React.useEffect(() => { if (currentSort) { @@ -74,6 +88,17 @@ export function UserDataTable({ } }, [currentSort]); + if (selectedUserId) { + return ( + + ); + } + return (
@@ -138,6 +163,15 @@ export function UserDataTable({ ? 'sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]' : '' }`} + onClick={() => { + if (cell.column.id === 'user_id') { + handleUserClick(cell.getValue() as string); + } + }} + style={{ + cursor: cell.column.id === 'user_id' ? 'pointer' : 'default', + color: cell.column.id === 'user_id' ? '#3b82f6' : 'inherit', + }} > {flexRender(cell.column.columnDef.cell, cell.getContext())} diff --git a/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx b/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx new file mode 100644 index 0000000000..4e82f20821 --- /dev/null +++ b/ui/litellm-dashboard/src/components/view_users/user_info_view.tsx @@ -0,0 +1,297 @@ +import React, { useState } from "react"; +import { + Card, + Text, + Button, + Grid, + Col, + Tab, + TabList, + TabGroup, + TabPanel, + TabPanels, + Title, + Badge, +} from "@tremor/react"; +import { ArrowLeftIcon, TrashIcon } from "@heroicons/react/outline"; +import { userInfoCall, userDeleteCall } from "../networking"; +import { message } from "antd"; +import { rolesWithWriteAccess } from '../../utils/roles'; + +interface UserInfoViewProps { + userId: string; + onClose: () => void; + accessToken: string | null; + userRole: string | null; + onDelete?: () => void; +} + +interface UserInfo { + user_id: string; + user_info: { + user_email: string | null; + user_role: string | null; + teams: any[] | null; + models: string[] | null; + max_budget: number | null; + spend: number | null; + metadata: Record | null; + created_at: string | null; + updated_at: string | null; + }; + keys: any[] | null; + teams: any[] | null; +} + +export default function UserInfoView({ userId, onClose, accessToken, userRole, onDelete }: UserInfoViewProps) { + const [userData, setUserData] = useState(null); + const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); + const [isLoading, setIsLoading] = useState(true); + + React.useEffect(() => { + console.log(`userId: ${userId}, userRole: ${userRole}, accessToken: ${accessToken}`) + const fetchUserData = async () => { + try { + if (!accessToken) return; + const data = await userInfoCall(accessToken, userId, userRole || "", false, null, null, true); + setUserData(data); + } catch (error) { + console.error("Error fetching user data:", error); + message.error("Failed to fetch user data"); + } finally { + setIsLoading(false); + } + }; + + fetchUserData(); + }, [accessToken, userId, userRole]); + + const handleDelete = async () => { + try { + if (!accessToken) return; + await userDeleteCall(accessToken, [userId]); + message.success("User deleted successfully"); + if (onDelete) { + onDelete(); + } + onClose(); + } catch (error) { + console.error("Error deleting user:", error); + message.error("Failed to delete user"); + } + }; + + if (isLoading) { + return ( +
+ + Loading user data... +
+ ); + } + + if (!userData) { + return ( +
+ + User not found +
+ ); + } + + return ( +
+
+
+ + {userData.user_info?.user_email || "User"} + {userData.user_id} +
+ {userRole && rolesWithWriteAccess.includes(userRole) && ( + + )} +
+ + {/* Delete Confirmation Modal */} + {isDeleteModalOpen && ( +
+
+ + + + +
+
+
+
+

+ Delete User +

+
+

+ Are you sure you want to delete this user? +

+
+
+
+
+
+ + +
+
+
+
+ )} + + + + Overview + Details + + + + {/* Overview Panel */} + + + + Spend +
+ ${Number(userData.user_info?.spend || 0).toFixed(4)} + of {userData.user_info?.max_budget !== null ? `$${userData.user_info.max_budget}` : "Unlimited"} +
+
+ + + Teams +
+ {userData.teams?.length || 0} teams +
+
+ + + API Keys +
+ {userData.keys?.length || 0} keys +
+
+
+
+ + {/* Details Panel */} + + +
+
+ User ID + {userData.user_id} +
+ +
+ Email + {userData.user_info?.user_email || "Not Set"} +
+ +
+ Role + {userData.user_info?.user_role || "Not Set"} +
+ +
+ Created + {userData.user_info?.created_at ? new Date(userData.user_info.created_at).toLocaleString() : "Unknown"} +
+ +
+ Last Updated + {userData.user_info?.updated_at ? new Date(userData.user_info.updated_at).toLocaleString() : "Unknown"} +
+ +
+ Teams +
+ {userData.teams?.length && userData.teams?.length > 0 ? ( + userData.teams?.map((team, index) => ( + + {team.team_alias || team.team_id} + + )) + ) : ( + No teams + )} +
+
+ +
+ API Keys +
+ {userData.keys?.length && userData.keys?.length > 0 ? ( + userData.keys.map((key, index) => ( + + {key.key_alias || key.token} + + )) + ) : ( + No API keys + )} +
+
+ +
+ Metadata +
+                    {JSON.stringify(userData.user_info?.metadata || {}, null, 2)}
+                  
+
+
+
+
+
+
+
+ ); +} \ No newline at end of file From 217681eb5e5ad7d1a25ad0c7cd4f9c149a5ccc39 Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Tue, 22 Apr 2025 23:58:43 -0700 Subject: [PATCH 15/40] Litellm dev 04 22 2025 p1 (#10206) * fix(openai.py): initial commit adding generic event type for openai responses api streaming Ensures handling for undocumented event types - e.g. "response.reasoning_summary_part.added" * fix(transformation.py): handle unknown openai response type * fix(datadog_llm_observability.py): handle dict[str, any] -> dict[str, str] conversion Fixes https://github.com/BerriAI/litellm/issues/9494 * test: add more unit testing * test: add unit test * fix(common_utils.py): fix message with content list * test: update testing --- .../integrations/datadog/datadog_llm_obs.py | 16 ++++- .../prompt_templates/common_utils.py | 31 +++++++++- .../llms/openai/responses/transformation.py | 2 +- litellm/proxy/_new_secret_config.yaml | 2 +- litellm/proxy/proxy_server.py | 2 +- litellm/responses/streaming_iterator.py | 4 +- litellm/types/integrations/datadog_llm_obs.py | 4 +- litellm/types/llms/openai.py | 12 +++- ...ore_utils_prompt_templates_common_utils.py | 61 +++++++++++++++++++ .../test_openai_responses_transformation.py | 19 ++++++ .../types/llms/test_types_llms_openai.py | 21 +++++++ tests/llm_translation/test_openai.py | 1 + 12 files changed, 165 insertions(+), 10 deletions(-) create mode 100644 tests/litellm/types/llms/test_types_llms_openai.py diff --git a/litellm/integrations/datadog/datadog_llm_obs.py b/litellm/integrations/datadog/datadog_llm_obs.py index e4e074bab7..bbb042c57b 100644 --- a/litellm/integrations/datadog/datadog_llm_obs.py +++ b/litellm/integrations/datadog/datadog_llm_obs.py @@ -13,10 +13,15 @@ import uuid from datetime import datetime from typing import Any, Dict, List, Optional, Union +import httpx + import litellm from litellm._logging import verbose_logger from litellm.integrations.custom_batch_logger import CustomBatchLogger from litellm.integrations.datadog.datadog import DataDogLogger +from litellm.litellm_core_utils.prompt_templates.common_utils import ( + handle_any_messages_to_chat_completion_str_messages_conversion, +) from litellm.llms.custom_httpx.http_handler import ( get_async_httpx_client, httpxSpecialProvider, @@ -106,7 +111,6 @@ class DataDogLLMObsLogger(DataDogLogger, CustomBatchLogger): }, ) - response.raise_for_status() if response.status_code != 202: raise Exception( f"DataDogLLMObs: Unexpected response - status_code: {response.status_code}, text: {response.text}" @@ -116,6 +120,10 @@ class DataDogLLMObsLogger(DataDogLogger, CustomBatchLogger): f"DataDogLLMObs: Successfully sent batch - status_code: {response.status_code}" ) self.log_queue.clear() + except httpx.HTTPStatusError as e: + verbose_logger.exception( + f"DataDogLLMObs: Error sending batch - {e.response.text}" + ) except Exception as e: verbose_logger.exception(f"DataDogLLMObs: Error sending batch - {str(e)}") @@ -133,7 +141,11 @@ class DataDogLLMObsLogger(DataDogLogger, CustomBatchLogger): metadata = kwargs.get("litellm_params", {}).get("metadata", {}) - input_meta = InputMeta(messages=messages) # type: ignore + input_meta = InputMeta( + messages=handle_any_messages_to_chat_completion_str_messages_conversion( + messages + ) + ) output_meta = OutputMeta(messages=self._get_response_messages(response_obj)) meta = Meta( diff --git a/litellm/litellm_core_utils/prompt_templates/common_utils.py b/litellm/litellm_core_utils/prompt_templates/common_utils.py index 40cd4e286b..963ab33f52 100644 --- a/litellm/litellm_core_utils/prompt_templates/common_utils.py +++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py @@ -6,7 +6,7 @@ import io import mimetypes import re from os import PathLike -from typing import Dict, List, Literal, Mapping, Optional, Union, cast +from typing import Any, Dict, List, Literal, Mapping, Optional, Union, cast from litellm.types.llms.openai import ( AllMessageValues, @@ -32,6 +32,35 @@ DEFAULT_ASSISTANT_CONTINUE_MESSAGE = ChatCompletionAssistantMessage( ) +def handle_any_messages_to_chat_completion_str_messages_conversion( + messages: Any, +) -> List[Dict[str, str]]: + """ + Handles any messages to chat completion str messages conversion + + Relevant Issue: https://github.com/BerriAI/litellm/issues/9494 + """ + import json + + if isinstance(messages, list): + try: + return cast( + List[Dict[str, str]], + handle_messages_with_content_list_to_str_conversion(messages), + ) + except Exception: + return [{"input": json.dumps(message, default=str)} for message in messages] + elif isinstance(messages, dict): + try: + return [{"input": json.dumps(messages, default=str)}] + except Exception: + return [{"input": str(messages)}] + elif isinstance(messages, str): + return [{"input": messages}] + else: + return [{"input": str(messages)}] + + def handle_messages_with_content_list_to_str_conversion( messages: List[AllMessageValues], ) -> List[AllMessageValues]: diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py index d4a443aedb..ab16a5647d 100644 --- a/litellm/llms/openai/responses/transformation.py +++ b/litellm/llms/openai/responses/transformation.py @@ -187,7 +187,7 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): model_class = event_models.get(cast(ResponsesAPIStreamEvents, event_type)) if not model_class: - raise ValueError(f"Unknown event type: {event_type}") + return GenericEvent return model_class diff --git a/litellm/proxy/_new_secret_config.yaml b/litellm/proxy/_new_secret_config.yaml index 8516e9c25b..ad9ae99f7a 100644 --- a/litellm/proxy/_new_secret_config.yaml +++ b/litellm/proxy/_new_secret_config.yaml @@ -33,7 +33,7 @@ model_list: litellm_settings: num_retries: 0 - callbacks: ["prometheus"] + callbacks: ["datadog_llm_observability"] check_provider_endpoint: true files_settings: diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index 4ca6b35db4..fd32a62ee4 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -1296,7 +1296,7 @@ class ProxyConfig: config=config, base_dir=os.path.dirname(os.path.abspath(file_path or "")) ) - verbose_proxy_logger.debug(f"loaded config={json.dumps(config, indent=4)}") + # verbose_proxy_logger.debug(f"loaded config={json.dumps(config, indent=4)}") return config def _process_includes(self, config: dict, base_dir: str) -> dict: diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.py index 3e12761ba0..a111fbec09 100644 --- a/litellm/responses/streaming_iterator.py +++ b/litellm/responses/streaming_iterator.py @@ -44,12 +44,12 @@ class BaseResponsesAPIStreamingIterator: self.responses_api_provider_config = responses_api_provider_config self.completed_response: Optional[ResponsesAPIStreamingResponse] = None self.start_time = datetime.now() - + # set request kwargs self.litellm_metadata = litellm_metadata self.custom_llm_provider = custom_llm_provider - def _process_chunk(self, chunk): + def _process_chunk(self, chunk) -> Optional[ResponsesAPIStreamingResponse]: """Process a single chunk of data from the stream""" if not chunk: return None diff --git a/litellm/types/integrations/datadog_llm_obs.py b/litellm/types/integrations/datadog_llm_obs.py index 9298b157d2..1a0f7df501 100644 --- a/litellm/types/integrations/datadog_llm_obs.py +++ b/litellm/types/integrations/datadog_llm_obs.py @@ -8,7 +8,9 @@ from typing import Any, Dict, List, Literal, Optional, TypedDict class InputMeta(TypedDict): - messages: List[Any] + messages: List[ + Dict[str, str] + ] # Relevant Issue: https://github.com/BerriAI/litellm/issues/9494 class OutputMeta(TypedDict): diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py index 24aebf12af..dc45ebe5cc 100644 --- a/litellm/types/llms/openai.py +++ b/litellm/types/llms/openai.py @@ -50,7 +50,7 @@ from openai.types.responses.response_create_params import ( ToolParam, ) from openai.types.responses.response_function_tool_call import ResponseFunctionToolCall -from pydantic import BaseModel, Discriminator, Field, PrivateAttr +from pydantic import BaseModel, ConfigDict, Discriminator, Field, PrivateAttr from typing_extensions import Annotated, Dict, Required, TypedDict, override from litellm.types.llms.base import BaseLiteLLMOpenAIResponseObject @@ -1013,6 +1013,9 @@ class ResponsesAPIStreamEvents(str, Enum): RESPONSE_FAILED = "response.failed" RESPONSE_INCOMPLETE = "response.incomplete" + # Part added + RESPONSE_PART_ADDED = "response.reasoning_summary_part.added" + # Output item events OUTPUT_ITEM_ADDED = "response.output_item.added" OUTPUT_ITEM_DONE = "response.output_item.done" @@ -1200,6 +1203,12 @@ class ErrorEvent(BaseLiteLLMOpenAIResponseObject): param: Optional[str] +class GenericEvent(BaseLiteLLMOpenAIResponseObject): + type: str + + model_config = ConfigDict(extra="allow", protected_namespaces=()) + + # Union type for all possible streaming responses ResponsesAPIStreamingResponse = Annotated[ Union[ @@ -1226,6 +1235,7 @@ ResponsesAPIStreamingResponse = Annotated[ WebSearchCallSearchingEvent, WebSearchCallCompletedEvent, ErrorEvent, + GenericEvent, ], Discriminator("type"), ] diff --git a/tests/litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py b/tests/litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py index aca0e02e17..1d349a44e5 100644 --- a/tests/litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py +++ b/tests/litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_common_utils.py @@ -11,6 +11,7 @@ sys.path.insert( from litellm.litellm_core_utils.prompt_templates.common_utils import ( get_format_from_file_id, + handle_any_messages_to_chat_completion_str_messages_conversion, update_messages_with_model_file_ids, ) @@ -64,3 +65,63 @@ def test_update_messages_with_model_file_ids(): ], } ] + + +def test_handle_any_messages_to_chat_completion_str_messages_conversion_list(): + # Test with list of messages + messages = [ + {"role": "user", "content": "Hello"}, + {"role": "assistant", "content": "Hi there"}, + ] + result = handle_any_messages_to_chat_completion_str_messages_conversion(messages) + assert len(result) == 2 + assert result[0] == messages[0] + assert result[1] == messages[1] + + +def test_handle_any_messages_to_chat_completion_str_messages_conversion_list_infinite_loop(): + # Test that list handling doesn't cause infinite recursion + messages = [ + {"role": "user", "content": "Hello"}, + {"role": "assistant", "content": "Hi there"}, + ] + # This should complete without stack overflow + result = handle_any_messages_to_chat_completion_str_messages_conversion(messages) + assert len(result) == 2 + assert result[0] == messages[0] + assert result[1] == messages[1] + + +def test_handle_any_messages_to_chat_completion_str_messages_conversion_dict(): + # Test with single dictionary message + message = {"role": "user", "content": "Hello"} + result = handle_any_messages_to_chat_completion_str_messages_conversion(message) + assert len(result) == 1 + assert result[0]["input"] == json.dumps(message) + + +def test_handle_any_messages_to_chat_completion_str_messages_conversion_str(): + # Test with string message + message = "Hello" + result = handle_any_messages_to_chat_completion_str_messages_conversion(message) + assert len(result) == 1 + assert result[0]["input"] == message + + +def test_handle_any_messages_to_chat_completion_str_messages_conversion_other(): + # Test with non-string/dict/list type + message = 123 + result = handle_any_messages_to_chat_completion_str_messages_conversion(message) + assert len(result) == 1 + assert result[0]["input"] == "123" + + +def test_handle_any_messages_to_chat_completion_str_messages_conversion_complex(): + # Test with complex nested structure + message = { + "role": "user", + "content": {"text": "Hello", "metadata": {"timestamp": "2024-01-01"}}, + } + result = handle_any_messages_to_chat_completion_str_messages_conversion(message) + assert len(result) == 1 + assert result[0]["input"] == json.dumps(message) diff --git a/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py b/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py index 3b9ae72da7..04b9de5616 100644 --- a/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py +++ b/tests/litellm/llms/openai/responses/test_openai_responses_transformation.py @@ -252,3 +252,22 @@ class TestOpenAIResponsesAPIConfig: ) assert result == "https://custom-openai.example.com/v1/responses" + + def test_get_event_model_class_generic_event(self): + """Test that get_event_model_class returns the correct event model class""" + from litellm.types.llms.openai import GenericEvent + + event_type = "test" + result = self.config.get_event_model_class(event_type) + assert result == GenericEvent + + def test_transform_streaming_response_generic_event(self): + """Test that transform_streaming_response returns the correct event model class""" + from litellm.types.llms.openai import GenericEvent + + chunk = {"type": "test", "test": "test"} + result = self.config.transform_streaming_response( + model=self.model, parsed_chunk=chunk, logging_obj=self.logging_obj + ) + assert isinstance(result, GenericEvent) + assert result.type == "test" diff --git a/tests/litellm/types/llms/test_types_llms_openai.py b/tests/litellm/types/llms/test_types_llms_openai.py new file mode 100644 index 0000000000..86c2cb3f1a --- /dev/null +++ b/tests/litellm/types/llms/test_types_llms_openai.py @@ -0,0 +1,21 @@ +import asyncio +import os +import sys +from typing import Optional +from unittest.mock import AsyncMock, patch + +import pytest + +sys.path.insert(0, os.path.abspath("../../..")) +import json + +import litellm + + +def test_generic_event(): + from litellm.types.llms.openai import GenericEvent + + event = {"type": "test", "test": "test"} + event = GenericEvent(**event) + assert event.type == "test" + assert event.test == "test" diff --git a/tests/llm_translation/test_openai.py b/tests/llm_translation/test_openai.py index 295bdb46f1..a470b53589 100644 --- a/tests/llm_translation/test_openai.py +++ b/tests/llm_translation/test_openai.py @@ -470,3 +470,4 @@ class TestOpenAIGPT4OAudioTranscription(BaseLLMAudioTranscriptionTest): def get_custom_llm_provider(self) -> litellm.LlmProviders: return litellm.LlmProviders.OPENAI + From f5996b2f6ba45ec3859a716e28f6e6eff0f7a0b3 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 00:01:02 -0700 Subject: [PATCH 16/40] test: update test to skip 'gemini-pro' - model deprecated --- tests/local_testing/test_amazing_vertex_completion.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.py index ec9b676772..54982fe6d8 100644 --- a/tests/local_testing/test_amazing_vertex_completion.py +++ b/tests/local_testing/test_amazing_vertex_completion.py @@ -454,6 +454,7 @@ async def test_async_vertexai_response(): or "002" in model or "gemini-2.0-flash-thinking-exp" in model or "gemini-2.0-pro-exp-02-05" in model + or "gemini-pro" in model ): # our account does not have access to this model continue @@ -501,6 +502,7 @@ async def test_async_vertexai_streaming_response(): or "002" in model or "gemini-2.0-flash-thinking-exp" in model or "gemini-2.0-pro-exp-02-05" in model + or "gemini-pro" in model ): # our account does not have access to this model continue From 34be7ffceb7356ff1fe2ff5570846274d4832a99 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos Orfanos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 23 Apr 2025 16:05:29 +0200 Subject: [PATCH 17/40] Discard duplicate sentence (#10231) --- security.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/security.md b/security.md index 35ec049193..d126dabcc6 100644 --- a/security.md +++ b/security.md @@ -22,9 +22,6 @@ - Audit Logs with retention policy - Control Allowed IP Addresses that can access your Cloud LiteLLM Instance -For security inquiries, please contact us at support@berri.ai - - For security inquiries, please contact us at support@berri.ai #### Supported data regions for LiteLLM Cloud From 47420d8d68b87325476c978b10abbe0518a2d70b Mon Sep 17 00:00:00 2001 From: Christian Owusu <36159205+crisshaker@users.noreply.github.com> Date: Wed, 23 Apr 2025 14:08:25 +0000 Subject: [PATCH 18/40] Require auth for all dashboard pages (#10229) * Require authentication for all Dashboard pages * Add test * Add test --- ...98bfca6820e.js => 117-1c5bfc45bfc4237d.js} | 0 .../static/chunks/250-7d480872c0e251dc.js | 1 + .../static/chunks/250-a927a558002d8fb9.js | 1 - ...f76eec1e568.js => 261-ee7f0f1f1c8c22a0.js} | 2 +- ...bbd712.js => 3014691f-b7b79b78e27792f3.js} | 0 .../static/chunks/42-59f99bfbf676f282.js | 1 - .../static/chunks/42-69f5b4e6a9942a9f.js | 1 + .../static/chunks/466-65538e7f331af98e.js | 14 ++--- ...36b70ac90c1.js => 699-2176ba2273e4676d.js} | 0 ...eaf6f21839c.js => 899-57685cedd1dcbc78.js} | 2 +- ...48357d161e.js => page-3b0daafcbe368586.js} | 0 ...94df7643.js => layout-311f9b6ff79980ae.js} | 2 +- ...783e81a6c1.js => page-a965e43ba9638156.js} | 2 +- .../app/onboarding/page-4f4c436bd23d48a0.js | 1 - .../app/onboarding/page-9598003bc1e91371.js | 1 + .../chunks/app/page-36914b80c40b5032.js | 1 + .../chunks/app/page-8f2fcc2af91a32fd.js | 1 - ...b8bb06.js => fd9d1056-205af899b895cbac.js} | 0 ...1a6d94.js => main-app-2b16cdb7ff4e1af7.js} | 2 +- .../out/_next/static/css/005c96178151b9fd.css | 3 + .../out/_next/static/css/3da1b0cfa7d4e161.css | 3 - .../_buildManifest.js | 0 .../_ssgManifest.js | 0 litellm/proxy/_experimental/out/index.html | 2 +- litellm/proxy/_experimental/out/index.txt | 4 +- litellm/proxy/_experimental/out/model_hub.txt | 4 +- .../proxy/_experimental/out/onboarding.html | 1 + .../proxy/_experimental/out/onboarding.txt | 4 +- .../e2e_ui_tests/redirect-fail-screenshot.png | Bin 0 -> 49131 bytes .../require_auth_for_dashboard.spec.ts | 31 ++++++++++ .../test-results/.last-run.json | 8 +-- ui/litellm-dashboard/out/404.html | 2 +- ...98bfca6820e.js => 117-1c5bfc45bfc4237d.js} | 0 .../static/chunks/250-7d480872c0e251dc.js | 1 + .../static/chunks/250-a927a558002d8fb9.js | 1 - ...f76eec1e568.js => 261-ee7f0f1f1c8c22a0.js} | 2 +- ...bbd712.js => 3014691f-b7b79b78e27792f3.js} | 0 .../static/chunks/42-59f99bfbf676f282.js | 1 - .../static/chunks/42-69f5b4e6a9942a9f.js | 1 + .../static/chunks/466-65538e7f331af98e.js | 14 ++--- ...36b70ac90c1.js => 699-2176ba2273e4676d.js} | 0 ...eaf6f21839c.js => 899-57685cedd1dcbc78.js} | 2 +- ...48357d161e.js => page-3b0daafcbe368586.js} | 0 ...94df7643.js => layout-311f9b6ff79980ae.js} | 2 +- ...783e81a6c1.js => page-a965e43ba9638156.js} | 2 +- .../app/onboarding/page-4f4c436bd23d48a0.js | 1 - .../app/onboarding/page-9598003bc1e91371.js | 1 + .../chunks/app/page-36914b80c40b5032.js | 1 + .../chunks/app/page-8f2fcc2af91a32fd.js | 1 - ...b8bb06.js => fd9d1056-205af899b895cbac.js} | 0 ...1a6d94.js => main-app-2b16cdb7ff4e1af7.js} | 2 +- .../out/_next/static/css/005c96178151b9fd.css | 3 + .../out/_next/static/css/3da1b0cfa7d4e161.css | 3 - .../_buildManifest.js | 0 .../_ssgManifest.js | 0 ui/litellm-dashboard/out/index.html | 2 +- ui/litellm-dashboard/out/index.txt | 4 +- ui/litellm-dashboard/out/model_hub.html | 2 +- ui/litellm-dashboard/out/model_hub.txt | 4 +- ui/litellm-dashboard/out/onboarding.html | 2 +- ui/litellm-dashboard/out/onboarding.txt | 4 +- ui/litellm-dashboard/package-lock.json | 50 ++++++++++++++--- ui/litellm-dashboard/package.json | 4 +- ui/litellm-dashboard/src/app/page.tsx | 32 ++++++++++- .../src/components/ui/ui-loading-spinner.tsx | 53 ++++++++++++++++++ .../src/hooks/use-safe-layout-effect.ts | 7 +++ ui/litellm-dashboard/src/lib/cva.config.ts | 8 +++ 67 files changed, 232 insertions(+), 72 deletions(-) rename litellm/proxy/_experimental/out/_next/static/chunks/{117-87ec698bfca6820e.js => 117-1c5bfc45bfc4237d.js} (100%) create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/250-a927a558002d8fb9.js rename litellm/proxy/_experimental/out/_next/static/chunks/{261-57d48f76eec1e568.js => 261-ee7f0f1f1c8c22a0.js} (99%) rename litellm/proxy/_experimental/out/_next/static/chunks/{3014691f-0b72c78cfebbd712.js => 3014691f-b7b79b78e27792f3.js} (100%) delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/42-59f99bfbf676f282.js create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/42-69f5b4e6a9942a9f.js rename ui/litellm-dashboard/out/_next/static/chunks/860-c1d8f124df444312.js => litellm/proxy/_experimental/out/_next/static/chunks/466-65538e7f331af98e.js (65%) rename litellm/proxy/_experimental/out/_next/static/chunks/{699-99a8a36b70ac90c1.js => 699-2176ba2273e4676d.js} (100%) rename litellm/proxy/_experimental/out/_next/static/chunks/{899-9af4feaf6f21839c.js => 899-57685cedd1dcbc78.js} (99%) rename litellm/proxy/_experimental/out/_next/static/chunks/app/_not-found/{page-8311f948357d161e.js => page-3b0daafcbe368586.js} (100%) rename litellm/proxy/_experimental/out/_next/static/chunks/app/{layout-429ad74a94df7643.js => layout-311f9b6ff79980ae.js} (59%) rename litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/{page-cde2fb783e81a6c1.js => page-a965e43ba9638156.js} (60%) delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-4f4c436bd23d48a0.js create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/page-36914b80c40b5032.js delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/page-8f2fcc2af91a32fd.js rename litellm/proxy/_experimental/out/_next/static/chunks/{fd9d1056-524b80e1a6b8bb06.js => fd9d1056-205af899b895cbac.js} (100%) rename litellm/proxy/_experimental/out/_next/static/chunks/{main-app-4f7318ae681a6d94.js => main-app-2b16cdb7ff4e1af7.js} (54%) create mode 100644 litellm/proxy/_experimental/out/_next/static/css/005c96178151b9fd.css delete mode 100644 litellm/proxy/_experimental/out/_next/static/css/3da1b0cfa7d4e161.css rename litellm/proxy/_experimental/out/_next/static/{FPIQgzUY81b7nl8zNun4_ => fzhvjOFL6KeNsWYrLD4ya}/_buildManifest.js (100%) rename litellm/proxy/_experimental/out/_next/static/{FPIQgzUY81b7nl8zNun4_ => fzhvjOFL6KeNsWYrLD4ya}/_ssgManifest.js (100%) create mode 100644 litellm/proxy/_experimental/out/onboarding.html create mode 100644 tests/proxy_admin_ui_tests/e2e_ui_tests/redirect-fail-screenshot.png create mode 100644 tests/proxy_admin_ui_tests/e2e_ui_tests/require_auth_for_dashboard.spec.ts rename ui/litellm-dashboard/out/_next/static/chunks/{117-87ec698bfca6820e.js => 117-1c5bfc45bfc4237d.js} (100%) create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/250-7d480872c0e251dc.js delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/250-a927a558002d8fb9.js rename ui/litellm-dashboard/out/_next/static/chunks/{261-57d48f76eec1e568.js => 261-ee7f0f1f1c8c22a0.js} (99%) rename ui/litellm-dashboard/out/_next/static/chunks/{3014691f-0b72c78cfebbd712.js => 3014691f-b7b79b78e27792f3.js} (100%) delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/42-59f99bfbf676f282.js create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/42-69f5b4e6a9942a9f.js rename litellm/proxy/_experimental/out/_next/static/chunks/860-c1d8f124df444312.js => ui/litellm-dashboard/out/_next/static/chunks/466-65538e7f331af98e.js (65%) rename ui/litellm-dashboard/out/_next/static/chunks/{699-99a8a36b70ac90c1.js => 699-2176ba2273e4676d.js} (100%) rename ui/litellm-dashboard/out/_next/static/chunks/{899-9af4feaf6f21839c.js => 899-57685cedd1dcbc78.js} (99%) rename ui/litellm-dashboard/out/_next/static/chunks/app/_not-found/{page-8311f948357d161e.js => page-3b0daafcbe368586.js} (100%) rename ui/litellm-dashboard/out/_next/static/chunks/app/{layout-429ad74a94df7643.js => layout-311f9b6ff79980ae.js} (59%) rename ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/{page-cde2fb783e81a6c1.js => page-a965e43ba9638156.js} (60%) delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-4f4c436bd23d48a0.js create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/page-36914b80c40b5032.js delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/page-8f2fcc2af91a32fd.js rename ui/litellm-dashboard/out/_next/static/chunks/{fd9d1056-524b80e1a6b8bb06.js => fd9d1056-205af899b895cbac.js} (100%) rename ui/litellm-dashboard/out/_next/static/chunks/{main-app-4f7318ae681a6d94.js => main-app-2b16cdb7ff4e1af7.js} (54%) create mode 100644 ui/litellm-dashboard/out/_next/static/css/005c96178151b9fd.css delete mode 100644 ui/litellm-dashboard/out/_next/static/css/3da1b0cfa7d4e161.css rename ui/litellm-dashboard/out/_next/static/{FPIQgzUY81b7nl8zNun4_ => fzhvjOFL6KeNsWYrLD4ya}/_buildManifest.js (100%) rename ui/litellm-dashboard/out/_next/static/{FPIQgzUY81b7nl8zNun4_ => fzhvjOFL6KeNsWYrLD4ya}/_ssgManifest.js (100%) create mode 100644 ui/litellm-dashboard/src/components/ui/ui-loading-spinner.tsx create mode 100644 ui/litellm-dashboard/src/hooks/use-safe-layout-effect.ts create mode 100644 ui/litellm-dashboard/src/lib/cva.config.ts diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/117-87ec698bfca6820e.js b/litellm/proxy/_experimental/out/_next/static/chunks/117-1c5bfc45bfc4237d.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/chunks/117-87ec698bfca6820e.js rename to litellm/proxy/_experimental/out/_next/static/chunks/117-1c5bfc45bfc4237d.js diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js b/litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js new file mode 100644 index 0000000000..3fb93afc11 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[250],{19250:function(e,t,o){o.d(t,{$I:function(){return K},AZ:function(){return D},Au:function(){return em},BL:function(){return eU},Br:function(){return b},E9:function(){return eZ},EB:function(){return te},EG:function(){return eX},EY:function(){return eK},Eb:function(){return C},FC:function(){return ei},Gh:function(){return eO},H1:function(){return v},H2:function(){return n},Hx:function(){return eg},I1:function(){return j},It:function(){return x},J$:function(){return ea},K8:function(){return d},K_:function(){return eY},LY:function(){return eI},Lp:function(){return eG},N3:function(){return eN},N8:function(){return ee},NL:function(){return e1},NV:function(){return f},Nc:function(){return ex},O3:function(){return eV},OD:function(){return e_},OU:function(){return eh},Of:function(){return S},Og:function(){return y},Ov:function(){return E},PT:function(){return X},Qg:function(){return eS},RQ:function(){return _},Rg:function(){return Q},Sb:function(){return eJ},So:function(){return et},TF:function(){return ta},Tj:function(){return e$},UM:function(){return e7},VA:function(){return G},Vt:function(){return eD},W_:function(){return V},X:function(){return er},XO:function(){return k},Xd:function(){return eT},Xm:function(){return F},YU:function(){return eL},Yo:function(){return J},Z9:function(){return R},Zr:function(){return m},a6:function(){return O},aC:function(){return to},ao:function(){return eq},b1:function(){return ed},cq:function(){return A},cu:function(){return eP},eH:function(){return Y},eZ:function(){return eF},fE:function(){return e8},fP:function(){return W},g:function(){return eQ},gX:function(){return eb},h3:function(){return es},hT:function(){return ej},hy:function(){return u},ix:function(){return H},j2:function(){return en},jA:function(){return eH},jE:function(){return ez},kK:function(){return p},kn:function(){return q},lP:function(){return h},lU:function(){return e4},lg:function(){return eE},mC:function(){return e9},mR:function(){return eo},mY:function(){return e5},m_:function(){return U},mp:function(){return eM},n$:function(){return ey},n9:function(){return e6},nd:function(){return e3},o6:function(){return $},oC:function(){return eC},ol:function(){return z},pf:function(){return eR},qI:function(){return g},qk:function(){return e0},qm:function(){return w},r1:function(){return tt},r6:function(){return B},rs:function(){return N},s0:function(){return L},sN:function(){return ev},t$:function(){return P},t0:function(){return ek},t3:function(){return eW},tB:function(){return e2},tN:function(){return el},u5:function(){return ec},um:function(){return eB},v9:function(){return ef},vh:function(){return eA},wX:function(){return T},wd:function(){return ew},xA:function(){return eu},xX:function(){return I},zg:function(){return ep}});var a=o(20347),r=o(41021);let n=null;console.log=function(){};let c=0,s=e=>new Promise(t=>setTimeout(t,e)),i=async e=>{let t=Date.now();t-c>6e4?(e.includes("Authentication Error - Expired Key")&&(r.ZP.info("UI Session Expired. Logging out."),c=t,await s(3e3),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",window.location.href="/"),c=t):console.log("Error suppressed to prevent spam:",e)},l="Authorization";function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Authorization";console.log("setGlobalLitellmHeaderName: ".concat(e)),l=e}let h=async()=>{let e=n?"".concat(n,"/openapi.json"):"/openapi.json",t=await fetch(e);return await t.json()},w=async e=>{try{let t=n?"".concat(n,"/get/litellm_model_cost_map"):"/get/litellm_model_cost_map",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}}),a=await o.json();return console.log("received litellm model cost data: ".concat(a)),a}catch(e){throw console.error("Failed to get model cost map:",e),e}},p=async(e,t)=>{try{let o=n?"".concat(n,"/model/new"):"/model/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text()||"Network response was not ok";throw r.ZP.error(e),Error(e)}let c=await a.json();return console.log("API Response:",c),r.ZP.destroy(),r.ZP.success("Model ".concat(t.model_name," created successfully"),2),c}catch(e){throw console.error("Failed to create key:",e),e}},u=async e=>{try{let t=n?"".concat(n,"/model/settings"):"/model/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){console.error("Failed to get model settings:",e)}},y=async(e,t)=>{console.log("model_id in model delete call: ".concat(t));try{let o=n?"".concat(n,"/model/delete"):"/model/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},f=async(e,t)=>{if(console.log("budget_id in budget delete call: ".concat(t)),null!=e)try{let o=n?"".concat(n,"/budget/delete"):"/budget/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},m=async(e,t)=>{try{console.log("Form Values in budgetCreateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/new"):"/budget/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},g=async(e,t)=>{try{console.log("Form Values in budgetUpdateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/update"):"/budget/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},k=async(e,t)=>{try{let o=n?"".concat(n,"/invitation/new"):"/invitation/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},_=async e=>{try{let t=n?"".concat(n,"/alerting/settings"):"/alerting/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},T=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/key/generate"):"/key/generate",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},E=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.auto_create_key=!1,o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/user/new"):"/user/new",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},j=async(e,t)=>{try{let o=n?"".concat(n,"/key/delete"):"/key/delete";console.log("in keyDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},C=async(e,t)=>{try{let o=n?"".concat(n,"/user/delete"):"/user/delete";console.log("in userDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_ids:t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete user(s):",e),e}},N=async(e,t)=>{try{let o=n?"".concat(n,"/team/delete"):"/team/delete";console.log("in teamDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},S=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,h=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null,w=arguments.length>9&&void 0!==arguments[9]?arguments[9]:null;try{let p=n?"".concat(n,"/user/list"):"/user/list";console.log("in userListCall");let u=new URLSearchParams;if(t&&t.length>0){let e=t.join(",");u.append("user_ids",e)}o&&u.append("page",o.toString()),a&&u.append("page_size",a.toString()),r&&u.append("user_email",r),c&&u.append("role",c),s&&u.append("team",s),d&&u.append("sso_user_ids",d),h&&u.append("sort_by",h),w&&u.append("sort_order",w);let y=u.toString();y&&(p+="?".concat(y));let f=await fetch(p,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!f.ok){let e=await f.text();throw i(e),Error("Network response was not ok")}let m=await f.json();return console.log("/user/list API Response:",m),m}catch(e){throw console.error("Failed to create key:",e),e}},b=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,c=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];console.log("userInfoCall: ".concat(t,", ").concat(o,", ").concat(a,", ").concat(r,", ").concat(c,", ").concat(s));try{let d;if(a){d=n?"".concat(n,"/user/list"):"/user/list";let e=new URLSearchParams;null!=r&&e.append("page",r.toString()),null!=c&&e.append("page_size",c.toString()),d+="?".concat(e.toString())}else d=n?"".concat(n,"/user/info"):"/user/info",("Admin"!==o&&"Admin Viewer"!==o||s)&&t&&(d+="?user_id=".concat(t));console.log("Requesting user data from:",d);let h=await fetch(d,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}let w=await h.json();return console.log("API Response:",w),w}catch(e){throw console.error("Failed to fetch user data:",e),e}},F=async(e,t)=>{try{let o=n?"".concat(n,"/team/info"):"/team/info";t&&(o="".concat(o,"?team_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},x=async function(e,t){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;try{let a=n?"".concat(n,"/team/list"):"/team/list";console.log("in teamInfoCall");let r=new URLSearchParams;o&&r.append("user_id",o.toString()),t&&r.append("organization_id",t.toString());let c=r.toString();c&&(a+="?".concat(c));let s=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log("/team/list API Response:",d),d}catch(e){throw console.error("Failed to create key:",e),e}},O=async e=>{try{let t=n?"".concat(n,"/team/available"):"/team/available";console.log("in availableTeamListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/team/available_teams API Response:",a),a}catch(e){throw e}},B=async e=>{try{let t=n?"".concat(n,"/organization/list"):"/organization/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},P=async(e,t)=>{try{let o=n?"".concat(n,"/organization/info"):"/organization/info";t&&(o="".concat(o,"?organization_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},v=async(e,t)=>{try{if(console.log("Form Values in organizationCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw console.error("Failed to parse metadata:",e),Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/organization/new"):"/organization/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},G=async(e,t)=>{try{console.log("Form Values in organizationUpdateCall:",t);let o=n?"".concat(n,"/organization/update"):"/organization/update",a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},A=async(e,t)=>{try{let o=n?"".concat(n,"/organization/delete"):"/organization/delete",a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Error deleting organization: ".concat(e))}return await a.json()}catch(e){throw console.error("Failed to delete organization:",e),e}},J=async(e,t)=>{try{let o=n?"".concat(n,"/utils/transform_request"):"/utils/transform_request",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},I=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;try{let r=n?"".concat(n,"/user/daily/activity"):"/user/daily/activity",c=new URLSearchParams;c.append("start_date",t.toISOString()),c.append("end_date",o.toISOString()),c.append("page_size","1000"),c.append("page",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}return await d.json()}catch(e){throw console.error("Failed to create key:",e),e}},R=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/tag/daily/activity"):"/tag/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("tags",r.join(","));let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},z=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/team/daily/activity"):"/team/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("team_ids",r.join(",")),s.append("exclude_team_ids","litellm-dashboard");let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},V=async e=>{try{let t=n?"".concat(n,"/onboarding/get_token"):"/onboarding/get_token";t+="?invite_link=".concat(e);let o=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},U=async(e,t,o,a)=>{let r=n?"".concat(n,"/onboarding/claim_token"):"/onboarding/claim_token";try{let n=await fetch(r,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({invitation_link:t,user_id:o,password:a})});if(!n.ok){let e=await n.text();throw i(e),Error("Network response was not ok")}let c=await n.json();return console.log(c),c}catch(e){throw console.error("Failed to delete key:",e),e}},L=async(e,t,o)=>{try{let a=n?"".concat(n,"/key/").concat(t,"/regenerate"):"/key/".concat(t,"/regenerate"),r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Regenerate key Response:",c),c}catch(e){throw console.error("Failed to regenerate key:",e),e}},M=!1,Z=null,D=async(e,t,o)=>{try{console.log("modelInfoCall:",e,t,o);let c=n?"".concat(n,"/v2/model/info"):"/v2/model/info";a.ZL.includes(o)||(c+="?user_models_only=true");let s=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw e+="error shown=".concat(M),M||(e.includes("No model list passed")&&(e="No Models Exist. Click Add Model to get started."),r.ZP.info(e,10),M=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{M=!1},1e4)),Error("Network response was not ok")}let i=await s.json();return console.log("modelInfoCall:",i),i}catch(e){throw console.error("Failed to create key:",e),e}},H=async(e,t)=>{try{let o=n?"".concat(n,"/v1/model/info"):"/v1/model/info";o+="?litellm_model_id=".concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");let r=await a.json();return console.log("modelInfoV1Call:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},q=async e=>{try{let t=n?"".concat(n,"/model_group/info"):"/model_group/info",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("modelHubCall:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},X=async e=>{try{let t=n?"".concat(n,"/get/allowed_ips"):"/get/allowed_ips",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw Error("Network response was not ok: ".concat(e))}let a=await o.json();return console.log("getAllowedIPs:",a),a.data}catch(e){throw console.error("Failed to get allowed IPs:",e),e}},Y=async(e,t)=>{try{let o=n?"".concat(n,"/add/allowed_ip"):"/add/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("addAllowedIP:",r),r}catch(e){throw console.error("Failed to add allowed IP:",e),e}},K=async(e,t)=>{try{let o=n?"".concat(n,"/delete/allowed_ip"):"/delete/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("deleteAllowedIP:",r),r}catch(e){throw console.error("Failed to delete allowed IP:",e),e}},$=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics"):"/model/metrics";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},Q=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/model/streaming_metrics"):"/model/streaming_metrics";t&&(r="".concat(r,"?_selected_model_group=").concat(t,"&startTime=").concat(o,"&endTime=").concat(a));let c=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},W=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/slow_responses"):"/model/metrics/slow_responses";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},ee=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/exceptions"):"/model/metrics/exceptions";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},et=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;console.log("in /models calls, globalLitellmHeaderName",l);try{let t=n?"".concat(n,"/models"):"/models",o=new URLSearchParams;!0===a&&o.append("return_wildcard_routes","True"),r&&o.append("team_id",r.toString()),o.toString()&&(t+="?".concat(o.toString()));let c=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},eo=async e=>{try{let t=n?"".concat(n,"/global/spend/teams"):"/global/spend/teams";console.log("in teamSpendLogsCall:",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ea=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/tags"):"/global/spend/tags";t&&o&&(r="".concat(r,"?start_date=").concat(t,"&end_date=").concat(o)),a&&(r+="".concat(r,"&tags=").concat(a.join(","))),console.log("in tagsSpendLogsCall:",r);let c=await fetch("".concat(r),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to create key:",e),e}},er=async e=>{try{let t=n?"".concat(n,"/global/spend/all_tag_names"):"/global/spend/all_tag_names";console.log("in global/spend/all_tag_names call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},en=async e=>{try{let t=n?"".concat(n,"/global/all_end_users"):"/global/all_end_users";console.log("in global/all_end_users call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ec=async(e,t)=>{try{let o=n?"".concat(n,"/user/filter/ui"):"/user/filter/ui";t.get("user_email")&&(o+="?user_email=".concat(t.get("user_email"))),t.get("user_id")&&(o+="?user_id=".concat(t.get("user_id")));let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},es=async(e,t,o,a,r,c,s,d,h)=>{try{let w=n?"".concat(n,"/spend/logs/ui"):"/spend/logs/ui",p=new URLSearchParams;t&&p.append("api_key",t),o&&p.append("team_id",o),a&&p.append("request_id",a),r&&p.append("start_date",r),c&&p.append("end_date",c),s&&p.append("page",s.toString()),d&&p.append("page_size",d.toString()),h&&p.append("user_id",h);let u=p.toString();u&&(w+="?".concat(u));let y=await fetch(w,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!y.ok){let e=await y.text();throw i(e),Error("Network response was not ok")}let f=await y.json();return console.log("Spend Logs Response:",f),f}catch(e){throw console.error("Failed to fetch spend logs:",e),e}},ei=async e=>{try{let t=n?"".concat(n,"/global/spend/logs"):"/global/spend/logs",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},el=async e=>{try{let t=n?"".concat(n,"/global/spend/keys?limit=5"):"/global/spend/keys?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ed=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/end_users"):"/global/spend/end_users",c="";c=t?JSON.stringify({api_key:t,startTime:o,endTime:a}):JSON.stringify({startTime:o,endTime:a});let s={method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:c},d=await fetch(r,s);if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log(h),h}catch(e){throw console.error("Failed to create key:",e),e}},eh=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/provider"):"/global/spend/provider";o&&a&&(r+="?start_date=".concat(o,"&end_date=").concat(a)),t&&(r+="&api_key=".concat(t));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log(d),d}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ew=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity"):"/global/activity";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ep=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/cache_hits"):"/global/activity/cache_hits";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},eu=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/model"):"/global/activity/model";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ey=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions"):"/global/activity/exceptions";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ef=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions/deployment"):"/global/activity/exceptions/deployment";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},em=async e=>{try{let t=n?"".concat(n,"/global/spend/models?limit=5"):"/global/spend/models?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},eg=async(e,t,o)=>{try{console.log("Sending model connection test request:",JSON.stringify(t));let r=n?"".concat(n,"/health/test_connection"):"/health/test_connection",c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",[l]:"Bearer ".concat(e)},body:JSON.stringify({litellm_params:t,mode:o})}),s=c.headers.get("content-type");if(!s||!s.includes("application/json")){let e=await c.text();throw console.error("Received non-JSON response:",e),Error("Received non-JSON response (".concat(c.status,": ").concat(c.statusText,"). Check network tab for details."))}let i=await c.json();if(!c.ok||"error"===i.status){if("error"===i.status);else{var a;return{status:"error",message:(null===(a=i.error)||void 0===a?void 0:a.message)||"Connection test failed: ".concat(c.status," ").concat(c.statusText)}}}return i}catch(e){throw console.error("Model connection test error:",e),e}},ek=async(e,t)=>{try{console.log("entering keyInfoV1Call");let o=n?"".concat(n,"/key/info"):"/key/info";o="".concat(o,"?key=").concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(console.log("response",a),!a.ok){let e=await a.text();i(e),r.ZP.error("Failed to fetch key info - "+e)}let c=await a.json();return console.log("data",c),c}catch(e){throw console.error("Failed to fetch key info:",e),e}},e_=async(e,t,o,a,r,c)=>{try{let s=n?"".concat(n,"/key/list"):"/key/list";console.log("in keyListCall");let d=new URLSearchParams;o&&d.append("team_id",o.toString()),t&&d.append("organization_id",t.toString()),a&&d.append("key_alias",a),r&&d.append("page",r.toString()),c&&d.append("size",c.toString()),d.append("return_full_object","true"),d.append("include_team_keys","true");let h=d.toString();h&&(s+="?".concat(h));let w=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!w.ok){let e=await w.text();throw i(e),Error("Network response was not ok")}let p=await w.json();return console.log("/team/list API Response:",p),p}catch(e){throw console.error("Failed to create key:",e),e}},eT=async(e,t)=>{try{let o=n?"".concat(n,"/user/get_users?role=").concat(t):"/user/get_users?role=".concat(t);console.log("in userGetAllUsersCall:",o);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to get requested models:",e),e}},eE=async e=>{try{let t=n?"".concat(n,"/user/available_roles"):"/user/available_roles",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("response from user/available_role",a),a}catch(e){throw e}},ej=async(e,t)=>{try{if(console.log("Form Values in teamCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/team/new"):"/team/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eC=async(e,t)=>{try{if(console.log("Form Values in credentialCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/credentials"):"/credentials",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eN=async e=>{try{let t=n?"".concat(n,"/credentials"):"/credentials";console.log("in credentialListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/credentials API Response:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},eS=async(e,t,o)=>{try{let a=n?"".concat(n,"/credentials"):"/credentials";t?a+="/by_name/".concat(t):o&&(a+="/by_model/".concat(o)),console.log("in credentialListCall");let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("/credentials API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eb=async(e,t)=>{try{let o=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t);console.log("in credentialDeleteCall:",t);let a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},eF=async(e,t,o)=>{try{if(console.log("Form Values in credentialUpdateCall:",o),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let a=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t),r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ex=async(e,t)=>{try{if(console.log("Form Values in keyUpdateCall:",t),t.model_tpm_limit){console.log("formValues.model_tpm_limit:",t.model_tpm_limit);try{t.model_tpm_limit=JSON.parse(t.model_tpm_limit)}catch(e){throw Error("Failed to parse model_tpm_limit: "+e)}}if(t.model_rpm_limit){console.log("formValues.model_rpm_limit:",t.model_rpm_limit);try{t.model_rpm_limit=JSON.parse(t.model_rpm_limit)}catch(e){throw Error("Failed to parse model_rpm_limit: "+e)}}let o=n?"".concat(n,"/key/update"):"/key/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update key Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eO=async(e,t)=>{try{console.log("Form Values in teamUpateCall:",t);let o=n?"".concat(n,"/team/update"):"/team/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eB=async(e,t)=>{try{console.log("Form Values in modelUpateCall:",t);let o=n?"".concat(n,"/model/update"):"/model/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error update from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update model Response:",r),r}catch(e){throw console.error("Failed to update model:",e),e}},eP=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_add"):"/team/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ev=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_update"):"/team/member_update",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,role:o.role,user_id:o.user_id})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eG=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_delete"):"/team/member_delete",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,...void 0!==o.user_email&&{user_email:o.user_email},...void 0!==o.user_id&&{user_id:o.user_id}})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eA=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/organization/member_add"):"/organization/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create organization member:",e),e}},eJ=async(e,t,o)=>{try{console.log("Form Values in organizationMemberDeleteCall:",o);let a=n?"".concat(n,"/organization/member_delete"):"/organization/member_delete",r=await fetch(a,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,user_id:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to delete organization member:",e),e}},eI=async(e,t,o)=>{try{console.log("Form Values in organizationMemberUpdateCall:",o);let a=n?"".concat(n,"/organization/member_update"):"/organization/member_update",r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to update organization member:",e),e}},eR=async(e,t,o)=>{try{console.log("Form Values in userUpdateUserCall:",t);let a=n?"".concat(n,"/user/update"):"/user/update",r={...t};null!==o&&(r.user_role=o),r=JSON.stringify(r);let c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:r});if(!c.ok){let e=await c.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let s=await c.json();return console.log("API Response:",s),s}catch(e){throw console.error("Failed to create key:",e),e}},ez=async(e,t)=>{try{let o=n?"".concat(n,"/health/services?service=").concat(t):"/health/services?service=".concat(t);console.log("Checking Slack Budget Alerts service health");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error(e)}let c=await a.json();return r.ZP.success("Test request to ".concat(t," made - check logs/alerts on ").concat(t," to verify")),c}catch(e){throw console.error("Failed to perform health check:",e),e}},eV=async e=>{try{let t=n?"".concat(n,"/budget/list"):"/budget/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eU=async(e,t,o)=>{try{let t=n?"".concat(n,"/get/config/callbacks"):"/get/config/callbacks",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eL=async e=>{try{let t=n?"".concat(n,"/config/list?config_type=general_settings"):"/config/list?config_type=general_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eM=async e=>{try{let t=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eZ=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/info?field_name=").concat(t):"/config/field/info?field_name=".concat(t),a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eD=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eH=async(e,t,o)=>{try{let a=n?"".concat(n,"/config/field/update"):"/config/field/update",c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,field_value:o,config_type:"general_settings"})});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}let s=await c.json();return r.ZP.success("Successfully updated value!"),s}catch(e){throw console.error("Failed to set callbacks:",e),e}},eq=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/delete"):"/config/field/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,config_type:"general_settings"})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return r.ZP.success("Field reset on proxy"),c}catch(e){throw console.error("Failed to get callbacks:",e),e}},eX=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint?endpoint_id=").concat(t):"/config/pass_through_endpoint".concat(t),a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eY=async(e,t)=>{try{let o=n?"".concat(n,"/config/update"):"/config/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eK=async e=>{try{let t=n?"".concat(n,"/health"):"/health",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to call /health:",e),e}},e$=async e=>{try{let t=n?"".concat(n,"/cache/ping"):"/cache/ping",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error(e)}return await o.json()}catch(e){throw console.error("Failed to call /cache/ping:",e),e}},eQ=async e=>{try{let t=n?"".concat(n,"/sso/get/ui_settings"):"/sso/get/ui_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eW=async e=>{try{let t=n?"".concat(n,"/guardrails/list"):"/guardrails/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Guardrails list response:",a),a}catch(e){throw console.error("Failed to fetch guardrails list:",e),e}},e0=async(e,t,o)=>{try{let a=n?"".concat(n,"/spend/logs/ui/").concat(t,"?start_date=").concat(encodeURIComponent(o)):"/spend/logs/ui/".concat(t,"?start_date=").concat(encodeURIComponent(o));console.log("Fetching log details from:",a);let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Fetched log details:",c),c}catch(e){throw console.error("Failed to fetch log details:",e),e}},e1=async e=>{try{let t=n?"".concat(n,"/get/internal_user_settings"):"/get/internal_user_settings";console.log("Fetching SSO settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched SSO settings:",a),a}catch(e){throw console.error("Failed to fetch SSO settings:",e),e}},e3=async(e,t)=>{try{let o=n?"".concat(n,"/update/internal_user_settings"):"/update/internal_user_settings";console.log("Updating internal user settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated internal user settings:",c),r.ZP.success("Internal user settings updated successfully"),c}catch(e){throw console.error("Failed to update internal user settings:",e),e}},e4=async e=>{try{let t=n?"".concat(n,"/mcp/tools/list"):"/mcp/tools/list";console.log("Fetching MCP tools from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched MCP tools:",a),a}catch(e){throw console.error("Failed to fetch MCP tools:",e),e}},e2=async(e,t,o)=>{try{let a=n?"".concat(n,"/mcp/tools/call"):"/mcp/tools/call";console.log("Calling MCP tool:",t,"with arguments:",o);let r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("MCP tool call response:",c),c}catch(e){throw console.error("Failed to call MCP tool:",e),e}},e5=async(e,t)=>{try{let o=n?"".concat(n,"/tag/new"):"/tag/new",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error creating tag:",e),e}},e6=async(e,t)=>{try{let o=n?"".concat(n,"/tag/update"):"/tag/update",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error updating tag:",e),e}},e9=async(e,t)=>{try{let o=n?"".concat(n,"/tag/info"):"/tag/info",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({names:t})});if(!a.ok){let e=await a.text();return await i(e),{}}return await a.json()}catch(e){throw console.error("Error getting tag info:",e),e}},e7=async e=>{try{let t=n?"".concat(n,"/tag/list"):"/tag/list",o=await fetch(t,{method:"GET",headers:{Authorization:"Bearer ".concat(e)}});if(!o.ok){let e=await o.text();return await i(e),{}}return await o.json()}catch(e){throw console.error("Error listing tags:",e),e}},e8=async(e,t)=>{try{let o=n?"".concat(n,"/tag/delete"):"/tag/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({name:t})});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error deleting tag:",e),e}},te=async e=>{try{let t=n?"".concat(n,"/get/default_team_settings"):"/get/default_team_settings";console.log("Fetching default team settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched default team settings:",a),a}catch(e){throw console.error("Failed to fetch default team settings:",e),e}},tt=async(e,t)=>{try{let o=n?"".concat(n,"/update/default_team_settings"):"/update/default_team_settings";console.log("Updating default team settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated default team settings:",c),r.ZP.success("Default team settings updated successfully"),c}catch(e){throw console.error("Failed to update default team settings:",e),e}},to=async(e,t)=>{try{let o=n?"".concat(n,"/team/permissions_list?team_id=").concat(t):"/team/permissions_list?team_id=".concat(t),a=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("Team permissions response:",r),r}catch(e){throw console.error("Failed to get team permissions:",e),e}},ta=async(e,t,o)=>{try{let a=n?"".concat(n,"/team/permissions_update"):"/team/permissions_update",r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({team_id:t,team_member_permissions:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Team permissions response:",c),c}catch(e){throw console.error("Failed to update team permissions:",e),e}}},20347:function(e,t,o){o.d(t,{LQ:function(){return n},ZL:function(){return a},lo:function(){return r},tY:function(){return c}});let a=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],r=["Internal User","Internal Viewer"],n=["Internal User","Admin"],c=e=>a.includes(e)}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/250-a927a558002d8fb9.js b/litellm/proxy/_experimental/out/_next/static/chunks/250-a927a558002d8fb9.js deleted file mode 100644 index 80c21540d2..0000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/250-a927a558002d8fb9.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[250],{19250:function(e,t,o){o.d(t,{$I:function(){return K},AZ:function(){return D},Au:function(){return em},BL:function(){return eU},Br:function(){return b},E9:function(){return eZ},EB:function(){return te},EG:function(){return eX},EY:function(){return eK},Eb:function(){return C},FC:function(){return ei},Gh:function(){return eO},H1:function(){return v},H2:function(){return n},Hx:function(){return eg},I1:function(){return j},It:function(){return x},J$:function(){return ea},K8:function(){return d},K_:function(){return eY},LY:function(){return eI},Lp:function(){return eG},N3:function(){return eN},N8:function(){return ee},NL:function(){return e1},NV:function(){return f},Nc:function(){return ex},O3:function(){return eV},OD:function(){return e_},OU:function(){return eh},Of:function(){return S},Og:function(){return y},Ov:function(){return E},PT:function(){return X},Qg:function(){return eS},RQ:function(){return _},Rg:function(){return Q},Sb:function(){return eJ},So:function(){return et},TF:function(){return ta},Tj:function(){return e$},UM:function(){return e7},VA:function(){return G},Vt:function(){return eD},W_:function(){return V},X:function(){return er},XO:function(){return k},Xd:function(){return eT},Xm:function(){return F},YU:function(){return eL},Yo:function(){return J},Z9:function(){return R},Zr:function(){return m},a6:function(){return O},aC:function(){return to},ao:function(){return eq},b1:function(){return ed},cq:function(){return A},cu:function(){return eP},eH:function(){return Y},eZ:function(){return eF},fE:function(){return e8},fP:function(){return W},g:function(){return eQ},gX:function(){return eb},h3:function(){return es},hT:function(){return ej},hy:function(){return u},ix:function(){return H},j2:function(){return en},jA:function(){return eH},jE:function(){return ez},kK:function(){return p},kn:function(){return q},lP:function(){return h},lU:function(){return e2},lg:function(){return eE},mC:function(){return e6},mR:function(){return eo},mY:function(){return e5},m_:function(){return U},mp:function(){return eM},n$:function(){return ey},n9:function(){return e9},nd:function(){return e3},o6:function(){return $},oC:function(){return eC},ol:function(){return z},pf:function(){return eR},qI:function(){return g},qk:function(){return e0},qm:function(){return w},r1:function(){return tt},r6:function(){return B},rs:function(){return N},s0:function(){return L},sN:function(){return ev},t$:function(){return P},t0:function(){return ek},t3:function(){return eW},tB:function(){return e4},tN:function(){return el},u5:function(){return ec},um:function(){return eB},v9:function(){return ef},vh:function(){return eA},wX:function(){return T},wd:function(){return ew},xA:function(){return eu},xX:function(){return I},zg:function(){return ep}});var a=o(20347),r=o(41021);let n=null;console.log=function(){};let c=0,s=e=>new Promise(t=>setTimeout(t,e)),i=async e=>{let t=Date.now();t-c>6e4?(e.includes("Authentication Error - Expired Key")&&(r.ZP.info("UI Session Expired. Logging out."),c=t,await s(3e3),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",window.location.href="/"),c=t):console.log("Error suppressed to prevent spam:",e)},l="Authorization";function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Authorization";console.log("setGlobalLitellmHeaderName: ".concat(e)),l=e}let h=async()=>{let e=n?"".concat(n,"/openapi.json"):"/openapi.json",t=await fetch(e);return await t.json()},w=async e=>{try{let t=n?"".concat(n,"/get/litellm_model_cost_map"):"/get/litellm_model_cost_map",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}}),a=await o.json();return console.log("received litellm model cost data: ".concat(a)),a}catch(e){throw console.error("Failed to get model cost map:",e),e}},p=async(e,t)=>{try{let o=n?"".concat(n,"/model/new"):"/model/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text()||"Network response was not ok";throw r.ZP.error(e),Error(e)}let c=await a.json();return console.log("API Response:",c),r.ZP.destroy(),r.ZP.success("Model ".concat(t.model_name," created successfully"),2),c}catch(e){throw console.error("Failed to create key:",e),e}},u=async e=>{try{let t=n?"".concat(n,"/model/settings"):"/model/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){console.error("Failed to get model settings:",e)}},y=async(e,t)=>{console.log("model_id in model delete call: ".concat(t));try{let o=n?"".concat(n,"/model/delete"):"/model/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},f=async(e,t)=>{if(console.log("budget_id in budget delete call: ".concat(t)),null!=e)try{let o=n?"".concat(n,"/budget/delete"):"/budget/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},m=async(e,t)=>{try{console.log("Form Values in budgetCreateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/new"):"/budget/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},g=async(e,t)=>{try{console.log("Form Values in budgetUpdateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/update"):"/budget/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},k=async(e,t)=>{try{let o=n?"".concat(n,"/invitation/new"):"/invitation/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},_=async e=>{try{let t=n?"".concat(n,"/alerting/settings"):"/alerting/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},T=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/key/generate"):"/key/generate",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},E=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.auto_create_key=!1,o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/user/new"):"/user/new",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},j=async(e,t)=>{try{let o=n?"".concat(n,"/key/delete"):"/key/delete";console.log("in keyDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},C=async(e,t)=>{try{let o=n?"".concat(n,"/user/delete"):"/user/delete";console.log("in userDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_ids:t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete user(s):",e),e}},N=async(e,t)=>{try{let o=n?"".concat(n,"/team/delete"):"/team/delete";console.log("in teamDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},S=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null;try{let r=n?"".concat(n,"/user/list"):"/user/list";console.log("in userListCall");let c=new URLSearchParams;if(t&&t.length>0){let e=t.join(",");c.append("user_ids",e)}o&&c.append("page",o.toString()),a&&c.append("page_size",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log("/user/list API Response:",h),h}catch(e){throw console.error("Failed to create key:",e),e}},b=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,c=arguments.length>5?arguments[5]:void 0;try{let s;if(a){s=n?"".concat(n,"/user/list"):"/user/list";let e=new URLSearchParams;null!=r&&e.append("page",r.toString()),null!=c&&e.append("page_size",c.toString()),s+="?".concat(e.toString())}else s=n?"".concat(n,"/user/info"):"/user/info","Admin"===o||"Admin Viewer"===o||t&&(s+="?user_id=".concat(t));console.log("Requesting user data from:",s);let d=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log("API Response:",h),h}catch(e){throw console.error("Failed to fetch user data:",e),e}},F=async(e,t)=>{try{let o=n?"".concat(n,"/team/info"):"/team/info";t&&(o="".concat(o,"?team_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},x=async function(e,t){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;try{let a=n?"".concat(n,"/team/list"):"/team/list";console.log("in teamInfoCall");let r=new URLSearchParams;o&&r.append("user_id",o.toString()),t&&r.append("organization_id",t.toString());let c=r.toString();c&&(a+="?".concat(c));let s=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log("/team/list API Response:",d),d}catch(e){throw console.error("Failed to create key:",e),e}},O=async e=>{try{let t=n?"".concat(n,"/team/available"):"/team/available";console.log("in availableTeamListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/team/available_teams API Response:",a),a}catch(e){throw e}},B=async e=>{try{let t=n?"".concat(n,"/organization/list"):"/organization/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},P=async(e,t)=>{try{let o=n?"".concat(n,"/organization/info"):"/organization/info";t&&(o="".concat(o,"?organization_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},v=async(e,t)=>{try{if(console.log("Form Values in organizationCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw console.error("Failed to parse metadata:",e),Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/organization/new"):"/organization/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},G=async(e,t)=>{try{console.log("Form Values in organizationUpdateCall:",t);let o=n?"".concat(n,"/organization/update"):"/organization/update",a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},A=async(e,t)=>{try{let o=n?"".concat(n,"/organization/delete"):"/organization/delete",a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Error deleting organization: ".concat(e))}return await a.json()}catch(e){throw console.error("Failed to delete organization:",e),e}},J=async(e,t)=>{try{let o=n?"".concat(n,"/utils/transform_request"):"/utils/transform_request",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},I=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;try{let r=n?"".concat(n,"/user/daily/activity"):"/user/daily/activity",c=new URLSearchParams;c.append("start_date",t.toISOString()),c.append("end_date",o.toISOString()),c.append("page_size","1000"),c.append("page",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}return await d.json()}catch(e){throw console.error("Failed to create key:",e),e}},R=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/tag/daily/activity"):"/tag/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("tags",r.join(","));let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},z=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/team/daily/activity"):"/team/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("team_ids",r.join(",")),s.append("exclude_team_ids","litellm-dashboard");let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},V=async e=>{try{let t=n?"".concat(n,"/onboarding/get_token"):"/onboarding/get_token";t+="?invite_link=".concat(e);let o=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},U=async(e,t,o,a)=>{let r=n?"".concat(n,"/onboarding/claim_token"):"/onboarding/claim_token";try{let n=await fetch(r,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({invitation_link:t,user_id:o,password:a})});if(!n.ok){let e=await n.text();throw i(e),Error("Network response was not ok")}let c=await n.json();return console.log(c),c}catch(e){throw console.error("Failed to delete key:",e),e}},L=async(e,t,o)=>{try{let a=n?"".concat(n,"/key/").concat(t,"/regenerate"):"/key/".concat(t,"/regenerate"),r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Regenerate key Response:",c),c}catch(e){throw console.error("Failed to regenerate key:",e),e}},M=!1,Z=null,D=async(e,t,o)=>{try{console.log("modelInfoCall:",e,t,o);let c=n?"".concat(n,"/v2/model/info"):"/v2/model/info";a.ZL.includes(o)||(c+="?user_models_only=true");let s=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw e+="error shown=".concat(M),M||(e.includes("No model list passed")&&(e="No Models Exist. Click Add Model to get started."),r.ZP.info(e,10),M=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{M=!1},1e4)),Error("Network response was not ok")}let i=await s.json();return console.log("modelInfoCall:",i),i}catch(e){throw console.error("Failed to create key:",e),e}},H=async(e,t)=>{try{let o=n?"".concat(n,"/v1/model/info"):"/v1/model/info";o+="?litellm_model_id=".concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");let r=await a.json();return console.log("modelInfoV1Call:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},q=async e=>{try{let t=n?"".concat(n,"/model_group/info"):"/model_group/info",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("modelHubCall:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},X=async e=>{try{let t=n?"".concat(n,"/get/allowed_ips"):"/get/allowed_ips",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw Error("Network response was not ok: ".concat(e))}let a=await o.json();return console.log("getAllowedIPs:",a),a.data}catch(e){throw console.error("Failed to get allowed IPs:",e),e}},Y=async(e,t)=>{try{let o=n?"".concat(n,"/add/allowed_ip"):"/add/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("addAllowedIP:",r),r}catch(e){throw console.error("Failed to add allowed IP:",e),e}},K=async(e,t)=>{try{let o=n?"".concat(n,"/delete/allowed_ip"):"/delete/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("deleteAllowedIP:",r),r}catch(e){throw console.error("Failed to delete allowed IP:",e),e}},$=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics"):"/model/metrics";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},Q=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/model/streaming_metrics"):"/model/streaming_metrics";t&&(r="".concat(r,"?_selected_model_group=").concat(t,"&startTime=").concat(o,"&endTime=").concat(a));let c=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},W=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/slow_responses"):"/model/metrics/slow_responses";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},ee=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/exceptions"):"/model/metrics/exceptions";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},et=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;console.log("in /models calls, globalLitellmHeaderName",l);try{let t=n?"".concat(n,"/models"):"/models",o=new URLSearchParams;!0===a&&o.append("return_wildcard_routes","True"),r&&o.append("team_id",r.toString()),o.toString()&&(t+="?".concat(o.toString()));let c=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},eo=async e=>{try{let t=n?"".concat(n,"/global/spend/teams"):"/global/spend/teams";console.log("in teamSpendLogsCall:",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ea=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/tags"):"/global/spend/tags";t&&o&&(r="".concat(r,"?start_date=").concat(t,"&end_date=").concat(o)),a&&(r+="".concat(r,"&tags=").concat(a.join(","))),console.log("in tagsSpendLogsCall:",r);let c=await fetch("".concat(r),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to create key:",e),e}},er=async e=>{try{let t=n?"".concat(n,"/global/spend/all_tag_names"):"/global/spend/all_tag_names";console.log("in global/spend/all_tag_names call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},en=async e=>{try{let t=n?"".concat(n,"/global/all_end_users"):"/global/all_end_users";console.log("in global/all_end_users call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ec=async(e,t)=>{try{let o=n?"".concat(n,"/user/filter/ui"):"/user/filter/ui";t.get("user_email")&&(o+="?user_email=".concat(t.get("user_email"))),t.get("user_id")&&(o+="?user_id=".concat(t.get("user_id")));let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},es=async(e,t,o,a,r,c,s,d,h)=>{try{let w=n?"".concat(n,"/spend/logs/ui"):"/spend/logs/ui",p=new URLSearchParams;t&&p.append("api_key",t),o&&p.append("team_id",o),a&&p.append("request_id",a),r&&p.append("start_date",r),c&&p.append("end_date",c),s&&p.append("page",s.toString()),d&&p.append("page_size",d.toString()),h&&p.append("user_id",h);let u=p.toString();u&&(w+="?".concat(u));let y=await fetch(w,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!y.ok){let e=await y.text();throw i(e),Error("Network response was not ok")}let f=await y.json();return console.log("Spend Logs Response:",f),f}catch(e){throw console.error("Failed to fetch spend logs:",e),e}},ei=async e=>{try{let t=n?"".concat(n,"/global/spend/logs"):"/global/spend/logs",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},el=async e=>{try{let t=n?"".concat(n,"/global/spend/keys?limit=5"):"/global/spend/keys?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ed=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/end_users"):"/global/spend/end_users",c="";c=t?JSON.stringify({api_key:t,startTime:o,endTime:a}):JSON.stringify({startTime:o,endTime:a});let s={method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:c},d=await fetch(r,s);if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log(h),h}catch(e){throw console.error("Failed to create key:",e),e}},eh=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/provider"):"/global/spend/provider";o&&a&&(r+="?start_date=".concat(o,"&end_date=").concat(a)),t&&(r+="&api_key=".concat(t));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log(d),d}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ew=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity"):"/global/activity";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ep=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/cache_hits"):"/global/activity/cache_hits";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},eu=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/model"):"/global/activity/model";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ey=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions"):"/global/activity/exceptions";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ef=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions/deployment"):"/global/activity/exceptions/deployment";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},em=async e=>{try{let t=n?"".concat(n,"/global/spend/models?limit=5"):"/global/spend/models?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},eg=async(e,t,o)=>{try{console.log("Sending model connection test request:",JSON.stringify(t));let r=n?"".concat(n,"/health/test_connection"):"/health/test_connection",c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",[l]:"Bearer ".concat(e)},body:JSON.stringify({litellm_params:t,mode:o})}),s=c.headers.get("content-type");if(!s||!s.includes("application/json")){let e=await c.text();throw console.error("Received non-JSON response:",e),Error("Received non-JSON response (".concat(c.status,": ").concat(c.statusText,"). Check network tab for details."))}let i=await c.json();if(!c.ok||"error"===i.status){if("error"===i.status);else{var a;return{status:"error",message:(null===(a=i.error)||void 0===a?void 0:a.message)||"Connection test failed: ".concat(c.status," ").concat(c.statusText)}}}return i}catch(e){throw console.error("Model connection test error:",e),e}},ek=async(e,t)=>{try{console.log("entering keyInfoV1Call");let o=n?"".concat(n,"/key/info"):"/key/info";o="".concat(o,"?key=").concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(console.log("response",a),!a.ok){let e=await a.text();i(e),r.ZP.error("Failed to fetch key info - "+e)}let c=await a.json();return console.log("data",c),c}catch(e){throw console.error("Failed to fetch key info:",e),e}},e_=async(e,t,o,a,r,c)=>{try{let s=n?"".concat(n,"/key/list"):"/key/list";console.log("in keyListCall");let d=new URLSearchParams;o&&d.append("team_id",o.toString()),t&&d.append("organization_id",t.toString()),a&&d.append("key_alias",a),r&&d.append("page",r.toString()),c&&d.append("size",c.toString()),d.append("return_full_object","true"),d.append("include_team_keys","true");let h=d.toString();h&&(s+="?".concat(h));let w=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!w.ok){let e=await w.text();throw i(e),Error("Network response was not ok")}let p=await w.json();return console.log("/team/list API Response:",p),p}catch(e){throw console.error("Failed to create key:",e),e}},eT=async(e,t)=>{try{let o=n?"".concat(n,"/user/get_users?role=").concat(t):"/user/get_users?role=".concat(t);console.log("in userGetAllUsersCall:",o);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to get requested models:",e),e}},eE=async e=>{try{let t=n?"".concat(n,"/user/available_roles"):"/user/available_roles",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("response from user/available_role",a),a}catch(e){throw e}},ej=async(e,t)=>{try{if(console.log("Form Values in teamCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/team/new"):"/team/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eC=async(e,t)=>{try{if(console.log("Form Values in credentialCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/credentials"):"/credentials",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eN=async e=>{try{let t=n?"".concat(n,"/credentials"):"/credentials";console.log("in credentialListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/credentials API Response:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},eS=async(e,t,o)=>{try{let a=n?"".concat(n,"/credentials"):"/credentials";t?a+="/by_name/".concat(t):o&&(a+="/by_model/".concat(o)),console.log("in credentialListCall");let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("/credentials API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eb=async(e,t)=>{try{let o=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t);console.log("in credentialDeleteCall:",t);let a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},eF=async(e,t,o)=>{try{if(console.log("Form Values in credentialUpdateCall:",o),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let a=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t),r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ex=async(e,t)=>{try{if(console.log("Form Values in keyUpdateCall:",t),t.model_tpm_limit){console.log("formValues.model_tpm_limit:",t.model_tpm_limit);try{t.model_tpm_limit=JSON.parse(t.model_tpm_limit)}catch(e){throw Error("Failed to parse model_tpm_limit: "+e)}}if(t.model_rpm_limit){console.log("formValues.model_rpm_limit:",t.model_rpm_limit);try{t.model_rpm_limit=JSON.parse(t.model_rpm_limit)}catch(e){throw Error("Failed to parse model_rpm_limit: "+e)}}let o=n?"".concat(n,"/key/update"):"/key/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update key Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eO=async(e,t)=>{try{console.log("Form Values in teamUpateCall:",t);let o=n?"".concat(n,"/team/update"):"/team/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eB=async(e,t)=>{try{console.log("Form Values in modelUpateCall:",t);let o=n?"".concat(n,"/model/update"):"/model/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error update from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update model Response:",r),r}catch(e){throw console.error("Failed to update model:",e),e}},eP=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_add"):"/team/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ev=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_update"):"/team/member_update",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,role:o.role,user_id:o.user_id})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eG=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_delete"):"/team/member_delete",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,...void 0!==o.user_email&&{user_email:o.user_email},...void 0!==o.user_id&&{user_id:o.user_id}})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eA=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/organization/member_add"):"/organization/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create organization member:",e),e}},eJ=async(e,t,o)=>{try{console.log("Form Values in organizationMemberDeleteCall:",o);let a=n?"".concat(n,"/organization/member_delete"):"/organization/member_delete",r=await fetch(a,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,user_id:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to delete organization member:",e),e}},eI=async(e,t,o)=>{try{console.log("Form Values in organizationMemberUpdateCall:",o);let a=n?"".concat(n,"/organization/member_update"):"/organization/member_update",r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to update organization member:",e),e}},eR=async(e,t,o)=>{try{console.log("Form Values in userUpdateUserCall:",t);let a=n?"".concat(n,"/user/update"):"/user/update",r={...t};null!==o&&(r.user_role=o),r=JSON.stringify(r);let c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:r});if(!c.ok){let e=await c.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let s=await c.json();return console.log("API Response:",s),s}catch(e){throw console.error("Failed to create key:",e),e}},ez=async(e,t)=>{try{let o=n?"".concat(n,"/health/services?service=").concat(t):"/health/services?service=".concat(t);console.log("Checking Slack Budget Alerts service health");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error(e)}let c=await a.json();return r.ZP.success("Test request to ".concat(t," made - check logs/alerts on ").concat(t," to verify")),c}catch(e){throw console.error("Failed to perform health check:",e),e}},eV=async e=>{try{let t=n?"".concat(n,"/budget/list"):"/budget/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eU=async(e,t,o)=>{try{let t=n?"".concat(n,"/get/config/callbacks"):"/get/config/callbacks",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eL=async e=>{try{let t=n?"".concat(n,"/config/list?config_type=general_settings"):"/config/list?config_type=general_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eM=async e=>{try{let t=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eZ=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/info?field_name=").concat(t):"/config/field/info?field_name=".concat(t),a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eD=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eH=async(e,t,o)=>{try{let a=n?"".concat(n,"/config/field/update"):"/config/field/update",c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,field_value:o,config_type:"general_settings"})});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}let s=await c.json();return r.ZP.success("Successfully updated value!"),s}catch(e){throw console.error("Failed to set callbacks:",e),e}},eq=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/delete"):"/config/field/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,config_type:"general_settings"})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return r.ZP.success("Field reset on proxy"),c}catch(e){throw console.error("Failed to get callbacks:",e),e}},eX=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint?endpoint_id=").concat(t):"/config/pass_through_endpoint".concat(t),a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eY=async(e,t)=>{try{let o=n?"".concat(n,"/config/update"):"/config/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eK=async e=>{try{let t=n?"".concat(n,"/health"):"/health",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to call /health:",e),e}},e$=async e=>{try{let t=n?"".concat(n,"/cache/ping"):"/cache/ping",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error(e)}return await o.json()}catch(e){throw console.error("Failed to call /cache/ping:",e),e}},eQ=async e=>{try{let t=n?"".concat(n,"/sso/get/ui_settings"):"/sso/get/ui_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eW=async e=>{try{let t=n?"".concat(n,"/guardrails/list"):"/guardrails/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Guardrails list response:",a),a}catch(e){throw console.error("Failed to fetch guardrails list:",e),e}},e0=async(e,t,o)=>{try{let a=n?"".concat(n,"/spend/logs/ui/").concat(t,"?start_date=").concat(encodeURIComponent(o)):"/spend/logs/ui/".concat(t,"?start_date=").concat(encodeURIComponent(o));console.log("Fetching log details from:",a);let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Fetched log details:",c),c}catch(e){throw console.error("Failed to fetch log details:",e),e}},e1=async e=>{try{let t=n?"".concat(n,"/get/internal_user_settings"):"/get/internal_user_settings";console.log("Fetching SSO settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched SSO settings:",a),a}catch(e){throw console.error("Failed to fetch SSO settings:",e),e}},e3=async(e,t)=>{try{let o=n?"".concat(n,"/update/internal_user_settings"):"/update/internal_user_settings";console.log("Updating internal user settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated internal user settings:",c),r.ZP.success("Internal user settings updated successfully"),c}catch(e){throw console.error("Failed to update internal user settings:",e),e}},e2=async e=>{try{let t=n?"".concat(n,"/mcp/tools/list"):"/mcp/tools/list";console.log("Fetching MCP tools from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched MCP tools:",a),a}catch(e){throw console.error("Failed to fetch MCP tools:",e),e}},e4=async(e,t,o)=>{try{let a=n?"".concat(n,"/mcp/tools/call"):"/mcp/tools/call";console.log("Calling MCP tool:",t,"with arguments:",o);let r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("MCP tool call response:",c),c}catch(e){throw console.error("Failed to call MCP tool:",e),e}},e5=async(e,t)=>{try{let o=n?"".concat(n,"/tag/new"):"/tag/new",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error creating tag:",e),e}},e9=async(e,t)=>{try{let o=n?"".concat(n,"/tag/update"):"/tag/update",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error updating tag:",e),e}},e6=async(e,t)=>{try{let o=n?"".concat(n,"/tag/info"):"/tag/info",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({names:t})});if(!a.ok){let e=await a.text();return await i(e),{}}return await a.json()}catch(e){throw console.error("Error getting tag info:",e),e}},e7=async e=>{try{let t=n?"".concat(n,"/tag/list"):"/tag/list",o=await fetch(t,{method:"GET",headers:{Authorization:"Bearer ".concat(e)}});if(!o.ok){let e=await o.text();return await i(e),{}}return await o.json()}catch(e){throw console.error("Error listing tags:",e),e}},e8=async(e,t)=>{try{let o=n?"".concat(n,"/tag/delete"):"/tag/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({name:t})});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error deleting tag:",e),e}},te=async e=>{try{let t=n?"".concat(n,"/get/default_team_settings"):"/get/default_team_settings";console.log("Fetching default team settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched default team settings:",a),a}catch(e){throw console.error("Failed to fetch default team settings:",e),e}},tt=async(e,t)=>{try{let o=n?"".concat(n,"/update/default_team_settings"):"/update/default_team_settings";console.log("Updating default team settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated default team settings:",c),r.ZP.success("Default team settings updated successfully"),c}catch(e){throw console.error("Failed to update default team settings:",e),e}},to=async(e,t)=>{try{let o=n?"".concat(n,"/team/permissions_list?team_id=").concat(t):"/team/permissions_list?team_id=".concat(t),a=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("Team permissions response:",r),r}catch(e){throw console.error("Failed to get team permissions:",e),e}},ta=async(e,t,o)=>{try{let a=n?"".concat(n,"/team/permissions_update"):"/team/permissions_update",r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({team_id:t,team_member_permissions:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Team permissions response:",c),c}catch(e){throw console.error("Failed to update team permissions:",e),e}}},20347:function(e,t,o){o.d(t,{LQ:function(){return n},ZL:function(){return a},lo:function(){return r},tY:function(){return c}});let a=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],r=["Internal User","Internal Viewer"],n=["Internal User","Admin"],c=e=>a.includes(e)}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/261-57d48f76eec1e568.js b/litellm/proxy/_experimental/out/_next/static/chunks/261-ee7f0f1f1c8c22a0.js similarity index 99% rename from litellm/proxy/_experimental/out/_next/static/chunks/261-57d48f76eec1e568.js rename to litellm/proxy/_experimental/out/_next/static/chunks/261-ee7f0f1f1c8c22a0.js index 44e5f1be73..78658f0a2e 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/261-57d48f76eec1e568.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/261-ee7f0f1f1c8c22a0.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[261],{23639:function(e,t,n){"use strict";n.d(t,{Z:function(){return s}});var a=n(1119),r=n(2265),i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M832 64H296c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h496v688c0 4.4 3.6 8 8 8h56c4.4 0 8-3.6 8-8V96c0-17.7-14.3-32-32-32zM704 192H192c-17.7 0-32 14.3-32 32v530.7c0 8.5 3.4 16.6 9.4 22.6l173.3 173.3c2.2 2.2 4.7 4 7.4 5.5v1.9h4.2c3.5 1.3 7.2 2 11 2H704c17.7 0 32-14.3 32-32V224c0-17.7-14.3-32-32-32zM350 856.2L263.9 770H350v86.2zM664 888H414V746c0-22.1-17.9-40-40-40H232V264h432v624z"}}]},name:"copy",theme:"outlined"},o=n(55015),s=r.forwardRef(function(e,t){return r.createElement(o.Z,(0,a.Z)({},e,{ref:t,icon:i}))})},77565:function(e,t,n){"use strict";n.d(t,{Z:function(){return s}});var a=n(1119),r=n(2265),i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M765.7 486.8L314.9 134.7A7.97 7.97 0 00302 141v77.3c0 4.9 2.3 9.6 6.1 12.6l360 281.1-360 281.1c-3.9 3-6.1 7.7-6.1 12.6V883c0 6.7 7.7 10.4 12.9 6.3l450.8-352.1a31.96 31.96 0 000-50.4z"}}]},name:"right",theme:"outlined"},o=n(55015),s=r.forwardRef(function(e,t){return r.createElement(o.Z,(0,a.Z)({},e,{ref:t,icon:i}))})},12485:function(e,t,n){"use strict";n.d(t,{Z:function(){return p}});var a=n(5853),r=n(31492),i=n(26898),o=n(65954),s=n(1153),l=n(2265),c=n(35242),u=n(42698);n(64016),n(8710),n(33232);let d=(0,s.fn)("Tab"),p=l.forwardRef((e,t)=>{let{icon:n,className:p,children:g}=e,m=(0,a._T)(e,["icon","className","children"]),b=(0,l.useContext)(c.O),f=(0,l.useContext)(u.Z);return l.createElement(r.O,Object.assign({ref:t,className:(0,o.q)(d("root"),"flex whitespace-nowrap truncate max-w-xs outline-none focus:ring-0 text-tremor-default transition duration-100",f?(0,s.bM)(f,i.K.text).selectTextColor:"solid"===b?"ui-selected:text-tremor-content-emphasis dark:ui-selected:text-dark-tremor-content-emphasis":"ui-selected:text-tremor-brand dark:ui-selected:text-dark-tremor-brand",function(e,t){switch(e){case"line":return(0,o.q)("ui-selected:border-b-2 hover:border-b-2 border-transparent transition duration-100 -mb-px px-2 py-2","hover:border-tremor-content hover:text-tremor-content-emphasis text-tremor-content","dark:hover:border-dark-tremor-content-emphasis dark:hover:text-dark-tremor-content-emphasis dark:text-dark-tremor-content",t?(0,s.bM)(t,i.K.border).selectBorderColor:"ui-selected:border-tremor-brand dark:ui-selected:border-dark-tremor-brand");case"solid":return(0,o.q)("border-transparent border rounded-tremor-small px-2.5 py-1","ui-selected:border-tremor-border ui-selected:bg-tremor-background ui-selected:shadow-tremor-input hover:text-tremor-content-emphasis ui-selected:text-tremor-brand","dark:ui-selected:border-dark-tremor-border dark:ui-selected:bg-dark-tremor-background dark:ui-selected:shadow-dark-tremor-input dark:hover:text-dark-tremor-content-emphasis dark:ui-selected:text-dark-tremor-brand",t?(0,s.bM)(t,i.K.text).selectTextColor:"text-tremor-content dark:text-dark-tremor-content")}}(b,f),p)},m),n?l.createElement(n,{className:(0,o.q)(d("icon"),"flex-none h-5 w-5",g?"mr-2":"")}):null,g?l.createElement("span",null,g):null)});p.displayName="Tab"},18135:function(e,t,n){"use strict";n.d(t,{Z:function(){return c}});var a=n(5853),r=n(31492),i=n(65954),o=n(1153),s=n(2265);let l=(0,o.fn)("TabGroup"),c=s.forwardRef((e,t)=>{let{defaultIndex:n,index:o,onIndexChange:c,children:u,className:d}=e,p=(0,a._T)(e,["defaultIndex","index","onIndexChange","children","className"]);return s.createElement(r.O.Group,Object.assign({as:"div",ref:t,defaultIndex:n,selectedIndex:o,onChange:c,className:(0,i.q)(l("root"),"w-full",d)},p),u)});c.displayName="TabGroup"},35242:function(e,t,n){"use strict";n.d(t,{O:function(){return c},Z:function(){return d}});var a=n(5853),r=n(2265),i=n(42698);n(64016),n(8710),n(33232);var o=n(31492),s=n(65954);let l=(0,n(1153).fn)("TabList"),c=(0,r.createContext)("line"),u={line:(0,s.q)("flex border-b space-x-4","border-tremor-border","dark:border-dark-tremor-border"),solid:(0,s.q)("inline-flex p-0.5 rounded-tremor-default space-x-1.5","bg-tremor-background-subtle","dark:bg-dark-tremor-background-subtle")},d=r.forwardRef((e,t)=>{let{color:n,variant:d="line",children:p,className:g}=e,m=(0,a._T)(e,["color","variant","children","className"]);return r.createElement(o.O.List,Object.assign({ref:t,className:(0,s.q)(l("root"),"justify-start overflow-x-clip",u[d],g)},m),r.createElement(c.Provider,{value:d},r.createElement(i.Z.Provider,{value:n},p)))});d.displayName="TabList"},29706:function(e,t,n){"use strict";n.d(t,{Z:function(){return u}});var a=n(5853);n(42698);var r=n(64016);n(8710);var i=n(33232),o=n(65954),s=n(1153),l=n(2265);let c=(0,s.fn)("TabPanel"),u=l.forwardRef((e,t)=>{let{children:n,className:s}=e,u=(0,a._T)(e,["children","className"]),{selectedValue:d}=(0,l.useContext)(i.Z),p=d===(0,l.useContext)(r.Z);return l.createElement("div",Object.assign({ref:t,className:(0,o.q)(c("root"),"w-full mt-2",p?"":"hidden",s),"aria-selected":p?"true":"false"},u),n)});u.displayName="TabPanel"},77991:function(e,t,n){"use strict";n.d(t,{Z:function(){return d}});var a=n(5853),r=n(31492);n(42698);var i=n(64016);n(8710);var o=n(33232),s=n(65954),l=n(1153),c=n(2265);let u=(0,l.fn)("TabPanels"),d=c.forwardRef((e,t)=>{let{children:n,className:l}=e,d=(0,a._T)(e,["children","className"]);return c.createElement(r.O.Panels,Object.assign({as:"div",ref:t,className:(0,s.q)(u("root"),"w-full",l)},d),e=>{let{selectedIndex:t}=e;return c.createElement(o.Z.Provider,{value:{selectedValue:t}},c.Children.map(n,(e,t)=>c.createElement(i.Z.Provider,{value:t},e)))})});d.displayName="TabPanels"},42698:function(e,t,n){"use strict";n.d(t,{Z:function(){return i}});var a=n(2265),r=n(7084);n(65954);let i=(0,a.createContext)(r.fr.Blue)},64016:function(e,t,n){"use strict";n.d(t,{Z:function(){return a}});let a=(0,n(2265).createContext)(0)},8710:function(e,t,n){"use strict";n.d(t,{Z:function(){return a}});let a=(0,n(2265).createContext)(void 0)},33232:function(e,t,n){"use strict";n.d(t,{Z:function(){return a}});let a=(0,n(2265).createContext)({selectedValue:void 0,handleValueChange:void 0})},93942:function(e,t,n){"use strict";n.d(t,{i:function(){return s}});var a=n(2265),r=n(50506),i=n(13959),o=n(71744);function s(e){return t=>a.createElement(i.ZP,{theme:{token:{motion:!1,zIndexPopupBase:0}}},a.createElement(e,Object.assign({},t)))}t.Z=(e,t,n,i)=>s(s=>{let{prefixCls:l,style:c}=s,u=a.useRef(null),[d,p]=a.useState(0),[g,m]=a.useState(0),[b,f]=(0,r.Z)(!1,{value:s.open}),{getPrefixCls:E}=a.useContext(o.E_),h=E(t||"select",l);a.useEffect(()=>{if(f(!0),"undefined"!=typeof ResizeObserver){let e=new ResizeObserver(e=>{let t=e[0].target;p(t.offsetHeight+8),m(t.offsetWidth)}),t=setInterval(()=>{var a;let r=n?".".concat(n(h)):".".concat(h,"-dropdown"),i=null===(a=u.current)||void 0===a?void 0:a.querySelector(r);i&&(clearInterval(t),e.observe(i))},10);return()=>{clearInterval(t),e.disconnect()}}},[]);let S=Object.assign(Object.assign({},s),{style:Object.assign(Object.assign({},c),{margin:0}),open:b,visible:b,getPopupContainer:()=>u.current});return i&&(S=i(S)),a.createElement("div",{ref:u,style:{paddingBottom:d,position:"relative",minWidth:g}},a.createElement(e,Object.assign({},S)))})},51369:function(e,t,n){"use strict";let a;n.d(t,{Z:function(){return eY}});var r=n(83145),i=n(2265),o=n(18404),s=n(71744),l=n(13959),c=n(8900),u=n(39725),d=n(54537),p=n(55726),g=n(36760),m=n.n(g),b=n(62236),f=n(68710),E=n(55274),h=n(29961),S=n(69819),y=n(73002),T=n(51248),A=e=>{let{type:t,children:n,prefixCls:a,buttonProps:r,close:o,autoFocus:s,emitEvent:l,isSilent:c,quitOnNullishReturnValue:u,actionFn:d}=e,p=i.useRef(!1),g=i.useRef(null),[m,b]=(0,S.Z)(!1),f=function(){null==o||o.apply(void 0,arguments)};i.useEffect(()=>{let e=null;return s&&(e=setTimeout(()=>{var e;null===(e=g.current)||void 0===e||e.focus()})),()=>{e&&clearTimeout(e)}},[]);let E=e=>{e&&e.then&&(b(!0),e.then(function(){b(!1,!0),f.apply(void 0,arguments),p.current=!1},e=>{if(b(!1,!0),p.current=!1,null==c||!c())return Promise.reject(e)}))};return i.createElement(y.ZP,Object.assign({},(0,T.nx)(t),{onClick:e=>{let t;if(!p.current){if(p.current=!0,!d){f();return}if(l){var n;if(t=d(e),u&&!((n=t)&&n.then)){p.current=!1,f(e);return}}else if(d.length)t=d(o),p.current=!1;else if(!(t=d())){f();return}E(t)}},loading:m,prefixCls:a},r,{ref:g}),n)};let R=i.createContext({}),{Provider:I}=R;var N=()=>{let{autoFocusButton:e,cancelButtonProps:t,cancelTextLocale:n,isSilent:a,mergedOkCancel:r,rootPrefixCls:o,close:s,onCancel:l,onConfirm:c}=(0,i.useContext)(R);return r?i.createElement(A,{isSilent:a,actionFn:l,close:function(){null==s||s.apply(void 0,arguments),null==c||c(!1)},autoFocus:"cancel"===e,buttonProps:t,prefixCls:"".concat(o,"-btn")},n):null},_=()=>{let{autoFocusButton:e,close:t,isSilent:n,okButtonProps:a,rootPrefixCls:r,okTextLocale:o,okType:s,onConfirm:l,onOk:c}=(0,i.useContext)(R);return i.createElement(A,{isSilent:n,type:s||"primary",actionFn:c,close:function(){null==t||t.apply(void 0,arguments),null==l||l(!0)},autoFocus:"ok"===e,buttonProps:a,prefixCls:"".concat(r,"-btn")},o)},v=n(49638),w=n(1119),k=n(26365),C=n(28036),O=i.createContext({}),x=n(31686),L=n(2161),D=n(92491),P=n(95814),M=n(18242);function F(e,t,n){var a=t;return!a&&n&&(a="".concat(e,"-").concat(n)),a}function U(e,t){var n=e["page".concat(t?"Y":"X","Offset")],a="scroll".concat(t?"Top":"Left");if("number"!=typeof n){var r=e.document;"number"!=typeof(n=r.documentElement[a])&&(n=r.body[a])}return n}var B=n(47970),G=n(28791),$=i.memo(function(e){return e.children},function(e,t){return!t.shouldUpdate}),H={width:0,height:0,overflow:"hidden",outline:"none"},z=i.forwardRef(function(e,t){var n,a,r,o=e.prefixCls,s=e.className,l=e.style,c=e.title,u=e.ariaId,d=e.footer,p=e.closable,g=e.closeIcon,b=e.onClose,f=e.children,E=e.bodyStyle,h=e.bodyProps,S=e.modalRender,y=e.onMouseDown,T=e.onMouseUp,A=e.holderRef,R=e.visible,I=e.forceRender,N=e.width,_=e.height,v=e.classNames,k=e.styles,C=i.useContext(O).panel,L=(0,G.x1)(A,C),D=(0,i.useRef)(),P=(0,i.useRef)();i.useImperativeHandle(t,function(){return{focus:function(){var e;null===(e=D.current)||void 0===e||e.focus()},changeActive:function(e){var t=document.activeElement;e&&t===P.current?D.current.focus():e||t!==D.current||P.current.focus()}}});var M={};void 0!==N&&(M.width=N),void 0!==_&&(M.height=_),d&&(n=i.createElement("div",{className:m()("".concat(o,"-footer"),null==v?void 0:v.footer),style:(0,x.Z)({},null==k?void 0:k.footer)},d)),c&&(a=i.createElement("div",{className:m()("".concat(o,"-header"),null==v?void 0:v.header),style:(0,x.Z)({},null==k?void 0:k.header)},i.createElement("div",{className:"".concat(o,"-title"),id:u},c))),p&&(r=i.createElement("button",{type:"button",onClick:b,"aria-label":"Close",className:"".concat(o,"-close")},g||i.createElement("span",{className:"".concat(o,"-close-x")})));var F=i.createElement("div",{className:m()("".concat(o,"-content"),null==v?void 0:v.content),style:null==k?void 0:k.content},r,a,i.createElement("div",(0,w.Z)({className:m()("".concat(o,"-body"),null==v?void 0:v.body),style:(0,x.Z)((0,x.Z)({},E),null==k?void 0:k.body)},h),f),n);return i.createElement("div",{key:"dialog-element",role:"dialog","aria-labelledby":c?u:null,"aria-modal":"true",ref:L,style:(0,x.Z)((0,x.Z)({},l),M),className:m()(o,s),onMouseDown:y,onMouseUp:T},i.createElement("div",{tabIndex:0,ref:D,style:H,"aria-hidden":"true"}),i.createElement($,{shouldUpdate:R||I},S?S(F):F),i.createElement("div",{tabIndex:0,ref:P,style:H,"aria-hidden":"true"}))}),j=i.forwardRef(function(e,t){var n=e.prefixCls,a=e.title,r=e.style,o=e.className,s=e.visible,l=e.forceRender,c=e.destroyOnClose,u=e.motionName,d=e.ariaId,p=e.onVisibleChanged,g=e.mousePosition,b=(0,i.useRef)(),f=i.useState(),E=(0,k.Z)(f,2),h=E[0],S=E[1],y={};function T(){var e,t,n,a,r,i=(n={left:(t=(e=b.current).getBoundingClientRect()).left,top:t.top},r=(a=e.ownerDocument).defaultView||a.parentWindow,n.left+=U(r),n.top+=U(r,!0),n);S(g?"".concat(g.x-i.left,"px ").concat(g.y-i.top,"px"):"")}return h&&(y.transformOrigin=h),i.createElement(B.ZP,{visible:s,onVisibleChanged:p,onAppearPrepare:T,onEnterPrepare:T,forceRender:l,motionName:u,removeOnLeave:c,ref:b},function(s,l){var c=s.className,u=s.style;return i.createElement(z,(0,w.Z)({},e,{ref:t,title:a,ariaId:d,prefixCls:n,holderRef:l,style:(0,x.Z)((0,x.Z)((0,x.Z)({},u),r),y),className:m()(o,c)}))})});function V(e){var t=e.prefixCls,n=e.style,a=e.visible,r=e.maskProps,o=e.motionName,s=e.className;return i.createElement(B.ZP,{key:"mask",visible:a,motionName:o,leavedClassName:"".concat(t,"-mask-hidden")},function(e,a){var o=e.className,l=e.style;return i.createElement("div",(0,w.Z)({ref:a,style:(0,x.Z)((0,x.Z)({},l),n),className:m()("".concat(t,"-mask"),o,s)},r))})}function W(e){var t=e.prefixCls,n=void 0===t?"rc-dialog":t,a=e.zIndex,r=e.visible,o=void 0!==r&&r,s=e.keyboard,l=void 0===s||s,c=e.focusTriggerAfterClose,u=void 0===c||c,d=e.wrapStyle,p=e.wrapClassName,g=e.wrapProps,b=e.onClose,f=e.afterOpenChange,E=e.afterClose,h=e.transitionName,S=e.animation,y=e.closable,T=e.mask,A=void 0===T||T,R=e.maskTransitionName,I=e.maskAnimation,N=e.maskClosable,_=e.maskStyle,v=e.maskProps,C=e.rootClassName,O=e.classNames,U=e.styles,B=(0,i.useRef)(),G=(0,i.useRef)(),$=(0,i.useRef)(),H=i.useState(o),z=(0,k.Z)(H,2),W=z[0],q=z[1],Y=(0,D.Z)();function K(e){null==b||b(e)}var Z=(0,i.useRef)(!1),X=(0,i.useRef)(),Q=null;return(void 0===N||N)&&(Q=function(e){Z.current?Z.current=!1:G.current===e.target&&K(e)}),(0,i.useEffect)(function(){o&&(q(!0),(0,L.Z)(G.current,document.activeElement)||(B.current=document.activeElement))},[o]),(0,i.useEffect)(function(){return function(){clearTimeout(X.current)}},[]),i.createElement("div",(0,w.Z)({className:m()("".concat(n,"-root"),C)},(0,M.Z)(e,{data:!0})),i.createElement(V,{prefixCls:n,visible:A&&o,motionName:F(n,R,I),style:(0,x.Z)((0,x.Z)({zIndex:a},_),null==U?void 0:U.mask),maskProps:v,className:null==O?void 0:O.mask}),i.createElement("div",(0,w.Z)({tabIndex:-1,onKeyDown:function(e){if(l&&e.keyCode===P.Z.ESC){e.stopPropagation(),K(e);return}o&&e.keyCode===P.Z.TAB&&$.current.changeActive(!e.shiftKey)},className:m()("".concat(n,"-wrap"),p,null==O?void 0:O.wrapper),ref:G,onClick:Q,style:(0,x.Z)((0,x.Z)((0,x.Z)({zIndex:a},d),null==U?void 0:U.wrapper),{},{display:W?null:"none"})},g),i.createElement(j,(0,w.Z)({},e,{onMouseDown:function(){clearTimeout(X.current),Z.current=!0},onMouseUp:function(){X.current=setTimeout(function(){Z.current=!1})},ref:$,closable:void 0===y||y,ariaId:Y,prefixCls:n,visible:o&&W,onClose:K,onVisibleChanged:function(e){if(e)!function(){if(!(0,L.Z)(G.current,document.activeElement)){var e;null===(e=$.current)||void 0===e||e.focus()}}();else{if(q(!1),A&&B.current&&u){try{B.current.focus({preventScroll:!0})}catch(e){}B.current=null}W&&(null==E||E())}null==f||f(e)},motionName:F(n,h,S)}))))}j.displayName="Content",n(32559);var q=function(e){var t=e.visible,n=e.getContainer,a=e.forceRender,r=e.destroyOnClose,o=void 0!==r&&r,s=e.afterClose,l=e.panelRef,c=i.useState(t),u=(0,k.Z)(c,2),d=u[0],p=u[1],g=i.useMemo(function(){return{panel:l}},[l]);return(i.useEffect(function(){t&&p(!0)},[t]),a||!o||d)?i.createElement(O.Provider,{value:g},i.createElement(C.Z,{open:t||a||d,autoDestroy:!1,getContainer:n,autoLock:t||d},i.createElement(W,(0,w.Z)({},e,{destroyOnClose:o,afterClose:function(){null==s||s(),p(!1)}})))):null};q.displayName="Dialog";var Y=function(e,t,n){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:i.createElement(v.Z,null),r=arguments.length>4&&void 0!==arguments[4]&&arguments[4];if("boolean"==typeof e?!e:void 0===t?!r:!1===t||null===t)return[!1,null];let o="boolean"==typeof t||null==t?a:t;return[!0,n?n(o):o]},K=n(94981),Z=n(95140),X=n(39109),Q=n(65658),J=n(74126);function ee(){}let et=i.createContext({add:ee,remove:ee});var en=n(86586),ea=()=>{let{cancelButtonProps:e,cancelTextLocale:t,onCancel:n}=(0,i.useContext)(R);return i.createElement(y.ZP,Object.assign({onClick:n},e),t)},er=()=>{let{confirmLoading:e,okButtonProps:t,okType:n,okTextLocale:a,onOk:r}=(0,i.useContext)(R);return i.createElement(y.ZP,Object.assign({},(0,T.nx)(n),{loading:e,onClick:r},t),a)},ei=n(92246);function eo(e,t){return i.createElement("span",{className:"".concat(e,"-close-x")},t||i.createElement(v.Z,{className:"".concat(e,"-close-icon")}))}let es=e=>{let t;let{okText:n,okType:a="primary",cancelText:o,confirmLoading:s,onOk:l,onCancel:c,okButtonProps:u,cancelButtonProps:d,footer:p}=e,[g]=(0,E.Z)("Modal",(0,ei.A)()),m={confirmLoading:s,okButtonProps:u,cancelButtonProps:d,okTextLocale:n||(null==g?void 0:g.okText),cancelTextLocale:o||(null==g?void 0:g.cancelText),okType:a,onOk:l,onCancel:c},b=i.useMemo(()=>m,(0,r.Z)(Object.values(m)));return"function"==typeof p||void 0===p?(t=i.createElement(i.Fragment,null,i.createElement(ea,null),i.createElement(er,null)),"function"==typeof p&&(t=p(t,{OkBtn:er,CancelBtn:ea})),t=i.createElement(I,{value:b},t)):t=p,i.createElement(en.n,{disabled:!1},t)};var el=n(12918),ec=n(11699),eu=n(691),ed=n(3104),ep=n(80669),eg=n(352);function em(e){return{position:e,inset:0}}let eb=e=>{let{componentCls:t,antCls:n}=e;return[{["".concat(t,"-root")]:{["".concat(t).concat(n,"-zoom-enter, ").concat(t).concat(n,"-zoom-appear")]:{transform:"none",opacity:0,animationDuration:e.motionDurationSlow,userSelect:"none"},["".concat(t).concat(n,"-zoom-leave ").concat(t,"-content")]:{pointerEvents:"none"},["".concat(t,"-mask")]:Object.assign(Object.assign({},em("fixed")),{zIndex:e.zIndexPopupBase,height:"100%",backgroundColor:e.colorBgMask,pointerEvents:"none",["".concat(t,"-hidden")]:{display:"none"}}),["".concat(t,"-wrap")]:Object.assign(Object.assign({},em("fixed")),{zIndex:e.zIndexPopupBase,overflow:"auto",outline:0,WebkitOverflowScrolling:"touch",["&:has(".concat(t).concat(n,"-zoom-enter), &:has(").concat(t).concat(n,"-zoom-appear)")]:{pointerEvents:"none"}})}},{["".concat(t,"-root")]:(0,ec.J$)(e)}]},ef=e=>{let{componentCls:t}=e;return[{["".concat(t,"-root")]:{["".concat(t,"-wrap-rtl")]:{direction:"rtl"},["".concat(t,"-centered")]:{textAlign:"center","&::before":{display:"inline-block",width:0,height:"100%",verticalAlign:"middle",content:'""'},[t]:{top:0,display:"inline-block",paddingBottom:0,textAlign:"start",verticalAlign:"middle"}},["@media (max-width: ".concat(e.screenSMMax,"px)")]:{[t]:{maxWidth:"calc(100vw - 16px)",margin:"".concat((0,eg.bf)(e.marginXS)," auto")},["".concat(t,"-centered")]:{[t]:{flex:1}}}}},{[t]:Object.assign(Object.assign({},(0,el.Wf)(e)),{pointerEvents:"none",position:"relative",top:100,width:"auto",maxWidth:"calc(100vw - ".concat((0,eg.bf)(e.calc(e.margin).mul(2).equal()),")"),margin:"0 auto",paddingBottom:e.paddingLG,["".concat(t,"-title")]:{margin:0,color:e.titleColor,fontWeight:e.fontWeightStrong,fontSize:e.titleFontSize,lineHeight:e.titleLineHeight,wordWrap:"break-word"},["".concat(t,"-content")]:{position:"relative",backgroundColor:e.contentBg,backgroundClip:"padding-box",border:0,borderRadius:e.borderRadiusLG,boxShadow:e.boxShadow,pointerEvents:"auto",padding:e.contentPadding},["".concat(t,"-close")]:Object.assign({position:"absolute",top:e.calc(e.modalHeaderHeight).sub(e.modalCloseBtnSize).div(2).equal(),insetInlineEnd:e.calc(e.modalHeaderHeight).sub(e.modalCloseBtnSize).div(2).equal(),zIndex:e.calc(e.zIndexPopupBase).add(10).equal(),padding:0,color:e.modalCloseIconColor,fontWeight:e.fontWeightStrong,lineHeight:1,textDecoration:"none",background:"transparent",borderRadius:e.borderRadiusSM,width:e.modalCloseBtnSize,height:e.modalCloseBtnSize,border:0,outline:0,cursor:"pointer",transition:"color ".concat(e.motionDurationMid,", background-color ").concat(e.motionDurationMid),"&-x":{display:"flex",fontSize:e.fontSizeLG,fontStyle:"normal",lineHeight:"".concat((0,eg.bf)(e.modalCloseBtnSize)),justifyContent:"center",textTransform:"none",textRendering:"auto"},"&:hover":{color:e.modalIconHoverColor,backgroundColor:e.closeBtnHoverBg,textDecoration:"none"},"&:active":{backgroundColor:e.closeBtnActiveBg}},(0,el.Qy)(e)),["".concat(t,"-header")]:{color:e.colorText,background:e.headerBg,borderRadius:"".concat((0,eg.bf)(e.borderRadiusLG)," ").concat((0,eg.bf)(e.borderRadiusLG)," 0 0"),marginBottom:e.headerMarginBottom,padding:e.headerPadding,borderBottom:e.headerBorderBottom},["".concat(t,"-body")]:{fontSize:e.fontSize,lineHeight:e.lineHeight,wordWrap:"break-word",padding:e.bodyPadding},["".concat(t,"-footer")]:{textAlign:"end",background:e.footerBg,marginTop:e.footerMarginTop,padding:e.footerPadding,borderTop:e.footerBorderTop,borderRadius:e.footerBorderRadius,["> ".concat(e.antCls,"-btn + ").concat(e.antCls,"-btn")]:{marginInlineStart:e.marginXS}},["".concat(t,"-open")]:{overflow:"hidden"}})},{["".concat(t,"-pure-panel")]:{top:"auto",padding:0,display:"flex",flexDirection:"column",["".concat(t,"-content,\n ").concat(t,"-body,\n ").concat(t,"-confirm-body-wrapper")]:{display:"flex",flexDirection:"column",flex:"auto"},["".concat(t,"-confirm-body")]:{marginBottom:"auto"}}}]},eE=e=>{let{componentCls:t}=e;return{["".concat(t,"-root")]:{["".concat(t,"-wrap-rtl")]:{direction:"rtl",["".concat(t,"-confirm-body")]:{direction:"rtl"}}}}},eh=e=>{let t=e.padding,n=e.fontSizeHeading5,a=e.lineHeightHeading5;return(0,ed.TS)(e,{modalHeaderHeight:e.calc(e.calc(a).mul(n).equal()).add(e.calc(t).mul(2).equal()).equal(),modalFooterBorderColorSplit:e.colorSplit,modalFooterBorderStyle:e.lineType,modalFooterBorderWidth:e.lineWidth,modalIconHoverColor:e.colorIconHover,modalCloseIconColor:e.colorIcon,modalCloseBtnSize:e.fontHeight,modalConfirmIconSize:e.fontHeight,modalTitleHeight:e.calc(e.titleFontSize).mul(e.titleLineHeight).equal()})},eS=e=>({footerBg:"transparent",headerBg:e.colorBgElevated,titleLineHeight:e.lineHeightHeading5,titleFontSize:e.fontSizeHeading5,contentBg:e.colorBgElevated,titleColor:e.colorTextHeading,closeBtnHoverBg:e.wireframe?"transparent":e.colorFillContent,closeBtnActiveBg:e.wireframe?"transparent":e.colorFillContentHover,contentPadding:e.wireframe?0:"".concat((0,eg.bf)(e.paddingMD)," ").concat((0,eg.bf)(e.paddingContentHorizontalLG)),headerPadding:e.wireframe?"".concat((0,eg.bf)(e.padding)," ").concat((0,eg.bf)(e.paddingLG)):0,headerBorderBottom:e.wireframe?"".concat((0,eg.bf)(e.lineWidth)," ").concat(e.lineType," ").concat(e.colorSplit):"none",headerMarginBottom:e.wireframe?0:e.marginXS,bodyPadding:e.wireframe?e.paddingLG:0,footerPadding:e.wireframe?"".concat((0,eg.bf)(e.paddingXS)," ").concat((0,eg.bf)(e.padding)):0,footerBorderTop:e.wireframe?"".concat((0,eg.bf)(e.lineWidth)," ").concat(e.lineType," ").concat(e.colorSplit):"none",footerBorderRadius:e.wireframe?"0 0 ".concat((0,eg.bf)(e.borderRadiusLG)," ").concat((0,eg.bf)(e.borderRadiusLG)):0,footerMarginTop:e.wireframe?0:e.marginSM,confirmBodyPadding:e.wireframe?"".concat((0,eg.bf)(2*e.padding)," ").concat((0,eg.bf)(2*e.padding)," ").concat((0,eg.bf)(e.paddingLG)):0,confirmIconMarginInlineEnd:e.wireframe?e.margin:e.marginSM,confirmBtnsMarginTop:e.wireframe?e.marginLG:e.marginSM});var ey=(0,ep.I$)("Modal",e=>{let t=eh(e);return[ef(t),eE(t),eb(t),(0,eu._y)(t,"zoom")]},eS,{unitless:{titleLineHeight:!0}}),eT=n(64024),eA=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n};(0,K.Z)()&&window.document.documentElement&&document.documentElement.addEventListener("click",e=>{a={x:e.pageX,y:e.pageY},setTimeout(()=>{a=null},100)},!0);var eR=e=>{var t;let{getPopupContainer:n,getPrefixCls:r,direction:o,modal:l}=i.useContext(s.E_),c=t=>{let{onCancel:n}=e;null==n||n(t)},{prefixCls:u,className:d,rootClassName:p,open:g,wrapClassName:E,centered:h,getContainer:S,closeIcon:y,closable:T,focusTriggerAfterClose:A=!0,style:R,visible:I,width:N=520,footer:_,classNames:w,styles:k}=e,C=eA(e,["prefixCls","className","rootClassName","open","wrapClassName","centered","getContainer","closeIcon","closable","focusTriggerAfterClose","style","visible","width","footer","classNames","styles"]),O=r("modal",u),x=r(),L=(0,eT.Z)(O),[D,P,M]=ey(O,L),F=m()(E,{["".concat(O,"-centered")]:!!h,["".concat(O,"-wrap-rtl")]:"rtl"===o}),U=null!==_&&i.createElement(es,Object.assign({},e,{onOk:t=>{let{onOk:n}=e;null==n||n(t)},onCancel:c})),[B,G]=Y(T,y,e=>eo(O,e),i.createElement(v.Z,{className:"".concat(O,"-close-icon")}),!0),$=function(e){let t=i.useContext(et),n=i.useRef();return(0,J.zX)(a=>{if(a){let r=e?a.querySelector(e):a;t.add(r),n.current=r}else t.remove(n.current)})}(".".concat(O,"-content")),[H,z]=(0,b.Cn)("Modal",C.zIndex);return D(i.createElement(Q.BR,null,i.createElement(X.Ux,{status:!0,override:!0},i.createElement(Z.Z.Provider,{value:z},i.createElement(q,Object.assign({width:N},C,{zIndex:H,getContainer:void 0===S?n:S,prefixCls:O,rootClassName:m()(P,p,M,L),footer:U,visible:null!=g?g:I,mousePosition:null!==(t=C.mousePosition)&&void 0!==t?t:a,onClose:c,closable:B,closeIcon:G,focusTriggerAfterClose:A,transitionName:(0,f.m)(x,"zoom",e.transitionName),maskTransitionName:(0,f.m)(x,"fade",e.maskTransitionName),className:m()(P,d,null==l?void 0:l.className),style:Object.assign(Object.assign({},null==l?void 0:l.style),R),classNames:Object.assign(Object.assign({wrapper:F},null==l?void 0:l.classNames),w),styles:Object.assign(Object.assign({},null==l?void 0:l.styles),k),panelRef:$}))))))};let eI=e=>{let{componentCls:t,titleFontSize:n,titleLineHeight:a,modalConfirmIconSize:r,fontSize:i,lineHeight:o,modalTitleHeight:s,fontHeight:l,confirmBodyPadding:c}=e,u="".concat(t,"-confirm");return{[u]:{"&-rtl":{direction:"rtl"},["".concat(e.antCls,"-modal-header")]:{display:"none"},["".concat(u,"-body-wrapper")]:Object.assign({},(0,el.dF)()),["&".concat(t," ").concat(t,"-body")]:{padding:c},["".concat(u,"-body")]:{display:"flex",flexWrap:"nowrap",alignItems:"start",["> ".concat(e.iconCls)]:{flex:"none",fontSize:r,marginInlineEnd:e.confirmIconMarginInlineEnd,marginTop:e.calc(e.calc(l).sub(r).equal()).div(2).equal()},["&-has-title > ".concat(e.iconCls)]:{marginTop:e.calc(e.calc(s).sub(r).equal()).div(2).equal()}},["".concat(u,"-paragraph")]:{display:"flex",flexDirection:"column",flex:"auto",rowGap:e.marginXS,maxWidth:"calc(100% - ".concat((0,eg.bf)(e.calc(e.modalConfirmIconSize).add(e.marginSM).equal()),")")},["".concat(u,"-title")]:{color:e.colorTextHeading,fontWeight:e.fontWeightStrong,fontSize:n,lineHeight:a},["".concat(u,"-content")]:{color:e.colorText,fontSize:i,lineHeight:o},["".concat(u,"-btns")]:{textAlign:"end",marginTop:e.confirmBtnsMarginTop,["".concat(e.antCls,"-btn + ").concat(e.antCls,"-btn")]:{marginBottom:0,marginInlineStart:e.marginXS}}},["".concat(u,"-error ").concat(u,"-body > ").concat(e.iconCls)]:{color:e.colorError},["".concat(u,"-warning ").concat(u,"-body > ").concat(e.iconCls,",\n ").concat(u,"-confirm ").concat(u,"-body > ").concat(e.iconCls)]:{color:e.colorWarning},["".concat(u,"-info ").concat(u,"-body > ").concat(e.iconCls)]:{color:e.colorInfo},["".concat(u,"-success ").concat(u,"-body > ").concat(e.iconCls)]:{color:e.colorSuccess}}};var eN=(0,ep.bk)(["Modal","confirm"],e=>[eI(eh(e))],eS,{order:-1e3}),e_=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n};function ev(e){let{prefixCls:t,icon:n,okText:a,cancelText:o,confirmPrefixCls:s,type:l,okCancel:g,footer:b,locale:f}=e,h=e_(e,["prefixCls","icon","okText","cancelText","confirmPrefixCls","type","okCancel","footer","locale"]),S=n;if(!n&&null!==n)switch(l){case"info":S=i.createElement(p.Z,null);break;case"success":S=i.createElement(c.Z,null);break;case"error":S=i.createElement(u.Z,null);break;default:S=i.createElement(d.Z,null)}let y=null!=g?g:"confirm"===l,T=null!==e.autoFocusButton&&(e.autoFocusButton||"ok"),[A]=(0,E.Z)("Modal"),R=f||A,v=a||(y?null==R?void 0:R.okText:null==R?void 0:R.justOkText),w=Object.assign({autoFocusButton:T,cancelTextLocale:o||(null==R?void 0:R.cancelText),okTextLocale:v,mergedOkCancel:y},h),k=i.useMemo(()=>w,(0,r.Z)(Object.values(w))),C=i.createElement(i.Fragment,null,i.createElement(N,null),i.createElement(_,null)),O=void 0!==e.title&&null!==e.title,x="".concat(s,"-body");return i.createElement("div",{className:"".concat(s,"-body-wrapper")},i.createElement("div",{className:m()(x,{["".concat(x,"-has-title")]:O})},S,i.createElement("div",{className:"".concat(s,"-paragraph")},O&&i.createElement("span",{className:"".concat(s,"-title")},e.title),i.createElement("div",{className:"".concat(s,"-content")},e.content))),void 0===b||"function"==typeof b?i.createElement(I,{value:k},i.createElement("div",{className:"".concat(s,"-btns")},"function"==typeof b?b(C,{OkBtn:_,CancelBtn:N}):C)):b,i.createElement(eN,{prefixCls:t}))}let ew=e=>{let{close:t,zIndex:n,afterClose:a,open:r,keyboard:o,centered:s,getContainer:l,maskStyle:c,direction:u,prefixCls:d,wrapClassName:p,rootPrefixCls:g,bodyStyle:E,closable:S=!1,closeIcon:y,modalRender:T,focusTriggerAfterClose:A,onConfirm:R,styles:I}=e,N="".concat(d,"-confirm"),_=e.width||416,v=e.style||{},w=void 0===e.mask||e.mask,k=void 0!==e.maskClosable&&e.maskClosable,C=m()(N,"".concat(N,"-").concat(e.type),{["".concat(N,"-rtl")]:"rtl"===u},e.className),[,O]=(0,h.ZP)(),x=i.useMemo(()=>void 0!==n?n:O.zIndexPopupBase+b.u6,[n,O]);return i.createElement(eR,{prefixCls:d,className:C,wrapClassName:m()({["".concat(N,"-centered")]:!!e.centered},p),onCancel:()=>{null==t||t({triggerCancel:!0}),null==R||R(!1)},open:r,title:"",footer:null,transitionName:(0,f.m)(g||"","zoom",e.transitionName),maskTransitionName:(0,f.m)(g||"","fade",e.maskTransitionName),mask:w,maskClosable:k,style:v,styles:Object.assign({body:E,mask:c},I),width:_,zIndex:x,afterClose:a,keyboard:o,centered:s,getContainer:l,closable:S,closeIcon:y,modalRender:T,focusTriggerAfterClose:A},i.createElement(ev,Object.assign({},e,{confirmPrefixCls:N})))};var ek=e=>{let{rootPrefixCls:t,iconPrefixCls:n,direction:a,theme:r}=e;return i.createElement(l.ZP,{prefixCls:t,iconPrefixCls:n,direction:a,theme:r},i.createElement(ew,Object.assign({},e)))},eC=[];let eO="",ex=e=>{var t,n;let{prefixCls:a,getContainer:r,direction:o}=e,l=(0,ei.A)(),c=(0,i.useContext)(s.E_),u=eO||c.getPrefixCls(),d=a||"".concat(u,"-modal"),p=r;return!1===p&&(p=void 0),i.createElement(ek,Object.assign({},e,{rootPrefixCls:u,prefixCls:d,iconPrefixCls:c.iconPrefixCls,theme:c.theme,direction:null!=o?o:c.direction,locale:null!==(n=null===(t=c.locale)||void 0===t?void 0:t.Modal)&&void 0!==n?n:l,getContainer:p}))};function eL(e){let t;let n=(0,l.w6)(),a=document.createDocumentFragment(),s=Object.assign(Object.assign({},e),{close:d,open:!0});function c(){for(var t=arguments.length,n=Array(t),i=0;ie&&e.triggerCancel);e.onCancel&&s&&e.onCancel.apply(e,[()=>{}].concat((0,r.Z)(n.slice(1))));for(let e=0;e{let t=n.getPrefixCls(void 0,eO),r=n.getIconPrefixCls(),s=n.getTheme(),c=i.createElement(ex,Object.assign({},e));(0,o.s)(i.createElement(l.ZP,{prefixCls:t,iconPrefixCls:r,theme:s},n.holderRender?n.holderRender(c):c),a)})}function d(){for(var t=arguments.length,n=Array(t),a=0;a{"function"==typeof e.afterClose&&e.afterClose(),c.apply(this,n)}})).visible&&delete s.visible,u(s)}return u(s),eC.push(d),{destroy:d,update:function(e){u(s="function"==typeof e?e(s):Object.assign(Object.assign({},s),e))}}}function eD(e){return Object.assign(Object.assign({},e),{type:"warning"})}function eP(e){return Object.assign(Object.assign({},e),{type:"info"})}function eM(e){return Object.assign(Object.assign({},e),{type:"success"})}function eF(e){return Object.assign(Object.assign({},e),{type:"error"})}function eU(e){return Object.assign(Object.assign({},e),{type:"confirm"})}var eB=n(93942),eG=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n},e$=(0,eB.i)(e=>{let{prefixCls:t,className:n,closeIcon:a,closable:r,type:o,title:l,children:c,footer:u}=e,d=eG(e,["prefixCls","className","closeIcon","closable","type","title","children","footer"]),{getPrefixCls:p}=i.useContext(s.E_),g=p(),b=t||p("modal"),f=(0,eT.Z)(g),[E,h,S]=ey(b,f),y="".concat(b,"-confirm"),T={};return T=o?{closable:null!=r&&r,title:"",footer:"",children:i.createElement(ev,Object.assign({},e,{prefixCls:b,confirmPrefixCls:y,rootPrefixCls:g,content:c}))}:{closable:null==r||r,title:l,footer:null!==u&&i.createElement(es,Object.assign({},e)),children:c},E(i.createElement(z,Object.assign({prefixCls:b,className:m()(h,"".concat(b,"-pure-panel"),o&&y,o&&"".concat(y,"-").concat(o),n,S,f)},d,{closeIcon:eo(b,a),closable:r},T)))}),eH=n(13823),ez=function(e,t){var n={};for(var a in e)Object.prototype.hasOwnProperty.call(e,a)&&0>t.indexOf(a)&&(n[a]=e[a]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var r=0,a=Object.getOwnPropertySymbols(e);rt.indexOf(a[r])&&Object.prototype.propertyIsEnumerable.call(e,a[r])&&(n[a[r]]=e[a[r]]);return n},ej=i.forwardRef((e,t)=>{var n,{afterClose:a,config:o}=e,l=ez(e,["afterClose","config"]);let[c,u]=i.useState(!0),[d,p]=i.useState(o),{direction:g,getPrefixCls:m}=i.useContext(s.E_),b=m("modal"),f=m(),h=function(){u(!1);for(var e=arguments.length,t=Array(e),n=0;ne&&e.triggerCancel);d.onCancel&&a&&d.onCancel.apply(d,[()=>{}].concat((0,r.Z)(t.slice(1))))};i.useImperativeHandle(t,()=>({destroy:h,update:e=>{p(t=>Object.assign(Object.assign({},t),e))}}));let S=null!==(n=d.okCancel)&&void 0!==n?n:"confirm"===d.type,[y]=(0,E.Z)("Modal",eH.Z.Modal);return i.createElement(ek,Object.assign({prefixCls:b,rootPrefixCls:f},d,{close:h,open:c,afterClose:()=>{var e;a(),null===(e=d.afterClose)||void 0===e||e.call(d)},okText:d.okText||(S?null==y?void 0:y.okText:null==y?void 0:y.justOkText),direction:d.direction||g,cancelText:d.cancelText||(null==y?void 0:y.cancelText)},l))});let eV=0,eW=i.memo(i.forwardRef((e,t)=>{let[n,a]=function(){let[e,t]=i.useState([]);return[e,i.useCallback(e=>(t(t=>[].concat((0,r.Z)(t),[e])),()=>{t(t=>t.filter(t=>t!==e))}),[])]}();return i.useImperativeHandle(t,()=>({patchElement:a}),[]),i.createElement(i.Fragment,null,n)}));function eq(e){return eL(eD(e))}eR.useModal=function(){let e=i.useRef(null),[t,n]=i.useState([]);i.useEffect(()=>{t.length&&((0,r.Z)(t).forEach(e=>{e()}),n([]))},[t]);let a=i.useCallback(t=>function(a){var o;let s,l;eV+=1;let c=i.createRef(),u=new Promise(e=>{s=e}),d=!1,p=i.createElement(ej,{key:"modal-".concat(eV),config:t(a),ref:c,afterClose:()=>{null==l||l()},isSilent:()=>d,onConfirm:e=>{s(e)}});return(l=null===(o=e.current)||void 0===o?void 0:o.patchElement(p))&&eC.push(l),{destroy:()=>{function e(){var e;null===(e=c.current)||void 0===e||e.destroy()}c.current?e():n(t=>[].concat((0,r.Z)(t),[e]))},update:e=>{function t(){var t;null===(t=c.current)||void 0===t||t.update(e)}c.current?t():n(e=>[].concat((0,r.Z)(e),[t]))},then:e=>(d=!0,u.then(e))}},[]);return[i.useMemo(()=>({info:a(eP),success:a(eM),error:a(eF),warning:a(eD),confirm:a(eU)}),[]),i.createElement(eW,{key:"modal-holder",ref:e})]},eR.info=function(e){return eL(eP(e))},eR.success=function(e){return eL(eM(e))},eR.error=function(e){return eL(eF(e))},eR.warning=eq,eR.warn=eq,eR.confirm=function(e){return eL(eU(e))},eR.destroyAll=function(){for(;eC.length;){let e=eC.pop();e&&e()}},eR.config=function(e){let{rootPrefixCls:t}=e;eO=t},eR._InternalPanelDoNotUseOrYouWillBeFired=e$;var eY=eR},11699:function(e,t,n){"use strict";n.d(t,{J$:function(){return s}});var a=n(352),r=n(37133);let i=new a.E4("antFadeIn",{"0%":{opacity:0},"100%":{opacity:1}}),o=new a.E4("antFadeOut",{"0%":{opacity:1},"100%":{opacity:0}}),s=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],{antCls:n}=e,a="".concat(n,"-fade"),s=t?"&":"";return[(0,r.R)(a,i,o,e.motionDurationMid,t),{["\n ".concat(s).concat(a,"-enter,\n ").concat(s).concat(a,"-appear\n ")]:{opacity:0,animationTimingFunction:"linear"},["".concat(s).concat(a,"-leave")]:{animationTimingFunction:"linear"}}]}},26035:function(e){"use strict";e.exports=function(e,n){for(var a,r,i,o=e||"",s=n||"div",l={},c=0;c4&&m.slice(0,4)===o&&s.test(t)&&("-"===t.charAt(4)?b=o+(n=t.slice(5).replace(l,d)).charAt(0).toUpperCase()+n.slice(1):(g=(p=t).slice(4),t=l.test(g)?p:("-"!==(g=g.replace(c,u)).charAt(0)&&(g="-"+g),o+g)),f=r),new f(b,t))};var s=/^data[-\w.:]+$/i,l=/-[a-z]/g,c=/[A-Z]/g;function u(e){return"-"+e.toLowerCase()}function d(e){return e.charAt(1).toUpperCase()}},30466:function(e,t,n){"use strict";var a=n(82855),r=n(64541),i=n(80808),o=n(44987),s=n(72731),l=n(98946);e.exports=a([i,r,o,s,l])},72731:function(e,t,n){"use strict";var a=n(20321),r=n(41757),i=a.booleanish,o=a.number,s=a.spaceSeparated;e.exports=r({transform:function(e,t){return"role"===t?t:"aria-"+t.slice(4).toLowerCase()},properties:{ariaActiveDescendant:null,ariaAtomic:i,ariaAutoComplete:null,ariaBusy:i,ariaChecked:i,ariaColCount:o,ariaColIndex:o,ariaColSpan:o,ariaControls:s,ariaCurrent:null,ariaDescribedBy:s,ariaDetails:null,ariaDisabled:i,ariaDropEffect:s,ariaErrorMessage:null,ariaExpanded:i,ariaFlowTo:s,ariaGrabbed:i,ariaHasPopup:null,ariaHidden:i,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:s,ariaLevel:o,ariaLive:null,ariaModal:i,ariaMultiLine:i,ariaMultiSelectable:i,ariaOrientation:null,ariaOwns:s,ariaPlaceholder:null,ariaPosInSet:o,ariaPressed:i,ariaReadOnly:i,ariaRelevant:null,ariaRequired:i,ariaRoleDescription:s,ariaRowCount:o,ariaRowIndex:o,ariaRowSpan:o,ariaSelected:i,ariaSetSize:o,ariaSort:null,ariaValueMax:o,ariaValueMin:o,ariaValueNow:o,ariaValueText:null,role:null}})},98946:function(e,t,n){"use strict";var a=n(20321),r=n(41757),i=n(53296),o=a.boolean,s=a.overloadedBoolean,l=a.booleanish,c=a.number,u=a.spaceSeparated,d=a.commaSeparated;e.exports=r({space:"html",attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},transform:i,mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:d,acceptCharset:u,accessKey:u,action:null,allow:null,allowFullScreen:o,allowPaymentRequest:o,allowUserMedia:o,alt:null,as:null,async:o,autoCapitalize:null,autoComplete:u,autoFocus:o,autoPlay:o,capture:o,charSet:null,checked:o,cite:null,className:u,cols:c,colSpan:null,content:null,contentEditable:l,controls:o,controlsList:u,coords:c|d,crossOrigin:null,data:null,dateTime:null,decoding:null,default:o,defer:o,dir:null,dirName:null,disabled:o,download:s,draggable:l,encType:null,enterKeyHint:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:o,formTarget:null,headers:u,height:c,hidden:o,high:c,href:null,hrefLang:null,htmlFor:u,httpEquiv:u,id:null,imageSizes:null,imageSrcSet:d,inputMode:null,integrity:null,is:null,isMap:o,itemId:null,itemProp:u,itemRef:u,itemScope:o,itemType:u,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:o,low:c,manifest:null,max:null,maxLength:c,media:null,method:null,min:null,minLength:c,multiple:o,muted:o,name:null,nonce:null,noModule:o,noValidate:o,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforePrint:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextMenu:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:o,optimum:c,pattern:null,ping:u,placeholder:null,playsInline:o,poster:null,preload:null,readOnly:o,referrerPolicy:null,rel:u,required:o,reversed:o,rows:c,rowSpan:c,sandbox:u,scope:null,scoped:o,seamless:o,selected:o,shape:null,size:c,sizes:null,slot:null,span:c,spellCheck:l,src:null,srcDoc:null,srcLang:null,srcSet:d,start:c,step:null,style:null,tabIndex:c,target:null,title:null,translate:null,type:null,typeMustMatch:o,useMap:null,value:l,width:c,wrap:null,align:null,aLink:null,archive:u,axis:null,background:null,bgColor:null,border:c,borderColor:null,bottomMargin:c,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:o,declare:o,event:null,face:null,frame:null,frameBorder:null,hSpace:c,leftMargin:c,link:null,longDesc:null,lowSrc:null,marginHeight:c,marginWidth:c,noResize:o,noHref:o,noShade:o,noWrap:o,object:null,profile:null,prompt:null,rev:null,rightMargin:c,rules:null,scheme:null,scrolling:l,standby:null,summary:null,text:null,topMargin:c,valueType:null,version:null,vAlign:null,vLink:null,vSpace:c,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:o,disableRemotePlayback:o,prefix:null,property:null,results:c,security:null,unselectable:null}})},53296:function(e,t,n){"use strict";var a=n(38781);e.exports=function(e,t){return a(e,t.toLowerCase())}},38781:function(e){"use strict";e.exports=function(e,t){return t in e?e[t]:t}},41757:function(e,t,n){"use strict";var a=n(96532),r=n(61723),i=n(51351);e.exports=function(e){var t,n,o=e.space,s=e.mustUseProperty||[],l=e.attributes||{},c=e.properties,u=e.transform,d={},p={};for(t in c)n=new i(t,u(l,t),c[t],o),-1!==s.indexOf(t)&&(n.mustUseProperty=!0),d[t]=n,p[a(t)]=t,p[a(n.attribute)]=t;return new r(d,p,o)}},51351:function(e,t,n){"use strict";var a=n(24192),r=n(20321);e.exports=s,s.prototype=new a,s.prototype.defined=!0;var i=["boolean","booleanish","overloadedBoolean","number","commaSeparated","spaceSeparated","commaOrSpaceSeparated"],o=i.length;function s(e,t,n,s){var l,c,u,d=-1;for(s&&(this.space=s),a.call(this,e,t);++d
}> + }> {invitation_id ? ( ; + +export function UiLoadingSpinner({ className = "", ...props }: LoadingSpinnerProps) { + const id = useId(); + + useSafeLayoutEffect(() => { + const animations = document + .getAnimations() + .filter((a) => a instanceof CSSAnimation && a.animationName === 'spin') as CSSAnimation[]; + + const self = animations.find( + (a) => (a.effect as KeyframeEffect).target?.getAttribute('data-spinner-id') === id, + ); + + const anyOther = animations.find( + (a) => + a.effect instanceof KeyframeEffect && + a.effect.target?.getAttribute('data-spinner-id') !== id, + ); + + if (self && anyOther) { + self.currentTime = anyOther.currentTime; + } + }, [id]); + + return ( + + + + + ); +} diff --git a/ui/litellm-dashboard/src/hooks/use-safe-layout-effect.ts b/ui/litellm-dashboard/src/hooks/use-safe-layout-effect.ts new file mode 100644 index 0000000000..1ccc961534 --- /dev/null +++ b/ui/litellm-dashboard/src/hooks/use-safe-layout-effect.ts @@ -0,0 +1,7 @@ +import { DependencyList, EffectCallback, useEffect, useLayoutEffect } from 'react'; + +export function useSafeLayoutEffect(effect: EffectCallback, deps?: DependencyList) { + const isSSR = typeof window === 'undefined'; + const safeUseLayoutEffect = isSSR ? useEffect : useLayoutEffect; + return safeUseLayoutEffect(effect, deps); +} diff --git a/ui/litellm-dashboard/src/lib/cva.config.ts b/ui/litellm-dashboard/src/lib/cva.config.ts new file mode 100644 index 0000000000..dbb90c3e2d --- /dev/null +++ b/ui/litellm-dashboard/src/lib/cva.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from 'cva'; +import { twMerge } from 'tailwind-merge'; + +export const { cva, cx, compose } = defineConfig({ + hooks: { + onComplete: (className) => twMerge(className), + }, +}); From 174a1aa00705d19dd76665f0158449d160ed793f Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 10:51:07 -0700 Subject: [PATCH 19/40] test: update test --- tests/local_testing/test_amazing_vertex_completion.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.py index 54982fe6d8..f3c8e32dc1 100644 --- a/tests/local_testing/test_amazing_vertex_completion.py +++ b/tests/local_testing/test_amazing_vertex_completion.py @@ -455,6 +455,7 @@ async def test_async_vertexai_response(): or "gemini-2.0-flash-thinking-exp" in model or "gemini-2.0-pro-exp-02-05" in model or "gemini-pro" in model + or "gemini-1.0-pro" in model ): # our account does not have access to this model continue @@ -465,6 +466,8 @@ async def test_async_vertexai_response(): model=model, messages=messages, temperature=0.7, timeout=5 ) print(f"response: {response}") + except litellm.NotFoundError as e: + pass except litellm.RateLimitError as e: pass except litellm.Timeout as e: @@ -503,6 +506,7 @@ async def test_async_vertexai_streaming_response(): or "gemini-2.0-flash-thinking-exp" in model or "gemini-2.0-pro-exp-02-05" in model or "gemini-pro" in model + or "gemini-1.0-pro" in model ): # our account does not have access to this model continue @@ -524,6 +528,8 @@ async def test_async_vertexai_streaming_response(): complete_response += chunk.choices[0].delta.content print(f"complete_response: {complete_response}") assert len(complete_response) > 0 + except litellm.NotFoundError as e: + pass except litellm.RateLimitError as e: pass except litellm.APIConnectionError: From 81841242172df4875f131a969deb4e3b363b51c8 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 11:21:50 -0700 Subject: [PATCH 20/40] test: update testing --- .../test_amazing_vertex_completion.py | 53 +------------------ 1 file changed, 1 insertion(+), 52 deletions(-) diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.py index f3c8e32dc1..97528132c9 100644 --- a/tests/local_testing/test_amazing_vertex_completion.py +++ b/tests/local_testing/test_amazing_vertex_completion.py @@ -147,7 +147,7 @@ async def test_get_response(): prompt = '\ndef count_nums(arr):\n """\n Write a function count_nums which takes an array of integers and returns\n the number of elements which has a sum of digits > 0.\n If a number is negative, then its first signed digit will be negative:\n e.g. -123 has signed digits -1, 2, and 3.\n >>> count_nums([]) == 0\n >>> count_nums([-1, 11, -11]) == 1\n >>> count_nums([1, 1, 2]) == 3\n """\n' try: response = await acompletion( - model="gemini-pro", + model="gemini-1.5-flash", messages=[ { "role": "system", @@ -1844,57 +1844,6 @@ async def test_gemini_pro_function_calling_streaming(sync_mode): pass -@pytest.mark.asyncio -@pytest.mark.flaky(retries=3, delay=1) -async def test_gemini_pro_async_function_calling(): - load_vertex_ai_credentials() - litellm.set_verbose = True - try: - tools = [ - { - "type": "function", - "function": { - "name": "get_current_weather", - "description": "Get the current weather in a given location.", - "parameters": { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. San Francisco, CA", - }, - "unit": { - "type": "string", - "enum": ["celsius", "fahrenheit"], - }, - }, - "required": ["location"], - }, - }, - } - ] - messages = [ - { - "role": "user", - "content": "What's the weather like in Boston today in fahrenheit?", - } - ] - completion = await litellm.acompletion( - model="gemini-pro", messages=messages, tools=tools, tool_choice="auto" - ) - print(f"completion: {completion}") - print(f"message content: {completion.choices[0].message.content}") - assert completion.choices[0].message.content is None - assert len(completion.choices[0].message.tool_calls) == 1 - - # except litellm.APIError as e: - # pass - except litellm.RateLimitError as e: - pass - except Exception as e: - pytest.fail(f"An exception occurred - {str(e)}") - # raise Exception("it worked!") - # asyncio.run(gemini_pro_async_function_calling()) From a649f10e6386055922051b43169e13003dd4da81 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 11:31:09 -0700 Subject: [PATCH 21/40] test: update test to not use gemini-pro google removed it --- tests/local_testing/test_amazing_vertex_completion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/local_testing/test_amazing_vertex_completion.py b/tests/local_testing/test_amazing_vertex_completion.py index 97528132c9..0aa552069c 100644 --- a/tests/local_testing/test_amazing_vertex_completion.py +++ b/tests/local_testing/test_amazing_vertex_completion.py @@ -1784,7 +1784,7 @@ async def test_gemini_pro_function_calling_streaming(sync_mode): load_vertex_ai_credentials() litellm.set_verbose = True data = { - "model": "vertex_ai/gemini-pro", + "model": "vertex_ai/gemini-1.5-flash", "messages": [ { "role": "user", From 36ee13251469f0e66185d90eaca32ebe135bc6c3 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Wed, 23 Apr 2025 12:20:55 -0700 Subject: [PATCH 22/40] [Feat] Add gpt-image-1 cost tracking (#10241) * add gpt-image-1 * add gpt-image-1 example to docs --- docs/my-website/docs/image_generation.md | 18 ++--- ...odel_prices_and_context_window_backup.json | 70 +++++++++++++++++++ model_prices_and_context_window.json | 70 +++++++++++++++++++ 3 files changed, 150 insertions(+), 8 deletions(-) diff --git a/docs/my-website/docs/image_generation.md b/docs/my-website/docs/image_generation.md index 958ff4c020..5fe0bfb7d4 100644 --- a/docs/my-website/docs/image_generation.md +++ b/docs/my-website/docs/image_generation.md @@ -20,9 +20,9 @@ print(f"response: {response}") ```yaml model_list: - - model_name: dall-e-2 ### RECEIVED MODEL NAME ### + - model_name: gpt-image-1 ### RECEIVED MODEL NAME ### litellm_params: # all params accepted by litellm.image_generation() - model: azure/dall-e-2 ### MODEL NAME sent to `litellm.image_generation()` ### + model: azure/gpt-image-1 ### MODEL NAME sent to `litellm.image_generation()` ### api_base: https://my-endpoint-europe-berri-992.openai.azure.com/ api_key: "os.environ/AZURE_API_KEY_EU" # does os.getenv("AZURE_API_KEY_EU") rpm: 6 # [OPTIONAL] Rate limit for this deployment: in requests per minute (rpm) @@ -47,7 +47,7 @@ curl -X POST 'http://0.0.0.0:4000/v1/images/generations' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer sk-1234' \ -D '{ - "model": "dall-e-2", + "model": "gpt-image-1", "prompt": "A cute baby sea otter", "n": 1, "size": "1024x1024" @@ -104,7 +104,7 @@ Any non-openai params, will be treated as provider-specific params, and sent in litellm_logging_obj=None, custom_llm_provider=None, -- `model`: *string (optional)* The model to use for image generation. Defaults to openai/dall-e-2 +- `model`: *string (optional)* The model to use for image generation. Defaults to openai/gpt-image-1 - `n`: *int (optional)* The number of images to generate. Must be between 1 and 10. For dall-e-3, only n=1 is supported. @@ -112,7 +112,7 @@ Any non-openai params, will be treated as provider-specific params, and sent in - `response_format`: *string (optional)* The format in which the generated images are returned. Must be one of url or b64_json. -- `size`: *string (optional)* The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. +- `size`: *string (optional)* The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for gpt-image-1. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models. - `timeout`: *integer* - The maximum time, in seconds, to wait for the API to respond. Defaults to 600 seconds (10 minutes). @@ -148,13 +148,14 @@ Any non-openai params, will be treated as provider-specific params, and sent in from litellm import image_generation import os os.environ['OPENAI_API_KEY'] = "" -response = image_generation(model='dall-e-2', prompt="cute baby otter") +response = image_generation(model='gpt-image-1', prompt="cute baby otter") ``` | Model Name | Function Call | Required OS Variables | |----------------------|---------------------------------------------|--------------------------------------| -| dall-e-2 | `image_generation(model='dall-e-2', prompt="cute baby otter")` | `os.environ['OPENAI_API_KEY']` | +| gpt-image-1 | `image_generation(model='gpt-image-1', prompt="cute baby otter")` | `os.environ['OPENAI_API_KEY']` | | dall-e-3 | `image_generation(model='dall-e-3', prompt="cute baby otter")` | `os.environ['OPENAI_API_KEY']` | +| dall-e-2 | `image_generation(model='dall-e-2', prompt="cute baby otter")` | `os.environ['OPENAI_API_KEY']` | ## Azure OpenAI Image Generation Models @@ -182,8 +183,9 @@ print(response) | Model Name | Function Call | |----------------------|---------------------------------------------| -| dall-e-2 | `image_generation(model="azure/", prompt="cute baby otter")` | +| gpt-image-1 | `image_generation(model="azure/", prompt="cute baby otter")` | | dall-e-3 | `image_generation(model="azure/", prompt="cute baby otter")` | +| dall-e-2 | `image_generation(model="azure/", prompt="cute baby otter")` | ## OpenAI Compatible Image Generation Models diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json index 95543d09c2..55052761c7 100644 --- a/litellm/model_prices_and_context_window_backup.json +++ b/litellm/model_prices_and_context_window_backup.json @@ -1437,6 +1437,76 @@ "output_cost_per_pixel": 0.0, "litellm_provider": "openai" }, + "gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "low/1024-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.0490417e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "medium/1024-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "high/1024-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.59263611e-7, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "low/1024-x-1536/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.0172526e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "medium/1024-x-1536/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "high/1024-x-1536/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.58945719e-7, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "low/1536-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.0172526e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "medium/1536-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "high/1536-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.58945719e-7, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, "gpt-4o-transcribe": { "mode": "audio_transcription", "input_cost_per_token": 0.0000025, diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json index 95543d09c2..55052761c7 100644 --- a/model_prices_and_context_window.json +++ b/model_prices_and_context_window.json @@ -1437,6 +1437,76 @@ "output_cost_per_pixel": 0.0, "litellm_provider": "openai" }, + "gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "low/1024-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.0490417e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "medium/1024-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "high/1024-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.59263611e-7, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "low/1024-x-1536/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.0172526e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "medium/1024-x-1536/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "high/1024-x-1536/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.58945719e-7, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "low/1536-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.0172526e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "medium/1536-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 4.0054321e-8, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, + "high/1536-x-1024/gpt-image-1": { + "mode": "image_generation", + "input_cost_per_pixel": 1.58945719e-7, + "output_cost_per_pixel": 0.0, + "litellm_provider": "openai", + "supported_endpoints": ["/v1/images/generations"] + }, "gpt-4o-transcribe": { "mode": "audio_transcription", "input_cost_per_token": 0.0000025, From baa5564f95b1e13fd46b7a30d0243f9cc201e09f Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Wed, 23 Apr 2025 14:07:43 -0700 Subject: [PATCH 23/40] cleanup remove stale dir --- litellm/openai-responses-starter-app | 1 - 1 file changed, 1 deletion(-) delete mode 160000 litellm/openai-responses-starter-app diff --git a/litellm/openai-responses-starter-app b/litellm/openai-responses-starter-app deleted file mode 160000 index bf0485467c..0000000000 --- a/litellm/openai-responses-starter-app +++ /dev/null @@ -1 +0,0 @@ -Subproject commit bf0485467c343957ba5c217db777f407b2e65453 From 2e58e47b43f38df3b892784a6b99bac070df6000 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Wed, 23 Apr 2025 15:16:40 -0700 Subject: [PATCH 24/40] [Bug Fix] Add Cost Tracking for gpt-image-1 when quality is unspecified (#10247) * TestOpenAIGPTImage1 * fixes for cost calc * fix ImageGenerationRequestQuality.MEDIUM --- litellm/cost_calculator.py | 54 +++++++++++-------- litellm/main.py | 27 +++++----- litellm/types/llms/openai.py | 45 +++++++++------- .../base_image_generation_test.py | 6 +-- .../image_gen_tests/test_image_generation.py | 3 ++ 5 files changed, 78 insertions(+), 57 deletions(-) diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py index 7f3d4fcc9f..eafd924bc6 100644 --- a/litellm/cost_calculator.py +++ b/litellm/cost_calculator.py @@ -57,6 +57,7 @@ from litellm.llms.vertex_ai.image_generation.cost_calculator import ( from litellm.responses.utils import ResponseAPILoggingUtils from litellm.types.llms.openai import ( HttpxBinaryResponseContent, + ImageGenerationRequestQuality, OpenAIRealtimeStreamList, OpenAIRealtimeStreamResponseBaseObject, OpenAIRealtimeStreamSessionEvents, @@ -642,9 +643,9 @@ def completion_cost( # noqa: PLR0915 or isinstance(completion_response, dict) ): # tts returns a custom class if isinstance(completion_response, dict): - usage_obj: Optional[ - Union[dict, Usage] - ] = completion_response.get("usage", {}) + usage_obj: Optional[Union[dict, Usage]] = ( + completion_response.get("usage", {}) + ) else: usage_obj = getattr(completion_response, "usage", {}) if isinstance(usage_obj, BaseModel) and not _is_known_usage_objects( @@ -913,7 +914,7 @@ def completion_cost( # noqa: PLR0915 def get_response_cost_from_hidden_params( - hidden_params: Union[dict, BaseModel] + hidden_params: Union[dict, BaseModel], ) -> Optional[float]: if isinstance(hidden_params, BaseModel): _hidden_params_dict = hidden_params.model_dump() @@ -1101,30 +1102,37 @@ def default_image_cost_calculator( f"{quality}/{base_model_name}" if quality else base_model_name ) + # gpt-image-1 models use low, medium, high quality. If user did not specify quality, use medium fot gpt-image-1 model family + model_name_with_v2_quality = ( + f"{ImageGenerationRequestQuality.MEDIUM.value}/{base_model_name}" + ) + verbose_logger.debug( f"Looking up cost for models: {model_name_with_quality}, {base_model_name}" ) - # Try model with quality first, fall back to base model name - if model_name_with_quality in litellm.model_cost: - cost_info = litellm.model_cost[model_name_with_quality] - elif base_model_name in litellm.model_cost: - cost_info = litellm.model_cost[base_model_name] - else: - # Try without provider prefix - model_without_provider = f"{size_str}/{model.split('/')[-1]}" - model_with_quality_without_provider = ( - f"{quality}/{model_without_provider}" if quality else model_without_provider - ) + model_without_provider = f"{size_str}/{model.split('/')[-1]}" + model_with_quality_without_provider = ( + f"{quality}/{model_without_provider}" if quality else model_without_provider + ) - if model_with_quality_without_provider in litellm.model_cost: - cost_info = litellm.model_cost[model_with_quality_without_provider] - elif model_without_provider in litellm.model_cost: - cost_info = litellm.model_cost[model_without_provider] - else: - raise Exception( - f"Model not found in cost map. Tried {model_name_with_quality}, {base_model_name}, {model_with_quality_without_provider}, and {model_without_provider}" - ) + # Try model with quality first, fall back to base model name + cost_info: Optional[dict] = None + models_to_check = [ + model_name_with_quality, + base_model_name, + model_name_with_v2_quality, + model_with_quality_without_provider, + model_without_provider, + ] + for model in models_to_check: + if model in litellm.model_cost: + cost_info = litellm.model_cost[model] + break + if cost_info is None: + raise Exception( + f"Model not found in cost map. Tried checking {models_to_check}" + ) return cost_info["input_cost_per_pixel"] * height * width * n diff --git a/litellm/main.py b/litellm/main.py index 80486fbe02..de0716fd96 100644 --- a/litellm/main.py +++ b/litellm/main.py @@ -182,6 +182,7 @@ from .types.llms.openai import ( ChatCompletionPredictionContentParam, ChatCompletionUserMessage, HttpxBinaryResponseContent, + ImageGenerationRequestQuality, ) from .types.utils import ( LITELLM_IMAGE_VARIATION_PROVIDERS, @@ -2688,9 +2689,9 @@ def completion( # type: ignore # noqa: PLR0915 "aws_region_name" not in optional_params or optional_params["aws_region_name"] is None ): - optional_params[ - "aws_region_name" - ] = aws_bedrock_client.meta.region_name + optional_params["aws_region_name"] = ( + aws_bedrock_client.meta.region_name + ) bedrock_route = BedrockModelInfo.get_bedrock_route(model) if bedrock_route == "converse": @@ -4412,9 +4413,9 @@ def adapter_completion( new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs) response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore - translated_response: Optional[ - Union[BaseModel, AdapterCompletionStreamWrapper] - ] = None + translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = ( + None + ) if isinstance(response, ModelResponse): translated_response = translation_obj.translate_completion_output_params( response=response @@ -4567,7 +4568,7 @@ def image_generation( # noqa: PLR0915 prompt: str, model: Optional[str] = None, n: Optional[int] = None, - quality: Optional[str] = None, + quality: Optional[Union[str, ImageGenerationRequestQuality]] = None, response_format: Optional[str] = None, size: Optional[str] = None, style: Optional[str] = None, @@ -5834,9 +5835,9 @@ def stream_chunk_builder( # noqa: PLR0915 ] if len(content_chunks) > 0: - response["choices"][0]["message"][ - "content" - ] = processor.get_combined_content(content_chunks) + response["choices"][0]["message"]["content"] = ( + processor.get_combined_content(content_chunks) + ) reasoning_chunks = [ chunk @@ -5847,9 +5848,9 @@ def stream_chunk_builder( # noqa: PLR0915 ] if len(reasoning_chunks) > 0: - response["choices"][0]["message"][ - "reasoning_content" - ] = processor.get_combined_reasoning_content(reasoning_chunks) + response["choices"][0]["message"]["reasoning_content"] = ( + processor.get_combined_reasoning_content(reasoning_chunks) + ) audio_chunks = [ chunk diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py index dc45ebe5cc..be5f7585bf 100644 --- a/litellm/types/llms/openai.py +++ b/litellm/types/llms/openai.py @@ -824,12 +824,12 @@ class OpenAIChatCompletionChunk(ChatCompletionChunk): class Hyperparameters(BaseModel): batch_size: Optional[Union[str, int]] = None # "Number of examples in each batch." - learning_rate_multiplier: Optional[ - Union[str, float] - ] = None # Scaling factor for the learning rate - n_epochs: Optional[ - Union[str, int] - ] = None # "The number of epochs to train the model for" + learning_rate_multiplier: Optional[Union[str, float]] = ( + None # Scaling factor for the learning rate + ) + n_epochs: Optional[Union[str, int]] = ( + None # "The number of epochs to train the model for" + ) class FineTuningJobCreate(BaseModel): @@ -856,18 +856,18 @@ class FineTuningJobCreate(BaseModel): model: str # "The name of the model to fine-tune." training_file: str # "The ID of an uploaded file that contains training data." - hyperparameters: Optional[ - Hyperparameters - ] = None # "The hyperparameters used for the fine-tuning job." - suffix: Optional[ - str - ] = None # "A string of up to 18 characters that will be added to your fine-tuned model name." - validation_file: Optional[ - str - ] = None # "The ID of an uploaded file that contains validation data." - integrations: Optional[ - List[str] - ] = None # "A list of integrations to enable for your fine-tuning job." + hyperparameters: Optional[Hyperparameters] = ( + None # "The hyperparameters used for the fine-tuning job." + ) + suffix: Optional[str] = ( + None # "A string of up to 18 characters that will be added to your fine-tuned model name." + ) + validation_file: Optional[str] = ( + None # "The ID of an uploaded file that contains validation data." + ) + integrations: Optional[List[str]] = ( + None # "A list of integrations to enable for your fine-tuning job." + ) seed: Optional[int] = None # "The seed controls the reproducibility of the job." @@ -1259,3 +1259,12 @@ class OpenAIRealtimeStreamResponseBaseObject(TypedDict): OpenAIRealtimeStreamList = List[ Union[OpenAIRealtimeStreamResponseBaseObject, OpenAIRealtimeStreamSessionEvents] ] + + +class ImageGenerationRequestQuality(str, Enum): + LOW = "low" + MEDIUM = "medium" + HIGH = "high" + AUTO = "auto" + STANDARD = "standard" + HD = "hd" diff --git a/tests/image_gen_tests/base_image_generation_test.py b/tests/image_gen_tests/base_image_generation_test.py index cf01390e07..76fa2f5540 100644 --- a/tests/image_gen_tests/base_image_generation_test.py +++ b/tests/image_gen_tests/base_image_generation_test.py @@ -66,8 +66,8 @@ class BaseImageGenTest(ABC): logged_standard_logging_payload = custom_logger.standard_logging_payload print("logged_standard_logging_payload", logged_standard_logging_payload) assert logged_standard_logging_payload is not None - # assert logged_standard_logging_payload["response_cost"] is not None - # assert logged_standard_logging_payload["response_cost"] > 0 + assert logged_standard_logging_payload["response_cost"] is not None + assert logged_standard_logging_payload["response_cost"] > 0 from openai.types.images_response import ImagesResponse @@ -85,4 +85,4 @@ class BaseImageGenTest(ABC): if "Your task failed as a result of our safety system." in str(e): pass else: - pytest.fail(f"An exception occurred - {str(e)}") + pytest.fail(f"An exception occurred - {str(e)}") \ No newline at end of file diff --git a/tests/image_gen_tests/test_image_generation.py b/tests/image_gen_tests/test_image_generation.py index bee9d1f7d5..21f96095a7 100644 --- a/tests/image_gen_tests/test_image_generation.py +++ b/tests/image_gen_tests/test_image_generation.py @@ -161,6 +161,9 @@ class TestOpenAIDalle3(BaseImageGenTest): def get_base_image_generation_call_args(self) -> dict: return {"model": "dall-e-3"} +class TestOpenAIGPTImage1(BaseImageGenTest): + def get_base_image_generation_call_args(self) -> dict: + return {"model": "gpt-image-1"} class TestAzureOpenAIDalle3(BaseImageGenTest): def get_base_image_generation_call_args(self) -> dict: From dc9b058dbde2eee43341864bf0c1bf6a41bedb65 Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Wed, 23 Apr 2025 15:19:29 -0700 Subject: [PATCH 25/40] [Feat] Add support for GET Responses Endpoint - OpenAI, Azure OpenAI (#10235) * Added get responses API (#10234) * test_basic_openai_responses_get_endpoint * transform_get_response_api_request * test_basic_openai_responses_get_endpoint --------- Co-authored-by: Prathamesh Saraf --- .../llms/azure/responses/transformation.py | 74 +++++-- .../llms/base_llm/responses/transformation.py | 27 ++- litellm/llms/custom_httpx/llm_http_handler.py | 156 +++++++++++++++ .../llms/openai/responses/transformation.py | 36 ++++ litellm/responses/main.py | 185 ++++++++++++++++++ .../base_responses_api.py | 39 ++++ .../test_anthropic_responses_api.py | 5 + 7 files changed, 501 insertions(+), 21 deletions(-) diff --git a/litellm/llms/azure/responses/transformation.py b/litellm/llms/azure/responses/transformation.py index 499d21cb0e..7d9244e31b 100644 --- a/litellm/llms/azure/responses/transformation.py +++ b/litellm/llms/azure/responses/transformation.py @@ -95,6 +95,35 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig): ######################################################### ########## DELETE RESPONSE API TRANSFORMATION ############## ######################################################### + def _construct_url_for_response_id_in_path( + self, api_base: str, response_id: str + ) -> str: + """ + Constructs a URL for the API request with the response_id in the path. + """ + from urllib.parse import urlparse, urlunparse + + # Parse the URL to separate its components + parsed_url = urlparse(api_base) + + # Insert the response_id at the end of the path component + # Remove trailing slash if present to avoid double slashes + path = parsed_url.path.rstrip("/") + new_path = f"{path}/{response_id}" + + # Reconstruct the URL with all original components but with the modified path + constructed_url = urlunparse( + ( + parsed_url.scheme, # http, https + parsed_url.netloc, # domain name, port + new_path, # path with response_id added + parsed_url.params, # parameters + parsed_url.query, # query string + parsed_url.fragment, # fragment + ) + ) + return constructed_url + def transform_delete_response_api_request( self, response_id: str, @@ -111,28 +140,33 @@ class AzureOpenAIResponsesAPIConfig(OpenAIResponsesAPIConfig): This function handles URLs with query parameters by inserting the response_id at the correct location (before any query parameters). """ - from urllib.parse import urlparse, urlunparse - - # Parse the URL to separate its components - parsed_url = urlparse(api_base) - - # Insert the response_id at the end of the path component - # Remove trailing slash if present to avoid double slashes - path = parsed_url.path.rstrip("/") - new_path = f"{path}/{response_id}" - - # Reconstruct the URL with all original components but with the modified path - delete_url = urlunparse( - ( - parsed_url.scheme, # http, https - parsed_url.netloc, # domain name, port - new_path, # path with response_id added - parsed_url.params, # parameters - parsed_url.query, # query string - parsed_url.fragment, # fragment - ) + delete_url = self._construct_url_for_response_id_in_path( + api_base=api_base, response_id=response_id ) data: Dict = {} verbose_logger.debug(f"delete response url={delete_url}") return delete_url, data + + ######################################################### + ########## GET RESPONSE API TRANSFORMATION ############### + ######################################################### + def transform_get_response_api_request( + self, + response_id: str, + api_base: str, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[str, Dict]: + """ + Transform the get response API request into a URL and data + + OpenAI API expects the following request + - GET /v1/responses/{response_id} + """ + get_url = self._construct_url_for_response_id_in_path( + api_base=api_base, response_id=response_id + ) + data: Dict = {} + verbose_logger.debug(f"get response url={get_url}") + return get_url, data diff --git a/litellm/llms/base_llm/responses/transformation.py b/litellm/llms/base_llm/responses/transformation.py index 15ce8cba3f..751d29dd56 100644 --- a/litellm/llms/base_llm/responses/transformation.py +++ b/litellm/llms/base_llm/responses/transformation.py @@ -141,9 +141,34 @@ class BaseResponsesAPIConfig(ABC): pass ######################################################### - ########## END DELETE RESPONSE API TRANSFORMATION ########## + ########## END DELETE RESPONSE API TRANSFORMATION ####### ######################################################### + ######################################################### + ########## GET RESPONSE API TRANSFORMATION ############### + ######################################################### + @abstractmethod + def transform_get_response_api_request( + self, + response_id: str, + api_base: str, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[str, Dict]: + pass + + @abstractmethod + def transform_get_response_api_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + ) -> ResponsesAPIResponse: + pass + + ######################################################### + ########## END GET RESPONSE API TRANSFORMATION ########## + ######################################################### + def get_error_class( self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers] ) -> BaseLLMException: diff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.py index 1958ef0b60..abbbc2e595 100644 --- a/litellm/llms/custom_httpx/llm_http_handler.py +++ b/litellm/llms/custom_httpx/llm_http_handler.py @@ -1426,6 +1426,162 @@ class BaseLLMHTTPHandler: logging_obj=logging_obj, ) + def get_responses( + self, + response_id: str, + responses_api_provider_config: BaseResponsesAPIConfig, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + custom_llm_provider: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + _is_async: bool = False, + ) -> Union[ResponsesAPIResponse, Coroutine[Any, Any, ResponsesAPIResponse]]: + """ + Get a response by ID + Uses GET /v1/responses/{response_id} endpoint in the responses API + """ + if _is_async: + return self.async_get_responses( + response_id=response_id, + responses_api_provider_config=responses_api_provider_config, + litellm_params=litellm_params, + logging_obj=logging_obj, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout, + client=client, + ) + + if client is None or not isinstance(client, HTTPHandler): + sync_httpx_client = _get_httpx_client( + params={"ssl_verify": litellm_params.get("ssl_verify", None)} + ) + else: + sync_httpx_client = client + + headers = responses_api_provider_config.validate_environment( + api_key=litellm_params.api_key, + headers=extra_headers or {}, + model="None", + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = responses_api_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url, data = responses_api_provider_config.transform_get_response_api_request( + response_id=response_id, + api_base=api_base, + litellm_params=litellm_params, + headers=headers, + ) + + ## LOGGING + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "complete_input_dict": data, + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = sync_httpx_client.get( + url=url, headers=headers, params=data + ) + except Exception as e: + raise self._handle_error( + e=e, + provider_config=responses_api_provider_config, + ) + + return responses_api_provider_config.transform_get_response_api_response( + raw_response=response, + logging_obj=logging_obj, + ) + + async def async_get_responses( + self, + response_id: str, + responses_api_provider_config: BaseResponsesAPIConfig, + litellm_params: GenericLiteLLMParams, + logging_obj: LiteLLMLoggingObj, + custom_llm_provider: Optional[str] = None, + extra_headers: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + client: Optional[Union[HTTPHandler, AsyncHTTPHandler]] = None, + ) -> ResponsesAPIResponse: + """ + Async version of get_responses + """ + if client is None or not isinstance(client, AsyncHTTPHandler): + async_httpx_client = get_async_httpx_client( + llm_provider=litellm.LlmProviders(custom_llm_provider), + params={"ssl_verify": litellm_params.get("ssl_verify", None)}, + ) + else: + async_httpx_client = client + + headers = responses_api_provider_config.validate_environment( + api_key=litellm_params.api_key, + headers=extra_headers or {}, + model="None", + ) + + if extra_headers: + headers.update(extra_headers) + + api_base = responses_api_provider_config.get_complete_url( + api_base=litellm_params.api_base, + litellm_params=dict(litellm_params), + ) + + url, data = responses_api_provider_config.transform_get_response_api_request( + response_id=response_id, + api_base=api_base, + litellm_params=litellm_params, + headers=headers, + ) + + ## LOGGING + logging_obj.pre_call( + input="", + api_key="", + additional_args={ + "complete_input_dict": data, + "api_base": api_base, + "headers": headers, + }, + ) + + try: + response = await async_httpx_client.get( + url=url, headers=headers, params=data + ) + + except Exception as e: + verbose_logger.exception(f"Error retrieving response: {e}") + raise self._handle_error( + e=e, + provider_config=responses_api_provider_config, + ) + + return responses_api_provider_config.transform_get_response_api_response( + raw_response=response, + logging_obj=logging_obj, + ) + def create_file( self, create_file_data: CreateFileRequest, diff --git a/litellm/llms/openai/responses/transformation.py b/litellm/llms/openai/responses/transformation.py index ab16a5647d..8cbdf6bdcc 100644 --- a/litellm/llms/openai/responses/transformation.py +++ b/litellm/llms/openai/responses/transformation.py @@ -250,3 +250,39 @@ class OpenAIResponsesAPIConfig(BaseResponsesAPIConfig): message=raw_response.text, status_code=raw_response.status_code ) return DeleteResponseResult(**raw_response_json) + + ######################################################### + ########## GET RESPONSE API TRANSFORMATION ############### + ######################################################### + def transform_get_response_api_request( + self, + response_id: str, + api_base: str, + litellm_params: GenericLiteLLMParams, + headers: dict, + ) -> Tuple[str, Dict]: + """ + Transform the get response API request into a URL and data + + OpenAI API expects the following request + - GET /v1/responses/{response_id} + """ + url = f"{api_base}/{response_id}" + data: Dict = {} + return url, data + + def transform_get_response_api_response( + self, + raw_response: httpx.Response, + logging_obj: LiteLLMLoggingObj, + ) -> ResponsesAPIResponse: + """ + Transform the get response API response into a ResponsesAPIResponse + """ + try: + raw_response_json = raw_response.json() + except Exception: + raise OpenAIError( + message=raw_response.text, status_code=raw_response.status_code + ) + return ResponsesAPIResponse(**raw_response_json) diff --git a/litellm/responses/main.py b/litellm/responses/main.py index 004a19a0ae..bd0c7246c0 100644 --- a/litellm/responses/main.py +++ b/litellm/responses/main.py @@ -434,3 +434,188 @@ def delete_responses( completion_kwargs=local_vars, extra_kwargs=kwargs, ) + +@client +async def aget_responses( + response_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> ResponsesAPIResponse: + """ + Async: Fetch a response by its ID. + + GET /v1/responses/{response_id} endpoint in the responses API + + Args: + response_id: The ID of the response to fetch. + custom_llm_provider: Optional provider name. If not specified, will be decoded from response_id. + + Returns: + The response object with complete information about the stored response. + """ + local_vars = locals() + try: + loop = asyncio.get_event_loop() + kwargs["aget_responses"] = True + + # get custom llm provider from response_id + decoded_response_id: DecodedResponseId = ( + ResponsesAPIRequestUtils._decode_responses_api_response_id( + response_id=response_id, + ) + ) + response_id = decoded_response_id.get("response_id") or response_id + custom_llm_provider = ( + decoded_response_id.get("custom_llm_provider") or custom_llm_provider + ) + + func = partial( + get_responses, + response_id=response_id, + custom_llm_provider=custom_llm_provider, + extra_headers=extra_headers, + extra_query=extra_query, + extra_body=extra_body, + timeout=timeout, + **kwargs, + ) + + ctx = contextvars.copy_context() + func_with_context = partial(ctx.run, func) + init_response = await loop.run_in_executor(None, func_with_context) + + if asyncio.iscoroutine(init_response): + response = await init_response + else: + response = init_response + + # Update the responses_api_response_id with the model_id + if isinstance(response, ResponsesAPIResponse): + response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id( + responses_api_response=response, + litellm_metadata=kwargs.get("litellm_metadata", {}), + custom_llm_provider=custom_llm_provider, + ) + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) + +@client +def get_responses( + response_id: str, + # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. + # The extra values given here take precedence over values defined on the client or passed to this method. + extra_headers: Optional[Dict[str, Any]] = None, + extra_query: Optional[Dict[str, Any]] = None, + extra_body: Optional[Dict[str, Any]] = None, + timeout: Optional[Union[float, httpx.Timeout]] = None, + # LiteLLM specific params, + custom_llm_provider: Optional[str] = None, + **kwargs, +) -> Union[ResponsesAPIResponse, Coroutine[Any, Any, ResponsesAPIResponse]]: + """ + Fetch a response by its ID. + + GET /v1/responses/{response_id} endpoint in the responses API + + Args: + response_id: The ID of the response to fetch. + custom_llm_provider: Optional provider name. If not specified, will be decoded from response_id. + + Returns: + The response object with complete information about the stored response. + """ + local_vars = locals() + try: + litellm_logging_obj: LiteLLMLoggingObj = kwargs.get("litellm_logging_obj") # type: ignore + litellm_call_id: Optional[str] = kwargs.get("litellm_call_id", None) + _is_async = kwargs.pop("aget_responses", False) is True + + # get llm provider logic + litellm_params = GenericLiteLLMParams(**kwargs) + + # get custom llm provider from response_id + decoded_response_id: DecodedResponseId = ( + ResponsesAPIRequestUtils._decode_responses_api_response_id( + response_id=response_id, + ) + ) + response_id = decoded_response_id.get("response_id") or response_id + custom_llm_provider = ( + decoded_response_id.get("custom_llm_provider") or custom_llm_provider + ) + + if custom_llm_provider is None: + raise ValueError("custom_llm_provider is required but passed as None") + + # get provider config + responses_api_provider_config: Optional[BaseResponsesAPIConfig] = ( + ProviderConfigManager.get_provider_responses_api_config( + model=None, + provider=litellm.LlmProviders(custom_llm_provider), + ) + ) + + if responses_api_provider_config is None: + raise ValueError( + f"GET responses is not supported for {custom_llm_provider}" + ) + + local_vars.update(kwargs) + + # Pre Call logging + litellm_logging_obj.update_environment_variables( + model=None, + optional_params={ + "response_id": response_id, + }, + litellm_params={ + "litellm_call_id": litellm_call_id, + }, + custom_llm_provider=custom_llm_provider, + ) + + # Call the handler with _is_async flag instead of directly calling the async handler + response = base_llm_http_handler.get_responses( + response_id=response_id, + custom_llm_provider=custom_llm_provider, + responses_api_provider_config=responses_api_provider_config, + litellm_params=litellm_params, + logging_obj=litellm_logging_obj, + extra_headers=extra_headers, + extra_body=extra_body, + timeout=timeout or request_timeout, + _is_async=_is_async, + client=kwargs.get("client"), + ) + + # Update the responses_api_response_id with the model_id + if isinstance(response, ResponsesAPIResponse): + response = ResponsesAPIRequestUtils._update_responses_api_response_id_with_model_id( + responses_api_response=response, + litellm_metadata=kwargs.get("litellm_metadata", {}), + custom_llm_provider=custom_llm_provider, + ) + + return response + except Exception as e: + raise litellm.exception_type( + model=None, + custom_llm_provider=custom_llm_provider, + original_exception=e, + completion_kwargs=local_vars, + extra_kwargs=kwargs, + ) \ No newline at end of file diff --git a/tests/llm_responses_api_testing/base_responses_api.py b/tests/llm_responses_api_testing/base_responses_api.py index 905b9b3219..83122f9876 100644 --- a/tests/llm_responses_api_testing/base_responses_api.py +++ b/tests/llm_responses_api_testing/base_responses_api.py @@ -274,5 +274,44 @@ class BaseResponsesAPITest(ABC): **base_completion_call_args ) + @pytest.mark.parametrize("sync_mode", [False, True]) + @pytest.mark.asyncio + async def test_basic_openai_responses_get_endpoint(self, sync_mode): + litellm._turn_on_debug() + litellm.set_verbose = True + base_completion_call_args = self.get_base_completion_call_args() + if sync_mode: + response = litellm.responses( + input="Basic ping", max_output_tokens=20, + **base_completion_call_args + ) + # get the response + if isinstance(response, ResponsesAPIResponse): + result = litellm.get_responses( + response_id=response.id, + **base_completion_call_args + ) + assert result is not None + assert result.id == response.id + assert result.output == response.output + else: + raise ValueError("response is not a ResponsesAPIResponse") + else: + response = await litellm.aresponses( + input="Basic ping", max_output_tokens=20, + **base_completion_call_args + ) + # async get the response + if isinstance(response, ResponsesAPIResponse): + result = await litellm.aget_responses( + response_id=response.id, + **base_completion_call_args + ) + assert result is not None + assert result.id == response.id + assert result.output == response.output + else: + raise ValueError("response is not a ResponsesAPIResponse") + diff --git a/tests/llm_responses_api_testing/test_anthropic_responses_api.py b/tests/llm_responses_api_testing/test_anthropic_responses_api.py index b02c9b8d11..3eabc0c15b 100644 --- a/tests/llm_responses_api_testing/test_anthropic_responses_api.py +++ b/tests/llm_responses_api_testing/test_anthropic_responses_api.py @@ -36,6 +36,11 @@ class TestAnthropicResponsesAPITest(BaseResponsesAPITest): async def test_basic_openai_responses_streaming_delete_endpoint(self, sync_mode=False): pass + async def test_basic_openai_responses_get_endpoint(self, sync_mode=False): + pass + + + def test_multiturn_tool_calls(): # Test streaming response with tools for Anthropic From edd15b09052c945f8b65569e3760614779b32c0a Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Wed, 23 Apr 2025 16:51:27 -0700 Subject: [PATCH 26/40] fix(user_dashboard.tsx): add token expiry logic to user dashboard (#10250) * fix(user_dashboard.tsx): add token expiry logic to user dashboard if token expired redirect to `/sso/key/generate` for login * fix(user_dashboard.tsx): check key health on login - if invalid -> redirect to login handles invalid / expired key scenario * fix(user_dashboard.tsx): fix linting error * fix(page.tsx): fix invitation link flow --- ui/litellm-dashboard/src/app/page.tsx | 6 +- .../src/components/networking.tsx | 3 + .../src/components/user_dashboard.tsx | 87 ++++++++++++++++--- 3 files changed, 84 insertions(+), 12 deletions(-) diff --git a/ui/litellm-dashboard/src/app/page.tsx b/ui/litellm-dashboard/src/app/page.tsx index bcfdfc280b..1fea83d054 100644 --- a/ui/litellm-dashboard/src/app/page.tsx +++ b/ui/litellm-dashboard/src/app/page.tsx @@ -139,6 +139,8 @@ export default function CreateKeyPage() { const [accessToken, setAccessToken] = useState(null); + const redirectToLogin = authLoading === false && token === null && invitation_id === null; + useEffect(() => { const token = getCookie("token"); setToken(token); @@ -146,7 +148,7 @@ export default function CreateKeyPage() { }, []); useEffect(() => { - if (authLoading === false && token === null) { + if (redirectToLogin) { window.location.href = (proxyBaseUrl || "") + "/sso/key/generate" } }, [token, authLoading]) @@ -221,7 +223,7 @@ export default function CreateKeyPage() { } }, [accessToken, userID, userRole]); - if (authLoading || (authLoading == false && token === null)) { + if (authLoading) { return } diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx index e518314e64..8d2c9f535f 100644 --- a/ui/litellm-dashboard/src/components/networking.tsx +++ b/ui/litellm-dashboard/src/components/networking.tsx @@ -2493,6 +2493,9 @@ export const keyInfoCall = async (accessToken: String, keys: String[]) => { if (!response.ok) { const errorData = await response.text(); + if (errorData.includes("Invalid proxy server token passed")) { + throw new Error("Invalid proxy server token passed"); + } handleError(errorData); throw new Error("Network response was not ok"); } diff --git a/ui/litellm-dashboard/src/components/user_dashboard.tsx b/ui/litellm-dashboard/src/components/user_dashboard.tsx index c0f4c96d86..4279c124d0 100644 --- a/ui/litellm-dashboard/src/components/user_dashboard.tsx +++ b/ui/litellm-dashboard/src/components/user_dashboard.tsx @@ -7,7 +7,8 @@ import { getProxyUISettings, Organization, organizationListCall, - DEFAULT_ORGANIZATION + DEFAULT_ORGANIZATION, + keyInfoCall } from "./networking"; import { fetchTeams } from "./common_components/fetch_teams"; import { Grid, Col, Card, Text, Title } from "@tremor/react"; @@ -192,6 +193,7 @@ const UserDashboard: React.FC = ({ null, null ); + setUserSpendData(response["user_info"]); console.log(`userSpendData: ${JSON.stringify(userSpendData)}`) @@ -238,8 +240,11 @@ const UserDashboard: React.FC = ({ "userModels" + userID, JSON.stringify(available_model_names) ); - } catch (error) { + } catch (error: any) { console.error("There was an error fetching the data", error); + if (error.message.includes("Invalid proxy server token passed")) { + gotoLogin(); + } // Optionally, update your UI to reflect the error state here as well } }; @@ -249,6 +254,24 @@ const UserDashboard: React.FC = ({ } }, [userID, token, accessToken, keys, userRole]); + + useEffect(() => { + // check key health - if it's invalid, redirect to login + if (accessToken) { + const fetchKeyInfo = async () => { + try { + const keyInfo = await keyInfoCall(accessToken, [accessToken]); + console.log("keyInfo: ", keyInfo); + } catch (error: any) { + if (error.message.includes("Invalid proxy server token passed")) { + gotoLogin(); + } + } + } + fetchKeyInfo(); + } + }, [accessToken]); + useEffect(() => { console.log(`currentOrg: ${JSON.stringify(currentOrg)}, accessToken: ${accessToken}, userID: ${userID}, userRole: ${userRole}`) if (accessToken) { @@ -295,24 +318,68 @@ const UserDashboard: React.FC = ({ ) } - - if (token == null) { - // user is not logged in as yet - console.log("All cookies before redirect:", document.cookie); - + function gotoLogin() { // Clear token cookies using the utility function clearTokenCookies(); const url = proxyBaseUrl ? `${proxyBaseUrl}/sso/key/generate` : `/sso/key/generate`; - + console.log("Full URL:", url); - window.location.href = url; + window.location.href = url; return null; - } else if (accessToken == null) { + } + + if (token == null) { + // user is not logged in as yet + console.log("All cookies before redirect:", document.cookie); + + // Clear token cookies using the utility function + gotoLogin(); return null; + } else { + // Check if token is expired + try { + const decoded = jwtDecode(token) as { [key: string]: any }; + console.log("Decoded token:", decoded); + const expTime = decoded.exp; + const currentTime = Math.floor(Date.now() / 1000); + + if (expTime && currentTime >= expTime) { + console.log("Token expired, redirecting to login"); + + // Clear token cookies + clearTokenCookies(); + + const url = proxyBaseUrl + ? `${proxyBaseUrl}/sso/key/generate` + : `/sso/key/generate`; + + console.log("Full URL for expired token:", url); + window.location.href = url; + + return null; + } + } catch (error) { + console.error("Error decoding token:", error); + // If there's an error decoding the token, consider it invalid + clearTokenCookies(); + + const url = proxyBaseUrl + ? `${proxyBaseUrl}/sso/key/generate` + : `/sso/key/generate`; + + console.log("Full URL after token decode error:", url); + window.location.href = url; + + return null; + } + + if (accessToken == null) { + return null; + } } if (userID == null) { From 1014529ed69060087c70a40a24944113a58fec3e Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 16:55:35 -0700 Subject: [PATCH 27/40] build(ui/): update ui build --- .../_buildManifest.js | 0 .../_ssgManifest.js | 0 .../out/_next/static/chunks/250-7d480872c0e251dc.js | 1 - .../out/_next/static/chunks/250-85fb4e9c2fdebf3e.js | 1 + .../{699-2176ba2273e4676d.js => 699-907a1bb245b7369a.js} | 0 .../out/_next/static/chunks/app/layout-429ad74a94df7643.js | 2 +- .../static/chunks/app/model_hub/page-3d2c374ee41b38e5.js | 2 +- .../static/chunks/app/onboarding/page-339a46b35fba4423.js | 1 + .../static/chunks/app/onboarding/page-9598003bc1e91371.js | 1 - .../out/_next/static/chunks/app/page-225a364dd94a768d.js | 1 + .../out/_next/static/chunks/app/page-36914b80c40b5032.js | 1 - ...n-app-2b16cdb7ff4e1af7.js => main-app-4f7318ae681a6d94.js} | 2 +- litellm/proxy/_experimental/out/index.html | 2 +- litellm/proxy/_experimental/out/index.txt | 4 ++-- litellm/proxy/_experimental/out/model_hub.txt | 4 ++-- litellm/proxy/_experimental/out/onboarding.html | 2 +- litellm/proxy/_experimental/out/onboarding.txt | 4 ++-- ui/litellm-dashboard/out/404.html | 2 +- .../_buildManifest.js | 0 .../_ssgManifest.js | 0 .../out/_next/static/chunks/250-7d480872c0e251dc.js | 1 - .../out/_next/static/chunks/250-85fb4e9c2fdebf3e.js | 1 + .../{699-2176ba2273e4676d.js => 699-907a1bb245b7369a.js} | 0 .../out/_next/static/chunks/app/layout-429ad74a94df7643.js | 2 +- .../static/chunks/app/model_hub/page-3d2c374ee41b38e5.js | 2 +- .../static/chunks/app/onboarding/page-339a46b35fba4423.js | 1 + .../static/chunks/app/onboarding/page-9598003bc1e91371.js | 1 - .../out/_next/static/chunks/app/page-225a364dd94a768d.js | 1 + .../out/_next/static/chunks/app/page-36914b80c40b5032.js | 1 - ...n-app-2b16cdb7ff4e1af7.js => main-app-4f7318ae681a6d94.js} | 2 +- ui/litellm-dashboard/out/index.html | 2 +- ui/litellm-dashboard/out/index.txt | 4 ++-- ui/litellm-dashboard/out/model_hub.html | 2 +- ui/litellm-dashboard/out/model_hub.txt | 4 ++-- ui/litellm-dashboard/out/onboarding.html | 2 +- ui/litellm-dashboard/out/onboarding.txt | 4 ++-- 36 files changed, 30 insertions(+), 30 deletions(-) rename litellm/proxy/_experimental/out/_next/static/{fzhvjOFL6KeNsWYrLD4ya => TGdu5EOOYr2m-EAOFIND0}/_buildManifest.js (100%) rename litellm/proxy/_experimental/out/_next/static/{fzhvjOFL6KeNsWYrLD4ya => TGdu5EOOYr2m-EAOFIND0}/_ssgManifest.js (100%) delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js rename litellm/proxy/_experimental/out/_next/static/chunks/{699-2176ba2273e4676d.js => 699-907a1bb245b7369a.js} (100%) rename ui/litellm-dashboard/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js => litellm/proxy/_experimental/out/_next/static/chunks/app/layout-429ad74a94df7643.js (59%) rename ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js => litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js (60%) create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js create mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/page-225a364dd94a768d.js delete mode 100644 litellm/proxy/_experimental/out/_next/static/chunks/app/page-36914b80c40b5032.js rename litellm/proxy/_experimental/out/_next/static/chunks/{main-app-2b16cdb7ff4e1af7.js => main-app-4f7318ae681a6d94.js} (54%) rename ui/litellm-dashboard/out/_next/static/{fzhvjOFL6KeNsWYrLD4ya => TGdu5EOOYr2m-EAOFIND0}/_buildManifest.js (100%) rename ui/litellm-dashboard/out/_next/static/{fzhvjOFL6KeNsWYrLD4ya => TGdu5EOOYr2m-EAOFIND0}/_ssgManifest.js (100%) delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/250-7d480872c0e251dc.js create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js rename ui/litellm-dashboard/out/_next/static/chunks/{699-2176ba2273e4676d.js => 699-907a1bb245b7369a.js} (100%) rename litellm/proxy/_experimental/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js => ui/litellm-dashboard/out/_next/static/chunks/app/layout-429ad74a94df7643.js (59%) rename litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js => ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js (60%) create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js create mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/page-225a364dd94a768d.js delete mode 100644 ui/litellm-dashboard/out/_next/static/chunks/app/page-36914b80c40b5032.js rename ui/litellm-dashboard/out/_next/static/chunks/{main-app-2b16cdb7ff4e1af7.js => main-app-4f7318ae681a6d94.js} (54%) diff --git a/litellm/proxy/_experimental/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_buildManifest.js b/litellm/proxy/_experimental/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_buildManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_buildManifest.js rename to litellm/proxy/_experimental/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_buildManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_ssgManifest.js b/litellm/proxy/_experimental/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_ssgManifest.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_ssgManifest.js rename to litellm/proxy/_experimental/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_ssgManifest.js diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js b/litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js deleted file mode 100644 index 3fb93afc11..0000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/250-7d480872c0e251dc.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[250],{19250:function(e,t,o){o.d(t,{$I:function(){return K},AZ:function(){return D},Au:function(){return em},BL:function(){return eU},Br:function(){return b},E9:function(){return eZ},EB:function(){return te},EG:function(){return eX},EY:function(){return eK},Eb:function(){return C},FC:function(){return ei},Gh:function(){return eO},H1:function(){return v},H2:function(){return n},Hx:function(){return eg},I1:function(){return j},It:function(){return x},J$:function(){return ea},K8:function(){return d},K_:function(){return eY},LY:function(){return eI},Lp:function(){return eG},N3:function(){return eN},N8:function(){return ee},NL:function(){return e1},NV:function(){return f},Nc:function(){return ex},O3:function(){return eV},OD:function(){return e_},OU:function(){return eh},Of:function(){return S},Og:function(){return y},Ov:function(){return E},PT:function(){return X},Qg:function(){return eS},RQ:function(){return _},Rg:function(){return Q},Sb:function(){return eJ},So:function(){return et},TF:function(){return ta},Tj:function(){return e$},UM:function(){return e7},VA:function(){return G},Vt:function(){return eD},W_:function(){return V},X:function(){return er},XO:function(){return k},Xd:function(){return eT},Xm:function(){return F},YU:function(){return eL},Yo:function(){return J},Z9:function(){return R},Zr:function(){return m},a6:function(){return O},aC:function(){return to},ao:function(){return eq},b1:function(){return ed},cq:function(){return A},cu:function(){return eP},eH:function(){return Y},eZ:function(){return eF},fE:function(){return e8},fP:function(){return W},g:function(){return eQ},gX:function(){return eb},h3:function(){return es},hT:function(){return ej},hy:function(){return u},ix:function(){return H},j2:function(){return en},jA:function(){return eH},jE:function(){return ez},kK:function(){return p},kn:function(){return q},lP:function(){return h},lU:function(){return e4},lg:function(){return eE},mC:function(){return e9},mR:function(){return eo},mY:function(){return e5},m_:function(){return U},mp:function(){return eM},n$:function(){return ey},n9:function(){return e6},nd:function(){return e3},o6:function(){return $},oC:function(){return eC},ol:function(){return z},pf:function(){return eR},qI:function(){return g},qk:function(){return e0},qm:function(){return w},r1:function(){return tt},r6:function(){return B},rs:function(){return N},s0:function(){return L},sN:function(){return ev},t$:function(){return P},t0:function(){return ek},t3:function(){return eW},tB:function(){return e2},tN:function(){return el},u5:function(){return ec},um:function(){return eB},v9:function(){return ef},vh:function(){return eA},wX:function(){return T},wd:function(){return ew},xA:function(){return eu},xX:function(){return I},zg:function(){return ep}});var a=o(20347),r=o(41021);let n=null;console.log=function(){};let c=0,s=e=>new Promise(t=>setTimeout(t,e)),i=async e=>{let t=Date.now();t-c>6e4?(e.includes("Authentication Error - Expired Key")&&(r.ZP.info("UI Session Expired. Logging out."),c=t,await s(3e3),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",window.location.href="/"),c=t):console.log("Error suppressed to prevent spam:",e)},l="Authorization";function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Authorization";console.log("setGlobalLitellmHeaderName: ".concat(e)),l=e}let h=async()=>{let e=n?"".concat(n,"/openapi.json"):"/openapi.json",t=await fetch(e);return await t.json()},w=async e=>{try{let t=n?"".concat(n,"/get/litellm_model_cost_map"):"/get/litellm_model_cost_map",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}}),a=await o.json();return console.log("received litellm model cost data: ".concat(a)),a}catch(e){throw console.error("Failed to get model cost map:",e),e}},p=async(e,t)=>{try{let o=n?"".concat(n,"/model/new"):"/model/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text()||"Network response was not ok";throw r.ZP.error(e),Error(e)}let c=await a.json();return console.log("API Response:",c),r.ZP.destroy(),r.ZP.success("Model ".concat(t.model_name," created successfully"),2),c}catch(e){throw console.error("Failed to create key:",e),e}},u=async e=>{try{let t=n?"".concat(n,"/model/settings"):"/model/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){console.error("Failed to get model settings:",e)}},y=async(e,t)=>{console.log("model_id in model delete call: ".concat(t));try{let o=n?"".concat(n,"/model/delete"):"/model/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},f=async(e,t)=>{if(console.log("budget_id in budget delete call: ".concat(t)),null!=e)try{let o=n?"".concat(n,"/budget/delete"):"/budget/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},m=async(e,t)=>{try{console.log("Form Values in budgetCreateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/new"):"/budget/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},g=async(e,t)=>{try{console.log("Form Values in budgetUpdateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/update"):"/budget/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},k=async(e,t)=>{try{let o=n?"".concat(n,"/invitation/new"):"/invitation/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},_=async e=>{try{let t=n?"".concat(n,"/alerting/settings"):"/alerting/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},T=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/key/generate"):"/key/generate",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},E=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.auto_create_key=!1,o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/user/new"):"/user/new",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},j=async(e,t)=>{try{let o=n?"".concat(n,"/key/delete"):"/key/delete";console.log("in keyDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},C=async(e,t)=>{try{let o=n?"".concat(n,"/user/delete"):"/user/delete";console.log("in userDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_ids:t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete user(s):",e),e}},N=async(e,t)=>{try{let o=n?"".concat(n,"/team/delete"):"/team/delete";console.log("in teamDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},S=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,h=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null,w=arguments.length>9&&void 0!==arguments[9]?arguments[9]:null;try{let p=n?"".concat(n,"/user/list"):"/user/list";console.log("in userListCall");let u=new URLSearchParams;if(t&&t.length>0){let e=t.join(",");u.append("user_ids",e)}o&&u.append("page",o.toString()),a&&u.append("page_size",a.toString()),r&&u.append("user_email",r),c&&u.append("role",c),s&&u.append("team",s),d&&u.append("sso_user_ids",d),h&&u.append("sort_by",h),w&&u.append("sort_order",w);let y=u.toString();y&&(p+="?".concat(y));let f=await fetch(p,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!f.ok){let e=await f.text();throw i(e),Error("Network response was not ok")}let m=await f.json();return console.log("/user/list API Response:",m),m}catch(e){throw console.error("Failed to create key:",e),e}},b=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,c=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];console.log("userInfoCall: ".concat(t,", ").concat(o,", ").concat(a,", ").concat(r,", ").concat(c,", ").concat(s));try{let d;if(a){d=n?"".concat(n,"/user/list"):"/user/list";let e=new URLSearchParams;null!=r&&e.append("page",r.toString()),null!=c&&e.append("page_size",c.toString()),d+="?".concat(e.toString())}else d=n?"".concat(n,"/user/info"):"/user/info",("Admin"!==o&&"Admin Viewer"!==o||s)&&t&&(d+="?user_id=".concat(t));console.log("Requesting user data from:",d);let h=await fetch(d,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}let w=await h.json();return console.log("API Response:",w),w}catch(e){throw console.error("Failed to fetch user data:",e),e}},F=async(e,t)=>{try{let o=n?"".concat(n,"/team/info"):"/team/info";t&&(o="".concat(o,"?team_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},x=async function(e,t){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;try{let a=n?"".concat(n,"/team/list"):"/team/list";console.log("in teamInfoCall");let r=new URLSearchParams;o&&r.append("user_id",o.toString()),t&&r.append("organization_id",t.toString());let c=r.toString();c&&(a+="?".concat(c));let s=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log("/team/list API Response:",d),d}catch(e){throw console.error("Failed to create key:",e),e}},O=async e=>{try{let t=n?"".concat(n,"/team/available"):"/team/available";console.log("in availableTeamListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/team/available_teams API Response:",a),a}catch(e){throw e}},B=async e=>{try{let t=n?"".concat(n,"/organization/list"):"/organization/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},P=async(e,t)=>{try{let o=n?"".concat(n,"/organization/info"):"/organization/info";t&&(o="".concat(o,"?organization_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},v=async(e,t)=>{try{if(console.log("Form Values in organizationCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw console.error("Failed to parse metadata:",e),Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/organization/new"):"/organization/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},G=async(e,t)=>{try{console.log("Form Values in organizationUpdateCall:",t);let o=n?"".concat(n,"/organization/update"):"/organization/update",a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},A=async(e,t)=>{try{let o=n?"".concat(n,"/organization/delete"):"/organization/delete",a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Error deleting organization: ".concat(e))}return await a.json()}catch(e){throw console.error("Failed to delete organization:",e),e}},J=async(e,t)=>{try{let o=n?"".concat(n,"/utils/transform_request"):"/utils/transform_request",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},I=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;try{let r=n?"".concat(n,"/user/daily/activity"):"/user/daily/activity",c=new URLSearchParams;c.append("start_date",t.toISOString()),c.append("end_date",o.toISOString()),c.append("page_size","1000"),c.append("page",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}return await d.json()}catch(e){throw console.error("Failed to create key:",e),e}},R=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/tag/daily/activity"):"/tag/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("tags",r.join(","));let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},z=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/team/daily/activity"):"/team/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("team_ids",r.join(",")),s.append("exclude_team_ids","litellm-dashboard");let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},V=async e=>{try{let t=n?"".concat(n,"/onboarding/get_token"):"/onboarding/get_token";t+="?invite_link=".concat(e);let o=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},U=async(e,t,o,a)=>{let r=n?"".concat(n,"/onboarding/claim_token"):"/onboarding/claim_token";try{let n=await fetch(r,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({invitation_link:t,user_id:o,password:a})});if(!n.ok){let e=await n.text();throw i(e),Error("Network response was not ok")}let c=await n.json();return console.log(c),c}catch(e){throw console.error("Failed to delete key:",e),e}},L=async(e,t,o)=>{try{let a=n?"".concat(n,"/key/").concat(t,"/regenerate"):"/key/".concat(t,"/regenerate"),r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Regenerate key Response:",c),c}catch(e){throw console.error("Failed to regenerate key:",e),e}},M=!1,Z=null,D=async(e,t,o)=>{try{console.log("modelInfoCall:",e,t,o);let c=n?"".concat(n,"/v2/model/info"):"/v2/model/info";a.ZL.includes(o)||(c+="?user_models_only=true");let s=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw e+="error shown=".concat(M),M||(e.includes("No model list passed")&&(e="No Models Exist. Click Add Model to get started."),r.ZP.info(e,10),M=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{M=!1},1e4)),Error("Network response was not ok")}let i=await s.json();return console.log("modelInfoCall:",i),i}catch(e){throw console.error("Failed to create key:",e),e}},H=async(e,t)=>{try{let o=n?"".concat(n,"/v1/model/info"):"/v1/model/info";o+="?litellm_model_id=".concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");let r=await a.json();return console.log("modelInfoV1Call:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},q=async e=>{try{let t=n?"".concat(n,"/model_group/info"):"/model_group/info",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("modelHubCall:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},X=async e=>{try{let t=n?"".concat(n,"/get/allowed_ips"):"/get/allowed_ips",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw Error("Network response was not ok: ".concat(e))}let a=await o.json();return console.log("getAllowedIPs:",a),a.data}catch(e){throw console.error("Failed to get allowed IPs:",e),e}},Y=async(e,t)=>{try{let o=n?"".concat(n,"/add/allowed_ip"):"/add/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("addAllowedIP:",r),r}catch(e){throw console.error("Failed to add allowed IP:",e),e}},K=async(e,t)=>{try{let o=n?"".concat(n,"/delete/allowed_ip"):"/delete/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("deleteAllowedIP:",r),r}catch(e){throw console.error("Failed to delete allowed IP:",e),e}},$=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics"):"/model/metrics";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},Q=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/model/streaming_metrics"):"/model/streaming_metrics";t&&(r="".concat(r,"?_selected_model_group=").concat(t,"&startTime=").concat(o,"&endTime=").concat(a));let c=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},W=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/slow_responses"):"/model/metrics/slow_responses";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},ee=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/exceptions"):"/model/metrics/exceptions";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},et=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;console.log("in /models calls, globalLitellmHeaderName",l);try{let t=n?"".concat(n,"/models"):"/models",o=new URLSearchParams;!0===a&&o.append("return_wildcard_routes","True"),r&&o.append("team_id",r.toString()),o.toString()&&(t+="?".concat(o.toString()));let c=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},eo=async e=>{try{let t=n?"".concat(n,"/global/spend/teams"):"/global/spend/teams";console.log("in teamSpendLogsCall:",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ea=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/tags"):"/global/spend/tags";t&&o&&(r="".concat(r,"?start_date=").concat(t,"&end_date=").concat(o)),a&&(r+="".concat(r,"&tags=").concat(a.join(","))),console.log("in tagsSpendLogsCall:",r);let c=await fetch("".concat(r),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to create key:",e),e}},er=async e=>{try{let t=n?"".concat(n,"/global/spend/all_tag_names"):"/global/spend/all_tag_names";console.log("in global/spend/all_tag_names call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},en=async e=>{try{let t=n?"".concat(n,"/global/all_end_users"):"/global/all_end_users";console.log("in global/all_end_users call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ec=async(e,t)=>{try{let o=n?"".concat(n,"/user/filter/ui"):"/user/filter/ui";t.get("user_email")&&(o+="?user_email=".concat(t.get("user_email"))),t.get("user_id")&&(o+="?user_id=".concat(t.get("user_id")));let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},es=async(e,t,o,a,r,c,s,d,h)=>{try{let w=n?"".concat(n,"/spend/logs/ui"):"/spend/logs/ui",p=new URLSearchParams;t&&p.append("api_key",t),o&&p.append("team_id",o),a&&p.append("request_id",a),r&&p.append("start_date",r),c&&p.append("end_date",c),s&&p.append("page",s.toString()),d&&p.append("page_size",d.toString()),h&&p.append("user_id",h);let u=p.toString();u&&(w+="?".concat(u));let y=await fetch(w,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!y.ok){let e=await y.text();throw i(e),Error("Network response was not ok")}let f=await y.json();return console.log("Spend Logs Response:",f),f}catch(e){throw console.error("Failed to fetch spend logs:",e),e}},ei=async e=>{try{let t=n?"".concat(n,"/global/spend/logs"):"/global/spend/logs",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},el=async e=>{try{let t=n?"".concat(n,"/global/spend/keys?limit=5"):"/global/spend/keys?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ed=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/end_users"):"/global/spend/end_users",c="";c=t?JSON.stringify({api_key:t,startTime:o,endTime:a}):JSON.stringify({startTime:o,endTime:a});let s={method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:c},d=await fetch(r,s);if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log(h),h}catch(e){throw console.error("Failed to create key:",e),e}},eh=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/provider"):"/global/spend/provider";o&&a&&(r+="?start_date=".concat(o,"&end_date=").concat(a)),t&&(r+="&api_key=".concat(t));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log(d),d}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ew=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity"):"/global/activity";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ep=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/cache_hits"):"/global/activity/cache_hits";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},eu=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/model"):"/global/activity/model";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ey=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions"):"/global/activity/exceptions";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ef=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions/deployment"):"/global/activity/exceptions/deployment";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},em=async e=>{try{let t=n?"".concat(n,"/global/spend/models?limit=5"):"/global/spend/models?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},eg=async(e,t,o)=>{try{console.log("Sending model connection test request:",JSON.stringify(t));let r=n?"".concat(n,"/health/test_connection"):"/health/test_connection",c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",[l]:"Bearer ".concat(e)},body:JSON.stringify({litellm_params:t,mode:o})}),s=c.headers.get("content-type");if(!s||!s.includes("application/json")){let e=await c.text();throw console.error("Received non-JSON response:",e),Error("Received non-JSON response (".concat(c.status,": ").concat(c.statusText,"). Check network tab for details."))}let i=await c.json();if(!c.ok||"error"===i.status){if("error"===i.status);else{var a;return{status:"error",message:(null===(a=i.error)||void 0===a?void 0:a.message)||"Connection test failed: ".concat(c.status," ").concat(c.statusText)}}}return i}catch(e){throw console.error("Model connection test error:",e),e}},ek=async(e,t)=>{try{console.log("entering keyInfoV1Call");let o=n?"".concat(n,"/key/info"):"/key/info";o="".concat(o,"?key=").concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(console.log("response",a),!a.ok){let e=await a.text();i(e),r.ZP.error("Failed to fetch key info - "+e)}let c=await a.json();return console.log("data",c),c}catch(e){throw console.error("Failed to fetch key info:",e),e}},e_=async(e,t,o,a,r,c)=>{try{let s=n?"".concat(n,"/key/list"):"/key/list";console.log("in keyListCall");let d=new URLSearchParams;o&&d.append("team_id",o.toString()),t&&d.append("organization_id",t.toString()),a&&d.append("key_alias",a),r&&d.append("page",r.toString()),c&&d.append("size",c.toString()),d.append("return_full_object","true"),d.append("include_team_keys","true");let h=d.toString();h&&(s+="?".concat(h));let w=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!w.ok){let e=await w.text();throw i(e),Error("Network response was not ok")}let p=await w.json();return console.log("/team/list API Response:",p),p}catch(e){throw console.error("Failed to create key:",e),e}},eT=async(e,t)=>{try{let o=n?"".concat(n,"/user/get_users?role=").concat(t):"/user/get_users?role=".concat(t);console.log("in userGetAllUsersCall:",o);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to get requested models:",e),e}},eE=async e=>{try{let t=n?"".concat(n,"/user/available_roles"):"/user/available_roles",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("response from user/available_role",a),a}catch(e){throw e}},ej=async(e,t)=>{try{if(console.log("Form Values in teamCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/team/new"):"/team/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eC=async(e,t)=>{try{if(console.log("Form Values in credentialCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/credentials"):"/credentials",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eN=async e=>{try{let t=n?"".concat(n,"/credentials"):"/credentials";console.log("in credentialListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/credentials API Response:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},eS=async(e,t,o)=>{try{let a=n?"".concat(n,"/credentials"):"/credentials";t?a+="/by_name/".concat(t):o&&(a+="/by_model/".concat(o)),console.log("in credentialListCall");let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("/credentials API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eb=async(e,t)=>{try{let o=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t);console.log("in credentialDeleteCall:",t);let a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},eF=async(e,t,o)=>{try{if(console.log("Form Values in credentialUpdateCall:",o),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let a=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t),r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ex=async(e,t)=>{try{if(console.log("Form Values in keyUpdateCall:",t),t.model_tpm_limit){console.log("formValues.model_tpm_limit:",t.model_tpm_limit);try{t.model_tpm_limit=JSON.parse(t.model_tpm_limit)}catch(e){throw Error("Failed to parse model_tpm_limit: "+e)}}if(t.model_rpm_limit){console.log("formValues.model_rpm_limit:",t.model_rpm_limit);try{t.model_rpm_limit=JSON.parse(t.model_rpm_limit)}catch(e){throw Error("Failed to parse model_rpm_limit: "+e)}}let o=n?"".concat(n,"/key/update"):"/key/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update key Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eO=async(e,t)=>{try{console.log("Form Values in teamUpateCall:",t);let o=n?"".concat(n,"/team/update"):"/team/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eB=async(e,t)=>{try{console.log("Form Values in modelUpateCall:",t);let o=n?"".concat(n,"/model/update"):"/model/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error update from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update model Response:",r),r}catch(e){throw console.error("Failed to update model:",e),e}},eP=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_add"):"/team/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ev=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_update"):"/team/member_update",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,role:o.role,user_id:o.user_id})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eG=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_delete"):"/team/member_delete",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,...void 0!==o.user_email&&{user_email:o.user_email},...void 0!==o.user_id&&{user_id:o.user_id}})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eA=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/organization/member_add"):"/organization/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create organization member:",e),e}},eJ=async(e,t,o)=>{try{console.log("Form Values in organizationMemberDeleteCall:",o);let a=n?"".concat(n,"/organization/member_delete"):"/organization/member_delete",r=await fetch(a,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,user_id:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to delete organization member:",e),e}},eI=async(e,t,o)=>{try{console.log("Form Values in organizationMemberUpdateCall:",o);let a=n?"".concat(n,"/organization/member_update"):"/organization/member_update",r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to update organization member:",e),e}},eR=async(e,t,o)=>{try{console.log("Form Values in userUpdateUserCall:",t);let a=n?"".concat(n,"/user/update"):"/user/update",r={...t};null!==o&&(r.user_role=o),r=JSON.stringify(r);let c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:r});if(!c.ok){let e=await c.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let s=await c.json();return console.log("API Response:",s),s}catch(e){throw console.error("Failed to create key:",e),e}},ez=async(e,t)=>{try{let o=n?"".concat(n,"/health/services?service=").concat(t):"/health/services?service=".concat(t);console.log("Checking Slack Budget Alerts service health");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error(e)}let c=await a.json();return r.ZP.success("Test request to ".concat(t," made - check logs/alerts on ").concat(t," to verify")),c}catch(e){throw console.error("Failed to perform health check:",e),e}},eV=async e=>{try{let t=n?"".concat(n,"/budget/list"):"/budget/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eU=async(e,t,o)=>{try{let t=n?"".concat(n,"/get/config/callbacks"):"/get/config/callbacks",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eL=async e=>{try{let t=n?"".concat(n,"/config/list?config_type=general_settings"):"/config/list?config_type=general_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eM=async e=>{try{let t=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eZ=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/info?field_name=").concat(t):"/config/field/info?field_name=".concat(t),a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eD=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eH=async(e,t,o)=>{try{let a=n?"".concat(n,"/config/field/update"):"/config/field/update",c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,field_value:o,config_type:"general_settings"})});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}let s=await c.json();return r.ZP.success("Successfully updated value!"),s}catch(e){throw console.error("Failed to set callbacks:",e),e}},eq=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/delete"):"/config/field/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,config_type:"general_settings"})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return r.ZP.success("Field reset on proxy"),c}catch(e){throw console.error("Failed to get callbacks:",e),e}},eX=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint?endpoint_id=").concat(t):"/config/pass_through_endpoint".concat(t),a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eY=async(e,t)=>{try{let o=n?"".concat(n,"/config/update"):"/config/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eK=async e=>{try{let t=n?"".concat(n,"/health"):"/health",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to call /health:",e),e}},e$=async e=>{try{let t=n?"".concat(n,"/cache/ping"):"/cache/ping",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error(e)}return await o.json()}catch(e){throw console.error("Failed to call /cache/ping:",e),e}},eQ=async e=>{try{let t=n?"".concat(n,"/sso/get/ui_settings"):"/sso/get/ui_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eW=async e=>{try{let t=n?"".concat(n,"/guardrails/list"):"/guardrails/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Guardrails list response:",a),a}catch(e){throw console.error("Failed to fetch guardrails list:",e),e}},e0=async(e,t,o)=>{try{let a=n?"".concat(n,"/spend/logs/ui/").concat(t,"?start_date=").concat(encodeURIComponent(o)):"/spend/logs/ui/".concat(t,"?start_date=").concat(encodeURIComponent(o));console.log("Fetching log details from:",a);let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Fetched log details:",c),c}catch(e){throw console.error("Failed to fetch log details:",e),e}},e1=async e=>{try{let t=n?"".concat(n,"/get/internal_user_settings"):"/get/internal_user_settings";console.log("Fetching SSO settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched SSO settings:",a),a}catch(e){throw console.error("Failed to fetch SSO settings:",e),e}},e3=async(e,t)=>{try{let o=n?"".concat(n,"/update/internal_user_settings"):"/update/internal_user_settings";console.log("Updating internal user settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated internal user settings:",c),r.ZP.success("Internal user settings updated successfully"),c}catch(e){throw console.error("Failed to update internal user settings:",e),e}},e4=async e=>{try{let t=n?"".concat(n,"/mcp/tools/list"):"/mcp/tools/list";console.log("Fetching MCP tools from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched MCP tools:",a),a}catch(e){throw console.error("Failed to fetch MCP tools:",e),e}},e2=async(e,t,o)=>{try{let a=n?"".concat(n,"/mcp/tools/call"):"/mcp/tools/call";console.log("Calling MCP tool:",t,"with arguments:",o);let r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("MCP tool call response:",c),c}catch(e){throw console.error("Failed to call MCP tool:",e),e}},e5=async(e,t)=>{try{let o=n?"".concat(n,"/tag/new"):"/tag/new",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error creating tag:",e),e}},e6=async(e,t)=>{try{let o=n?"".concat(n,"/tag/update"):"/tag/update",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error updating tag:",e),e}},e9=async(e,t)=>{try{let o=n?"".concat(n,"/tag/info"):"/tag/info",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({names:t})});if(!a.ok){let e=await a.text();return await i(e),{}}return await a.json()}catch(e){throw console.error("Error getting tag info:",e),e}},e7=async e=>{try{let t=n?"".concat(n,"/tag/list"):"/tag/list",o=await fetch(t,{method:"GET",headers:{Authorization:"Bearer ".concat(e)}});if(!o.ok){let e=await o.text();return await i(e),{}}return await o.json()}catch(e){throw console.error("Error listing tags:",e),e}},e8=async(e,t)=>{try{let o=n?"".concat(n,"/tag/delete"):"/tag/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({name:t})});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error deleting tag:",e),e}},te=async e=>{try{let t=n?"".concat(n,"/get/default_team_settings"):"/get/default_team_settings";console.log("Fetching default team settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched default team settings:",a),a}catch(e){throw console.error("Failed to fetch default team settings:",e),e}},tt=async(e,t)=>{try{let o=n?"".concat(n,"/update/default_team_settings"):"/update/default_team_settings";console.log("Updating default team settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated default team settings:",c),r.ZP.success("Default team settings updated successfully"),c}catch(e){throw console.error("Failed to update default team settings:",e),e}},to=async(e,t)=>{try{let o=n?"".concat(n,"/team/permissions_list?team_id=").concat(t):"/team/permissions_list?team_id=".concat(t),a=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("Team permissions response:",r),r}catch(e){throw console.error("Failed to get team permissions:",e),e}},ta=async(e,t,o)=>{try{let a=n?"".concat(n,"/team/permissions_update"):"/team/permissions_update",r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({team_id:t,team_member_permissions:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Team permissions response:",c),c}catch(e){throw console.error("Failed to update team permissions:",e),e}}},20347:function(e,t,o){o.d(t,{LQ:function(){return n},ZL:function(){return a},lo:function(){return r},tY:function(){return c}});let a=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],r=["Internal User","Internal Viewer"],n=["Internal User","Admin"],c=e=>a.includes(e)}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js b/litellm/proxy/_experimental/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js new file mode 100644 index 0000000000..d058e3dd01 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[250],{19250:function(e,t,o){o.d(t,{$I:function(){return K},AZ:function(){return D},Au:function(){return em},BL:function(){return eL},Br:function(){return b},E9:function(){return eD},EB:function(){return tt},EG:function(){return eY},EY:function(){return e$},Eb:function(){return C},FC:function(){return ei},Gh:function(){return eB},H1:function(){return v},H2:function(){return n},Hx:function(){return ek},I1:function(){return j},It:function(){return x},J$:function(){return ea},K8:function(){return d},K_:function(){return eK},LY:function(){return eR},Lp:function(){return eA},N3:function(){return eS},N8:function(){return ee},NL:function(){return e3},NV:function(){return f},Nc:function(){return eO},O3:function(){return eU},OD:function(){return eT},OU:function(){return eh},Of:function(){return S},Og:function(){return y},Ov:function(){return E},PT:function(){return X},Qg:function(){return eb},RQ:function(){return _},Rg:function(){return Q},Sb:function(){return eI},So:function(){return et},TF:function(){return tr},Tj:function(){return eQ},UM:function(){return e8},VA:function(){return G},Vt:function(){return eH},W_:function(){return V},X:function(){return er},XO:function(){return k},Xd:function(){return eE},Xm:function(){return F},YU:function(){return eM},Yo:function(){return J},Z9:function(){return R},Zr:function(){return m},a6:function(){return O},aC:function(){return ta},ao:function(){return eX},b1:function(){return ed},cq:function(){return A},cu:function(){return ev},e2:function(){return eg},eH:function(){return Y},eZ:function(){return ex},fE:function(){return te},fP:function(){return W},g:function(){return eW},gX:function(){return eF},h3:function(){return es},hT:function(){return eC},hy:function(){return u},ix:function(){return H},j2:function(){return en},jA:function(){return eq},jE:function(){return eV},kK:function(){return p},kn:function(){return q},lP:function(){return h},lU:function(){return e4},lg:function(){return ej},mC:function(){return e7},mR:function(){return eo},mY:function(){return e6},m_:function(){return U},mp:function(){return eZ},n$:function(){return ey},n9:function(){return e9},nd:function(){return e2},o6:function(){return $},oC:function(){return eN},ol:function(){return z},pf:function(){return ez},qI:function(){return g},qk:function(){return e1},qm:function(){return w},r1:function(){return to},r6:function(){return B},rs:function(){return N},s0:function(){return L},sN:function(){return eG},t$:function(){return P},t0:function(){return e_},t3:function(){return e0},tB:function(){return e5},tN:function(){return el},u5:function(){return ec},um:function(){return eP},v9:function(){return ef},vh:function(){return eJ},wX:function(){return T},wd:function(){return ew},xA:function(){return eu},xX:function(){return I},zg:function(){return ep}});var a=o(20347),r=o(41021);let n=null;console.log=function(){};let c=0,s=e=>new Promise(t=>setTimeout(t,e)),i=async e=>{let t=Date.now();t-c>6e4?(e.includes("Authentication Error - Expired Key")&&(r.ZP.info("UI Session Expired. Logging out."),c=t,await s(3e3),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",window.location.href="/"),c=t):console.log("Error suppressed to prevent spam:",e)},l="Authorization";function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Authorization";console.log("setGlobalLitellmHeaderName: ".concat(e)),l=e}let h=async()=>{let e=n?"".concat(n,"/openapi.json"):"/openapi.json",t=await fetch(e);return await t.json()},w=async e=>{try{let t=n?"".concat(n,"/get/litellm_model_cost_map"):"/get/litellm_model_cost_map",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}}),a=await o.json();return console.log("received litellm model cost data: ".concat(a)),a}catch(e){throw console.error("Failed to get model cost map:",e),e}},p=async(e,t)=>{try{let o=n?"".concat(n,"/model/new"):"/model/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text()||"Network response was not ok";throw r.ZP.error(e),Error(e)}let c=await a.json();return console.log("API Response:",c),r.ZP.destroy(),r.ZP.success("Model ".concat(t.model_name," created successfully"),2),c}catch(e){throw console.error("Failed to create key:",e),e}},u=async e=>{try{let t=n?"".concat(n,"/model/settings"):"/model/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){console.error("Failed to get model settings:",e)}},y=async(e,t)=>{console.log("model_id in model delete call: ".concat(t));try{let o=n?"".concat(n,"/model/delete"):"/model/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},f=async(e,t)=>{if(console.log("budget_id in budget delete call: ".concat(t)),null!=e)try{let o=n?"".concat(n,"/budget/delete"):"/budget/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},m=async(e,t)=>{try{console.log("Form Values in budgetCreateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/new"):"/budget/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},g=async(e,t)=>{try{console.log("Form Values in budgetUpdateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/update"):"/budget/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},k=async(e,t)=>{try{let o=n?"".concat(n,"/invitation/new"):"/invitation/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},_=async e=>{try{let t=n?"".concat(n,"/alerting/settings"):"/alerting/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},T=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/key/generate"):"/key/generate",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},E=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.auto_create_key=!1,o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/user/new"):"/user/new",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},j=async(e,t)=>{try{let o=n?"".concat(n,"/key/delete"):"/key/delete";console.log("in keyDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},C=async(e,t)=>{try{let o=n?"".concat(n,"/user/delete"):"/user/delete";console.log("in userDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_ids:t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete user(s):",e),e}},N=async(e,t)=>{try{let o=n?"".concat(n,"/team/delete"):"/team/delete";console.log("in teamDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},S=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,h=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null,w=arguments.length>9&&void 0!==arguments[9]?arguments[9]:null;try{let p=n?"".concat(n,"/user/list"):"/user/list";console.log("in userListCall");let u=new URLSearchParams;if(t&&t.length>0){let e=t.join(",");u.append("user_ids",e)}o&&u.append("page",o.toString()),a&&u.append("page_size",a.toString()),r&&u.append("user_email",r),c&&u.append("role",c),s&&u.append("team",s),d&&u.append("sso_user_ids",d),h&&u.append("sort_by",h),w&&u.append("sort_order",w);let y=u.toString();y&&(p+="?".concat(y));let f=await fetch(p,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!f.ok){let e=await f.text();throw i(e),Error("Network response was not ok")}let m=await f.json();return console.log("/user/list API Response:",m),m}catch(e){throw console.error("Failed to create key:",e),e}},b=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,c=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];console.log("userInfoCall: ".concat(t,", ").concat(o,", ").concat(a,", ").concat(r,", ").concat(c,", ").concat(s));try{let d;if(a){d=n?"".concat(n,"/user/list"):"/user/list";let e=new URLSearchParams;null!=r&&e.append("page",r.toString()),null!=c&&e.append("page_size",c.toString()),d+="?".concat(e.toString())}else d=n?"".concat(n,"/user/info"):"/user/info",("Admin"!==o&&"Admin Viewer"!==o||s)&&t&&(d+="?user_id=".concat(t));console.log("Requesting user data from:",d);let h=await fetch(d,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}let w=await h.json();return console.log("API Response:",w),w}catch(e){throw console.error("Failed to fetch user data:",e),e}},F=async(e,t)=>{try{let o=n?"".concat(n,"/team/info"):"/team/info";t&&(o="".concat(o,"?team_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},x=async function(e,t){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;try{let a=n?"".concat(n,"/team/list"):"/team/list";console.log("in teamInfoCall");let r=new URLSearchParams;o&&r.append("user_id",o.toString()),t&&r.append("organization_id",t.toString());let c=r.toString();c&&(a+="?".concat(c));let s=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log("/team/list API Response:",d),d}catch(e){throw console.error("Failed to create key:",e),e}},O=async e=>{try{let t=n?"".concat(n,"/team/available"):"/team/available";console.log("in availableTeamListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/team/available_teams API Response:",a),a}catch(e){throw e}},B=async e=>{try{let t=n?"".concat(n,"/organization/list"):"/organization/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},P=async(e,t)=>{try{let o=n?"".concat(n,"/organization/info"):"/organization/info";t&&(o="".concat(o,"?organization_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},v=async(e,t)=>{try{if(console.log("Form Values in organizationCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw console.error("Failed to parse metadata:",e),Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/organization/new"):"/organization/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},G=async(e,t)=>{try{console.log("Form Values in organizationUpdateCall:",t);let o=n?"".concat(n,"/organization/update"):"/organization/update",a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},A=async(e,t)=>{try{let o=n?"".concat(n,"/organization/delete"):"/organization/delete",a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Error deleting organization: ".concat(e))}return await a.json()}catch(e){throw console.error("Failed to delete organization:",e),e}},J=async(e,t)=>{try{let o=n?"".concat(n,"/utils/transform_request"):"/utils/transform_request",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},I=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;try{let r=n?"".concat(n,"/user/daily/activity"):"/user/daily/activity",c=new URLSearchParams;c.append("start_date",t.toISOString()),c.append("end_date",o.toISOString()),c.append("page_size","1000"),c.append("page",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}return await d.json()}catch(e){throw console.error("Failed to create key:",e),e}},R=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/tag/daily/activity"):"/tag/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("tags",r.join(","));let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},z=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/team/daily/activity"):"/team/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("team_ids",r.join(",")),s.append("exclude_team_ids","litellm-dashboard");let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},V=async e=>{try{let t=n?"".concat(n,"/onboarding/get_token"):"/onboarding/get_token";t+="?invite_link=".concat(e);let o=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},U=async(e,t,o,a)=>{let r=n?"".concat(n,"/onboarding/claim_token"):"/onboarding/claim_token";try{let n=await fetch(r,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({invitation_link:t,user_id:o,password:a})});if(!n.ok){let e=await n.text();throw i(e),Error("Network response was not ok")}let c=await n.json();return console.log(c),c}catch(e){throw console.error("Failed to delete key:",e),e}},L=async(e,t,o)=>{try{let a=n?"".concat(n,"/key/").concat(t,"/regenerate"):"/key/".concat(t,"/regenerate"),r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Regenerate key Response:",c),c}catch(e){throw console.error("Failed to regenerate key:",e),e}},M=!1,Z=null,D=async(e,t,o)=>{try{console.log("modelInfoCall:",e,t,o);let c=n?"".concat(n,"/v2/model/info"):"/v2/model/info";a.ZL.includes(o)||(c+="?user_models_only=true");let s=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw e+="error shown=".concat(M),M||(e.includes("No model list passed")&&(e="No Models Exist. Click Add Model to get started."),r.ZP.info(e,10),M=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{M=!1},1e4)),Error("Network response was not ok")}let i=await s.json();return console.log("modelInfoCall:",i),i}catch(e){throw console.error("Failed to create key:",e),e}},H=async(e,t)=>{try{let o=n?"".concat(n,"/v1/model/info"):"/v1/model/info";o+="?litellm_model_id=".concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");let r=await a.json();return console.log("modelInfoV1Call:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},q=async e=>{try{let t=n?"".concat(n,"/model_group/info"):"/model_group/info",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("modelHubCall:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},X=async e=>{try{let t=n?"".concat(n,"/get/allowed_ips"):"/get/allowed_ips",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw Error("Network response was not ok: ".concat(e))}let a=await o.json();return console.log("getAllowedIPs:",a),a.data}catch(e){throw console.error("Failed to get allowed IPs:",e),e}},Y=async(e,t)=>{try{let o=n?"".concat(n,"/add/allowed_ip"):"/add/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("addAllowedIP:",r),r}catch(e){throw console.error("Failed to add allowed IP:",e),e}},K=async(e,t)=>{try{let o=n?"".concat(n,"/delete/allowed_ip"):"/delete/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("deleteAllowedIP:",r),r}catch(e){throw console.error("Failed to delete allowed IP:",e),e}},$=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics"):"/model/metrics";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},Q=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/model/streaming_metrics"):"/model/streaming_metrics";t&&(r="".concat(r,"?_selected_model_group=").concat(t,"&startTime=").concat(o,"&endTime=").concat(a));let c=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},W=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/slow_responses"):"/model/metrics/slow_responses";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},ee=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/exceptions"):"/model/metrics/exceptions";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},et=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;console.log("in /models calls, globalLitellmHeaderName",l);try{let t=n?"".concat(n,"/models"):"/models",o=new URLSearchParams;!0===a&&o.append("return_wildcard_routes","True"),r&&o.append("team_id",r.toString()),o.toString()&&(t+="?".concat(o.toString()));let c=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},eo=async e=>{try{let t=n?"".concat(n,"/global/spend/teams"):"/global/spend/teams";console.log("in teamSpendLogsCall:",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ea=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/tags"):"/global/spend/tags";t&&o&&(r="".concat(r,"?start_date=").concat(t,"&end_date=").concat(o)),a&&(r+="".concat(r,"&tags=").concat(a.join(","))),console.log("in tagsSpendLogsCall:",r);let c=await fetch("".concat(r),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to create key:",e),e}},er=async e=>{try{let t=n?"".concat(n,"/global/spend/all_tag_names"):"/global/spend/all_tag_names";console.log("in global/spend/all_tag_names call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},en=async e=>{try{let t=n?"".concat(n,"/global/all_end_users"):"/global/all_end_users";console.log("in global/all_end_users call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ec=async(e,t)=>{try{let o=n?"".concat(n,"/user/filter/ui"):"/user/filter/ui";t.get("user_email")&&(o+="?user_email=".concat(t.get("user_email"))),t.get("user_id")&&(o+="?user_id=".concat(t.get("user_id")));let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},es=async(e,t,o,a,r,c,s,d,h)=>{try{let w=n?"".concat(n,"/spend/logs/ui"):"/spend/logs/ui",p=new URLSearchParams;t&&p.append("api_key",t),o&&p.append("team_id",o),a&&p.append("request_id",a),r&&p.append("start_date",r),c&&p.append("end_date",c),s&&p.append("page",s.toString()),d&&p.append("page_size",d.toString()),h&&p.append("user_id",h);let u=p.toString();u&&(w+="?".concat(u));let y=await fetch(w,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!y.ok){let e=await y.text();throw i(e),Error("Network response was not ok")}let f=await y.json();return console.log("Spend Logs Response:",f),f}catch(e){throw console.error("Failed to fetch spend logs:",e),e}},ei=async e=>{try{let t=n?"".concat(n,"/global/spend/logs"):"/global/spend/logs",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},el=async e=>{try{let t=n?"".concat(n,"/global/spend/keys?limit=5"):"/global/spend/keys?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ed=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/end_users"):"/global/spend/end_users",c="";c=t?JSON.stringify({api_key:t,startTime:o,endTime:a}):JSON.stringify({startTime:o,endTime:a});let s={method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:c},d=await fetch(r,s);if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log(h),h}catch(e){throw console.error("Failed to create key:",e),e}},eh=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/provider"):"/global/spend/provider";o&&a&&(r+="?start_date=".concat(o,"&end_date=").concat(a)),t&&(r+="&api_key=".concat(t));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log(d),d}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ew=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity"):"/global/activity";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ep=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/cache_hits"):"/global/activity/cache_hits";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},eu=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/model"):"/global/activity/model";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ey=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions"):"/global/activity/exceptions";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ef=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions/deployment"):"/global/activity/exceptions/deployment";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},em=async e=>{try{let t=n?"".concat(n,"/global/spend/models?limit=5"):"/global/spend/models?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},eg=async(e,t)=>{try{let o=n?"".concat(n,"/v2/key/info"):"/v2/key/info",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:t})});if(!a.ok){let e=await a.text();if(e.includes("Invalid proxy server token passed"))throw Error("Invalid proxy server token passed");throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},ek=async(e,t,o)=>{try{console.log("Sending model connection test request:",JSON.stringify(t));let r=n?"".concat(n,"/health/test_connection"):"/health/test_connection",c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",[l]:"Bearer ".concat(e)},body:JSON.stringify({litellm_params:t,mode:o})}),s=c.headers.get("content-type");if(!s||!s.includes("application/json")){let e=await c.text();throw console.error("Received non-JSON response:",e),Error("Received non-JSON response (".concat(c.status,": ").concat(c.statusText,"). Check network tab for details."))}let i=await c.json();if(!c.ok||"error"===i.status){if("error"===i.status);else{var a;return{status:"error",message:(null===(a=i.error)||void 0===a?void 0:a.message)||"Connection test failed: ".concat(c.status," ").concat(c.statusText)}}}return i}catch(e){throw console.error("Model connection test error:",e),e}},e_=async(e,t)=>{try{console.log("entering keyInfoV1Call");let o=n?"".concat(n,"/key/info"):"/key/info";o="".concat(o,"?key=").concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(console.log("response",a),!a.ok){let e=await a.text();i(e),r.ZP.error("Failed to fetch key info - "+e)}let c=await a.json();return console.log("data",c),c}catch(e){throw console.error("Failed to fetch key info:",e),e}},eT=async(e,t,o,a,r,c)=>{try{let s=n?"".concat(n,"/key/list"):"/key/list";console.log("in keyListCall");let d=new URLSearchParams;o&&d.append("team_id",o.toString()),t&&d.append("organization_id",t.toString()),a&&d.append("key_alias",a),r&&d.append("page",r.toString()),c&&d.append("size",c.toString()),d.append("return_full_object","true"),d.append("include_team_keys","true");let h=d.toString();h&&(s+="?".concat(h));let w=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!w.ok){let e=await w.text();throw i(e),Error("Network response was not ok")}let p=await w.json();return console.log("/team/list API Response:",p),p}catch(e){throw console.error("Failed to create key:",e),e}},eE=async(e,t)=>{try{let o=n?"".concat(n,"/user/get_users?role=").concat(t):"/user/get_users?role=".concat(t);console.log("in userGetAllUsersCall:",o);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to get requested models:",e),e}},ej=async e=>{try{let t=n?"".concat(n,"/user/available_roles"):"/user/available_roles",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("response from user/available_role",a),a}catch(e){throw e}},eC=async(e,t)=>{try{if(console.log("Form Values in teamCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/team/new"):"/team/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eN=async(e,t)=>{try{if(console.log("Form Values in credentialCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/credentials"):"/credentials",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eS=async e=>{try{let t=n?"".concat(n,"/credentials"):"/credentials";console.log("in credentialListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/credentials API Response:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},eb=async(e,t,o)=>{try{let a=n?"".concat(n,"/credentials"):"/credentials";t?a+="/by_name/".concat(t):o&&(a+="/by_model/".concat(o)),console.log("in credentialListCall");let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("/credentials API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eF=async(e,t)=>{try{let o=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t);console.log("in credentialDeleteCall:",t);let a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},ex=async(e,t,o)=>{try{if(console.log("Form Values in credentialUpdateCall:",o),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let a=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t),r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eO=async(e,t)=>{try{if(console.log("Form Values in keyUpdateCall:",t),t.model_tpm_limit){console.log("formValues.model_tpm_limit:",t.model_tpm_limit);try{t.model_tpm_limit=JSON.parse(t.model_tpm_limit)}catch(e){throw Error("Failed to parse model_tpm_limit: "+e)}}if(t.model_rpm_limit){console.log("formValues.model_rpm_limit:",t.model_rpm_limit);try{t.model_rpm_limit=JSON.parse(t.model_rpm_limit)}catch(e){throw Error("Failed to parse model_rpm_limit: "+e)}}let o=n?"".concat(n,"/key/update"):"/key/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update key Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eB=async(e,t)=>{try{console.log("Form Values in teamUpateCall:",t);let o=n?"".concat(n,"/team/update"):"/team/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eP=async(e,t)=>{try{console.log("Form Values in modelUpateCall:",t);let o=n?"".concat(n,"/model/update"):"/model/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error update from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update model Response:",r),r}catch(e){throw console.error("Failed to update model:",e),e}},ev=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_add"):"/team/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eG=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_update"):"/team/member_update",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,role:o.role,user_id:o.user_id})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eA=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_delete"):"/team/member_delete",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,...void 0!==o.user_email&&{user_email:o.user_email},...void 0!==o.user_id&&{user_id:o.user_id}})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eJ=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/organization/member_add"):"/organization/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create organization member:",e),e}},eI=async(e,t,o)=>{try{console.log("Form Values in organizationMemberDeleteCall:",o);let a=n?"".concat(n,"/organization/member_delete"):"/organization/member_delete",r=await fetch(a,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,user_id:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to delete organization member:",e),e}},eR=async(e,t,o)=>{try{console.log("Form Values in organizationMemberUpdateCall:",o);let a=n?"".concat(n,"/organization/member_update"):"/organization/member_update",r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to update organization member:",e),e}},ez=async(e,t,o)=>{try{console.log("Form Values in userUpdateUserCall:",t);let a=n?"".concat(n,"/user/update"):"/user/update",r={...t};null!==o&&(r.user_role=o),r=JSON.stringify(r);let c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:r});if(!c.ok){let e=await c.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let s=await c.json();return console.log("API Response:",s),s}catch(e){throw console.error("Failed to create key:",e),e}},eV=async(e,t)=>{try{let o=n?"".concat(n,"/health/services?service=").concat(t):"/health/services?service=".concat(t);console.log("Checking Slack Budget Alerts service health");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error(e)}let c=await a.json();return r.ZP.success("Test request to ".concat(t," made - check logs/alerts on ").concat(t," to verify")),c}catch(e){throw console.error("Failed to perform health check:",e),e}},eU=async e=>{try{let t=n?"".concat(n,"/budget/list"):"/budget/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eL=async(e,t,o)=>{try{let t=n?"".concat(n,"/get/config/callbacks"):"/get/config/callbacks",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eM=async e=>{try{let t=n?"".concat(n,"/config/list?config_type=general_settings"):"/config/list?config_type=general_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eZ=async e=>{try{let t=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eD=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/info?field_name=").concat(t):"/config/field/info?field_name=".concat(t),a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eH=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eq=async(e,t,o)=>{try{let a=n?"".concat(n,"/config/field/update"):"/config/field/update",c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,field_value:o,config_type:"general_settings"})});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}let s=await c.json();return r.ZP.success("Successfully updated value!"),s}catch(e){throw console.error("Failed to set callbacks:",e),e}},eX=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/delete"):"/config/field/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,config_type:"general_settings"})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return r.ZP.success("Field reset on proxy"),c}catch(e){throw console.error("Failed to get callbacks:",e),e}},eY=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint?endpoint_id=").concat(t):"/config/pass_through_endpoint".concat(t),a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eK=async(e,t)=>{try{let o=n?"".concat(n,"/config/update"):"/config/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},e$=async e=>{try{let t=n?"".concat(n,"/health"):"/health",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to call /health:",e),e}},eQ=async e=>{try{let t=n?"".concat(n,"/cache/ping"):"/cache/ping",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error(e)}return await o.json()}catch(e){throw console.error("Failed to call /cache/ping:",e),e}},eW=async e=>{try{let t=n?"".concat(n,"/sso/get/ui_settings"):"/sso/get/ui_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},e0=async e=>{try{let t=n?"".concat(n,"/guardrails/list"):"/guardrails/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Guardrails list response:",a),a}catch(e){throw console.error("Failed to fetch guardrails list:",e),e}},e1=async(e,t,o)=>{try{let a=n?"".concat(n,"/spend/logs/ui/").concat(t,"?start_date=").concat(encodeURIComponent(o)):"/spend/logs/ui/".concat(t,"?start_date=").concat(encodeURIComponent(o));console.log("Fetching log details from:",a);let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Fetched log details:",c),c}catch(e){throw console.error("Failed to fetch log details:",e),e}},e3=async e=>{try{let t=n?"".concat(n,"/get/internal_user_settings"):"/get/internal_user_settings";console.log("Fetching SSO settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched SSO settings:",a),a}catch(e){throw console.error("Failed to fetch SSO settings:",e),e}},e2=async(e,t)=>{try{let o=n?"".concat(n,"/update/internal_user_settings"):"/update/internal_user_settings";console.log("Updating internal user settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated internal user settings:",c),r.ZP.success("Internal user settings updated successfully"),c}catch(e){throw console.error("Failed to update internal user settings:",e),e}},e4=async e=>{try{let t=n?"".concat(n,"/mcp/tools/list"):"/mcp/tools/list";console.log("Fetching MCP tools from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched MCP tools:",a),a}catch(e){throw console.error("Failed to fetch MCP tools:",e),e}},e5=async(e,t,o)=>{try{let a=n?"".concat(n,"/mcp/tools/call"):"/mcp/tools/call";console.log("Calling MCP tool:",t,"with arguments:",o);let r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("MCP tool call response:",c),c}catch(e){throw console.error("Failed to call MCP tool:",e),e}},e6=async(e,t)=>{try{let o=n?"".concat(n,"/tag/new"):"/tag/new",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error creating tag:",e),e}},e9=async(e,t)=>{try{let o=n?"".concat(n,"/tag/update"):"/tag/update",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error updating tag:",e),e}},e7=async(e,t)=>{try{let o=n?"".concat(n,"/tag/info"):"/tag/info",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({names:t})});if(!a.ok){let e=await a.text();return await i(e),{}}return await a.json()}catch(e){throw console.error("Error getting tag info:",e),e}},e8=async e=>{try{let t=n?"".concat(n,"/tag/list"):"/tag/list",o=await fetch(t,{method:"GET",headers:{Authorization:"Bearer ".concat(e)}});if(!o.ok){let e=await o.text();return await i(e),{}}return await o.json()}catch(e){throw console.error("Error listing tags:",e),e}},te=async(e,t)=>{try{let o=n?"".concat(n,"/tag/delete"):"/tag/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({name:t})});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error deleting tag:",e),e}},tt=async e=>{try{let t=n?"".concat(n,"/get/default_team_settings"):"/get/default_team_settings";console.log("Fetching default team settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched default team settings:",a),a}catch(e){throw console.error("Failed to fetch default team settings:",e),e}},to=async(e,t)=>{try{let o=n?"".concat(n,"/update/default_team_settings"):"/update/default_team_settings";console.log("Updating default team settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated default team settings:",c),r.ZP.success("Default team settings updated successfully"),c}catch(e){throw console.error("Failed to update default team settings:",e),e}},ta=async(e,t)=>{try{let o=n?"".concat(n,"/team/permissions_list?team_id=").concat(t):"/team/permissions_list?team_id=".concat(t),a=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("Team permissions response:",r),r}catch(e){throw console.error("Failed to get team permissions:",e),e}},tr=async(e,t,o)=>{try{let a=n?"".concat(n,"/team/permissions_update"):"/team/permissions_update",r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({team_id:t,team_member_permissions:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Team permissions response:",c),c}catch(e){throw console.error("Failed to update team permissions:",e),e}}},20347:function(e,t,o){o.d(t,{LQ:function(){return n},ZL:function(){return a},lo:function(){return r},tY:function(){return c}});let a=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],r=["Internal User","Internal Viewer"],n=["Internal User","Admin"],c=e=>a.includes(e)}}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/699-2176ba2273e4676d.js b/litellm/proxy/_experimental/out/_next/static/chunks/699-907a1bb245b7369a.js similarity index 100% rename from litellm/proxy/_experimental/out/_next/static/chunks/699-2176ba2273e4676d.js rename to litellm/proxy/_experimental/out/_next/static/chunks/699-907a1bb245b7369a.js diff --git a/ui/litellm-dashboard/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js b/litellm/proxy/_experimental/out/_next/static/chunks/app/layout-429ad74a94df7643.js similarity index 59% rename from ui/litellm-dashboard/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js rename to litellm/proxy/_experimental/out/_next/static/chunks/app/layout-429ad74a94df7643.js index 54014d8da6..b655a049db 100644 --- a/ui/litellm-dashboard/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/app/layout-429ad74a94df7643.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{35677:function(n,e,t){Promise.resolve().then(t.t.bind(t,39974,23)),Promise.resolve().then(t.t.bind(t,2778,23))},2778:function(){},39974:function(n){n.exports={style:{fontFamily:"'__Inter_cf7686', '__Inter_Fallback_cf7686'",fontStyle:"normal"},className:"__className_cf7686"}}},function(n){n.O(0,[919,986,971,117,744],function(){return n(n.s=35677)}),_N_E=n.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{96443:function(n,e,t){Promise.resolve().then(t.t.bind(t,39974,23)),Promise.resolve().then(t.t.bind(t,2778,23))},2778:function(){},39974:function(n){n.exports={style:{fontFamily:"'__Inter_cf7686', '__Inter_Fallback_cf7686'",fontStyle:"normal"},className:"__className_cf7686"}}},function(n){n.O(0,[919,986,971,117,744],function(){return n(n.s=96443)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js b/litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js similarity index 60% rename from ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js rename to litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js index e9399e4533..d78551c3fc 100644 --- a/ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[418],{56668:function(e,n,u){Promise.resolve().then(u.bind(u,52829))},52829:function(e,n,u){"use strict";u.r(n),u.d(n,{default:function(){return f}});var t=u(57437),s=u(2265),r=u(99376),c=u(92699);function f(){let e=(0,r.useSearchParams)().get("key"),[n,u]=(0,s.useState)(null);return(0,s.useEffect)(()=>{e&&u(e)},[e]),(0,t.jsx)(c.Z,{accessToken:n,publicPage:!0,premiumUser:!1})}}},function(e){e.O(0,[42,261,250,699,971,117,744],function(){return e(e.s=56668)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[418],{21024:function(e,n,u){Promise.resolve().then(u.bind(u,52829))},52829:function(e,n,u){"use strict";u.r(n),u.d(n,{default:function(){return f}});var t=u(57437),s=u(2265),r=u(99376),c=u(92699);function f(){let e=(0,r.useSearchParams)().get("key"),[n,u]=(0,s.useState)(null);return(0,s.useEffect)(()=>{e&&u(e)},[e]),(0,t.jsx)(c.Z,{accessToken:n,publicPage:!0,premiumUser:!1})}}},function(e){e.O(0,[42,261,250,699,971,117,744],function(){return e(e.s=21024)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js b/litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js new file mode 100644 index 0000000000..a995e87291 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[461],{8672:function(e,t,n){Promise.resolve().then(n.bind(n,12011))},12011:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return S}});var s=n(57437),o=n(2265),a=n(99376),c=n(20831),i=n(94789),l=n(12514),r=n(49804),u=n(67101),m=n(84264),d=n(49566),h=n(96761),x=n(84566),p=n(19250),f=n(14474),k=n(13634),g=n(73002),j=n(3914);function S(){let[e]=k.Z.useForm(),t=(0,a.useSearchParams)();(0,j.e)("token");let n=t.get("invitation_id"),[S,w]=(0,o.useState)(null),[Z,_]=(0,o.useState)(""),[N,b]=(0,o.useState)(""),[T,y]=(0,o.useState)(null),[E,v]=(0,o.useState)(""),[C,U]=(0,o.useState)("");return(0,o.useEffect)(()=>{n&&(0,p.W_)(n).then(e=>{let t=e.login_url;console.log("login_url:",t),v(t);let n=e.token,s=(0,f.o)(n);U(n),console.log("decoded:",s),w(s.key),console.log("decoded user email:",s.user_email),b(s.user_email),y(s.user_id)})},[n]),(0,s.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,s.jsxs)(l.Z,{children:[(0,s.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,s.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,s.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,s.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,s.jsxs)(u.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,s.jsx)(r.Z,{children:"SSO is under the Enterprise Tier."}),(0,s.jsx)(r.Z,{children:(0,s.jsx)(c.Z,{variant:"primary",className:"mb-2",children:(0,s.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,s.jsxs)(k.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",S,"token:",C,"formValues:",e),S&&C&&(e.user_email=N,T&&n&&(0,p.m_)(S,n,T,e.password).then(e=>{let t="/ui/";t+="?login=success",document.cookie="token="+C,console.log("redirecting to:",t),window.location.href=t}))},children:[(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Z.Item,{label:"Email Address",name:"user_email",children:(0,s.jsx)(d.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,s.jsx)(k.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,s.jsx)(d.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,s.jsx)("div",{className:"mt-10",children:(0,s.jsx)(g.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},3914:function(e,t,n){"use strict";function s(){let e=window.location.hostname,t=["Lax","Strict","None"];["/","/ui"].forEach(n=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,";"),t.forEach(t=>{let s="None"===t?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; SameSite=").concat(t,";").concat(s),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,"; SameSite=").concat(t,";").concat(s)})}),console.log("After clearing cookies:",document.cookie)}function o(e){let t=document.cookie.split("; ").find(t=>t.startsWith(e+"="));return t?t.split("=")[1]:null}n.d(t,{b:function(){return s},e:function(){return o}})}},function(e){e.O(0,[665,42,899,250,971,117,744],function(){return e(e.s=8672)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js b/litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js deleted file mode 100644 index 5e22c7e73d..0000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[461],{23781:function(e,t,n){Promise.resolve().then(n.bind(n,12011))},12011:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return S}});var s=n(57437),o=n(2265),a=n(99376),c=n(20831),i=n(94789),l=n(12514),r=n(49804),u=n(67101),m=n(84264),d=n(49566),h=n(96761),x=n(84566),p=n(19250),f=n(14474),k=n(13634),g=n(73002),j=n(3914);function S(){let[e]=k.Z.useForm(),t=(0,a.useSearchParams)();(0,j.e)("token");let n=t.get("invitation_id"),[S,w]=(0,o.useState)(null),[Z,_]=(0,o.useState)(""),[N,b]=(0,o.useState)(""),[T,y]=(0,o.useState)(null),[E,v]=(0,o.useState)(""),[C,U]=(0,o.useState)("");return(0,o.useEffect)(()=>{n&&(0,p.W_)(n).then(e=>{let t=e.login_url;console.log("login_url:",t),v(t);let n=e.token,s=(0,f.o)(n);U(n),console.log("decoded:",s),w(s.key),console.log("decoded user email:",s.user_email),b(s.user_email),y(s.user_id)})},[n]),(0,s.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,s.jsxs)(l.Z,{children:[(0,s.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,s.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,s.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,s.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,s.jsxs)(u.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,s.jsx)(r.Z,{children:"SSO is under the Enterprise Tier."}),(0,s.jsx)(r.Z,{children:(0,s.jsx)(c.Z,{variant:"primary",className:"mb-2",children:(0,s.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,s.jsxs)(k.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",S,"token:",C,"formValues:",e),S&&C&&(e.user_email=N,T&&n&&(0,p.m_)(S,n,T,e.password).then(e=>{let t="/ui/";t+="?login=success",document.cookie="token="+C,console.log("redirecting to:",t),window.location.href=t}))},children:[(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Z.Item,{label:"Email Address",name:"user_email",children:(0,s.jsx)(d.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,s.jsx)(k.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,s.jsx)(d.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,s.jsx)("div",{className:"mt-10",children:(0,s.jsx)(g.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},3914:function(e,t,n){"use strict";function s(){let e=window.location.hostname,t=["Lax","Strict","None"];["/","/ui"].forEach(n=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,";"),t.forEach(t=>{let s="None"===t?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; SameSite=").concat(t,";").concat(s),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,"; SameSite=").concat(t,";").concat(s)})}),console.log("After clearing cookies:",document.cookie)}function o(e){let t=document.cookie.split("; ").find(t=>t.startsWith(e+"="));return t?t.split("=")[1]:null}n.d(t,{b:function(){return s},e:function(){return o}})}},function(e){e.O(0,[665,42,899,250,971,117,744],function(){return e(e.s=23781)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/app/page-225a364dd94a768d.js b/litellm/proxy/_experimental/out/_next/static/chunks/app/page-225a364dd94a768d.js new file mode 100644 index 0000000000..3d3bf48015 --- /dev/null +++ b/litellm/proxy/_experimental/out/_next/static/chunks/app/page-225a364dd94a768d.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{36362:function(e,s,l){Promise.resolve().then(l.bind(l,76737))},12011:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return y}});var t=l(57437),a=l(2265),r=l(99376),n=l(20831),i=l(94789),o=l(12514),c=l(49804),d=l(67101),m=l(84264),u=l(49566),h=l(96761),x=l(84566),p=l(19250),g=l(14474),j=l(13634),f=l(73002),_=l(3914);function y(){let[e]=j.Z.useForm(),s=(0,r.useSearchParams)();(0,_.e)("token");let l=s.get("invitation_id"),[y,v]=(0,a.useState)(null),[b,Z]=(0,a.useState)(""),[N,w]=(0,a.useState)(""),[k,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(""),[T,A]=(0,a.useState)("");return(0,a.useEffect)(()=>{l&&(0,p.W_)(l).then(e=>{let s=e.login_url;console.log("login_url:",s),I(s);let l=e.token,t=(0,g.o)(l);A(l),console.log("decoded:",t),v(t.key),console.log("decoded user email:",t.user_email),w(t.user_email),S(t.user_id)})},[l]),(0,t.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,t.jsxs)(o.Z,{children:[(0,t.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,t.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,t.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,t.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,t.jsxs)(d.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,t.jsx)(c.Z,{children:"SSO is under the Enterprise Tier."}),(0,t.jsx)(c.Z,{children:(0,t.jsx)(n.Z,{variant:"primary",className:"mb-2",children:(0,t.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,t.jsxs)(j.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",y,"token:",T,"formValues:",e),y&&T&&(e.user_email=N,k&&l&&(0,p.m_)(y,l,k,e.password).then(e=>{let s="/ui/";s+="?login=success",document.cookie="token="+T,console.log("redirecting to:",s),window.location.href=s}))},children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(j.Z.Item,{label:"Email Address",name:"user_email",children:(0,t.jsx)(u.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,t.jsx)(j.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,t.jsx)(u.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,t.jsx)("div",{className:"mt-10",children:(0,t.jsx)(f.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},76737:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return aD}});var t,a,r,n,i,o,c=l(57437),d=l(2265),m=l(99376),u=l(14474),h=l(21623),x=l(29827),p=l(27648),g=l(80795),j=l(15883),f=l(40428),_=l(3914),y=l(19250);let v=async e=>{if(!e)return null;try{return await (0,y.g)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};var b=e=>{let{userID:s,userEmail:l,userRole:t,premiumUser:a,proxySettings:r,setProxySettings:n,accessToken:i}=e,[o,m]=(0,d.useState)("");(0,d.useEffect)(()=>{(async()=>{if(i){let e=await v(i);console.log("response from fetchProxySettings",e),e&&n(e)}})()},[i]),(0,d.useEffect)(()=>{m((null==r?void 0:r.PROXY_LOGOUT_URL)||"")},[r]);let u=[{key:"1",label:(0,c.jsxs)("div",{className:"py-1",children:[(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Role: ",t]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Email: ",l||"Unknown"]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[(0,c.jsx)(j.Z,{})," ",s]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Premium User: ",String(a)]})]})},{key:"2",label:(0,c.jsxs)("p",{className:"text-sm hover:text-gray-900",onClick:()=>{(0,_.b)(),window.location.href=o},children:[(0,c.jsx)(f.Z,{})," Logout"]})}];return(0,c.jsx)("nav",{className:"bg-white border-b border-gray-200 sticky top-0 z-10",children:(0,c.jsx)("div",{className:"w-full",children:(0,c.jsxs)("div",{className:"flex items-center h-12 px-4",children:[(0,c.jsx)("div",{className:"flex items-center flex-shrink-0",children:(0,c.jsx)(p.default,{href:"/",className:"flex items-center",children:(0,c.jsx)("img",{src:"/get_image",alt:"LiteLLM Brand",className:"h-8 w-auto"})})}),(0,c.jsxs)("div",{className:"flex items-center space-x-5 ml-auto",children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/",target:"_blank",rel:"noopener noreferrer",className:"text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:"Docs"}),(0,c.jsx)(g.Z,{menu:{items:u,style:{padding:"4px",marginTop:"4px"}},children:(0,c.jsxs)("button",{className:"inline-flex items-center text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:["User",(0,c.jsx)("svg",{className:"ml-1 w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19 9l-7 7-7-7"})})]})})]})]})})})};let Z=async(e,s,l,t,a)=>{let r;r="Admin"!=l&&"Admin Viewer"!=l?await (0,y.It)(e,(null==t?void 0:t.organization_id)||null,s):await (0,y.It)(e,(null==t?void 0:t.organization_id)||null),console.log("givenTeams: ".concat(r)),a(r)};var N=l(49804),w=l(67101),k=l(20831),S=l(49566),C=l(87452),I=l(88829),T=l(72208),A=l(84264),E=l(96761),P=l(29233),O=l(52787),L=l(13634),D=l(41021),M=l(51369),F=l(29967),R=l(73002),q=l(56632),U=l(30150),z=e=>{let{step:s=.01,style:l={width:"100%"},placeholder:t="Enter a numerical value",min:a,max:r,onChange:n,...i}=e;return(0,c.jsx)(U.Z,{onWheel:e=>e.currentTarget.blur(),step:s,style:l,placeholder:t,min:a,max:r,onChange:n,...i})};let V=async(e,s,l)=>{try{if(null===e||null===s)return;if(null!==l){let t=(await (0,y.So)(l,e,s,!0)).data.map(e=>e.id),a=[],r=[];return t.forEach(e=>{e.endsWith("/*")?a.push(e):r.push(e)}),[...a,...r]}}catch(e){console.error("Error fetching user models:",e)}},K=e=>{if(e.endsWith("/*")){let s=e.replace("/*","");return"All ".concat(s," models")}return e},B=(e,s)=>{let l=[],t=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));t.push(...r),l.push(e)}else t.push(e)}),[...l,...t].filter((e,s,l)=>l.indexOf(e)===s)};var H=l(20577),J=l(15424),W=l(75957);let G=(e,s)=>["metadata","config","enforced_params","aliases"].includes(e)||"json"===s.format,Y=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch(e){return!1}},$=(e,s,l)=>{let t={max_budget:"Enter maximum budget in USD (e.g., 100.50)",budget_duration:"Select a time period for budget reset",tpm_limit:"Enter maximum tokens per minute (whole number)",rpm_limit:"Enter maximum requests per minute (whole number)",duration:"Enter duration (e.g., 30s, 24h, 7d)",metadata:'Enter JSON object with key-value pairs\nExample: {"team": "research", "project": "nlp"}',config:'Enter configuration as JSON object\nExample: {"setting": "value"}',permissions:"Enter comma-separated permission strings",enforced_params:'Enter parameters as JSON object\nExample: {"param": "value"}',blocked:"Enter true/false or specific block conditions",aliases:'Enter aliases as JSON object\nExample: {"alias1": "value1", "alias2": "value2"}',models:"Select one or more model names",key_alias:"Enter a unique identifier for this key",tags:"Enter comma-separated tag strings"}[e]||({string:"Text input",number:"Numeric input",integer:"Whole number input",boolean:"True/False value"})[l]||"Text input";return G(e,s)?"".concat(t,"\nMust be valid JSON format"):s.enum?"Select from available options\nAllowed values: ".concat(s.enum.join(", ")):t};var X=e=>{let{schemaComponent:s,excludedFields:l=[],form:t,overrideLabels:a={},overrideTooltips:r={},customValidation:n={},defaultValues:i={}}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null);(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.lP)()).components.schemas[s];if(!e)throw Error('Schema component "'.concat(s,'" not found'));m(e);let a={};Object.keys(e.properties).filter(e=>!l.includes(e)&&void 0!==i[e]).forEach(e=>{a[e]=i[e]}),t.setFieldsValue(a)}catch(e){console.error("Schema fetch error:",e),h(e instanceof Error?e.message:"Failed to fetch schema")}})()},[s,t,l]);let x=e=>{if(e.type)return e.type;if(e.anyOf){let s=e.anyOf.map(e=>e.type);if(s.includes("number")||s.includes("integer"))return"number";s.includes("string")}return"string"},p=(e,s)=>{var l;let t;let d=x(s),m=null==o?void 0:null===(l=o.required)||void 0===l?void 0:l.includes(e),u=a[e]||s.title||e,h=r[e]||s.description,p=[];m&&p.push({required:!0,message:"".concat(u," is required")}),n[e]&&p.push({validator:n[e]}),G(e,s)&&p.push({validator:async(e,s)=>{if(s&&!Y(s))throw Error("Please enter valid JSON")}});let g=h?(0,c.jsxs)("span",{children:[u," ",(0,c.jsx)(W.Z,{title:h,children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}):u;return t=G(e,s)?(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter as JSON",className:"font-mono"}):s.enum?(0,c.jsx)(O.default,{children:s.enum.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"number"===d||"integer"===d?(0,c.jsx)(H.Z,{style:{width:"100%"},precision:"integer"===d?0:void 0}):"duration"===e?(0,c.jsx)(S.Z,{placeholder:"eg: 30s, 30h, 30d"}):(0,c.jsx)(S.Z,{placeholder:h||""}),(0,c.jsx)(L.Z.Item,{label:g,name:e,className:"mt-8",rules:p,initialValue:i[e],help:(0,c.jsx)("div",{className:"text-xs text-gray-500",children:$(e,s,d)}),children:t},e)};return u?(0,c.jsxs)("div",{className:"text-red-500",children:["Error: ",u]}):(null==o?void 0:o.properties)?(0,c.jsx)("div",{children:Object.entries(o.properties).filter(e=>{let[s]=e;return!l.includes(s)}).map(e=>{let[s,l]=e;return p(s,l)})}):null},Q=e=>{let{teams:s,value:l,onChange:t}=e;return(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:t,filterOption:(e,s)=>{var l,t,a;return!!s&&((null===(a=s.children)||void 0===a?void 0:null===(t=a[0])||void 0===t?void 0:null===(l=t.props)||void 0===l?void 0:l.children)||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==s?void 0:s.map(e=>(0,c.jsxs)(O.default.Option,{value:e.team_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})},ee=l(57365),es=l(93192);function el(e){let{isInvitationLinkModalVisible:s,setIsInvitationLinkModalVisible:l,baseUrl:t,invitationLinkData:a}=e,{Title:r,Paragraph:n}=es.default,i=()=>(null==a?void 0:a.has_user_setup_sso)?new URL("/ui",t).toString():new URL("/ui?invitation_id=".concat(null==a?void 0:a.id),t).toString();return(0,c.jsxs)(M.Z,{title:"Invitation Link",visible:s,width:800,footer:null,onOk:()=>{l(!1)},onCancel:()=>{l(!1)},children:[(0,c.jsx)(n,{children:"Copy and send the generated link to onboard this user to the proxy."}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"User ID"}),(0,c.jsx)(A.Z,{children:null==a?void 0:a.user_id})]}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{children:"Invitation Link"}),(0,c.jsx)(A.Z,{children:(0,c.jsx)(A.Z,{children:i()})})]}),(0,c.jsx)("div",{className:"flex justify-end mt-5",children:(0,c.jsx)(P.CopyToClipboard,{text:i(),onCopy:()=>D.ZP.success("Copied!"),children:(0,c.jsx)(k.Z,{variant:"primary",children:"Copy invitation link"})})})]})}var et=l(77388),ea=l(1709),er=l(73879),en=l(3632),ei=l(15452),eo=l.n(ei),ec=l(71157),ed=l(44643),em=e=>{let{accessToken:s,teams:l,possibleUIRoles:t,onUsersCreated:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.g)(s);g(e)}catch(e){console.error("Error fetching UI settings:",e)}})(),f(new URL("/",window.location.href).toString())},[s]);let _=async()=>{u(!0);let e=i.map(e=>({...e,status:"pending"}));o(e);let l=!1;for(let a=0;ae.trim())),e.models&&"string"==typeof e.models&&(e.models=e.models.split(",").map(e=>e.trim())),e.max_budget&&""!==e.max_budget.toString().trim()&&(e.max_budget=parseFloat(e.max_budget.toString()));let r=await (0,y.Ov)(s,null,e);if(console.log("Full response:",r),r&&(r.key||r.user_id)){l=!0,console.log("Success case triggered");let e=(null===(t=r.data)||void 0===t?void 0:t.user_id)||r.user_id;try{if(null==p?void 0:p.SSO_ENABLED){let e=new URL("/ui",j).toString();o(s=>s.map((s,l)=>l===a?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let l=await (0,y.XO)(s,e),t=new URL("/ui?invitation_id=".concat(l.id),j).toString();o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,invitation_link:t}:e))}}catch(e){console.error("Error creating invitation:",e),o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=(null==r?void 0:r.error)||"Failed to create user";console.log("Error message:",e),o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=(null==s?void 0:null===(n=s.response)||void 0===n?void 0:null===(r=n.data)||void 0===r?void 0:r.error)||(null==s?void 0:s.message)||String(s);o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}u(!1),l&&a&&a()};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>n(!0),children:"+ Bulk Invite Users"}),(0,c.jsx)(M.Z,{title:"Bulk Invite Users",visible:r,width:800,onCancel:()=>n(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,c.jsx)("div",{className:"flex flex-col",children:0===i.length?(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,c.jsxs)("div",{className:"ml-11 mb-6",children:[(0,c.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,c.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,c.jsx)("li",{children:"Download our CSV template"}),(0,c.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,c.jsx)("li",{children:"Save the file and upload it here"}),(0,c.jsx)("li",{children:"After creation, download the results file containing the API keys for each user"})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,c.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_email"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_role"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_view_only", "internal_user", "internal_user_view_only")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"teams"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"models"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=new Blob([eo().unparse([["user_email","user_role","teams","max_budget","budget_duration","models"],["user@example.com","internal_user","team-id-1,team-id-2","100","30d","gpt-3.5-turbo,gpt-4"]])],{type:"text/csv"}),s=window.URL.createObjectURL(e),l=document.createElement("a");l.href=s,l.download="bulk_users_template.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(s)},size:"lg",className:"w-full md:w-auto",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download CSV Template"]})]}),(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,c.jsx)("div",{className:"ml-11",children:(0,c.jsx)(et.Z,{beforeUpload:e=>(x(null),eo().parse(e,{complete:e=>{let s=e.data[0],l=["user_email","user_role"].filter(e=>!s.includes(e));if(l.length>0){x("Your CSV is missing these required columns: ".concat(l.join(", "))),o([]);return}try{let l=e.data.slice(1).map((e,l)=>{var t,a,r,n,i,o;let c={user_email:(null===(t=e[s.indexOf("user_email")])||void 0===t?void 0:t.trim())||"",user_role:(null===(a=e[s.indexOf("user_role")])||void 0===a?void 0:a.trim())||"",teams:null===(r=e[s.indexOf("teams")])||void 0===r?void 0:r.trim(),max_budget:null===(n=e[s.indexOf("max_budget")])||void 0===n?void 0:n.trim(),budget_duration:null===(i=e[s.indexOf("budget_duration")])||void 0===i?void 0:i.trim(),models:null===(o=e[s.indexOf("models")])||void 0===o?void 0:o.trim(),rowNumber:l+2,isValid:!0,error:""},d=[];c.user_email||d.push("Email is required"),c.user_role||d.push("Role is required"),c.user_email&&!c.user_email.includes("@")&&d.push("Invalid email format");let m=["proxy_admin","proxy_admin_view_only","internal_user","internal_user_view_only"];return c.user_role&&!m.includes(c.user_role)&&d.push("Invalid role. Must be one of: ".concat(m.join(", "))),c.max_budget&&isNaN(parseFloat(c.max_budget.toString()))&&d.push("Max budget must be a number"),d.length>0&&(c.isValid=!1,c.error=d.join(", ")),c}),t=l.filter(e=>e.isValid);o(l),0===t.length?x("No valid users found in the CSV. Please check the errors below."):t.length{x("Failed to parse CSV file: ".concat(e.message)),o([])},header:!1}),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,c.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,c.jsx)(en.Z,{className:"text-3xl text-gray-400 mb-2"}),(0,c.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,c.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,c.jsx)(k.Z,{size:"sm",children:"Browse files"})]})})})]}):(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:i.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),h&&(0,c.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,c.jsx)(A.Z,{className:"text-red-600 font-medium",children:h})}),(0,c.jsxs)("div",{className:"ml-11",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,c.jsx)("div",{className:"flex items-center",children:i.some(e=>"success"===e.status||"failed"===e.status)?(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[i.filter(e=>"success"===e.status).length," Successful"]}),i.some(e=>"failed"===e.status)&&(0,c.jsxs)(A.Z,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[i.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[i.filter(e=>e.isValid).length," of ",i.length," users valid"]})]})}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex space-x-3",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]})]}),i.some(e=>"success"===e.status)&&(0,c.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"mr-3 mt-1",children:(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-blue-500"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,c.jsxs)(A.Z,{className:"block text-sm text-blue-700 mt-1",children:[(0,c.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing API keys and invitation links. Users will need these API keys to make LLM requests through LiteLLM."]})]})]})}),(0,c.jsx)(ea.Z,{dataSource:i,columns:[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,s)=>s.isValid?s.status&&"pending"!==s.status?"success"===s.status?(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}),(0,c.jsx)("span",{className:"text-green-500",children:"Success"})]}),s.invitation_link&&(0,c.jsx)("div",{className:"mt-1",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:s.invitation_link}),(0,c.jsx)(P.CopyToClipboard,{text:s.invitation_link,onCopy:()=>D.ZP.success("Invitation link copied!"),children:(0,c.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Failed"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(s.error)})]}):(0,c.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:s.error})]})}],size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]}),i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Start New Bulk Import"}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=i.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([eo().unparse(e)],{type:"text/csv"}),l=window.URL.createObjectURL(s),t=document.createElement("a");t.href=l,t.download="bulk_users_results.csv",document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(l)},variant:"primary",className:"flex items-center",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download User Credentials"]})]})]})]})})})]})};let{Option:eu}=O.default;var eh=e=>{let{userID:s,accessToken:l,teams:t,possibleUIRoles:a,onUserCreated:r,isEmbedded:n=!1}=e,[i,o]=(0,d.useState)(null),[u]=L.Z.useForm(),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),N=(0,m.useRouter)(),[w,P]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.So)(l,s,"any"),t=[];for(let s=0;s{N&&P(new URL("/",window.location.href).toString())},[N]);let F=async e=>{var t,a,o;try{D.ZP.info("Making API Call"),n||x(!0),e.models&&0!==e.models.length||(e.models=["no-default-models"]),console.log("formValues in create user:",e);let a=await (0,y.Ov)(l,null,e);console.log("user create Response:",a),g(!0);let o=(null===(t=a.data)||void 0===t?void 0:t.user_id)||a.user_id;if(r&&n){r(o),u.resetFields();return}if(null==i?void 0:i.SSO_ENABLED){let e={id:crypto.randomUUID(),user_id:o,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:s,updated_at:new Date,updated_by:s,has_user_setup_sso:!0};Z(e),v(!0)}else(0,y.XO)(l,o).then(e=>{e.has_user_setup_sso=!1,Z(e),v(!0)});D.ZP.success("API user Created"),u.resetFields(),localStorage.removeItem("userData"+s)}catch(s){let e=(null===(o=s.response)||void 0===o?void 0:null===(a=o.data)||void 0===a?void 0:a.detail)||(null==s?void 0:s.message)||"Error creating the user";D.ZP.error(e),console.error("Error creating the user:",s)}};return n?(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]}):(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>x(!0),children:"+ Invite User"}),(0,c.jsx)(em,{accessToken:l,teams:t,possibleUIRoles:a}),(0,c.jsxs)(M.Z,{title:"Invite User",visible:h,width:800,footer:null,onOk:()=>{x(!1),u.resetFields()},onCancel:()=>{x(!1),g(!1),u.resetFields()},children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Create a User who can own keys"}),(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Global Proxy Role"," ",(0,c.jsx)(W.Z,{title:"This is the role that the user will globally on the proxy. This role is independent of any team/org specific roles.",children:(0,c.jsx)(J.Z,{})})]}),name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{children:"Personal Key Creation"})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(L.Z.Item,{className:"gap-2",label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Models user has access to, outside of team scope.",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),j.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]})]}),p&&(0,c.jsx)(el,{isInvitationLinkModalVisible:_,setIsInvitationLinkModalVisible:v,baseUrl:w,invitationLinkData:b})]})},ex=l(7310),ep=l.n(ex),eg=l(20347);let{Option:ej}=O.default,ef=e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set";var e_=e=>{let{value:s,onChange:l,className:t="",style:a={}}=e;return(0,c.jsxs)(O.default,{style:{width:"100%",...a},value:s||void 0,onChange:l,className:t,placeholder:"n/a",children:[(0,c.jsx)(ej,{value:"24h",children:"daily"}),(0,c.jsx)(ej,{value:"7d",children:"weekly"}),(0,c.jsx)(ej,{value:"30d",children:"monthly"})]})};let{Option:ey}=O.default,ev=e=>{let s=[];if(console.log("data:",JSON.stringify(e)),e)for(let l of e)l.metadata&&l.metadata.tags&&s.push(...l.metadata.tags);let l=Array.from(new Set(s)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",l),l},eb=async(e,s,l,t)=>{try{if(null===e||null===s)return[];if(null!==l){let a=(await (0,y.So)(l,e,s,!0,t)).data.map(e=>e.id);return console.log("available_model_names:",a),a}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},eZ=async(e,s,l,t)=>{try{if(null===e||null===s)return;if(null!==l){let a=(await (0,y.So)(l,e,s)).data.map(e=>e.id);console.log("available_model_names:",a),t(a)}}catch(e){console.error("Error fetching user models:",e)}};var eN=e=>{let{userID:s,team:l,teams:t,userRole:a,accessToken:r,data:n,setData:i}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)("you"),[U,V]=(0,d.useState)(ev(n)),[B,H]=(0,d.useState)([]),[G,Y]=(0,d.useState)(l),[$,ee]=(0,d.useState)(!1),[es,el]=(0,d.useState)(null),[et,ea]=(0,d.useState)({}),[er,en]=(0,d.useState)([]),[ei,eo]=(0,d.useState)(!1),ec=()=>{u(!1),o.resetFields()},ed=()=>{u(!1),x(null),Y(null),o.resetFields()};(0,d.useEffect)(()=>{s&&a&&r&&eZ(s,a,r,f)},[r,s,a]),(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.t3)(r)).guardrails.map(e=>e.guardrail_name);H(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[r]),(0,d.useEffect)(()=>{(async()=>{try{if(r){let e=sessionStorage.getItem("possibleUserRoles");if(e)ea(JSON.parse(e));else{let e=await (0,y.lg)(r);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),ea(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[r]);let em=async e=>{try{var l,t,a;let c=null!==(l=null==e?void 0:e.key_alias)&&void 0!==l?l:"",d=null!==(t=null==e?void 0:e.team_id)&&void 0!==t?t:null;if((null!==(a=null==n?void 0:n.filter(e=>e.team_id===d).map(e=>e.key_alias))&&void 0!==a?a:[]).includes(c))throw Error("Key alias ".concat(c," already exists for team with ID ").concat(d,", please provide another key alias"));if(D.ZP.info("Making API Call"),u(!0),"you"===b&&(e.user_id=s),"service_account"===b){let s={};try{s=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}s.service_account_id=e.key_alias,e.metadata=JSON.stringify(s)}let m=await (0,y.wX)(r,s,e);console.log("key create Response:",m),i(e=>e?[...e,m]:[m]),window.addNewKeyToList&&window.addNewKeyToList(m),x(m.key),g(m.soft_budget),D.ZP.success("API Key Created"),o.resetFields(),localStorage.removeItem("userData"+s)}catch(e){console.log("error in create key:",e),D.ZP.error("Error creating the key: ".concat(e))}};(0,d.useEffect)(()=>{if(s&&a&&r){var e;eb(s,a,r,null!==(e=null==G?void 0:G.team_id)&&void 0!==e?e:null).then(e=>{var s;v(Array.from(new Set([...null!==(s=null==G?void 0:G.models)&&void 0!==s?s:[],...e])))})}o.setFieldValue("models",[])},[G,r,s,a]);let eu=async e=>{if(!e){en([]);return}eo(!0);try{let s=new URLSearchParams;if(s.append("user_email",e),null==r)return;let l=(await (0,y.u5)(r,s)).map(e=>({label:"".concat(e.user_email," (").concat(e.user_id,")"),value:e.user_id,user:e}));en(l)}catch(e){console.error("Error fetching users:",e),D.ZP.error("Failed to search for users")}finally{eo(!1)}},ex=(0,d.useCallback)(ep()(e=>eu(e),300),[r]),ej=(e,s)=>{let l=s.user;o.setFieldsValue({user_id:l.user_id})};return(0,c.jsxs)("div",{children:[a&&eg.LQ.includes(a)&&(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>u(!0),children:"+ Create New Key"}),(0,c.jsx)(M.Z,{visible:m,width:1e3,footer:null,onOk:ec,onCancel:ed,children:(0,c.jsxs)(L.Z,{form:o,onFinish:em,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Ownership"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Owned By"," ",(0,c.jsx)(W.Z,{title:"Select who will own this API key",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,c.jsxs)(F.ZP.Group,{onChange:e=>Z(e.target.value),value:b,children:[(0,c.jsx)(F.ZP,{value:"you",children:"You"}),(0,c.jsx)(F.ZP,{value:"service_account",children:"Service Account"}),"Admin"===a&&(0,c.jsx)(F.ZP,{value:"another_user",children:"Another User"})]})}),"another_user"===b&&(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["User ID"," ",(0,c.jsx)(W.Z,{title:"The user who will own this key and be responsible for its usage",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===b,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{ex(e)},onSelect:(e,s)=>ej(e,s),options:er,loading:ei,allowClear:!0,style:{width:"100%"},notFoundContent:ei?"Searching...":"No users found"}),(0,c.jsx)(R.ZP,{onClick:()=>ee(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,c.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Team"," ",(0,c.jsx)(W.Z,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:l?l.team_id:null,className:"mt-4",children:(0,c.jsx)(Q,{teams:t,onChange:e=>{Y((null==t?void 0:t.find(s=>s.team_id===e))||null)}})})]}),(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Details"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["you"===b||"another_user"===b?"Key Name":"Service Account ID"," ",(0,c.jsx)(W.Z,{title:"you"===b||"another_user"===b?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:"Please input a ".concat("you"===b?"key name":"service account ID")}],help:"required",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",className:"mt-4",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},onChange:e=>{e.includes("all-team-models")&&o.setFieldsValue({models:["all-team-models"]})},children:[(0,c.jsx)(ey,{value:"all-team-models",children:"All Team Models"},"all-team-models"),_.map(e=>(0,c.jsx)(ey,{value:e,children:K(e)},e))]})})]}),(0,c.jsx)("div",{className:"mb-8",children:(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{className:"m-0",children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Max Budget (USD)"," ",(0,c.jsx)(W.Z,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:"Budget cannot exceed team max budget: $".concat((null==l?void 0:l.max_budget)!==null&&(null==l?void 0:l.max_budget)!==void 0?null==l?void 0:l.max_budget:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.max_budget&&s>l.max_budget)throw Error("Budget cannot exceed team max budget: $".concat(l.max_budget))}}],children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Reset Budget"," ",(0,c.jsx)(W.Z,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:"Team Reset Budget: ".concat((null==l?void 0:l.budget_duration)!==null&&(null==l?void 0:l.budget_duration)!==void 0?null==l?void 0:l.budget_duration:"None"),children:(0,c.jsx)(e_,{onChange:e=>o.setFieldValue("budget_duration",e)})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:"TPM cannot exceed team TPM limit: ".concat((null==l?void 0:l.tpm_limit)!==null&&(null==l?void 0:l.tpm_limit)!==void 0?null==l?void 0:l.tpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.tpm_limit&&s>l.tpm_limit)throw Error("TPM limit cannot exceed team TPM limit: ".concat(l.tpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:"RPM cannot exceed team RPM limit: ".concat((null==l?void 0:l.rpm_limit)!==null&&(null==l?void 0:l.rpm_limit)!==void 0?null==l?void 0:l.rpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.rpm_limit&&s>l.rpm_limit)throw Error("RPM limit cannot exceed team RPM limit: ".concat(l.rpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Expire Key"," ",(0,c.jsx)(W.Z,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days)",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"duration",className:"mt-4",children:(0,c.jsx)(S.Z,{placeholder:"e.g., 30d"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:B.map(e=>({value:e,label:e}))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Metadata"," ",(0,c.jsx)(W.Z,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Tags"," ",(0,c.jsx)(W.Z,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:U})}),(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("b",{children:"Advanced Settings"}),(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,c.jsx)("a",{href:y.H2?"".concat(y.H2,"/#/key%20management/generate_key_fn_key_generate_post"):"/#/key%20management/generate_key_fn_key_generate_post",target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:"documentation"})]}),children:(0,c.jsx)(J.Z,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(X,{schemaComponent:"GenerateKeyRequest",form:o,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Key"})})]})}),$&&(0,c.jsx)(M.Z,{title:"Create New User",visible:$,onCancel:()=>ee(!1),footer:null,width:800,children:(0,c.jsx)(eh,{userID:s,accessToken:r,teams:t,possibleUIRoles:et,onUserCreated:e=>{el(e),o.setFieldsValue({user_id:e}),ee(!1)},isEmbedded:!0})}),h&&(0,c.jsx)(M.Z,{visible:m,onOk:ec,onCancel:ed,footer:null,children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Save your Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please save this secret key somewhere safe and accessible. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:null!=h?(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:h})}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>{D.ZP.success("API Key copied to clipboard")},children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]}):(0,c.jsx)(A.Z,{children:"Key being created, this might take 30s"})})]})})]})},ew=l(7366),ek=e=>{let{selectedTeam:s,currentOrg:l,selectedKeyAlias:t,accessToken:a,currentPage:r=1}=e,[n,i]=(0,d.useState)({keys:[],total_count:0,current_page:1,total_pages:0}),[o,c]=(0,d.useState)(!0),[m,u]=(0,d.useState)(null),h=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};try{if(console.log("calling fetchKeys"),!a){console.log("accessToken",a);return}c(!0);let r=await (0,y.OD)(a,(null==l?void 0:l.organization_id)||null,(null==s?void 0:s.team_id)||"",t,e.page||1,50);console.log("data",r),i(r),u(null)}catch(e){u(e instanceof Error?e:Error("An error occurred"))}finally{c(!1)}};return(0,d.useEffect)(()=>{h(),console.log("selectedTeam",s,"currentOrg",l,"accessToken",a,"selectedKeyAlias",t)},[s,l,a,t]),{keys:n.keys,isLoading:o,error:m,pagination:{currentPage:n.current_page,totalPages:n.total_pages,totalCount:n.total_count},refresh:h,setKeys:e=>{i(s=>{let l="function"==typeof e?e(s.keys):e;return{...s,keys:l}})}}},eS=l(71594),eC=l(24525),eI=l(21626),eT=l(97214),eA=l(28241),eE=l(58834),eP=l(69552),eO=l(71876);function eL(e){let{data:s=[],columns:l,getRowCanExpand:t,renderSubComponent:a,isLoading:r=!1,expandedRequestId:n,onRowExpand:i}=e,o=(0,eS.b7)({data:s,columns:l,getRowCanExpand:t,getCoreRowModel:(0,eC.sC)(),getExpandedRowModel:(0,eC.rV)(),state:{expanded:n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{}},onExpandedChange:e=>{if(!i)return;let l=n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{},t="function"==typeof e?e(l):e;if(0===Object.keys(t).length){i(null);return}let a=Object.keys(t)[0],r=void 0!==a?s[parseInt(a)]:null;i(r?r.request_id:null)}});return(0,c.jsx)("div",{className:"rounded-lg custom-border",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:r?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading logs..."})})})}):o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))}),e.getIsExpanded()&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:e.getVisibleCells().length,children:a({row:e})})})]},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No logs found"})})})})})]})})}var eD=l(27281),eM=l(41649),eF=l(12514),eR=l(12485),eq=l(18135),eU=l(35242),ez=l(29706),eV=l(77991),eK=l(10900),eB=l(23628),eH=l(74998);function eJ(e){var s,l;let{keyData:t,onCancel:a,onSubmit:r,teams:n,accessToken:i,userID:o,userRole:m}=e,[u]=L.Z.useForm(),[h,x]=(0,d.useState)([]),p=null==n?void 0:n.find(e=>e.team_id===t.team_id),[g,j]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(o&&m&&i)try{if(null===t.team_id){let e=(await (0,y.So)(i,o,m)).data.map(e=>e.id);j(e)}else if(null==p?void 0:p.team_id){let e=await eb(o,m,i,p.team_id);j(Array.from(new Set([...p.models,...e])))}}catch(e){console.error("Error fetching models:",e)}})()},[o,m,i,p,t.team_id]);let f={...t,budget_duration:(l=t.budget_duration)&&({"24h":"daily","7d":"weekly","30d":"monthly"})[l]||null,metadata:t.metadata?JSON.stringify(t.metadata,null,2):"",guardrails:(null===(s=t.metadata)||void 0===s?void 0:s.guardrails)||[]};return(0,c.jsxs)(L.Z,{form:u,onFinish:r,initialValues:f,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Key Alias",name:"key_alias",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[g.length>0&&(0,c.jsx)(O.default.Option,{value:"all-team-models",children:"All Team Models"}),g.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"daily",children:"Daily"}),(0,c.jsx)(O.default.Option,{value:"weekly",children:"Weekly"}),(0,c.jsx)(O.default.Option,{value:"monthly",children:"Monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Guardrails",name:"guardrails",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsx)(L.Z.Item,{name:"token",hidden:!0,children:(0,c.jsx)(q.default,{})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(k.Z,{variant:"light",onClick:a,children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]})}function eW(e){let{selectedToken:s,visible:l,onClose:t,accessToken:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(!1);(0,d.useEffect)(()=>{l&&s&&r.setFieldsValue({key_alias:s.key_alias,max_budget:s.max_budget,tpm_limit:s.tpm_limit,rpm_limit:s.rpm_limit,duration:s.duration||""})},[l,s,r]),(0,d.useEffect)(()=>{l||(i(null),p(!1),r.resetFields())},[l,r]),(0,d.useEffect)(()=>{(null==o?void 0:o.duration)?h((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString()}catch(e){return null}})(o.duration)):h(null)},[null==o?void 0:o.duration]);let g=async()=>{if(s&&a){p(!0);try{let e=await r.validateFields(),l=await (0,y.s0)(a,s.token,e);i(l.key),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key"),p(!1)}}},j=()=>{i(null),p(!1),r.resetFields(),t()};return(0,c.jsx)(M.Z,{title:"Regenerate API Key",open:l,onCancel:j,footer:n?[(0,c.jsx)(k.Z,{onClick:j,children:"Close"},"close")]:[(0,c.jsx)(k.Z,{onClick:j,className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:g,disabled:x,children:x?"Regenerating...":"Regenerate"},"regenerate")],children:n?(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:(null==s?void 0:s.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:n})}),(0,c.jsx)(P.CopyToClipboard,{text:n,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]}):(0,c.jsxs)(L.Z,{form:r,layout:"vertical",onValuesChange:e=>{"duration"in e&&m(s=>({...s,duration:e.duration}))},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",(null==s?void 0:s.expires)?new Date(s.expires).toLocaleString():"Never"]}),u&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",u]})]})})}function eG(e){var s,l;let{keyId:t,onClose:a,keyData:r,accessToken:n,userID:i,userRole:o,teams:m,onKeyDataUpdate:u,onDelete:h}=e,[x,p]=(0,d.useState)(!1),[g]=L.Z.useForm(),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1);if(!r)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(A.Z,{children:"Key not found"})]});let b=async e=>{try{var s,l;if(!n)return;let t=e.token;if(e.key=t,e.metadata&&"string"==typeof e.metadata)try{let l=JSON.parse(e.metadata);e.metadata={...l,...(null===(s=e.guardrails)||void 0===s?void 0:s.length)>0?{guardrails:e.guardrails}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),D.ZP.error("Invalid metadata JSON");return}else e.metadata={...e.metadata||{},...(null===(l=e.guardrails)||void 0===l?void 0:l.length)>0?{guardrails:e.guardrails}:{}};e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,y.Nc)(n,e);u&&u(a),D.ZP.success("Key updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update key"),console.error("Error updating key:",e)}},Z=async()=>{try{if(!n)return;await (0,y.I1)(n,r.token),D.ZP.success("Key deleted successfully"),h&&h(),a()}catch(e){console.error("Error deleting the key:",e),D.ZP.error("Failed to delete key")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(E.Z,{children:r.key_alias||"API Key"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:r.token})]}),o&&eg.LQ.includes(o)&&(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{icon:eB.Z,variant:"secondary",onClick:()=>v(!0),className:"flex items-center",children:"Regenerate Key"}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>f(!0),className:"flex items-center",children:"Delete Key"})]})]}),(0,c.jsx)(eW,{selectedToken:r,visible:_,onClose:()=>v(!1),accessToken:n}),j&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:Z,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>f(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number(r.spend).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",null!==r.max_budget?"$".concat(r.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Key Settings"}),!x&&o&&eg.LQ.includes(o)&&(0,c.jsx)(k.Z,{variant:"light",onClick:()=>p(!0),children:"Edit Settings"})]}),x?(0,c.jsx)(eJ,{keyData:r,onCancel:()=>p(!1),onSubmit:b,teams:m,accessToken:n,userID:i,userRole:o}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.token})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key Alias"}),(0,c.jsx)(A.Z,{children:r.key_alias||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Secret Key"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.key_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)(A.Z,{children:r.team_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),(0,c.jsx)(A.Z,{children:r.organization_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:new Date(r.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Expires"}),(0,c.jsx)(A.Z,{children:r.expires?new Date(r.expires).toLocaleString():"Never"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Spend"}),(0,c.jsxs)(A.Z,{children:["$",Number(r.spend).toFixed(4)," USD"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsx)(A.Z,{children:null!==r.max_budget?"$".concat(r.max_budget," USD"):"Unlimited"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",null!==r.max_parallel_requests?r.max_parallel_requests:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model TPM Limits: ",(null===(s=r.metadata)||void 0===s?void 0:s.model_tpm_limit)?JSON.stringify(r.metadata.model_tpm_limit):"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model RPM Limits: ",(null===(l=r.metadata)||void 0===l?void 0:l.model_rpm_limit)?JSON.stringify(r.metadata.model_rpm_limit):"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(r.metadata,null,2)})]})]})]})})]})]})]})}var eY=l(87908),e$=l(82422),eX=l(2356),eQ=l(44633),e0=l(86462),e1=l(3837),e2=e=>{var s;let{options:l,onApplyFilters:t,onResetFilters:a,initialValues:r={},buttonLabel:n="Filter"}=e,[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)((null===(s=l[0])||void 0===s?void 0:s.name)||""),[h,x]=(0,d.useState)(r),[p,j]=(0,d.useState)(r),[f,_]=(0,d.useState)(!1),[y,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),S=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=e=>{let s=e.target;!S.current||S.current.contains(s)||s.closest(".ant-dropdown")||s.closest(".ant-select-dropdown")||o(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{l.length>0&&l[0].isSearchable&&l[0].searchFn&&C(l[0])},[]);let C=async e=>{if(e.isSearchable&&e.searchFn){Z(!0);try{let s=await e.searchFn("");v(s)}catch(e){console.error("Error loading initial options:",e),v([])}finally{Z(!1)}}};(0,d.useEffect)(()=>{i&&(null==L?void 0:L.isSearchable)&&(null==L?void 0:L.searchFn)&&C(L)},[i,m]);let I=e=>{u(e),_(!1);let s=l.find(s=>s.name===e);(null==s?void 0:s.isSearchable)&&(null==s?void 0:s.searchFn)?C(s):v([])},T=(0,d.useCallback)(ep()(async(e,s)=>{if(s.isSearchable&&s.searchFn){Z(!0);try{let l=await s.searchFn(e);v(l)}catch(e){console.error("Error searching:",e),v([])}finally{Z(!1)}}},300),[]),A=e=>{j(s=>({...s,[m]:e}))},E=()=>{let e={};l.forEach(s=>{e[s.name]=""}),j(e)},P=l.map(e=>({key:e.name,label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[m===e.name&&(0,c.jsx)(e$.Z,{className:"h-4 w-4 text-blue-600"}),e.label||e.name]})})),L=l.find(e=>e.name===m);return(0,c.jsxs)("div",{className:"relative",ref:S,children:[(0,c.jsx)(k.Z,{icon:eX.Z,onClick:()=>o(!i),variant:"secondary",size:"xs",className:"flex items-center pr-2",children:n}),i&&(0,c.jsx)(eF.Z,{className:"absolute left-0 mt-2 w-[500px] z-50 border border-gray-200 shadow-lg",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsx)(g.Z,{menu:{items:P,onClick:e=>{let{key:s}=e;return I(s)},style:{minWidth:"200px"}},onOpenChange:_,open:f,trigger:["click"],children:(0,c.jsxs)(R.ZP,{className:"min-w-40 text-left flex justify-between items-center",children:[(null==L?void 0:L.label)||m,f?(0,c.jsx)(eQ.Z,{className:"h-4 w-4"}):(0,c.jsx)(e0.Z,{className:"h-4 w-4"})]})}),(null==L?void 0:L.isSearchable)?(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search ".concat(L.label||m,"..."),value:p[m]||void 0,onChange:e=>A(e),onSearch:e=>{w(e),T(e,L)},onInputKeyDown:e=>{"Enter"===e.key&&N&&(A(N),e.preventDefault())},filterOption:!1,className:"flex-1 w-full max-w-full truncate min-w-100",loading:b,options:y,allowClear:!0,notFoundContent:b?(0,c.jsx)(eY.Z,{size:"small"}):(0,c.jsx)("div",{className:"p-2",children:N&&(0,c.jsxs)(R.ZP,{type:"link",className:"p-0 mt-1",onClick:()=>{A(N);let e=document.activeElement;e&&e.blur()},children:["Use “",N,"” as filter value"]})})}):(0,c.jsx)(q.default,{placeholder:"Enter value...",value:p[m]||"",onChange:e=>A(e.target.value),className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",suffix:p[m]?(0,c.jsx)(e1.Z,{className:"h-4 w-4 cursor-pointer text-gray-400 hover:text-gray-500",onClick:e=>{e.stopPropagation(),A("")}}):null})]}),(0,c.jsxs)("div",{className:"flex gap-2 justify-end",children:[(0,c.jsx)(R.ZP,{onClick:()=>{E(),a(),o(!1)},children:"Reset"}),(0,c.jsx)(R.ZP,{onClick:()=>{x(p),t(p),o(!1)},children:"Apply Filters"})]})]})})]})},e4=l(16593);let e5=async e=>{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.OD)(e,null,"",null,l,100),r=a.keys.map(e=>e.key_alias).filter(Boolean);s=[...s,...r],l{if(!e)return[];try{let l=[],t=1,a=!0;for(;a;){let r=await (0,y.It)(e,s||null,null);l=[...l,...r.teams],t{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.r6)(e);s=[...s,...a.organizations],l{if(!s){g([]);return}let e=[...s];o["Team ID"]&&(e=e.filter(e=>e.team_id===o["Team ID"])),o["Organization ID"]&&(e=e.filter(e=>e.organization_id===o["Organization ID"])),g(e)},[s,o]),(0,d.useEffect)(()=>{let e=async()=>{let e=await e3(a);e.length>0&&u(e);let s=await e6(a);s.length>0&&x(s)};a&&e()},[a]);let j=(0,e4.a)({queryKey:["allKeys"],queryFn:async()=>{if(!a)throw Error("Access token required");return await e5(a)},enabled:!!a}).data||[];return(0,d.useEffect)(()=>{l&&l.length>0&&u(e=>e.length{t&&t.length>0&&x(e=>e.length{if(c({"Team ID":e["Team ID"]||"","Organization ID":e["Organization ID"]||"","Key Alias":e["Key Alias"]||""}),e["Team ID"]){let s=null==m?void 0:m.find(s=>s.team_id===e["Team ID"]);s&&r(s)}if(e["Organization ID"]){let s=null==h?void 0:h.find(s=>s.organization_id===e["Organization ID"]);s&&n(s)}let s=e["Key Alias"];i(s&&j.find(e=>e===s)||null)},handleFilterReset:()=>{c({"Team ID":"","Organization ID":"","Key Alias":""}),r(null),n(null)}}}({keys:s,teams:i,organizations:j,accessToken:x,setSelectedTeam:m,setCurrentOrg:f,setSelectedKeyAlias:h});(0,d.useEffect)(()=>{if(x){let e=s.map(e=>e.user_id).filter(e=>null!==e);(async()=>{N((await (0,y.Of)(x,e,1,100)).users)})()}},[x,s]),(0,d.useEffect)(()=>{if(_){let e=()=>{_()};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}},[_]);let P=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return s.getCanExpand()?(0,c.jsx)("button",{onClick:s.getToggleExpandedHandler(),style:{cursor:"pointer"},children:s.getIsExpanded()?"▼":"▶"}):null}},{header:"Key ID",accessorKey:"token",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>b(e.getValue()),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>{let s=e.getValue();return(0,c.jsx)(W.Z,{title:s,children:s?s.length>20?"".concat(s.slice(0,20),"..."):s:"-"})}},{header:"Secret Key",accessorKey:"key_name",cell:e=>(0,c.jsx)("span",{className:"font-mono text-xs",children:e.getValue()})},{header:"Team Alias",accessorKey:"team_id",cell:e=>{let{row:s,getValue:l}=e,t=l(),a=null==I?void 0:I.find(e=>e.team_id===t);return(null==a?void 0:a.team_alias)||"Unknown"}},{header:"Team ID",accessorKey:"team_id",cell:e=>(0,c.jsx)(W.Z,{title:e.getValue(),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})},{header:"Organization ID",accessorKey:"organization_id",cell:e=>e.getValue()?e.renderValue():"-"},{header:"User Email",accessorKey:"user_id",cell:e=>{let s=e.getValue(),l=Z.find(e=>e.user_id===s);return(null==l?void 0:l.user_email)?l.user_email:"-"}},{header:"User ID",accessorKey:"user_id",cell:e=>{let s=e.getValue();return s?(0,c.jsx)(W.Z,{title:s,children:(0,c.jsxs)("span",{children:[s.slice(0,7),"..."]})}):"-"}},{header:"Created At",accessorKey:"created_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"-"}},{header:"Created By",accessorKey:"created_by",cell:e=>e.getValue()||"Unknown"},{header:"Expires",accessorKey:"expires",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"Never"}},{header:"Spend (USD)",accessorKey:"spend",cell:e=>Number(e.getValue()).toFixed(4)},{header:"Budget (USD)",accessorKey:"max_budget",cell:e=>null!==e.getValue()&&void 0!==e.getValue()?e.getValue():"Unlimited"},{header:"Budget Reset",accessorKey:"budget_reset_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleString():"Never"}},{header:"Models",accessorKey:"models",cell:e=>{let s=e.getValue();return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:s&&s.length>0?s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):"-"})}},{header:"Rate Limits",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{children:["TPM: ",null!==l.tpm_limit?l.tpm_limit:"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",null!==l.rpm_limit?l.rpm_limit:"Unlimited"]})]})}}];return(0,c.jsx)("div",{className:"w-full h-full overflow-hidden",children:v?(0,c.jsx)(eG,{keyId:v,onClose:()=>b(null),keyData:s.find(e=>e.token===v),onKeyDataUpdate:e=>{l(s=>s.map(s=>s.token===e.token?e8(s,e):s))},onDelete:()=>{l(e=>e.filter(e=>e.token!==v))},accessToken:x,userID:p,userRole:g,teams:I}):(0,c.jsxs)("div",{className:"border-b py-4 flex-1 overflow-hidden",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between w-full mb-2",children:[(0,c.jsx)(e2,{options:[{name:"Team ID",label:"Team ID",isSearchable:!0,searchFn:async e=>I&&0!==I.length?I.filter(s=>s.team_id.toLowerCase().includes(e.toLowerCase())||s.team_alias&&s.team_alias.toLowerCase().includes(e.toLowerCase())).map(e=>({label:"".concat(e.team_alias||e.team_id," (").concat(e.team_id,")"),value:e.team_id})):[]},{name:"Organization ID",label:"Organization ID",isSearchable:!0,searchFn:async e=>T&&0!==T.length?T.filter(s=>{var l,t;return null!==(t=null===(l=s.organization_id)||void 0===l?void 0:l.toLowerCase().includes(e.toLowerCase()))&&void 0!==t&&t}).filter(e=>null!==e.organization_id&&void 0!==e.organization_id).map(e=>({label:"".concat(e.organization_id||"Unknown"," (").concat(e.organization_id,")"),value:e.organization_id})):[]},{name:"Key Alias",label:"Key Alias",isSearchable:!0,searchFn:async e=>C.filter(s=>s.toLowerCase().includes(e.toLowerCase())).map(e=>({label:e,value:e}))}],onApplyFilters:A,initialValues:w,onResetFilters:E}),(0,c.jsxs)("div",{className:"flex items-center gap-4",children:[(0,c.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:["Showing ",t?"...":"".concat((a.currentPage-1)*n+1," - ").concat(Math.min(a.currentPage*n,a.totalCount))," of ",t?"...":a.totalCount," results"]}),(0,c.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",t?"...":a.currentPage," of ",t?"...":a.totalPages]}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage-1),disabled:t||1===a.currentPage,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage+1),disabled:t||a.currentPage===a.totalPages,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]}),(0,c.jsx)("div",{className:"h-[75vh] overflow-auto",children:(0,c.jsx)(eL,{columns:P.filter(e=>"expander"!==e.id),data:S,isLoading:t,getRowCanExpand:()=>!1,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{})})})]})})}console.log=function(){};var e9=e=>{let{userID:s,userRole:l,accessToken:t,selectedTeam:a,setSelectedTeam:r,data:n,setData:i,teams:o,premiumUser:m,currentOrg:u,organizations:h,setCurrentOrg:x,selectedKeyAlias:p,setSelectedKeyAlias:g}=e,[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),[C,I]=(0,d.useState)(null),[T,O]=(0,d.useState)(null),[F,R]=(0,d.useState)((null==a?void 0:a.team_id)||""),[q,U]=(0,d.useState)("");(0,d.useEffect)(()=>{R((null==a?void 0:a.team_id)||"")},[a]);let{keys:z,isLoading:K,error:B,pagination:J,refresh:W,setKeys:G}=ek({selectedTeam:a,currentOrg:u,selectedKeyAlias:p,accessToken:t});window.refreshKeysList=W,window.addNewKeyToList=e=>{G(s=>[e,...s])};let[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(null),[el,et]=(0,d.useState)([]),ea=new Set,[er,en]=(0,d.useState)(!1),[ei,eo]=(0,d.useState)(!1),[ec,ed]=(0,d.useState)(null),[em,eu]=(0,d.useState)(null),[eh]=L.Z.useForm(),[ex,ep]=(0,d.useState)(null),[eg,ej]=(0,d.useState)(ea),[ef,e_]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("in calculateNewExpiryTime for selectedToken",ee),(null==em?void 0:em.duration)?ep((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString("en-US",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!0})}catch(e){return null}})(em.duration)):ep(null),console.log("calculateNewExpiryTime:",ex)},[ee,null==em?void 0:em.duration]),(0,d.useEffect)(()=>{(async()=>{try{if(null===s||null===l||null===t)return;let e=await V(s,l,t);e&&et(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,s,l]),(0,d.useEffect)(()=>{if(o){let e=new Set;o.forEach((s,l)=>{let t=s.team_id;e.add(t)}),ej(e)}},[o]);let ey=async()=>{if(null!=b&&null!=n){try{await (0,y.I1)(t,b);let e=n.filter(e=>e.token!==b);i(e)}catch(e){console.error("Error deleting the key:",e)}v(!1),Z(null)}},ev=(e,s)=>{eu(l=>({...l,[e]:s}))},eb=async()=>{if(!m){D.ZP.error("Regenerate API Key is an Enterprise feature. Please upgrade to use this feature.");return}if(null!=ee)try{let e=await eh.validateFields(),s=await (0,y.s0)(t,ee.token,e);if(ed(s.key),n){let l=n.map(l=>l.token===(null==ee?void 0:ee.token)?{...l,key_name:s.key_name,...e}:l);i(l)}eo(!1),eh.resetFields(),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key")}};return(0,c.jsxs)("div",{children:[(0,c.jsx)(e7,{keys:z,setKeys:G,isLoading:K,pagination:J,onPageChange:e=>{W({page:e})},pageSize:100,teams:o,selectedTeam:a,setSelectedTeam:r,accessToken:t,userID:s,userRole:l,organizations:h,setCurrentOrg:x,refresh:W,selectedKeyAlias:p,setSelectedKeyAlias:g}),_&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ey,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{v(!1),Z(null)},children:"Cancel"})]})]})]})}),(0,c.jsx)(M.Z,{title:"Regenerate API Key",visible:ei,onCancel:()=>{eo(!1),eh.resetFields()},footer:[(0,c.jsx)(k.Z,{onClick:()=>{eo(!1),eh.resetFields()},className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:eb,disabled:!m,children:m?"Regenerate":"Upgrade to Regenerate"},"regenerate")],children:m?(0,c.jsxs)(L.Z,{form:eh,layout:"vertical",onValuesChange:(e,s)=>{"duration"in e&&ev("duration",e.duration)},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry:"," ",(null==ee?void 0:ee.expires)!=null?new Date(ee.expires).toLocaleString():"Never"]}),ex&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",ex]})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to use this feature"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat",target:"_blank",children:"Get Free Trial"})})]})}),ec&&(0,c.jsx)(M.Z,{visible:!!ec,onCancel:()=>ed(null),footer:[(0,c.jsx)(k.Z,{onClick:()=>ed(null),children:"Close"},"close")],children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:(null==ee?void 0:ee.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:ec})}),(0,c.jsx)(P.CopyToClipboard,{text:ec,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]})})]})},se=l(12011);console.log=function(){},console.log("isLocal:",!1);var ss=e=>{let{userID:s,userRole:l,teams:t,keys:a,setUserRole:r,userEmail:n,setUserEmail:i,setTeams:o,setKeys:h,premiumUser:x,organizations:p}=e,[g,j]=(0,d.useState)(null),[f,v]=(0,d.useState)(null),b=(0,m.useSearchParams)(),k=function(e){console.log("COOKIES",document.cookie);let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token"),S=b.get("invitation_id"),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)(null),[E,P]=(0,d.useState)([]),[O,L]=(0,d.useState)(null),[D,M]=(0,d.useState)(null),[F,R]=(0,d.useState)(null);if(window.addEventListener("beforeunload",function(){sessionStorage.clear()}),(0,d.useEffect)(()=>{if(k){let e=(0,u.o)(k);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),I(e.key),e.user_role){let s=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"app_user":return"App User";case"internal_user":return"Internal User";case"internal_user_viewer":return"Internal Viewer";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",s),r(s)}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e))}}if(s&&C&&l&&!a&&!g){let e=sessionStorage.getItem("userModels"+s);e?P(JSON.parse(e)):(console.log("currentOrg: ".concat(JSON.stringify(f))),(async()=>{try{let e=await (0,y.g)(C);L(e);let t=await (0,y.Br)(C,s,l,!1,null,null);j(t.user_info),console.log("userSpendData: ".concat(JSON.stringify(g))),(null==t?void 0:t.teams[0].keys)?h(t.keys.concat(t.teams.filter(e=>"Admin"===l||e.user_id===s).flatMap(e=>e.keys))):h(t.keys),sessionStorage.setItem("userData"+s,JSON.stringify(t.keys)),sessionStorage.setItem("userSpendData"+s,JSON.stringify(t.user_info));let a=(await (0,y.So)(C,s,l)).data.map(e=>e.id);console.log("available_model_names:",a),P(a),console.log("userModels:",E),sessionStorage.setItem("userModels"+s,JSON.stringify(a))}catch(e){console.error("There was an error fetching the data",e),e.message.includes("Invalid proxy server token passed")&&q()}})(),Z(C,s,l,f,o))}},[s,k,C,a,l]),(0,d.useEffect)(()=>{C&&(async()=>{try{let e=await (0,y.e2)(C,[C]);console.log("keyInfo: ",e)}catch(e){e.message.includes("Invalid proxy server token passed")&&q()}})()},[C]),(0,d.useEffect)(()=>{console.log("currentOrg: ".concat(JSON.stringify(f),", accessToken: ").concat(C,", userID: ").concat(s,", userRole: ").concat(l)),C&&(console.log("fetching teams"),Z(C,s,l,f,o))},[f]),(0,d.useEffect)(()=>{if(null!==a&&null!=D&&null!==D.team_id){let e=0;for(let s of(console.log("keys: ".concat(JSON.stringify(a))),a))D.hasOwnProperty("team_id")&&null!==s.team_id&&s.team_id===D.team_id&&(e+=s.spend);console.log("sum: ".concat(e)),A(e)}else if(null!==a){let e=0;for(let s of a)e+=s.spend;A(e)}},[D]),null!=S)return(0,c.jsx)(se.default,{});function q(){(0,_.b)();let e="/sso/key/generate";return console.log("Full URL:",e),window.location.href=e,null}if(null==k)return console.log("All cookies before redirect:",document.cookie),q(),null;try{let e=(0,u.o)(k);console.log("Decoded token:",e);let s=e.exp,l=Math.floor(Date.now()/1e3);if(s&&l>=s){console.log("Token expired, redirecting to login"),(0,_.b)();let e="/sso/key/generate";return console.log("Full URL for expired token:",e),window.location.href=e,null}}catch(s){console.error("Error decoding token:",s),(0,_.b)();let e="/sso/key/generate";return console.log("Full URL after token decode error:",e),window.location.href=e,null}if(null==C)return null;if(null==s)return(0,c.jsx)("h1",{children:"User ID is not set"});if(null==l&&r("App Owner"),l&&"Admin Viewer"==l){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to create keys"})]})}return console.log("inside user dashboard, selected team",D),console.log("All cookies after redirect:",document.cookie),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(N.Z,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,c.jsx)(eN,{userID:s,team:D,teams:t,userRole:l,accessToken:C,data:a,setData:h},D?D.team_id:null),(0,c.jsx)(e9,{userID:s,userRole:l,accessToken:C,selectedTeam:D||null,setSelectedTeam:M,selectedKeyAlias:F,setSelectedKeyAlias:R,data:a,setData:h,premiumUser:x,teams:t,currentOrg:f,setCurrentOrg:v,organizations:p})]})})})},sl=l(97765);(t=n||(n={})).OpenAI="OpenAI",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.Anthropic="Anthropic",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.Google_AI_Studio="Google AI Studio",t.Bedrock="Amazon Bedrock",t.Groq="Groq",t.MistralAI="Mistral AI",t.Deepseek="Deepseek",t.Cohere="Cohere",t.Databricks="Databricks",t.Ollama="Ollama",t.xAI="xAI",t.AssemblyAI="AssemblyAI",t.Cerebras="Cerebras",t.Sambanova="Sambanova",t.Perplexity="Perplexity",t.TogetherAI="TogetherAI",t.Openrouter="Openrouter",t.FireworksAI="Fireworks AI";let st={OpenAI:"openai",OpenAI_Text:"text-completion-openai",Azure:"azure",Azure_AI_Studio:"azure_ai",Anthropic:"anthropic",Google_AI_Studio:"gemini",Bedrock:"bedrock",Groq:"groq",MistralAI:"mistral",Cohere:"cohere_chat",OpenAI_Compatible:"openai",OpenAI_Text_Compatible:"text-completion-openai",Vertex_AI:"vertex_ai",Databricks:"databricks",xAI:"xai",Deepseek:"deepseek",Ollama:"ollama",AssemblyAI:"assemblyai",Cerebras:"cerebras",Sambanova:"sambanova",Perplexity:"perplexity",TogetherAI:"togetherai",Openrouter:"openrouter",FireworksAI:"fireworks_ai"},sa="/ui/assets/logos/",sr={Anthropic:"".concat(sa,"anthropic.svg"),AssemblyAI:"".concat(sa,"assemblyai_small.png"),Azure:"".concat(sa,"microsoft_azure.svg"),"Azure AI Foundry (Studio)":"".concat(sa,"microsoft_azure.svg"),"Amazon Bedrock":"".concat(sa,"bedrock.svg"),Cerebras:"".concat(sa,"cerebras.svg"),Cohere:"".concat(sa,"cohere.svg"),Databricks:"".concat(sa,"databricks.svg"),Deepseek:"".concat(sa,"deepseek.svg"),"Fireworks AI":"".concat(sa,"fireworks.svg"),Groq:"".concat(sa,"groq.svg"),"Google AI Studio":"".concat(sa,"google.svg"),"Mistral AI":"".concat(sa,"mistral.svg"),Ollama:"".concat(sa,"ollama.svg"),OpenAI:"".concat(sa,"openai_small.svg"),"OpenAI Text Completion":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Text Completion Models (Together AI, etc.)":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Endpoints (Together AI, etc.)":"".concat(sa,"openai_small.svg"),Openrouter:"".concat(sa,"openrouter.svg"),Perplexity:"".concat(sa,"perplexity-ai.svg"),Sambanova:"".concat(sa,"sambanova.svg"),TogetherAI:"".concat(sa,"togetherai.svg"),"Vertex AI (Anthropic, Gemini, etc.)":"".concat(sa,"google.svg"),xAI:"".concat(sa,"xai.svg")},sn=e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:sr[e],displayName:e}}let s=Object.keys(st).find(s=>st[s].toLowerCase()===e.toLowerCase());if(!s)return{logo:"",displayName:e};let l=n[s];return{logo:sr[l],displayName:l}},si=e=>"Vertex AI (Anthropic, Gemini, etc.)"===e?"gemini-pro":"Anthropic"==e||"Amazon Bedrock"==e?"claude-3-opus":"Google AI Studio"==e?"gemini-pro":"Azure AI Foundry (Studio)"==e?"azure_ai/command-r-plus":"Azure"==e?"azure/my-deployment":"gpt-3.5-turbo",so=(e,s)=>{console.log("Provider key: ".concat(e));let l=st[e];console.log("Provider mapped to: ".concat(l));let t=[];return e&&"object"==typeof s&&(Object.entries(s).forEach(e=>{let[s,a]=e;null!==a&&"object"==typeof a&&"litellm_provider"in a&&(a.litellm_provider===l||a.litellm_provider.includes(l))&&t.push(s)}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(s).forEach(e=>{let[s,l]=e;null!==l&&"object"==typeof l&&"litellm_provider"in l&&"cohere"===l.litellm_provider&&t.push(s)}))),t},sc=async(e,s,l)=>{try{console.log("handling submit for formValues:",e);let s=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let l=st[e.custom_llm_provider]+"/*";e.model_name=l,s.push({public_name:l,litellm_model:l}),e.model=l}let l=[];for(let t of s){let s={},a={},r=t.public_name;for(let[l,r]of(s.model=t.litellm_model,e.input_cost_per_token&&(e.input_cost_per_token=Number(e.input_cost_per_token)/1e6),e.output_cost_per_token&&(e.output_cost_per_token=Number(e.output_cost_per_token)/1e6),s.model=t.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==r&&"custom_pricing"!==l&&"pricing_model"!==l&&"cache_control"!==l){if("model_name"==l)s.model=r;else if("custom_llm_provider"==l){console.log("custom_llm_provider:",r);let e=st[r];s.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==l)continue;else if("base_model"===l)a[l]=r;else if("team_id"===l)a.team_id=r;else if("mode"==l)console.log("placing mode in modelInfo"),a.mode=r,delete s.mode;else if("custom_model_name"===l)s.model=r;else if("litellm_extra_params"==l){console.log("litellm_extra_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,t]of Object.entries(e))s[l]=t}}else if("model_info_params"==l){console.log("model_info_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[s,l]of Object.entries(e))a[s]=l}}else if("input_cost_per_token"===l||"output_cost_per_token"===l||"input_cost_per_second"===l){r&&(s[l]=Number(r));continue}else s[l]=r}l.push({litellmParamsObj:s,modelInfoObj:a,modelName:r})}return l}catch(e){D.ZP.error("Failed to create model: "+e,10)}},sd=async(e,s,l,t)=>{try{let a=await sc(e,s,l);if(!a||0===a.length)return;for(let e of a){let{litellmParamsObj:l,modelInfoObj:t,modelName:a}=e,r={model_name:a,litellm_params:l,model_info:t},n=await (0,y.kK)(s,r);console.log("response for model create call: ".concat(n.data))}t&&t(),l.resetFields()}catch(e){D.ZP.error("Failed to add model: "+e,10)}};var sm=l(53410),su=l(47451),sh=l(69410);let{Link:sx}=es.default,sp={[n.OpenAI]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Vertex_AI]:[{key:"vertex_project",label:"Vertex Project",placeholder:"adroit-cadet-1234..",required:!0},{key:"vertex_location",label:"Vertex Location",placeholder:"us-east-1",required:!0},{key:"vertex_credentials",label:"Vertex Credentials",required:!0,type:"upload"}],[n.AssemblyAI]:[{key:"api_base",label:"API Base",type:"select",required:!0,options:["https://api.assemblyai.com","https://api.eu.assemblyai.com"]},{key:"api_key",label:"AssemblyAI API Key",type:"password",required:!0}],[n.Azure]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_version",label:"API Version",placeholder:"2023-07-01-preview",tooltip:"By default litellm will use the latest version. If you want to use a different version, you can specify it here"},{key:"base_model",label:"Base Model",placeholder:"azure/gpt-3.5-turbo"},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.Azure_AI_Studio]:[{key:"api_base",label:"API Base",placeholder:"https://.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",tooltip:"Enter your full Target URI from Azure Foundry here. Example: https://litellm8397336933.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",required:!0},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.OpenAI_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Bedrock]:[{key:"aws_access_key_id",label:"AWS Access Key ID",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_secret_access_key",label:"AWS Secret Access Key",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_region_name",label:"AWS Region Name",placeholder:"us-east-1",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."}],[n.Ollama]:[],[n.Anthropic]:[{key:"api_key",label:"API Key",placeholder:"sk-",type:"password",required:!0}],[n.Google_AI_Studio]:[{key:"api_key",label:"API Key",placeholder:"aig-",type:"password",required:!0}],[n.Groq]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.MistralAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Deepseek]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cohere]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Databricks]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.xAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cerebras]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Sambanova]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Perplexity]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.TogetherAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Openrouter]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.FireworksAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}]};var sg=e=>{let{selectedProvider:s,uploadProps:l}=e,t=n[s],a=d.useMemo(()=>sp[t]||[],[t]);return(0,c.jsx)(c.Fragment,{children:a.map(e=>{var s;return(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:e.label,name:e.key,rules:e.required?[{required:!0,message:"Required"}]:void 0,tooltip:e.tooltip,className:"vertex_credentials"===e.key?"mb-0":void 0,children:"select"===e.type?(0,c.jsx)(O.default,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"upload"===e.type?(0,c.jsx)(et.Z,{...l,children:(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(en.Z,{}),children:"Click to Upload"})}):(0,c.jsx)(S.Z,{placeholder:e.placeholder,type:"password"===e.type?"password":"text"})}),"vertex_credentials"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Give litellm a gcp service account(.json file), so it can make the relevant calls"})})]}),"base_model"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,c.jsx)(sx,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key)})})};let{Title:sj,Link:sf}=es.default;var s_=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,onUpdateCredential:a,uploadProps:r,addOrEdit:i,existingCredential:o}=e,[m]=L.Z.useForm(),[u,h]=(0,d.useState)(n.OpenAI),[x,p]=(0,d.useState)(!1);return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(o))),(0,c.jsx)(M.Z,{title:"add"===i?"Add New Credential":"Edit Credential",visible:s,onCancel:()=>{l(),m.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:m,onFinish:e=>{"add"===i?t(e):a(e),m.resetFields()},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==o?void 0:o.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials",disabled:null!=o&&!!o.credential_name})}),(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,c.jsx)(O.default,{value:(null==o?void 0:o.credential_info.custom_llm_provider)||u,onChange:e=>{h(e)},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sg,{selectedProvider:u,uploadProps:r}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sf,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),m.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"add"===i?"Add Credential":"Update Credential"})]})]})]})})},sy=e=>{let{accessToken:s,uploadProps:l,credentialList:t,fetchCredentials:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)(null),[h]=L.Z.useForm();console.log("selectedCredential in credentials panel: ".concat(JSON.stringify(m)));let x=["credential_name","custom_llm_provider"],p=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.eZ)(s,e.credential_name,t);D.ZP.success("Credential updated successfully"),console.log("response: ".concat(JSON.stringify(r))),o(!1),a(s)},g=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.oC)(s,t);D.ZP.success("Credential added successfully"),console.log("response: ".concat(JSON.stringify(r))),n(!1),a(s)};(0,d.useEffect)(()=>{s&&a(s)},[s]);let j=e=>{let s={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"},l=s[e.toLowerCase()]||s.default;return(0,c.jsx)(eM.Z,{color:l,size:"xs",children:e})},f=async e=>{if(!s){console.error("No access token found");return}let l=await (0,y.gX)(s,e);console.log("response: ".concat(JSON.stringify(l))),D.ZP.success("Credential deleted successfully"),a(s)};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsxs)(A.Z,{children:["Configured credentials for different AI providers. Add and manage your API credentials."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/credentials",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]})}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Credential Name"}),(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Description"})]})}),(0,c.jsx)(eT.Z,{children:t&&0!==t.length?t.map((e,s)=>{var l,t;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.credential_name}),(0,c.jsx)(eA.Z,{children:j((null===(l=e.credential_info)||void 0===l?void 0:l.custom_llm_provider)||"-")}),(0,c.jsx)(eA.Z,{children:(null===(t=e.credential_info)||void 0===t?void 0:t.description)||"-"}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{icon:sm.Z,variant:"light",size:"sm",onClick:()=>{console.log("credential being set: ".concat(JSON.stringify(e))),u(e),o(!0)}}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"light",size:"sm",onClick:()=>f(e.credential_name)})]})]},s)}):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),className:"mt-4",children:"Add Credential"}),r&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:r,onCancel:()=>n(!1),uploadProps:l,addOrEdit:"add",onUpdateCredential:p,existingCredential:null}),i&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:i,existingCredential:m,onUpdateCredential:p,uploadProps:l,onCancel:()=>o(!1),addOrEdit:"edit"})]})};let sv=e=>{var s;return(null==e?void 0:null===(s=e.model_info)||void 0===s?void 0:s.team_public_model_name)?e.model_info.team_public_model_name:(null==e?void 0:e.model_name)||"-"};var sb=l(53003),sZ=l(47323),sN=l(75105),sw=l(40278),sk=l(14301),sS=l(59664),sC=e=>{let{modelMetrics:s,modelMetricsCategories:l,customTooltip:t,premiumUser:a}=e;return(0,c.jsx)(sS.Z,{title:"Time to First token (s)",className:"h-72",data:s,index:"date",showLegend:!1,categories:l,colors:["indigo","rose"],connectNulls:!0,customTooltip:t})},sI=e=>{let{teamData:s,canEditTeam:l,handleMemberDelete:t,setSelectedEditMember:a,setIsEditMemberModalVisible:r,setIsAddMemberModalVisible:n}=e;return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"User Email"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:s.team_info.members_with_roles.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_email})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.role})}),(0,c.jsx)(eA.Z,{children:l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{a(e),r(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(e)})]})})]},s))})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),children:"Add Member"})]})},sT=l(61994),sA=l(85180),sE=l(89245),sP=l(78355);let sO={"/key/generate":"Member can generate a virtual key for this team","/key/update":"Member can update a virtual key belonging to this team","/key/delete":"Member can delete a virtual key belonging to this team","/key/info":"Member can get info about a virtual key belonging to this team","/key/regenerate":"Member can regenerate a virtual key belonging to this team","/key/{key_id}/regenerate":"Member can regenerate a virtual key belonging to this team","/key/list":"Member can list virtual keys belonging to this team","/key/block":"Member can block a virtual key belonging to this team","/key/unblock":"Member can unblock a virtual key belonging to this team"},sL=e=>e.includes("/info")||e.includes("/list")?"GET":"POST",sD=e=>{let s=sL(e),l=sO[e];if(!l){for(let[s,t]of Object.entries(sO))if(e.includes(s)){l=t;break}}return l||(l="Access ".concat(e)),{method:s,endpoint:e,description:l,route:e}};var sM=e=>{let{teamId:s,accessToken:l,canEditTeam:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)(!0),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),g=async()=>{try{if(m(!0),!l)return;let e=await (0,y.aC)(l,s),t=e.all_available_permissions||[];r(t);let a=e.team_member_permissions||[];i(a),p(!1)}catch(e){D.ZP.error("Failed to load permissions"),console.error("Error fetching permissions:",e)}finally{m(!1)}};(0,d.useEffect)(()=>{g()},[s,l]);let j=(e,s)=>{i(s?[...n,e]:n.filter(s=>s!==e)),p(!0)},f=async()=>{try{if(!l)return;h(!0),await (0,y.TF)(l,s,n),D.ZP.success("Permissions updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update permissions"),console.error("Error updating permissions:",e)}finally{h(!1)}};if(o)return(0,c.jsx)("div",{className:"p-6 text-center",children:"Loading permissions..."});let _=a.length>0;return(0,c.jsxs)(eF.Z,{className:"bg-white shadow-md rounded-md p-6",children:[(0,c.jsxs)("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center border-b pb-4 mb-6",children:[(0,c.jsx)(E.Z,{className:"mb-2 sm:mb-0",children:"Member Permissions"}),t&&x&&(0,c.jsxs)("div",{className:"flex gap-3",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(sE.Z,{}),onClick:()=>{g()},children:"Reset"}),(0,c.jsxs)(k.Z,{onClick:f,loading:u,className:"flex items-center gap-2",children:[(0,c.jsx)(sP.Z,{})," Save Changes"]})]})]}),(0,c.jsx)(A.Z,{className:"mb-6 text-gray-600",children:"Control what team members can do when they are not team admins."}),_?(0,c.jsxs)(eI.Z,{className:"mt-4",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Method"}),(0,c.jsx)(eP.Z,{children:"Endpoint"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Access"})]})}),(0,c.jsx)(eT.Z,{children:a.map(e=>{let s=sD(e);return(0,c.jsxs)(eO.Z,{className:"hover:bg-gray-50 transition-colors",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"px-2 py-1 rounded text-xs font-medium ".concat("GET"===s.method?"bg-blue-100 text-blue-800":"bg-green-100 text-green-800"),children:s.method})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"font-mono text-sm text-gray-800",children:s.endpoint})}),(0,c.jsx)(eA.Z,{className:"text-gray-700",children:s.description}),(0,c.jsx)(eA.Z,{className:"text-right",children:(0,c.jsx)(sT.Z,{checked:n.includes(e),onChange:s=>j(e,s.target.checked),disabled:!t})})]},e)})})]}):(0,c.jsx)("div",{className:"py-12",children:(0,c.jsx)(sA.Z,{description:"No permissions available"})})]})},sF=e=>{var s,l,t;let{visible:a,onCancel:r,onSubmit:n,initialData:i,mode:o,config:m}=e,[u]=L.Z.useForm();console.log("Initial Data:",i),(0,d.useEffect)(()=>{if(a){if("edit"===o&&i)u.setFieldsValue({...i,role:i.role||m.defaultRole});else{var e;u.resetFields(),u.setFieldsValue({role:m.defaultRole||(null===(e=m.roleOptions[0])||void 0===e?void 0:e.value)})}}},[a,i,o,u,m.defaultRole,m.roleOptions]);let h=async e=>{try{let s=Object.entries(e).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:"string"==typeof t?t.trim():t}},{});n(s),u.resetFields(),D.ZP.success("Successfully ".concat("add"===o?"added":"updated"," member"))}catch(e){D.ZP.error("Failed to submit form"),console.error("Form submission error:",e)}},x=e=>{switch(e.type){case"input":return(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",onChange:e=>{e.target.value=e.target.value.trim()}});case"select":var s;return(0,c.jsx)(O.default,{children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))});default:return null}};return(0,c.jsx)(M.Z,{title:m.title||("add"===o?"Add Member":"Edit Member"),open:a,width:800,footer:null,onCancel:r,children:(0,c.jsxs)(L.Z,{form:u,onFinish:h,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[m.showEmail&&(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user@example.com",onChange:e=>{e.target.value=e.target.value.trim()}})}),m.showEmail&&m.showUserId&&(0,c.jsx)("div",{className:"text-center mb-4",children:(0,c.jsx)(A.Z,{children:"OR"})}),m.showUserId&&(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user_123",onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"Role"}),"edit"===o&&i&&(0,c.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(l=i.role,(null===(t=m.roleOptions.find(e=>e.value===l))||void 0===t?void 0:t.label)||l),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,c.jsx)(O.default,{children:"edit"===o&&i?[...m.roleOptions.filter(e=>e.value===i.role),...m.roleOptions.filter(e=>e.value!==i.role)].map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value)):m.roleOptions.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))})}),null===(s=m.additionalFields)||void 0===s?void 0:s.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:x(e)},e.name)),(0,c.jsxs)("div",{className:"text-right mt-6",children:[(0,c.jsx)(R.ZP,{onClick:r,className:"mr-2",children:"Cancel"}),(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"add"===o?"Add Member":"Save Changes"})]})]})})},sR=e=>{let{isVisible:s,onCancel:l,onSubmit:t,accessToken:a,title:r="Add Team Member",roles:n=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:i="user"}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)("user_email"),j=async(e,s)=>{if(!e){u([]);return}x(!0);try{let l=new URLSearchParams;if(l.append(s,e),null==a)return;let t=(await (0,y.u5)(a,l)).map(e=>({label:"user_email"===s?"".concat(e.user_email):"".concat(e.user_id),value:"user_email"===s?e.user_email:e.user_id,user:e}));u(t)}catch(e){console.error("Error fetching users:",e)}finally{x(!1)}},f=(0,d.useCallback)(ep()((e,s)=>j(e,s),300),[]),_=(e,s)=>{g(s),f(e,s)},v=(e,s)=>{let l=s.user;o.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:o.getFieldValue("role")})};return(0,c.jsx)(M.Z,{title:r,open:s,onCancel:()=>{o.resetFields(),u([]),l()},footer:null,width:800,children:(0,c.jsxs)(L.Z,{form:o,onFinish:t,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:i},children:[(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>_(e,"user_email"),onSelect:(e,s)=>v(e,s),options:"user_email"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>_(e,"user_id"),onSelect:(e,s)=>v(e,s),options:"user_id"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)(L.Z.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:i,children:n.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:(0,c.jsxs)(W.Z,{title:e.description,children:[(0,c.jsx)("span",{className:"font-medium",children:e.label}),(0,c.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,c.jsx)("div",{className:"text-right mt-4",children:(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"Add Member"})})]})})},sq=e=>{var s;let{teamId:l,onClose:t,accessToken:a,is_team_admin:r,is_proxy_admin:n,userModels:i,editTeam:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p,g]=(0,d.useState)(!1),[j]=L.Z.useForm(),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(null),[Z,N]=(0,d.useState)(!1);console.log("userModels in team info",i);let S=r||n,C=async()=>{try{if(x(!0),!a)return;let e=await (0,y.Xm)(a,l);u(e)}catch(e){D.ZP.error("Failed to load team information"),console.error("Error fetching team info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{C()},[l,a]);let I=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.cu)(a,l,s),D.ZP.success("Team member added successfully"),g(!1),j.resetFields(),C()}catch(e){D.ZP.error("Failed to add team member"),console.error("Error adding team member:",e)}},T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.sN)(a,l,s),D.ZP.success("Team member updated successfully"),_(!1),C()}catch(e){D.ZP.error("Failed to update team member"),console.error("Error updating team member:",e)}},P=async e=>{try{if(null==a)return;await (0,y.Lp)(a,l,e),D.ZP.success("Team member removed successfully"),C()}catch(e){D.ZP.error("Failed to remove team member"),console.error("Error removing team member:",e)}},M=async e=>{try{if(!a)return;let s={};try{s=e.metadata?JSON.parse(e.metadata):{}}catch(e){D.ZP.error("Invalid JSON in metadata field");return}let t={team_id:l,team_alias:e.team_alias,models:e.models,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration,metadata:{...s,guardrails:e.guardrails||[]}};await (0,y.Gh)(a,t),D.ZP.success("Team settings updated successfully"),N(!1),C()}catch(e){D.ZP.error("Failed to update team settings"),console.error("Error updating team:",e)}};if(h)return(0,c.jsx)("div",{className:"p-4",children:"Loading..."});if(!(null==m?void 0:m.team_info))return(0,c.jsx)("div",{className:"p-4",children:"Team not found"});let{team_info:F}=m;return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:F.team_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:F.team_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?3:0,children:[(0,c.jsx)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"},"overview"),...S?[(0,c.jsx)(eR.Z,{children:"Members"},"members"),(0,c.jsx)(eR.Z,{children:"Member Permissions"},"member-permissions"),(0,c.jsx)(eR.Z,{children:"Settings"},"settings")]:[]]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",F.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===F.max_budget?"Unlimited":"$".concat(F.max_budget)]}),F.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",F.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",F.rpm_limit||"Unlimited"]}),F.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",F.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sI,{teamData:m,canEditTeam:S,handleMemberDelete:P,setSelectedEditMember:b,setIsEditMemberModalVisible:_,setIsAddMemberModalVisible:g})}),S&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sM,{teamId:l,accessToken:a,canEditTeam:S})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Team Settings"}),S&&!Z&&(0,c.jsx)(k.Z,{onClick:()=>N(!0),children:"Edit Settings"})]}),Z?(0,c.jsxs)(L.Z,{form:j,onFinish:M,initialValues:{...F,team_alias:F.team_alias,models:F.models,tpm_limit:F.tpm_limit,rpm_limit:F.rpm_limit,max_budget:F.max_budget,budget_duration:F.budget_duration,guardrails:(null===(s=F.metadata)||void 0===s?void 0:s.guardrails)||[],metadata:F.metadata?JSON.stringify(F.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(q.default,{type:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map((e,s)=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},s))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>N(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team Name"}),(0,c.jsx)("div",{children:F.team_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"font-mono",children:F.team_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(F.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",F.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==F.max_budget?"$".concat(F.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",F.budget_duration||"Never"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Status"}),(0,c.jsx)(eM.Z,{color:F.blocked?"red":"green",children:F.blocked?"Blocked":"Active"})]})]})]})})]})]}),(0,c.jsx)(sF,{visible:f,onCancel:()=>_(!1),onSubmit:T,initialData:v,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Admin",value:"admin"},{label:"User",value:"user"}]}}),(0,c.jsx)(sR,{isVisible:p,onCancel:()=>g(!1),onSubmit:I,accessToken:a})]})},sU=l(45589);let{Title:sz,Link:sV}=es.default;var sK=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,existingCredential:a,setIsCredentialModalOpen:r}=e,[n]=L.Z.useForm();return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(a))),(0,c.jsx)(M.Z,{title:"Reuse Credentials",visible:s,onCancel:()=>{l(),n.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:n,onFinish:e=>{t(e),n.resetFields(),r(!1)},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==a?void 0:a.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries((null==a?void 0:a.credential_values)||{}).map(e=>{let[s,l]=e;return(0,c.jsx)(L.Z.Item,{label:s,name:s,initialValue:l,children:(0,c.jsx)(S.Z,{placeholder:"Enter ".concat(s),disabled:!0})},s)}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sV,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})},sB=l(63709),sH=l(45246),sJ=l(96473);let{Text:sW}=es.default;var sG=e=>{let{form:s,showCacheControl:l,onCacheControlChange:t}=e,a=e=>{let l=s.getFieldValue("litellm_extra_params");try{let t=l?JSON.parse(l):{};e.length>0?t.cache_control_injection_points=e:delete t.cache_control_injection_points,Object.keys(t).length>0?s.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):s.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Cache Control Injection Points",name:"cache_control",valuePropName:"checked",className:"mb-4",tooltip:"Tell litellm where to inject cache control checkpoints. You can specify either by role (to apply to all messages of that role) or by specific message index.",children:(0,c.jsx)(sB.Z,{onChange:t,className:"bg-gray-600"})}),l&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(sW,{className:"text-sm text-gray-500 block mb-4",children:"Providers like Anthropic, Bedrock API require users to specify where to inject cache control checkpoints, litellm can automatically add them for you as a cost saving feature."}),(0,c.jsx)(L.Z.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(e,l)=>{let{add:t,remove:r}=l;return(0,c.jsxs)(c.Fragment,{children:[e.map((l,t)=>(0,c.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,c.jsx)(L.Z.Item,{...l,label:"Type",name:[l.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,c.jsx)(O.default,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,c.jsx)(L.Z.Item,{...l,label:"Role",name:[l.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,c.jsx)(O.default,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),(0,c.jsx)(L.Z.Item,{...l,label:"Index",name:[l.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,c.jsx)(z,{type:"number",placeholder:"Optional",step:1,min:0,onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),e.length>1&&(0,c.jsx)(sH.Z,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{r(l.name),setTimeout(()=>{a(s.getFieldValue("cache_control_points"))},0)}})]},l.key)),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)("button",{type:"button",className:"flex items-center justify-center w-full border border-dashed border-gray-300 py-2 px-4 text-gray-600 hover:text-blue-600 hover:border-blue-300 transition-all rounded",onClick:()=>t(),children:[(0,c.jsx)(sJ.Z,{className:"mr-2"}),"Add Injection Point"]})})]})}})]})]})};function sY(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j,f,_,v,b,Z,N;let{modelId:C,onClose:I,modelData:T,accessToken:P,userID:O,userRole:F,editModel:q,setEditModalVisible:U,setSelectedModel:V,onModelUpdate:K}=e,[B]=L.Z.useForm(),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(!1),[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)(null),[en,ei]=(0,d.useState)(!1),eo="Admin"===F||T.model_info.created_by===O,ec=(null===(s=T.litellm_params)||void 0===s?void 0:s.litellm_credential_name)!=null&&(null===(l=T.litellm_params)||void 0===l?void 0:l.litellm_credential_name)!=void 0;console.log("usingExistingCredential, ",ec),console.log("modelData.litellm_params.litellm_credential_name, ",T.litellm_params.litellm_credential_name),(0,d.useEffect)(()=>{let e=async()=>{var e;if(!P)return;let s=await (0,y.ix)(P,C);console.log("modelInfoResponse, ",s);let l=s.data[0];J(l),(null==l?void 0:null===(e=l.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&ei(!0)};(async()=>{if(console.log("accessToken, ",P),!P||ec)return;let e=await (0,y.Qg)(P,null,C);console.log("existingCredentialResponse, ",e),er({credential_name:e.credential_name,credential_values:e.credential_values,credential_info:e.credential_info})})(),e()},[P,C]);let ed=async e=>{var s;if(console.log("values, ",e),!P)return;let l={credential_name:e.credential_name,model_id:C,credential_info:{custom_llm_provider:null===(s=H.litellm_params)||void 0===s?void 0:s.custom_llm_provider}};D.ZP.info("Storing credential.."),console.log("credentialResponse, ",await (0,y.oC)(P,l)),D.ZP.success("Credential stored successfully")},em=async e=>{try{var s;if(!P)return;es(!0);let l={...H.litellm_params,model:e.litellm_model_name,api_base:e.api_base,custom_llm_provider:e.custom_llm_provider,organization:e.organization,tpm:e.tpm,rpm:e.rpm,max_retries:e.max_retries,timeout:e.timeout,stream_timeout:e.stream_timeout,input_cost_per_token:e.input_cost/1e6,output_cost_per_token:e.output_cost/1e6};e.cache_control&&(null===(s=e.cache_control_injection_points)||void 0===s?void 0:s.length)>0?l.cache_control_injection_points=e.cache_control_injection_points:delete l.cache_control_injection_points;let t={model_name:e.model_name,litellm_params:l,model_info:{id:C}};await (0,y.um)(P,t);let a={...H,model_name:e.model_name,litellm_model_name:e.litellm_model_name,litellm_params:l};J(a),K&&K(a),D.ZP.success("Model settings updated successfully"),Q(!1),et(!1)}catch(e){console.error("Error updating model:",e),D.ZP.error("Failed to update model settings")}finally{es(!1)}};if(!T)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsx)(A.Z,{children:"Model not found"})]});let eu=async()=>{try{if(!P)return;await (0,y.Og)(P,C),D.ZP.success("Model deleted successfully"),K&&K({deleted:!0,model_info:{id:C}}),I()}catch(e){console.error("Error deleting the model:",e),D.ZP.error("Failed to delete model")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsxs)(E.Z,{children:["Public Model Name: ",sv(T)]}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:T.model_info.id})]}),(0,c.jsxs)("div",{className:"flex gap-2",children:["Admin"===F&&(0,c.jsx)(k.Z,{icon:sU.Z,variant:"secondary",onClick:()=>$(!0),className:"flex items-center",children:"Re-use Credentials"}),eo&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>G(!0),className:"flex items-center",children:"Delete Model"})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-6",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Raw JSON"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Provider"}),(0,c.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[T.provider&&(0,c.jsx)("img",{src:sn(T.provider).logo,alt:"".concat(T.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,l=s.parentElement;if(l){var t;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(t=T.provider)||void 0===t?void 0:t.charAt(0))||"-",l.replaceChild(e,s)}}}),(0,c.jsx)(E.Z,{children:T.provider||"Not Set"})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"LiteLLM Model"}),(0,c.jsx)("pre",{children:(0,c.jsx)(E.Z,{children:T.litellm_model_name||"Not Set"})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Pricing"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Input: $",T.input_cost,"/1M tokens"]}),(0,c.jsxs)(A.Z,{children:["Output: $",T.output_cost,"/1M tokens"]})]})]})]}),(0,c.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Created At ",T.model_info.created_at?new Date(T.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})}),"Created By ",T.model_info.created_by||"Not Set"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Model Settings"}),eo&&!el&&(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>et(!0),className:"flex items-center",children:"Edit Model"})]}),H?(0,c.jsx)(L.Z,{form:B,onFinish:em,initialValues:{model_name:H.model_name,litellm_model_name:H.litellm_model_name,api_base:H.litellm_params.api_base,custom_llm_provider:H.litellm_params.custom_llm_provider,organization:H.litellm_params.organization,tpm:H.litellm_params.tpm,rpm:H.litellm_params.rpm,max_retries:H.litellm_params.max_retries,timeout:H.litellm_params.timeout,stream_timeout:H.litellm_params.stream_timeout,input_cost:H.litellm_params.input_cost_per_token?1e6*H.litellm_params.input_cost_per_token:(null===(t=H.model_info)||void 0===t?void 0:t.input_cost_per_token)*1e6||null,output_cost:(null===(a=H.litellm_params)||void 0===a?void 0:a.output_cost_per_token)?1e6*H.litellm_params.output_cost_per_token:(null===(r=H.model_info)||void 0===r?void 0:r.output_cost_per_token)*1e6||null,cache_control:null!==(n=H.litellm_params)&&void 0!==n&&!!n.cache_control_injection_points,cache_control_injection_points:(null===(i=H.litellm_params)||void 0===i?void 0:i.cache_control_injection_points)||[]},layout:"vertical",onValuesChange:()=>Q(!0),children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"LiteLLM Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"litellm_model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter LiteLLM model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.litellm_model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"input_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter input cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(o=H.litellm_params)||void 0===o?void 0:o.input_cost_per_token)?((null===(m=H.litellm_params)||void 0===m?void 0:m.input_cost_per_token)*1e6).toFixed(4):(null==H?void 0:null===(u=H.model_info)||void 0===u?void 0:u.input_cost_per_token)?(1e6*H.model_info.input_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"output_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter output cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(h=H.litellm_params)||void 0===h?void 0:h.output_cost_per_token)?(1e6*H.litellm_params.output_cost_per_token).toFixed(4):(null==H?void 0:null===(x=H.model_info)||void 0===x?void 0:x.output_cost_per_token)?(1e6*H.model_info.output_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Base"}),el?(0,c.jsx)(L.Z.Item,{name:"api_base",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter API base"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(p=H.litellm_params)||void 0===p?void 0:p.api_base)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Custom LLM Provider"}),el?(0,c.jsx)(L.Z.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom LLM provider"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(g=H.litellm_params)||void 0===g?void 0:g.custom_llm_provider)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),el?(0,c.jsx)(L.Z.Item,{name:"organization",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter organization"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(j=H.litellm_params)||void 0===j?void 0:j.organization)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"TPM (Tokens per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"tpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter TPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(f=H.litellm_params)||void 0===f?void 0:f.tpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"RPM (Requests per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"rpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter RPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(_=H.litellm_params)||void 0===_?void 0:_.rpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Max Retries"}),el?(0,c.jsx)(L.Z.Item,{name:"max_retries",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter max retries"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(v=H.litellm_params)||void 0===v?void 0:v.max_retries)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(b=H.litellm_params)||void 0===b?void 0:b.timeout)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Stream Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"stream_timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter stream timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(Z=H.litellm_params)||void 0===Z?void 0:Z.stream_timeout)||"Not Set"})]}),el?(0,c.jsx)(sG,{form:B,showCacheControl:en,onCacheControlChange:e=>ei(e)}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Cache Control"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(N=H.litellm_params)||void 0===N?void 0:N.cache_control_injection_points)?(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{children:"Enabled"}),(0,c.jsx)("div",{className:"mt-2",children:H.litellm_params.cache_control_injection_points.map((e,s)=>(0,c.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,c.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,c.jsxs)("span",{children:[" Index: ",e.index]})]},s))})]}):"Disabled"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:T.model_info.team_id||"Not Set"})]})]}),el&&(0,c.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{B.resetFields(),Q(!1),et(!1)},children:"Cancel"}),(0,c.jsx)(k.Z,{variant:"primary",onClick:()=>B.submit(),loading:ee,children:"Save Changes"})]})]})}):(0,c.jsx)(A.Z,{children:"Loading..."})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(T,null,2)})})})]})]}),W&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Model"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this model?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(R.ZP,{onClick:eu,className:"ml-2",danger:!0,children:"Delete"}),(0,c.jsx)(R.ZP,{onClick:()=>G(!1),children:"Cancel"})]})]})]})}),Y&&!ec?(0,c.jsx)(sK,{isVisible:Y,onCancel:()=>$(!1),onAddCredential:ed,existingCredential:ea,setIsCredentialModalOpen:$}):(0,c.jsx)(M.Z,{open:Y,onCancel:()=>$(!1),title:"Using Existing Credential",children:(0,c.jsx)(A.Z,{children:T.litellm_params.litellm_credential_name})})]})}var s$=l(67960),sX=e=>{let{selectedProvider:s,providerModels:l,getPlaceholder:t}=e,a=L.Z.useFormInstance(),r=e=>{let s=e.target.value,l=(a.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:s,litellm_model:s}:e);a.setFieldsValue({model_mappings:l})};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)(L.Z.Item,{label:"LiteLLM Model Name(s)",tooltip:"Actual model name used for making litellm.completion() / litellm.embedding() call.",className:"mb-0",children:[(0,c.jsx)(L.Z.Item,{name:"model",rules:[{required:!0,message:"Please select at least one model."}],noStyle:!0,children:s===n.Azure||s===n.OpenAI_Compatible||s===n.Ollama?(0,c.jsx)(S.Z,{placeholder:t(s)}):l.length>0?(0,c.jsx)(O.default,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:e=>{let s=Array.isArray(e)?e:[e];if(s.includes("all-wildcard"))a.setFieldsValue({model_name:void 0,model_mappings:[]});else{let e=s.map(e=>({public_name:e,litellm_model:e}));a.setFieldsValue({model_mappings:e})}},optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:"All ".concat(s," Models (Wildcard)"),value:"all-wildcard"},...l.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,c.jsx)(S.Z,{placeholder:t(s)})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.model!==s.model,children:e=>{let{getFieldValue:s}=e,l=s("model")||[];return(Array.isArray(l)?l:[l]).includes("custom")&&(0,c.jsx)(L.Z.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom model name",onChange:r})})}})]}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Actual model name used for making litellm.completion() call. We loadbalance models with the same public name"})})]})]})},sQ=()=>{let e=L.Z.useFormInstance(),[s,l]=(0,d.useState)(0),t=L.Z.useWatch("model",e)||[],a=Array.isArray(t)?t:[t],r=L.Z.useWatch("custom_model_name",e),n=!a.includes("all-wildcard");if((0,d.useEffect)(()=>{if(r&&a.includes("custom")){let s=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:r,litellm_model:r}:e);e.setFieldValue("model_mappings",s),l(e=>e+1)}},[r,a,e]),(0,d.useEffect)(()=>{if(a.length>0&&!a.includes("all-wildcard")){let s=a.map(e=>"custom"===e&&r?{public_name:r,litellm_model:r}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",s),l(e=>e+1)}},[a,r,e]),!n)return null;let i=[{title:"Public Name",dataIndex:"public_name",key:"public_name",render:(s,l,t)=>(0,c.jsx)(S.Z,{value:s,onChange:s=>{let l=[...e.getFieldValue("model_mappings")];l[t].public_name=s.target.value,e.setFieldValue("model_mappings",l)}})},{title:"LiteLLM Model",dataIndex:"litellm_model",key:"litellm_model"}];return(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(L.Z.Item,{label:"Model Mappings",name:"model_mappings",tooltip:"Map public model names to LiteLLM model names for load balancing",labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",required:!0,children:(0,c.jsx)(ea.Z,{dataSource:e.getFieldValue("model_mappings"),columns:i,pagination:!1,size:"small"},s)})})},s0=l(90464);let{Link:s1}=es.default;var s2=e=>{let{showAdvancedSettings:s,setShowAdvancedSettings:l,teams:t}=e,[a]=L.Z.useForm(),[r,n]=d.useState(!1),[i,o]=d.useState("per_token"),[m,u]=d.useState(!1),h=(e,s)=>s&&(isNaN(Number(s))||0>Number(s))?Promise.reject("Please enter a valid positive number"):Promise.resolve(),x=(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject("Please enter valid JSON")}};return(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(C.Z,{className:"mt-2 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Advanced Settings"})}),(0,c.jsx)(I.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,c.jsx)(L.Z.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,c.jsx)(sB.Z,{onChange:e=>{n(e),e||a.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),r&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(L.Z.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:"per_token",onChange:e=>o(e),options:[{value:"per_token",label:"Per Million Tokens"},{value:"per_second",label:"Per Second"}]})}),"per_token"===i?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}):(0,c.jsx)(L.Z.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)(L.Z.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,c.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,c.jsx)(sB.Z,{onChange:e=>{let s=a.getFieldValue("litellm_extra_params");try{let l=s?JSON.parse(s):{};e?l.use_in_pass_through=!0:delete l.use_in_pass_through,Object.keys(l).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):a.setFieldValue("litellm_extra_params","")}catch(s){e?a.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):a.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,c.jsx)(sG,{form:a,showCacheControl:m,onCacheControlChange:e=>{if(u(e),!e){let e=a.getFieldValue("litellm_extra_params");try{let s=e?JSON.parse(e):{};delete s.cache_control_injection_points,Object.keys(s).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):a.setFieldValue("litellm_extra_params","")}catch(e){a.setFieldValue("litellm_extra_params","")}}}}),(0,c.jsx)(L.Z.Item,{label:"LiteLLM Params",name:"litellm_extra_params",tooltip:"Optional litellm params used for making a litellm.completion() call.",className:"mb-4 mt-4",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,c.jsxs)(su.Z,{className:"mb-4",children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,c.jsx)(L.Z.Item,{label:"Model Info",name:"model_info_params",tooltip:"Optional model info params. Returned when calling `/model/info` endpoint.",className:"mb-0",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})},s4=l(29),s5=l.n(s4),s3=l(23496),s6=l(35291),s8=l(23639);let{Text:s7}=es.default;var s9=e=>{let{formValues:s,accessToken:l,testMode:t,modelName:a="this model",onClose:r,onTestComplete:n}=e,[i,o]=d.useState(null),[m,u]=d.useState(null),[h,x]=d.useState(null),[p,g]=d.useState(!0),[j,f]=d.useState(!1),[_,v]=d.useState(!1),b=async()=>{g(!0),v(!1),o(null),u(null),x(null),f(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",s);let a=await sc(s,l,null);if(!a){console.log("No result from prepareModelAddRequest"),o("Failed to prepare model data. Please check your form inputs."),f(!1),g(!1);return}console.log("Result from prepareModelAddRequest:",a);let{litellmParamsObj:r,modelInfoObj:n,modelName:i}=a[0],c=await (0,y.Hx)(l,r,null==n?void 0:n.mode);if("success"===c.status)D.ZP.success("Connection test successful!"),o(null),f(!0);else{var e,t;let s=(null===(e=c.result)||void 0===e?void 0:e.error)||c.message||"Unknown error";o(s),u(r),x(null===(t=c.result)||void 0===t?void 0:t.raw_request_typed_dict),f(!1)}}catch(e){console.error("Test connection error:",e),o(e instanceof Error?e.message:String(e)),f(!1)}finally{g(!1),n&&n()}};d.useEffect(()=>{let e=setTimeout(()=>{b()},200);return()=>clearTimeout(e)},[]);let Z=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",N="string"==typeof i?Z(i):(null==i?void 0:i.message)?Z(i.message):"Unknown error",w=h?((e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")})(h.raw_request_api_base,h.raw_request_body,h.raw_request_headers||{}):"";return(0,c.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[p?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-776cdcbc0448e4ea",children:[(0,c.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-776cdcbc0448e4ea loading-spinner",children:(0,c.jsx)("div",{style:{border:"3px solid #f3f3f3",borderTop:"3px solid #1890ff",borderRadius:"50%",width:"30px",height:"30px",animation:"spin 1s linear infinite",margin:"0 auto"},className:"jsx-776cdcbc0448e4ea"})}),(0,c.jsxs)(s7,{style:{fontSize:"16px"},children:["Testing connection to ",a,"..."]}),(0,c.jsx)(s5(),{id:"776cdcbc0448e4ea",children:"@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);transform:rotate(0deg)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spin{0%{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}"})]}):j?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},children:[(0,c.jsx)("div",{style:{color:"#52c41a",fontSize:"32px",marginBottom:"16px"},children:(0,c.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,c.jsx)("path",{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"})})}),(0,c.jsxs)(s7,{type:"success",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," successful!"]})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,c.jsx)(s6.Z,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,c.jsxs)(s7,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," failed"]})]}),(0,c.jsxs)("div",{style:{backgroundColor:"#fff2f0",border:"1px solid #ffccc7",borderRadius:"8px",padding:"16px",marginBottom:"20px",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px"},children:"Error: "}),(0,c.jsx)(s7,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:N}),i&&(0,c.jsx)("div",{style:{marginTop:"12px"},children:(0,c.jsx)(R.ZP,{type:"link",onClick:()=>v(!_),style:{paddingLeft:0,height:"auto"},children:_?"Hide Details":"Show Details"})})]}),_&&(0,c.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"200px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:"string"==typeof i?i:JSON.stringify(i,null,2)})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:w||"No request data available"}),(0,c.jsx)(R.ZP,{style:{marginTop:"8px"},icon:(0,c.jsx)(s8.Z,{}),onClick:()=>{navigator.clipboard.writeText(w||""),D.ZP.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,c.jsx)(s3.Z,{style:{margin:"24px 0 16px"}}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,c.jsx)(R.ZP,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,c.jsx)(J.Z,{}),children:"View Documentation"})})]})};let le=[{value:"chat",label:"Chat - /chat/completions"},{value:"completion",label:"Completion - /completions"},{value:"embedding",label:"Embedding - /embeddings"},{value:"audio_speech",label:"Audio Speech - /audio/speech"},{value:"audio_transcription",label:"Audio Transcription - /audio/transcriptions"},{value:"image_generation",label:"Image Generation - /images/generations"},{value:"rerank",label:"Rerank - /rerank"},{value:"realtime",label:"Realtime - /realtime"}],{Title:ls,Link:ll}=es.default;var lt=e=>{let{form:s,handleOk:l,selectedProvider:t,setSelectedProvider:a,providerModels:r,setProviderModelsFn:i,getPlaceholder:o,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,credentials:p,accessToken:g,userRole:j}=e,[f,_]=(0,d.useState)("chat"),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),k=async()=>{Z(!0),w("test-".concat(Date.now())),v(!0)},S=eg.ZL.includes(j);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ls,{level:2,children:"Add new model"}),(0,c.jsx)(s$.Z,{children:(0,c.jsx)(L.Z,{form:s,onFinish:l,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"E.g. OpenAI, Azure OpenAI, Anthropic, Bedrock, etc.",labelCol:{span:10},labelAlign:"left",children:(0,c.jsx)(O.default,{showSearch:!0,value:t,onChange:e=>{a(e),i(e),s.setFieldsValue({model:[],model_name:void 0})},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sX,{selectedProvider:t,providerModels:r,getPlaceholder:o}),(0,c.jsx)(sQ,{}),(0,c.jsx)(L.Z.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,c.jsx)(O.default,{style:{width:"100%"},value:f,onChange:e=>_(e),options:le})}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-5 mt-1",children:[(0,c.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model ",(0,c.jsx)(ll,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,c.jsx)("div",{className:"mb-4",children:(0,c.jsx)(es.default.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,c.jsx)(L.Z.Item,{label:"Existing Credentials",name:"litellm_credential_name",children:(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{value:null,label:"None"},...p.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.litellm_credential_name!==s.litellm_credential_name||e.provider!==s.provider,children:e=>{let{getFieldValue:s}=e,l=s("litellm_credential_name");return(console.log("\uD83D\uDD11 Credential Name Changed:",l),l)?(0,c.jsx)("div",{className:"text-gray-500 text-sm text-center",children:"Using existing credentials - no additional provider fields needed"}):(0,c.jsx)(sg,{selectedProvider:t,uploadProps:m})}}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Team Settings"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{label:"Team",name:"team_id",className:"mb-4",tooltip:"Only keys for this team, will be able to call this model.",rules:[{required:!S,message:"Please select a team."}],children:(0,c.jsx)(Q,{teams:x})}),(0,c.jsx)(s2,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x}),(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(es.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{className:"space-x-2",children:[(0,c.jsx)(R.ZP,{onClick:k,loading:b,children:"Test Connect"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,c.jsx)(M.Z,{title:"Connection Test Results",open:y,onCancel:()=>{v(!1),Z(!1)},footer:[(0,c.jsx)(R.ZP,{onClick:()=>{v(!1),Z(!1)},children:"Close"},"close")],width:700,children:y&&(0,c.jsx)(s9,{formValues:s.getFieldsValue(),accessToken:g,testMode:f,modelName:s.getFieldValue("model_name")||s.getFieldValue("model"),onClose:()=>{v(!1),Z(!1)},onTestComplete:()=>Z(!1)},N)})]})},la=l(32986),lr=l(49084);function ln(e){let{data:s=[],columns:l,isLoading:t=!1}=e,[a,r]=d.useState([{id:"model_info.created_at",desc:!0}]),[n]=d.useState("onChange"),[i,o]=d.useState({}),[m,u]=d.useState({}),[h,x]=d.useState(!1),p=d.useRef(null);d.useEffect(()=>{let e=e=>{p.current&&!p.current.contains(e.target)&&x(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let g=(0,eS.b7)({data:s,columns:l,state:{sorting:a,columnSizing:i,columnVisibility:m},columnResizeMode:n,onSortingChange:r,onColumnSizingChange:o,onColumnVisibilityChange:u,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}}),j=e=>{if("string"==typeof e)return e;if("function"==typeof e){let s=e();if(s&&s.props&&s.props.children){let e=s.props.children;if("string"==typeof e)return e;if(e.props&&e.props.children)return e.props.children}}return""};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)("div",{className:"flex justify-end",children:(0,c.jsxs)("div",{className:"relative",ref:p,children:[(0,c.jsxs)("button",{onClick:()=>x(!h),className:"flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:[(0,c.jsx)(la.Z,{className:"h-4 w-4"}),"Columns"]}),h&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-56 bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50",children:(0,c.jsx)("div",{className:"py-1",children:g.getAllLeafColumns().map(e=>"actions"===e.id?null:(0,c.jsxs)("div",{className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer",onClick:()=>e.toggleVisibility(),children:[(0,c.jsx)("input",{type:"checkbox",checked:e.getIsVisible(),onChange:()=>e.toggleVisibility(),className:"h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,c.jsx)("span",{className:"ml-2",children:j(e.columnDef.header)})]},e.id))})})]})}),(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsx)("div",{className:"relative min-w-full",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1 w-full",children:[(0,c.jsx)(eE.Z,{children:g.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsxs)(eP.Z,{className:"py-1 h-8 relative ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getToggleSortingHandler(),children:[(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,c.jsx)("div",{onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:"absolute right-0 top-0 h-full w-2 cursor-col-resize select-none touch-none ".concat(e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200")})]},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading models..."})})})}):g.getRowModel().rows.length>0?g.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.column.id?120:e.column.getSize(),minWidth:"actions"===e.column.id?120:e.column.getSize(),maxWidth:"actions"===e.column.id?120:e.column.getSize(),position:"actions"===e.column.id?"sticky":"relative",right:"actions"===e.column.id?0:"auto"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No models found"})})})})})]})})})})]})}let li=(e,s,l,t,a,r,n,i,o)=>[{header:"Model ID",accessorKey:"model_info.id",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.model_info.id,children:(0,c.jsx)("div",{className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left w-full truncate whitespace-nowrap cursor-pointer",onClick:()=>t(l.model_info.id),children:l.model_info.id})})}},{header:"Public Model Name",accessorKey:"model_name",cell:e=>{let{row:s}=e,l=r(s.original)||"-";return(0,c.jsx)(W.Z,{title:l,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l})})}},{header:"Provider",accessorKey:"provider",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l.provider&&(0,c.jsx)("img",{src:sn(l.provider).logo,alt:"".concat(l.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,t=s.parentElement;if(t){var a;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(a=l.provider)||void 0===a?void 0:a.charAt(0))||"-",t.replaceChild(e,s)}}}),(0,c.jsx)("p",{className:"text-xs",children:l.provider||"-"})]})}},{header:"LiteLLM Model Name",accessorKey:"litellm_model_name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.litellm_model_name,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l.litellm_model_name||"-"})})}},{header:"Created At",accessorKey:"model_info.created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_at?new Date(l.model_info.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"model_info.updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.updated_at?new Date(l.model_info.updated_at).toLocaleDateString():"-"})}},{header:"Created By",accessorKey:"model_info.created_by",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_by||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Input Cost"})}),accessorKey:"input_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.input_cost||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Output Cost"})}),accessorKey:"output_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.output_cost||"-"})}},{header:"Team ID",accessorKey:"model_info.team_id",cell:e=>{let{row:s}=e,l=s.original;return l.model_info.team_id?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.model_info.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>a(l.model_info.team_id),children:[l.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:"Credentials",accessorKey:"litellm_credential_name",cell:e=>{let{row:s}=e,l=s.original;return l.litellm_params&&l.litellm_params.litellm_credential_name?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsxs)(W.Z,{title:l.litellm_params.litellm_credential_name,children:[l.litellm_params.litellm_credential_name.slice(0,7),"..."]})}):(0,c.jsx)("span",{className:"text-gray-400",children:"-"})}},{header:"Status",accessorKey:"model_info.db_model",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"\n inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium\n ".concat(l.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600","\n "),children:l.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:"",cell:l=>{var a;let{row:r}=l,n=r.original,i="Admin"===e||(null===(a=n.model_info)||void 0===a?void 0:a.created_by)===s;return(0,c.jsxs)("div",{className:"flex items-center justify-end gap-2 pr-4",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!0))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!1))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"})]})}}],{Title:lo,Link:lc}=es.default,ld={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"};var lm=e=>{let{accessToken:s,token:l,userRole:t,userID:a,modelData:r={data:[]},keys:i,setModelData:o,premiumUser:m,teams:u}=e,[h,x]=(0,d.useState)([]),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)([]);Object.values(n).filter(e=>isNaN(Number(e)));let[Z,N]=(0,d.useState)([]),[S,C]=(0,d.useState)(n.OpenAI),[I,T]=(0,d.useState)(""),[P,O]=(0,d.useState)(!1),[M,F]=(0,d.useState)(null),[R,q]=(0,d.useState)([]),[U,z]=(0,d.useState)([]),[V,K]=(0,d.useState)(null),[B,J]=(0,d.useState)([]),[W,G]=(0,d.useState)([]),[Y,$]=(0,d.useState)([]),[X,Q]=(0,d.useState)([]),[el,et]=(0,d.useState)([]),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)([]),[eo,ec]=(0,d.useState)([]),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[ex,ep]=(0,d.useState)(null),[ej,ef]=(0,d.useState)(0),[e_,ey]=(0,d.useState)({}),[ev,eb]=(0,d.useState)([]),[eZ,eN]=(0,d.useState)(!1),[ew,ek]=(0,d.useState)(null),[eS,eC]=(0,d.useState)(null),[eL,eM]=(0,d.useState)([]),[eK,eH]=(0,d.useState)([]),[eJ,eW]=(0,d.useState)(!1),[eG,eY]=(0,d.useState)(null),[e$,eQ]=(0,d.useState)(!1),[e0,e1]=(0,d.useState)(null),e2=async(e,l,r)=>{if(console.log("Updating model metrics for group:",e),!s||!a||!t||!l||!r)return;console.log("inside updateModelMetrics - startTime:",l,"endTime:",r),K(e);let n=null==ew?void 0:ew.token;void 0===n&&(n=null);let i=eS;void 0===i&&(i=null),l.setHours(0),l.setMinutes(0),l.setSeconds(0),r.setHours(23),r.setMinutes(59),r.setSeconds(59);try{let o=await (0,y.o6)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model metrics response:",o),G(o.data),$(o.all_api_bases);let c=await (0,y.Rg)(s,e,l.toISOString(),r.toISOString());Q(c.data),et(c.all_api_bases);let d=await (0,y.N8)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model exceptions response:",d),er(d.data),ei(d.exception_types);let m=await (0,y.fP)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);if(console.log("slowResponses:",m),em(m),e){let t=await (0,y.n$)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);ey(t);let a=await (0,y.v9)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);eb(a)}}catch(e){console.error("Failed to fetch model metrics",e)}},e4=async e=>{try{let s=await (0,y.N3)(e);console.log("credentials: ".concat(JSON.stringify(s))),eH(s.credentials)}catch(e){console.error("Error fetching credentials:",e)}};(0,d.useEffect)(()=>{e2(V,eu.from,eu.to)},[ew,eS]);let e5={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let s=new FileReader;s.onload=e=>{if(e.target){let s=e.target.result;p.setFieldsValue({vertex_credentials:s})}},s.readAsText(e)}return!1},onChange(e){"uploading"!==e.file.status&&console.log(e.file,e.fileList),"done"===e.file.status?D.ZP.success("".concat(e.file.name," file uploaded successfully")):"error"===e.file.status&&D.ZP.error("".concat(e.file.name," file upload failed."))}},e3=()=>{_(new Date().toLocaleString())},e6=async()=>{if(!s){console.error("Access token is missing");return}console.log("new modelGroupRetryPolicy:",ex);try{await (0,y.K_)(s,{router_settings:{model_group_retry_policy:ex}}),D.ZP.success("Retry settings saved successfully")}catch(e){console.error("Failed to save retry settings:",e),D.ZP.error("Failed to save retry settings")}};if((0,d.useEffect)(()=>{if(!s||!l||!t||!a)return;let e=async()=>{try{var e,l,r,n,i,c,d,m,u,h,x,p;let g=await (0,y.AZ)(s,a,t);console.log("Model data response:",g.data),o(g);let j=await (0,y.hy)(s);j&&N(j);let f=new Set;for(let e=0;e0&&(v=_[_.length-1],console.log("_initial_model_group:",v)),console.log("selectedModelGroup:",V);let b=await (0,y.o6)(s,a,t,v,null===(e=eu.from)||void 0===e?void 0:e.toISOString(),null===(l=eu.to)||void 0===l?void 0:l.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model metrics response:",b),G(b.data),$(b.all_api_bases);let Z=await (0,y.Rg)(s,v,null===(r=eu.from)||void 0===r?void 0:r.toISOString(),null===(n=eu.to)||void 0===n?void 0:n.toISOString());Q(Z.data),et(Z.all_api_bases);let w=await (0,y.N8)(s,a,t,v,null===(i=eu.from)||void 0===i?void 0:i.toISOString(),null===(c=eu.to)||void 0===c?void 0:c.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model exceptions response:",w),er(w.data),ei(w.exception_types);let k=await (0,y.fP)(s,a,t,v,null===(d=eu.from)||void 0===d?void 0:d.toISOString(),null===(m=eu.to)||void 0===m?void 0:m.toISOString(),null==ew?void 0:ew.token,eS),S=await (0,y.n$)(s,null===(u=eu.from)||void 0===u?void 0:u.toISOString().split("T")[0],null===(h=eu.to)||void 0===h?void 0:h.toISOString().split("T")[0],v);ey(S);let C=await (0,y.v9)(s,null===(x=eu.from)||void 0===x?void 0:x.toISOString().split("T")[0],null===(p=eu.to)||void 0===p?void 0:p.toISOString().split("T")[0],v);eb(C),console.log("dailyExceptions:",S),console.log("dailyExceptionsPerDeplyment:",C),console.log("slowResponses:",k),em(k);let I=await (0,y.j2)(s);eM(null==I?void 0:I.end_users);let T=(await (0,y.BL)(s,a,t)).router_settings;console.log("routerSettingsInfo:",T);let A=T.model_group_retry_policy,E=T.num_retries;console.log("model_group_retry_policy:",A),console.log("default_retries:",E),ep(A),ef(E)}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&t&&a&&e();let r=async()=>{let e=await (0,y.qm)(s);console.log("received model cost map data: ".concat(Object.keys(e))),j(e)};null==g&&r(),e3()},[s,l,t,a,g,f]),!r||!s||!l||!t||!a)return(0,c.jsx)("div",{children:"Loading..."});let e8=[],e7=[];for(let e=0;e(console.log("GET PROVIDER CALLED! - ".concat(g)),null!=g&&"object"==typeof g&&e in g)?g[e].litellm_provider:"openai";if(l){let e=l.split("/"),s=e[0];(n=t)||(n=1===e.length?u(l):s)}else n="-";a&&(i=null==a?void 0:a.input_cost_per_token,o=null==a?void 0:a.output_cost_per_token,c=null==a?void 0:a.max_tokens,d=null==a?void 0:a.max_input_tokens),(null==s?void 0:s.litellm_params)&&(m=Object.fromEntries(Object.entries(null==s?void 0:s.litellm_params).filter(e=>{let[s]=e;return"model"!==s&&"api_base"!==s}))),r.data[e].provider=n,r.data[e].input_cost=i,r.data[e].output_cost=o,r.data[e].litellm_model_name=l,e7.push(n),r.data[e].input_cost&&(r.data[e].input_cost=(1e6*Number(r.data[e].input_cost)).toFixed(2)),r.data[e].output_cost&&(r.data[e].output_cost=(1e6*Number(r.data[e].output_cost)).toFixed(2)),r.data[e].max_tokens=c,r.data[e].max_input_tokens=d,r.data[e].api_base=null==s?void 0:null===(ss=s.litellm_params)||void 0===ss?void 0:ss.api_base,r.data[e].cleanedLitellmParams=m,e8.push(s.model_name),console.log(r.data[e])}if(t&&"Admin Viewer"==t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to view all models"})]})}let sa=async()=>{try{D.ZP.info("Running health check..."),T("");let e=await (0,y.EY)(s);T(e)}catch(e){console.error("Error running health check:",e),T("Error running health check")}},sr=(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Select API Key Name"}),m?(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{ek(e)},children:e.key_alias},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>{eC(e)},children:e},s))]})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsxs)(ee.Z,{value:String(s),disabled:!0,onClick:()=>{ek(e)},children:["✨ ",e.key_alias," (Enterprise only Feature)"]},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsxs)(ee.Z,{value:e,disabled:!0,onClick:()=>{eC(e)},children:["✨ ",e," (Enterprise only Feature)"]},s))]})]})]}),sn=e=>{var s,l;let{payload:t,active:a}=e;if(!a||!t)return null;let r=null===(l=t[0])||void 0===l?void 0:null===(s=l.payload)||void 0===s?void 0:s.date,n=t.sort((e,s)=>s.value-e.value);if(n.length>5){let e=n.length-5;(n=n.slice(0,5)).push({dataKey:"".concat(e," other deployments"),value:t.slice(5).reduce((e,s)=>e+s.value,0),color:"gray"})}return(0,c.jsxs)("div",{className:"w-150 rounded-tremor-default border border-tremor-border bg-tremor-background p-2 text-tremor-default shadow-tremor-dropdown",children:[r&&(0,c.jsxs)("p",{className:"text-tremor-content-emphasis mb-2",children:["Date: ",r]}),n.map((e,s)=>{let l=parseFloat(e.value.toFixed(5)),t=0===l&&e.value>0?"<0.00001":l.toFixed(5);return(0,c.jsxs)("div",{className:"flex justify-between",children:[(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("div",{className:"w-2 h-2 mt-1 rounded-full bg-".concat(e.color,"-500")}),(0,c.jsx)("p",{className:"text-tremor-content",children:e.dataKey})]}),(0,c.jsx)("p",{className:"font-medium text-tremor-content-emphasis text-righ ml-2",children:t})]},s)})]})};console.log("selectedProvider: ".concat(S)),console.log("providerModels.length: ".concat(v.length));let sc=Object.keys(n).find(e=>n[e]===S);return(sc&&Z&&Z.find(e=>e.name===st[sc]),e0)?(0,c.jsx)("div",{className:"w-full h-full",children:(0,c.jsx)(sq,{teamId:e0,onClose:()=>e1(null),accessToken:s,is_team_admin:"Admin"===t,is_proxy_admin:"Proxy Admin"===t,userModels:e8,editTeam:!1,onUpdate:e3})}):(0,c.jsx)("div",{style:{width:"100%",height:"100%"},children:eG?(0,c.jsx)(sY,{modelId:eG,editModel:!0,onClose:()=>{eY(null),eQ(!1)},modelData:r.data.find(e=>e.model_info.id===eG),accessToken:s,userID:a,userRole:t,setEditModalVisible:O,setSelectedModel:F,onModelUpdate:e=>{o({...r,data:r.data.map(s=>s.model_info.id===e.model_info.id?e:s)}),e3()}}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[eg.ZL.includes(t)?(0,c.jsx)(eR.Z,{children:"All Models"}):(0,c.jsx)(eR.Z,{children:"Your Models"}),(0,c.jsx)(eR.Z,{children:"Add Model"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"LLM Credentials"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"/health Models"})}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Analytics"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Retry Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:e3})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(E.Z,{children:"Model Management"}),eg.ZL.includes(t)?(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add and manage models for the proxy"}):(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add models for teams you are an admin for."})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name:"}),(0,c.jsxs)(eD.Z,{className:"w-64",defaultValue:null!=V?V:"all",onValueChange:e=>K("all"===e?"all":e),value:null!=V?V:"all",children:[(0,c.jsx)(ee.Z,{value:"all",children:"All Models"}),R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))]})]})]}),(0,c.jsx)(ln,{columns:li(t,a,m,eY,e1,sv,e=>{F(e),O(!0)},e3,eQ),data:r.data.filter(e=>"all"===V||e.model_name===V||!V),isLoading:!1})]})}),(0,c.jsx)(ez.Z,{className:"h-full",children:(0,c.jsx)(lt,{form:p,handleOk:()=>{p.validateFields().then(e=>{sd(e,s,p,e3)}).catch(e=>{console.error("Validation failed:",e)})},selectedProvider:S,setSelectedProvider:C,providerModels:v,setProviderModelsFn:e=>{let s=so(e,g);b(s),console.log("providerModels: ".concat(s))},getPlaceholder:si,uploadProps:e5,showAdvancedSettings:eJ,setShowAdvancedSettings:eW,teams:u,credentials:eK,accessToken:s,userRole:t})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sy,{accessToken:s,uploadProps:e5,credentialList:eK,fetchCredentials:e4})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"`/health` will run a very small request through your models configured on litellm"}),(0,c.jsx)(k.Z,{onClick:sa,children:"Run `/health`"}),I&&(0,c.jsx)("pre",{children:JSON.stringify(I,null,2)})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:4,className:"mt-2 mb-2",children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:eu,className:"mr-2",onValueChange:e=>{eh(e),e2(V,e.from,e.to)}})]}),(0,c.jsxs)(sh.Z,{className:"ml-2",children:[(0,c.jsx)(A.Z,{children:"Select Model Group"}),(0,c.jsx)(eD.Z,{defaultValue:V||R[0],value:V||R[0],children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>e2(e,eu.from,eu.to),children:e},s))})]}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(sk.Z,{trigger:"click",content:sr,overlayStyle:{width:"20vw"},children:(0,c.jsx)(k.Z,{icon:eX.Z,size:"md",variant:"secondary",className:"mt-4 ml-2",style:{border:"none"},onClick:()=>eN(!0)})})})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"mr-2 max-h-[400px] min-h-[400px]",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Avg. Latency per Token"}),(0,c.jsx)(eR.Z,{value:"2",children:"Time to first token"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)("p",{className:"text-gray-500 italic",children:" (seconds/token)"}),(0,c.jsx)(A.Z,{className:"text-gray-500 italic mt-1 mb-1",children:"average Latency for successfull requests divided by the total tokens"}),W&&Y&&(0,c.jsx)(sN.Z,{title:"Model Latency",className:"h-72",data:W,showLegend:!1,index:"date",categories:Y,connectNulls:!0,customTooltip:sn})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sC,{modelMetrics:X,modelMetricsCategories:el,customTooltip:sn,premiumUser:m})})]})]})})}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"ml-2 max-h-[400px] min-h-[400px] overflow-y-auto",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Deployment"}),(0,c.jsx)(eP.Z,{children:"Success Responses"}),(0,c.jsxs)(eP.Z,{children:["Slow Responses ",(0,c.jsx)("p",{children:"Success Responses taking 600+s"})]})]})}),(0,c.jsx)(eT.Z,{children:ed.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.api_base}),(0,c.jsx)(eA.Z,{children:e.total_count}),(0,c.jsx)(eA.Z,{children:e.slow_count})]},s))})]})})})]}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Exceptions for ",V]}),(0,c.jsx)(sw.Z,{className:"h-60",data:ea,index:"model",categories:en,stack:!0,yAxisWidth:30})]})}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Up Rate Limit Errors (429) for ",V]}),(0,c.jsxs)(w.Z,{numItems:1,children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e_.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e_.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]}),(0,c.jsx)(sh.Z,{})]})]}),m?(0,c.jsx)(c.Fragment,{children:ev.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base?e.api_base:"Unknown API Base"}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors (429) ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]},s))}):(0,c.jsx)(c.Fragment,{children:ev&&ev.length>0&&ev.slice(0,1).map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"✨ Rate Limit Errors by Deployment"}),(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to see exceptions for all deployments"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]})]},s))})]})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name"}),(0,c.jsx)(eD.Z,{className:"mb-4 mt-2 ml-2 w-50",defaultValue:V||R[0],value:V||R[0],onValueChange:e=>K(e),children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))})]}),(0,c.jsxs)(E.Z,{children:["Retry Policy for ",V]}),(0,c.jsx)(A.Z,{className:"mb-6",children:"How many retries should be attempted based on the Exception"}),ld&&(0,c.jsx)("table",{children:(0,c.jsx)("tbody",{children:Object.entries(ld).map((e,s)=>{var l;let[t,a]=e,r=null==ex?void 0:null===(l=ex[V])||void 0===l?void 0:l[a];return null==r&&(r=ej),(0,c.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,c.jsx)("td",{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)("td",{children:(0,c.jsx)(H.Z,{className:"ml-5",value:r,min:0,step:1,onChange:e=>{ep(s=>{var l;let t=null!==(l=null==s?void 0:s[V])&&void 0!==l?l:{};return{...null!=s?s:{},[V]:{...t,[a]:e}}})}})})]},s)})})}),(0,c.jsx)(k.Z,{className:"mt-6 mr-8",onClick:e6,children:"Save"})]})]})]})})},lu=e=>{let{visible:s,possibleUIRoles:l,onCancel:t,user:a,onSubmit:r}=e,[n,i]=(0,d.useState)(a),[o]=L.Z.useForm();(0,d.useEffect)(()=>{o.resetFields()},[a]);let m=async()=>{o.resetFields(),t()},u=async e=>{r(e),o.resetFields(),t()};return a?(0,c.jsx)(M.Z,{visible:s,onCancel:m,footer:null,title:"Edit User "+a.user_id,width:1e3,children:(0,c.jsx)(L.Z,{form:o,onFinish:u,initialValues:a,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:l&&Object.entries(l).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Spend (USD)",name:"spend",tooltip:"(float) - Spend of all LLM calls completed by this user",help:"Across all keys (including keys with team_id).",children:(0,c.jsx)(H.Z,{min:0,step:.01})}),(0,c.jsx)(L.Z.Item,{label:"User Budget (USD)",name:"max_budget",tooltip:"(float) - Maximum budget of this user",help:"Maximum budget of this user.",children:(0,c.jsx)(z,{min:0,step:.01})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})}):null},lh=l(15731);let lx=(e,s,l)=>[{header:"User ID",accessorKey:"user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)(W.Z,{title:s.original.user_id,children:(0,c.jsx)("span",{className:"text-xs",children:s.original.user_id?"".concat(s.original.user_id.slice(0,7),"..."):"-"})})}},{header:"User Email",accessorKey:"user_email",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.user_email||"-"})}},{header:"Global Proxy Role",accessorKey:"user_role",cell:s=>{var l;let{row:t}=s;return(0,c.jsx)("span",{className:"text-xs",children:(null==e?void 0:null===(l=e[t.original.user_role])||void 0===l?void 0:l.ui_label)||"-"})}},{header:"User Spend ($ USD)",accessorKey:"spend",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.spend?s.original.spend.toFixed(2):"-"})}},{header:"User Max Budget ($ USD)",accessorKey:"max_budget",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.max_budget?s.original.max_budget:"Unlimited"})}},{header:()=>(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"SSO ID"}),(0,c.jsx)(W.Z,{title:"SSO ID is the ID of the user in the SSO provider. If the user is not using SSO, this will be null.",children:(0,c.jsx)(lh.Z,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.sso_user_id?s.original.sso_user_id:"-"})}},{header:"API Keys",accessorKey:"key_count",cell:e=>{let{row:s}=e;return(0,c.jsx)(w.Z,{numItems:2,children:s.original.key_count>0?(0,c.jsxs)(eM.Z,{size:"xs",color:"indigo",children:[s.original.key_count," Keys"]}):(0,c.jsx)(eM.Z,{size:"xs",color:"gray",children:"No Keys"})})}},{header:"Created At",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.created_at?new Date(s.original.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.updated_at?new Date(s.original.updated_at).toLocaleDateString():"-"})}},{id:"actions",header:"",cell:e=>{let{row:t}=e;return(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>s(t.original)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>l(t.original.user_id)})]})}}];function lp(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j;let{userId:f,onClose:_,accessToken:v,userRole:b,onDelete:Z}=e,[N,S]=(0,d.useState)(null),[C,I]=(0,d.useState)(!1),[T,P]=(0,d.useState)(!0);d.useEffect(()=>{console.log("userId: ".concat(f,", userRole: ").concat(b,", accessToken: ").concat(v)),(async()=>{try{if(!v)return;let e=await (0,y.Br)(v,f,b||"",!1,null,null,!0);S(e)}catch(e){console.error("Error fetching user data:",e),D.ZP.error("Failed to fetch user data")}finally{P(!1)}})()},[v,f,b]);let O=async()=>{try{if(!v)return;await (0,y.Eb)(v,[f]),D.ZP.success("User deleted successfully"),Z&&Z(),_()}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}};return T?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"Loading user data..."})]}):N?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(E.Z,{children:(null===(s=N.user_info)||void 0===s?void 0:s.user_email)||"User"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:N.user_id})]}),b&&eg.LQ.includes(b)&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>I(!0),className:"flex items-center",children:"Delete User"})]}),C&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:O,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>I(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Details"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number((null===(l=N.user_info)||void 0===l?void 0:l.spend)||0).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",(null===(t=N.user_info)||void 0===t?void 0:t.max_budget)!==null?"$".concat(N.user_info.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Teams"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(a=N.teams)||void 0===a?void 0:a.length)||0," teams"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"API Keys"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(r=N.keys)||void 0===r?void 0:r.length)||0," keys"]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"User ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:N.user_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Email"}),(0,c.jsx)(A.Z,{children:(null===(n=N.user_info)||void 0===n?void 0:n.user_email)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Role"}),(0,c.jsx)(A.Z,{children:(null===(i=N.user_info)||void 0===i?void 0:i.user_role)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:(null===(o=N.user_info)||void 0===o?void 0:o.created_at)?new Date(N.user_info.created_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:(null===(m=N.user_info)||void 0===m?void 0:m.updated_at)?new Date(N.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Teams"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(u=N.teams)||void 0===u?void 0:u.length)&&(null===(h=N.teams)||void 0===h?void 0:h.length)>0?null===(x=N.teams)||void 0===x?void 0:x.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e.team_alias||e.team_id},s)):(0,c.jsx)(A.Z,{children:"No teams"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Keys"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(p=N.keys)||void 0===p?void 0:p.length)&&(null===(g=N.keys)||void 0===g?void 0:g.length)>0?N.keys.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-green-100 rounded text-xs",children:e.key_alias||e.token},s)):(0,c.jsx)(A.Z,{children:"No API keys"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify((null===(j=N.user_info)||void 0===j?void 0:j.metadata)||{},null,2)})]})]})})})]})]})]}):(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"User not found"})]})}function lg(e){let{data:s=[],columns:l,isLoading:t=!1,onSortChange:a,currentSort:r,accessToken:n,userRole:i}=e,[o,m]=d.useState([{id:(null==r?void 0:r.sortBy)||"created_at",desc:(null==r?void 0:r.sortOrder)==="desc"}]),[u,h]=d.useState(null),x=(0,eS.b7)({data:s,columns:l,state:{sorting:o},onSortingChange:e=>{if(m(e),e.length>0){let s=e[0],l=s.id,t=s.desc?"desc":"asc";null==a||a(l,t)}},getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0}),p=e=>{h(e)};return(d.useEffect(()=>{r&&m([{id:r.sortBy,desc:"desc"===r.sortOrder}])},[r]),u)?(0,c.jsx)(lp,{userId:u,onClose:()=>{h(null)},accessToken:n,userRole:i}):(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:x.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading users..."})})})}):s.length>0?x.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:()=>{"user_id"===e.column.id&&p(e.getValue())},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No users found"})})})})})]})})})}var lj=l(67982),lf=e=>{var s;let{accessToken:l,possibleUIRoles:t,userID:a,userRole:r}=e,[n,i]=(0,d.useState)(!0),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)({}),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)([]),{Paragraph:v}=es.default,{Option:b}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){i(!1);return}try{let e=await (0,y.NL)(l);if(m(e),p(e.values||{}),l)try{let e=await (0,y.So)(l,a,r);if(e&&e.data){let s=e.data.map(e=>e.id);_(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),D.ZP.error("Failed to fetch SSO settings")}finally{i(!1)}})()},[l]);let Z=async()=>{if(l){j(!0);try{let e=await (0,y.nd)(l,x);m({...o,values:e.settings}),h(!1)}catch(e){console.error("Error updating SSO settings:",e),D.ZP.error("Failed to update settings")}finally{j(!1)}}},N=(e,s)=>{p(l=>({...l,[e]:s}))},w=(e,s,l)=>{var a;let r=s.type;return"user_role"===e&&t?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:Object.entries(t).filter(e=>{let[s]=e;return s.includes("internal_user")}).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(b,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{children:l}),(0,c.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:t})]})},s)})}):"budget_duration"===e?(0,c.jsx)(e_,{value:x[e]||null,onChange:s=>N(e,s),className:"mt-2"}):"boolean"===r?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!x[e],onChange:s=>N(e,s)})}):"array"===r&&(null===(a=s.items)||void 0===a?void 0:a.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:f.map(e=>(0,c.jsx)(b,{value:e,children:K(e)},e))}):"string"===r&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==x[e]?String(x[e]):"",onChange:s=>N(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},C=(e,s)=>{if(null==s)return(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"});if("user_role"===e&&t&&t[s]){let{ui_label:e,description:l}=t[s];return(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{className:"font-medium",children:e}),l&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:l})]})}return"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)})};return n?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):o?(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex justify-end items-center mb-4",children:!n&&o&&(u?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{h(!1),p(o.values||{})},disabled:g,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:Z,loading:g,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>h(!0),children:"Edit Settings"}))}),(null==o?void 0:null===(s=o.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(v,{className:"mb-4",children:o.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=o;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(v,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),u?(0,c.jsx)("div",{className:"mt-2",children:w(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:C(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No settings available or you do not have permission to view them."})})};console.log=function(){};var l_=e=>{let{accessToken:s,token:l,keys:t,userRole:a,userID:r,teams:n,setKeys:i}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(1),[g,j]=d.useState(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),[w,S]=(0,d.useState)(!1),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)({}),[E,P]=(0,d.useState)(""),[O,L]=(0,d.useState)("users"),[M,F]=(0,d.useState)({email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"}),[R,q]=(0,d.useState)(!1),[U,z]=(0,d.useState)(!1),[V,K]=(0,d.useState)("Email");(0,d.useRef)(null);let B=(0,d.useRef)(0);window.addEventListener("beforeunload",function(){sessionStorage.clear()});let H=(e,s)=>{let l={...M,[e]:s};F(l),console.log("called from handleFilterChange - newFilters:",JSON.stringify(l)),J(l)},J=(0,d.useCallback)(ep()(async e=>{if(!s||!l||!a||!r)return;let t=Date.now();B.current=t;try{let l=await (0,y.Of)(s,e.user_id?[e.user_id]:null,1,25,e.email||null,e.user_role||null,e.team||null,e.sso_user_id||null,e.sort_by,e.sort_order);t===B.current&&l&&(m(l),console.log("called from debouncedSearch filters:",JSON.stringify(e)),console.log("called from debouncedSearch data:",JSON.stringify(l)))}catch(e){console.error("Error searching users:",e)}},300),[s,l,a,r]);(0,d.useEffect)(()=>()=>{J.cancel()},[J]);let W=async()=>{if(C&&s)try{if(await (0,y.Eb)(s,[C]),D.ZP.success("User deleted successfully"),o){var e;let s=null===(e=o.users)||void 0===e?void 0:e.filter(e=>e.user_id!==C);m({...o,users:s||[]})}}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}S(!1),I(null)},G=async()=>{N(null),b(!1)},Y=async e=>{if(console.log("inside handleEditSubmit:",e),s&&l&&a&&r){try{await (0,y.pf)(s,e,null),D.ZP.success("User ".concat(e.user_id," updated successfully"))}catch(e){console.error("There was an error updating the user",e)}if(o){var t;let s=null===(t=o.users)||void 0===t?void 0:t.map(s=>s.user_id===e.user_id?e:s);m({...o,users:s||[]})}N(null),b(!1)}},$=async e=>{if(s&&l&&a&&r)try{let l=await (0,y.Of)(s,M.user_id?[M.user_id]:null,e,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(e),JSON.stringify(l)),m(l),p(e)}catch(e){console.error("Error changing page:",e)}};if((0,d.useEffect)(()=>{if(!s||!l||!a||!r)return;let e=async()=>{try{let e=sessionStorage.getItem("userList_".concat(x));if(e){let s=JSON.parse(e);m(s),console.log("called from useEffect")}else{let e=await (0,y.Of)(s,M.user_id?[M.user_id]:null,x,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(x),JSON.stringify(e)),m(e),console.log("called from useEffect 2")}let l=sessionStorage.getItem("possibleUserRoles");if(l)A(JSON.parse(l));else{let e=await (0,y.lg)(s);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),A(e)}}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&a&&r&&e()},[s,l,a,r]),!o||!s||!l||!a||!r)return(0,c.jsx)("div",{children:"Loading..."});let X=lx(T,e=>{N(e),b(!0)},e=>{I(e),S(!0)});return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Users"}),(0,c.jsx)("div",{className:"flex space-x-3",children:(0,c.jsx)(eh,{userID:r,accessToken:s,teams:n,possibleUIRoles:T})})]}),(0,c.jsxs)(eq.Z,{defaultIndex:0,onIndexChange:e=>L(0===e?"users":"settings"),children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Users"}),(0,c.jsx)(eR.Z,{children:"Default User Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by email...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.email,onChange:e=>H("email",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ".concat(R?"bg-gray-100":""),onClick:()=>q(!R),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filters",(M.user_id||M.user_role||M.team)&&(0,c.jsx)("span",{className:"w-2 h-2 rounded-full bg-blue-500"})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{F({email:"",user_id:"",user_role:"",team:"",sso_user_id:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"})},children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Reset Filters"]})]}),R&&(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Filter by User ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.user_id,onChange:e=>H("user_id",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})]}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.user_role,onValueChange:e=>H("user_role",e),placeholder:"Select Role",children:Object.entries(T).map(e=>{let[s,l]=e;return(0,c.jsx)(ee.Z,{value:s,children:l.ui_label},s)})})}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.team,onValueChange:e=>H("team",e),placeholder:"Select Team",children:null==n?void 0:n.map(e=>(0,c.jsx)(ee.Z,{value:e.team_id,children:e.team_alias||e.team_id},e.team_id))})}),(0,c.jsx)("div",{className:"relative w-64",children:(0,c.jsx)("input",{type:"text",placeholder:"Filter by SSO ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.sso_user_id,onChange:e=>H("sso_user_id",e.target.value)})})]}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",o&&o.users&&o.users.length>0?(o.page-1)*o.page_size+1:0," ","-"," ",o&&o.users?Math.min(o.page*o.page_size,o.total):0," ","of ",o?o.total:0," results"]}),(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>$(x-1),disabled:1===x,className:"px-3 py-1 text-sm border rounded-md ".concat(1===x?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),(0,c.jsx)("button",{onClick:()=>$(x+1),disabled:!o||x>=o.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(!o||x>=o.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})]})]})}),(0,c.jsx)(lg,{data:(null==o?void 0:o.users)||[],columns:X,isLoading:!o,accessToken:s,userRole:a,onSortChange:(e,s)=>{let l={...M,sort_by:e,sort_order:s};F(l),J(l)},currentSort:{sortBy:M.sort_by,sortOrder:M.sort_order}})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lf,{accessToken:s,possibleUIRoles:T,userID:r,userRole:a})})]})]}),(0,c.jsx)(lu,{visible:v,possibleUIRoles:T,onCancel:G,user:Z,onSubmit:Y}),w&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"}),(0,c.jsxs)("p",{className:"text-sm font-medium text-gray-900 mt-2",children:["User ID: ",C]})]})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:W,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{S(!1),I(null)},children:"Cancel"})]})]})]})})]})},ly=e=>{var s;let{accessToken:l,userID:t,userRole:a}=e,[r,n]=(0,d.useState)(!0),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)({}),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),{Paragraph:_}=es.default,{Option:v}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){n(!1);return}try{let e=await (0,y.EB)(l);if(o(e),x(e.values||{}),l)try{let e=await (0,y.So)(l,t,a);if(e&&e.data){let s=e.data.map(e=>e.id);f(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching team SSO settings:",e),D.ZP.error("Failed to fetch team settings")}finally{n(!1)}})()},[l]);let b=async()=>{if(l){g(!0);try{let e=await (0,y.r1)(l,h);o({...i,values:e.settings}),u(!1),D.ZP.success("Default team settings updated successfully")}catch(e){console.error("Error updating team settings:",e),D.ZP.error("Failed to update team settings")}finally{g(!1)}}},Z=(e,s)=>{x(l=>({...l,[e]:s}))},N=(e,s,l)=>{var t;let a=s.type;return"budget_duration"===e?(0,c.jsx)(e_,{value:h[e]||null,onChange:s=>Z(e,s),className:"mt-2"}):"boolean"===a?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!h[e],onChange:s=>Z(e,s)})}):"array"===a&&(null===(t=s.items)||void 0===t?void 0:t.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:j.map(e=>(0,c.jsx)(v,{value:e,children:K(e)},e))}):"string"===a&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:h[e]||"",onChange:s=>Z(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==h[e]?String(h[e]):"",onChange:s=>Z(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},w=(e,s)=>null==s?(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"}):"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)});return r?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):i?(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{className:"text-xl",children:"Default Team Settings"}),!r&&i&&(m?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{u(!1),x(i.values||{})},disabled:p,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:b,loading:p,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Settings"}))]}),(0,c.jsx)(A.Z,{children:"These settings will be applied by default when creating new teams."}),(null==i?void 0:null===(s=i.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(_,{className:"mb-4 mt-2",children:i.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=i;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(_,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),m?(0,c.jsx)("div",{className:"mt-2",children:N(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:w(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No team settings available or you do not have permission to view them."})})},lv=e=>{let{accessToken:s,userID:l}=e,[t,a]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(s&&l)try{let e=await (0,y.a6)(s);a(e)}catch(e){console.error("Error fetching available teams:",e)}})()},[s,l]);let r=async e=>{if(s&&l)try{await (0,y.cu)(s,e,{user_id:l,role:"user"}),D.ZP.success("Successfully joined team"),a(s=>s.filter(s=>s.team_id!==e))}catch(e){console.error("Error joining team:",e),D.ZP.error("Failed to join team")}};return(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{children:"Members"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsxs)(eT.Z,{children:[t.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.team_alias})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.description||"No description available"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[e.members_with_roles.length," members"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"flex flex-col",children:e.models&&0!==e.models.length?e.models.map((e,s)=>(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(e.slice(0,30),"..."):e})},s)):(0,c.jsx)(eM.Z,{size:"xs",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})})})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{size:"xs",variant:"secondary",onClick:()=>r(e.team_id),children:"Join Team"})})]},e.team_id)),0===t.length&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:5,className:"text-center",children:(0,c.jsx)(A.Z,{children:"No available teams to join"})})})]})]})})};console.log=function(){};let lb=(e,s)=>{let l=[];return e&&e.models.length>0?(console.log("organization.models: ".concat(e.models)),l=e.models):l=s,B(l,s)};var lZ=e=>{let{teams:s,searchParams:l,accessToken:t,setTeams:a,userID:r,userRole:n,organizations:i}=e,[o,m]=(0,d.useState)(""),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(null);(0,d.useEffect)(()=>{console.log("inside useeffect - ".concat(o)),t&&Z(t,r,n,u,a),ey()},[o]);let[g]=L.Z.useForm(),[j]=L.Z.useForm(),{Title:f,Paragraph:_}=es.default,[v,b]=(0,d.useState)(""),[E,P]=(0,d.useState)(!1),[F,U]=(0,d.useState)(null),[B,H]=(0,d.useState)(null),[G,Y]=(0,d.useState)(!1),[$,X]=(0,d.useState)(!1),[Q,ee]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)(!1),[eo,ec]=(0,d.useState)(null),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({}),[ex,ep]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("currentOrgForCreateTeam: ".concat(x));let e=lb(x,ea);console.log("models: ".concat(e)),em(e),g.setFieldValue("models",[])},[x,ea]),(0,d.useEffect)(()=>{(async()=>{try{if(null==t)return;let e=(await (0,y.t3)(t)).guardrails.map(e=>e.guardrail_name);ep(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[t]);let ej=async e=>{ec(e),ei(!0)},ef=async()=>{if(null!=eo&&null!=s&&null!=t){try{await (0,y.rs)(t,eo),Z(t,r,n,u,a)}catch(e){console.error("Error deleting the team:",e)}ei(!1),ec(null)}};(0,d.useEffect)(()=>{(async()=>{try{if(null===r||null===n||null===t)return;let e=await V(r,n,t);e&&er(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,r,n,s]);let e_=async e=>{try{if(console.log("formValues: ".concat(JSON.stringify(e))),null!=t){var l;let r=null==e?void 0:e.team_alias,n=null!==(l=null==s?void 0:s.map(e=>e.team_alias))&&void 0!==l?l:[],i=(null==e?void 0:e.organization_id)||(null==u?void 0:u.organization_id);if(""===i||"string"!=typeof i?e.organization_id=null:e.organization_id=i.trim(),n.includes(r))throw Error("Team alias ".concat(r," already exists, please pick another alias"));D.ZP.info("Creating Team");let o=await (0,y.hT)(t,e);null!==s?a([...s,o]):a([o]),console.log("response for team create call: ".concat(o)),D.ZP.success("Team created"),g.resetFields(),X(!1)}}catch(e){console.error("Error creating the team:",e),D.ZP.error("Error creating the team: "+e,20)}},ey=()=>{m(new Date().toLocaleString())};return(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:B?(0,c.jsx)(sq,{teamId:B,onUpdate:e=>{a(s=>null==s?s:s.map(s=>e.team_id===s.team_id?e8(s,e):s))},onClose:()=>{H(null),Y(!1)},accessToken:t,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let s=0;se.team_id===B)),is_proxy_admin:"Admin"==n,userModels:ea,editTeam:G}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Your Teams"}),(0,c.jsx)(eR.Z,{children:"Available Teams"}),(0,eg.tY)(n||"")&&(0,c.jsx)(eR.Z,{children:"Default Team Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[o&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",o]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:ey})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(A.Z,{children:["Click on “Team ID” to view team details ",(0,c.jsx)("b",{children:"and"})," manage team members."]}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Team ID"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Organization"}),(0,c.jsx)(eP.Z,{children:"Info"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.filter(e=>!u||e.organization_id===u.organization_id).sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{H(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.spend}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},children:Array.isArray(e.models)?(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)})},s))}):null}),(0,c.jsx)(eA.Z,{children:e.organization_id}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].keys&&eu[e.team_id].keys.length," ","Keys"]}),(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].members_with_roles&&eu[e.team_id].members_with_roles.length," ","Members"]})]}),(0,c.jsx)(eA.Z,{children:"Admin"==n?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{H(e.team_id),Y(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>ej(e.team_id),icon:eH.Z,size:"sm"})]}):null})]},e.team_id)):null})]}),en&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Team"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this team ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ef,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{ei(!1),ec(null)},children:"Cancel"})]})]})]})})]})}),"Admin"==n||"Org Admin"==n?(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>X(!0),children:"+ Create New Team"}),(0,c.jsx)(M.Z,{title:"Create Team",visible:$,width:800,footer:null,onOk:()=>{X(!1),g.resetFields()},onCancel:()=>{X(!1),g.resetFields()},children:(0,c.jsxs)(L.Z,{form:g,onFinish:e_,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Organization"," ",(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:u?u.organization_id:null,className:"mt-8",children:(0,c.jsx)(O.default,{showSearch:!0,allowClear:!0,placeholder:"Search or select an Organization",onChange:e=>{g.setFieldValue("organization_id",e),p((null==i?void 0:i.find(s=>s.organization_id===e))||null)},filterOption:(e,s)=>{var l;return!!s&&((null===(l=s.children)||void 0===l?void 0:l.toString())||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==i?void 0:i.map(e=>(0,c.jsxs)(O.default.Option,{value:e.organization_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"These are the models that your selected team has access to",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),ed.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Additional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,c.jsx)(S.Z,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:ex.map(e=>({value:e,label:e}))})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Team"})})]})})]}):null]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lv,{accessToken:t,userID:r})}),(0,eg.tY)(n||"")&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ly,{accessToken:t,userID:r||"",userRole:n||""})})]})]})})},lN=e=>{var s;let{organizationId:l,onClose:t,accessToken:a,is_org_admin:r,is_proxy_admin:n,userModels:i,editOrg:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),C=r||n,I=async()=>{try{if(x(!0),!a)return;let e=await (0,y.t$)(a,l);u(e)}catch(e){D.ZP.error("Failed to load organization information"),console.error("Error fetching organization info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{I()},[l,a]);let T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.vh)(a,l,s),D.ZP.success("Organization member added successfully"),_(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to add organization member"),console.error("Error adding organization member:",e)}},P=async e=>{try{if(!a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.LY)(a,l,s),D.ZP.success("Organization member updated successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to update organization member"),console.error("Error updating organization member:",e)}},M=async e=>{try{if(!a)return;await (0,y.Sb)(a,l,e.user_id),D.ZP.success("Organization member deleted successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to delete organization member"),console.error("Error deleting organization member:",e)}},F=async e=>{try{if(!a)return;let s={organization_id:l,organization_alias:e.organization_alias,models:e.models,litellm_budget_table:{tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration},metadata:e.metadata?JSON.parse(e.metadata):null};await (0,y.VA)(a,s),D.ZP.success("Organization settings updated successfully"),j(!1),I()}catch(e){D.ZP.error("Failed to update organization settings"),console.error("Error updating organization:",e)}};return h?(0,c.jsx)("div",{className:"p-4",children:"Loading..."}):m?(0,c.jsxs)("div",{className:"w-full h-screen p-4 bg-white",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:m.organization_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:m.organization_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?2:0,children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Members"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Organization Details"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Created: ",new Date(m.created_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Updated: ",new Date(m.updated_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Created By: ",m.created_by]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",m.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===m.litellm_budget_table.max_budget?"Unlimited":"$".concat(m.litellm_budget_table.max_budget)]}),m.litellm_budget_table.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",m.litellm_budget_table.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]}),m.litellm_budget_table.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",m.litellm_budget_table.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[75vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Created At"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:null===(s=m.members)||void 0===s?void 0:s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_role})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["$",e.spend.toFixed(6)]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:new Date(e.created_at).toLocaleString()})}),(0,c.jsx)(eA.Z,{children:C&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{N({role:e.user_role,user_email:e.user_email,user_id:e.user_id}),b(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{M(e)}})]})})]},s))})]})}),C&&(0,c.jsx)(k.Z,{onClick:()=>{_(!0)},children:"Add Member"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Organization Settings"}),C&&!g&&(0,c.jsx)(k.Z,{onClick:()=>j(!0),children:"Edit Settings"})]}),g?(0,c.jsxs)(L.Z,{form:p,onFinish:F,initialValues:{organization_alias:m.organization_alias,models:m.models,tpm_limit:m.litellm_budget_table.tpm_limit,rpm_limit:m.litellm_budget_table.rpm_limit,max_budget:m.litellm_budget_table.max_budget,budget_duration:m.litellm_budget_table.budget_duration,metadata:m.metadata?JSON.stringify(m.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>j(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization Name"}),(0,c.jsx)("div",{children:m.organization_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization ID"}),(0,c.jsx)("div",{className:"font-mono",children:m.organization_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(m.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==m.litellm_budget_table.max_budget?"$".concat(m.litellm_budget_table.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",m.litellm_budget_table.budget_duration||"Never"]})]})]})]})})]})]}),(0,c.jsx)(sR,{isVisible:f,onCancel:()=>_(!1),onSubmit:T,accessToken:a,title:"Add Organization Member",roles:[{label:"org_admin",value:"org_admin",description:"Can add and remove members, and change their roles."},{label:"internal_user",value:"internal_user",description:"Can view/create keys for themselves within organization."},{label:"internal_user_viewer",value:"internal_user_viewer",description:"Can only view their keys within organization."}],defaultRole:"internal_user"}),(0,c.jsx)(sF,{visible:v,onCancel:()=>b(!1),onSubmit:P,initialData:Z,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Org Admin",value:"org_admin"},{label:"Internal User",value:"internal_user"},{label:"Internal User Viewer",value:"internal_user_viewer"}]}})]}):(0,c.jsx)("div",{className:"p-4",children:"Organization not found"})};let lw=async(e,s)=>{s(await (0,y.r6)(e))};var lk=e=>{let{organizations:s,userRole:l,userModels:t,accessToken:a,lastRefreshed:r,handleRefreshClick:n,currentOrg:i,guardrailsList:o=[],setOrganizations:m,premiumUser:u}=e,[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(null),[b,Z]=(0,d.useState)(!1),[C]=L.Z.useForm();(0,d.useEffect)(()=>{0===s.length&&a&&lw(a,m)},[s,a]);let I=e=>{e&&(v(e),f(!0))},T=async()=>{if(_&&a)try{await (0,y.cq)(a,_),D.ZP.success("Organization deleted successfully"),f(!1),v(null),lw(a,m)}catch(e){console.error("Error deleting organization:",e)}},E=async e=>{try{if(!a)return;console.log("values in organizations new create call: ".concat(JSON.stringify(e))),await (0,y.H1)(a,e),Z(!1),C.resetFields(),lw(a,m)}catch(e){console.error("Error creating organization:",e)}};return u?h?(0,c.jsx)(lN,{organizationId:h,onClose:()=>{x(null),g(!1)},accessToken:a,is_org_admin:!0,is_proxy_admin:"Admin"===l,userModels:t,editOrg:p}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsx)("div",{className:"flex",children:(0,c.jsx)(eR.Z,{children:"Your Organizations"})}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[r&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",r]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:n})]})]}),(0,c.jsx)(eV.Z,{children:(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(A.Z,{children:"Click on “Organization ID” to view organization details."}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Organization ID"}),(0,c.jsx)(eP.Z,{children:"Organization Name"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"TPM / RPM Limits"}),(0,c.jsx)(eP.Z,{children:"Info"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>{var s,t,a,r,n,i,o,d,m;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.organization_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>x(e.organization_id),children:[null===(s=e.organization_id)||void 0===s?void 0:s.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{children:e.organization_alias}),(0,c.jsx)(eA.Z,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{children:e.spend}),(0,c.jsx)(eA.Z,{children:(null===(t=e.litellm_budget_table)||void 0===t?void 0:t.max_budget)!==null&&(null===(a=e.litellm_budget_table)||void 0===a?void 0:a.max_budget)!==void 0?null===(r=e.litellm_budget_table)||void 0===r?void 0:r.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{children:Array.isArray(e.models)&&(0,c.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)},s))})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["TPM: ",(null===(n=e.litellm_budget_table)||void 0===n?void 0:n.tpm_limit)?null===(i=e.litellm_budget_table)||void 0===i?void 0:i.tpm_limit:"Unlimited",(0,c.jsx)("br",{}),"RPM: ",(null===(o=e.litellm_budget_table)||void 0===o?void 0:o.rpm_limit)?null===(d=e.litellm_budget_table)||void 0===d?void 0:d.rpm_limit:"Unlimited"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[(null===(m=e.members)||void 0===m?void 0:m.length)||0," Members"]})}),(0,c.jsx)(eA.Z,{children:"Admin"===l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{x(e.organization_id),g(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>I(e.organization_id),icon:eH.Z,size:"sm"})]})})]},e.organization_id)}):null})]})})}),("Admin"===l||"Org Admin"===l)&&(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>Z(!0),children:"+ Create New Organization"}),(0,c.jsx)(M.Z,{title:"Create Organization",visible:b,width:800,footer:null,onCancel:()=>{Z(!1),C.resetFields()},children:(0,c.jsxs)(L.Z,{form:C,onFinish:E,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),t&&t.length>0&&t.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Organization"})})]})})]})]})]})}),j?(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Organization"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this organization?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:T,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{f(!1),v(null)},children:"Cancel"})]})]})]})}):(0,c.jsx)(c.Fragment,{})]}):(0,c.jsx)("div",{children:(0,c.jsxs)(A.Z,{children:["This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key ",(0,c.jsx)("a",{href:"https://litellm.ai/pricing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})},lS=l(94789);let lC={google:"https://artificialanalysis.ai/img/logos/google_small.svg",microsoft:"https://upload.wikimedia.org/wikipedia/commons/a/a8/Microsoft_Azure_Logo.svg",okta:"https://www.okta.com/sites/default/files/Okta_Logo_BrightBlue_Medium.png",generic:""},lI={google:{envVarMap:{google_client_id:"GOOGLE_CLIENT_ID",google_client_secret:"GOOGLE_CLIENT_SECRET"},fields:[{label:"GOOGLE CLIENT ID",name:"google_client_id"},{label:"GOOGLE CLIENT SECRET",name:"google_client_secret"}]},microsoft:{envVarMap:{microsoft_client_id:"MICROSOFT_CLIENT_ID",microsoft_client_secret:"MICROSOFT_CLIENT_SECRET",microsoft_tenant:"MICROSOFT_TENANT"},fields:[{label:"MICROSOFT CLIENT ID",name:"microsoft_client_id"},{label:"MICROSOFT CLIENT SECRET",name:"microsoft_client_secret"},{label:"MICROSOFT TENANT",name:"microsoft_tenant"}]},okta:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint",placeholder:"https://your-okta-domain/authorize"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint",placeholder:"https://your-okta-domain/token"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint",placeholder:"https://your-okta-domain/userinfo"}]},generic:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint"}]}};var lT=e=>{let{isAddSSOModalVisible:s,isInstructionsModalVisible:l,handleAddSSOOk:t,handleAddSSOCancel:a,handleShowInstructions:r,handleInstructionsOk:n,handleInstructionsCancel:i,form:o}=e,d=e=>{let s=lI[e];return s?s.fields.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,rules:[{required:!0,message:"Please enter the ".concat(e.label.toLowerCase())}],children:e.name.includes("client")?(0,c.jsx)(q.default.Password,{}):(0,c.jsx)(S.Z,{placeholder:e.placeholder})},e.name)):null};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(M.Z,{title:"Add SSO",visible:s,width:800,footer:null,onOk:t,onCancel:a,children:(0,c.jsxs)(L.Z,{form:o,onFinish:r,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,c.jsx)(O.default,{children:Object.entries(lC).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[l&&(0,c.jsx)("img",{src:l,alt:s,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,c.jsxs)("span",{children:[s.charAt(0).toUpperCase()+s.slice(1)," SSO"]})]})},s)})})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("sso_provider");return l?d(l):null}}),(0,c.jsx)(L.Z.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"PROXY BASE URL",name:"proxy_base_url",rules:[{required:!0,message:"Please enter the proxy base url"}],children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})}),(0,c.jsxs)(M.Z,{title:"SSO Setup Instructions",visible:l,width:800,footer:null,onOk:n,onCancel:i,children:[(0,c.jsx)("p",{children:"Follow these steps to complete the SSO setup:"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"1. DO NOT Exit this TAB"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"2. Open a new tab, visit your proxy base url"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"3. Confirm your SSO is configured correctly and you can login on the new Tab"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"4. If Step 3 is successful, you can close this tab"}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{onClick:n,children:"Done"})})]})]})},lA=l(62272),lE=l(92403),lP=l(29271),lO=l(34419),lL=e=>{let{accessToken:s,userID:l,proxySettings:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)("");(0,d.useEffect)(()=>{let e="";u(t&&t.PROXY_BASE_URL&&void 0!==t.PROXY_BASE_URL?t.PROXY_BASE_URL:window.location.origin)},[t]);let h="".concat(m,"/scim/v2"),x=async e=>{if(!s||!l){D.ZP.error("You need to be logged in to create a SCIM token");return}try{n(!0);let t={key_alias:e.key_alias||"SCIM Access Token",team_id:null,models:[],allowed_routes:["/scim/*"]},a=await (0,y.wX)(s,l,t);o(a),D.ZP.success("SCIM token created successfully")}catch(e){console.error("Error creating SCIM token:",e),D.ZP.error("Failed to create SCIM token")}finally{n(!1)}};return(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex items-center mb-4",children:(0,c.jsx)(E.Z,{children:"SCIM Configuration"})}),(0,c.jsx)(A.Z,{className:"text-gray-600",children:"System for Cross-domain Identity Management (SCIM) allows you to automatically provision and manage users and groups in LiteLLM."}),(0,c.jsx)(lj.Z,{}),(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"1"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lA.Z,{className:"h-5 w-5 mr-2"}),"SCIM Tenant URL"]})]}),(0,c.jsx)(A.Z,{className:"text-gray-600 mb-3",children:"Use this URL in your identity provider SCIM integration settings."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:h,disabled:!0,className:"flex-grow"}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>D.ZP.success("URL copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"ml-2 flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"2"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-5 w-5 mr-2"}),"Authentication Token"]})]}),(0,c.jsx)(lS.Z,{title:"Using SCIM",color:"blue",className:"mb-4",children:"You need a SCIM token to authenticate with the SCIM API. Create one below and use it in your SCIM provider configuration."}),i?(0,c.jsxs)(eF.Z,{className:"border border-yellow-300 bg-yellow-50",children:[(0,c.jsxs)("div",{className:"flex items-center mb-2 text-yellow-800",children:[(0,c.jsx)(lP.Z,{className:"h-5 w-5 mr-2"}),(0,c.jsx)(E.Z,{className:"text-lg text-yellow-800",children:"Your SCIM Token"})]}),(0,c.jsx)(A.Z,{className:"text-yellow-800 mb-4 font-medium",children:"Make sure to copy this token now. You will not be able to see it again."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:i.token,className:"flex-grow mr-2 bg-white",type:"password",disabled:!0}),(0,c.jsx)(P.CopyToClipboard,{text:i.token,onCopy:()=>D.ZP.success("Token copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]}),(0,c.jsxs)(k.Z,{className:"mt-4 flex items-center",variant:"secondary",onClick:()=>o(null),children:[(0,c.jsx)(lO.Z,{className:"h-4 w-4 mr-1"}),"Create Another Token"]})]}):(0,c.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,c.jsxs)(L.Z,{form:a,onFinish:x,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Token Name",rules:[{required:!0,message:"Please enter a name for your token"}],children:(0,c.jsx)(S.Z,{placeholder:"SCIM Access Token"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)(k.Z,{variant:"primary",type:"submit",loading:r,className:"flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-4 w-4 mr-1"}),"Create SCIM Token"]})})]})})]})]})]})})};let lD=()=>{let[e,s]=(0,d.useState)("http://localhost:4000");return(0,d.useEffect)(()=>{{let{protocol:e,host:l}=window.location;s("".concat(e,"//").concat(l))}},[]),e};var lM=e=>{let{searchParams:s,accessToken:l,showSSOBanner:t,premiumUser:a,proxySettings:r}=e,[n]=L.Z.useForm(),[i]=L.Z.useForm(),{Title:o,Paragraph:u}=es.default,[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)(null),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(!1),[S,C]=(0,d.useState)(!1),[I,T]=(0,d.useState)(!1),[A,E]=(0,d.useState)(!1),[P,O]=(0,d.useState)(!1),[F,U]=(0,d.useState)(!1),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)([]),[H,J]=(0,d.useState)(null);(0,m.useRouter)();let[W,G]=(0,d.useState)(null);console.log=function(){};let Y=lD(),$="All IP Addresses Allowed",X=Y;X+="/fallback/login";let Q=async()=>{try{if(!0!==a){D.ZP.error("This feature is only available for premium users. Please upgrade your account.");return}if(l){let e=await (0,y.PT)(l);B(e&&e.length>0?e:[$])}else B([$])}catch(e){console.error("Error fetching allowed IPs:",e),D.ZP.error("Failed to fetch allowed IPs ".concat(e)),B([$])}finally{!0===a&&O(!0)}},ee=async e=>{try{if(l){await (0,y.eH)(l,e.ip);let s=await (0,y.PT)(l);B(s),D.ZP.success("IP address added successfully")}}catch(e){console.error("Error adding IP:",e),D.ZP.error("Failed to add IP address ".concat(e))}finally{U(!1)}},el=async e=>{J(e),V(!0)},et=async()=>{if(H&&l)try{await (0,y.$I)(l,H);let e=await (0,y.PT)(l);B(e.length>0?e:[$]),D.ZP.success("IP address deleted successfully")}catch(e){console.error("Error deleting IP:",e),D.ZP.error("Failed to delete IP address ".concat(e))}finally{V(!1),J(null)}};(0,d.useEffect)(()=>{(async()=>{if(null!=l){let e=[],s=await (0,y.Xd)(l,"proxy_admin_viewer");console.log("proxy admin viewer response: ",s);let t=s.users;console.log("proxy viewers response: ".concat(t)),t.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy viewers: ".concat(t));let a=(await (0,y.Xd)(l,"proxy_admin")).users;a.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy admins: ".concat(a)),console.log("combinedList: ".concat(e)),g(e),G(await (0,y.lg)(l))}})()},[l]);let ea=async e=>{try{if(null!=l&&null!=p){var s;D.ZP.info("Making API Call"),e.user_email,e.user_id;let t=await (0,y.pf)(l,e,"proxy_admin"),a=(null===(s=t.data)||void 0===s?void 0:s.user_id)||t.user_id;(0,y.XO)(l,a).then(e=>{f(e),v(!0)}),console.log("response for team create call: ".concat(t));let r=p.findIndex(e=>(console.log("user.user_id=".concat(e.user_id,"; response.user_id=").concat(a)),e.user_id===t.user_id));console.log("foundIndex: ".concat(r)),-1==r&&(console.log("updates admin with new user"),p.push(t),g(p)),n.resetFields(),w(!1)}}catch(e){console.error("Error creating the key:",e)}},er=async e=>{if(null==l)return;let s=lI[e.sso_provider],t={PROXY_BASE_URL:e.proxy_base_url};s&&Object.entries(s.envVarMap).forEach(s=>{let[l,a]=s;e[l]&&(t[a]=e[l])}),(0,y.K_)(l,{environment_variables:t})};return console.log("admins: ".concat(null==p?void 0:p.length)),(0,c.jsxs)("div",{className:"w-full m-2 mt-2 p-8",children:[(0,c.jsx)(o,{level:4,children:"Admin Access "}),(0,c.jsx)(u,{children:"Go to 'Internal Users' page to add other admins."}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Security Settings"}),(0,c.jsx)(eR.Z,{children:"SCIM"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(o,{level:4,children:" ✨ Security Settings"}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem"},children:[(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:()=>!0===a?T(!0):D.ZP.error("Only premium users can add SSO"),children:"Add SSO"})}),(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:Q,children:"Allowed IPs"})})]})]}),(0,c.jsxs)("div",{className:"flex justify-start mb-4",children:[(0,c.jsx)(lT,{isAddSSOModalVisible:I,isInstructionsModalVisible:A,handleAddSSOOk:()=>{T(!1),n.resetFields()},handleAddSSOCancel:()=>{T(!1),n.resetFields()},handleShowInstructions:e=>{ea(e),er(e),T(!1),E(!0)},handleInstructionsOk:()=>{E(!1)},handleInstructionsCancel:()=>{E(!1)},form:n}),(0,c.jsx)(M.Z,{title:"Manage Allowed IP Addresses",width:800,visible:P,onCancel:()=>O(!1),footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>U(!0),children:"Add IP Address"},"add"),(0,c.jsx)(k.Z,{onClick:()=>O(!1),children:"Close"},"close")],children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"IP Address"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:K.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e}),(0,c.jsx)(eA.Z,{className:"text-right",children:e!==$&&(0,c.jsx)(k.Z,{onClick:()=>el(e),color:"red",size:"xs",children:"Delete"})})]},s))})]})}),(0,c.jsx)(M.Z,{title:"Add Allowed IP Address",visible:F,onCancel:()=>U(!1),footer:null,children:(0,c.jsxs)(L.Z,{onFinish:ee,children:[(0,c.jsx)(L.Z.Item,{name:"ip",rules:[{required:!0,message:"Please enter an IP address"}],children:(0,c.jsx)(q.default,{placeholder:"Enter IP address"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add IP Address"})})]})}),(0,c.jsx)(M.Z,{title:"Confirm Delete",visible:z,onCancel:()=>V(!1),onOk:et,footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>et(),children:"Yes"},"delete"),(0,c.jsx)(k.Z,{onClick:()=>V(!1),children:"Close"},"close")],children:(0,c.jsxs)("p",{children:["Are you sure you want to delete the IP address: ",H,"?"]})})]}),(0,c.jsxs)(lS.Z,{title:"Login without SSO",color:"teal",children:["If you need to login without sso, you can access"," ",(0,c.jsxs)("a",{href:X,target:"_blank",children:[(0,c.jsx)("b",{children:X})," "]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lL,{accessToken:l,userID:p&&p.length>0?p[0].user_id:null,proxySettings:r})})]})]})]})},lF=l(92858),lR=e=>{let{alertingSettings:s,handleInputChange:l,handleResetField:t,handleSubmit:a,premiumUser:r}=e,[n]=L.Z.useForm();return(0,c.jsxs)(L.Z,{form:n,onFinish:()=>{console.log("INSIDE ONFINISH");let e=n.getFieldsValue(),s=Object.entries(e).every(e=>{let[s,l]=e;return"boolean"!=typeof l&&(""===l||null==l)});console.log("formData: ".concat(JSON.stringify(e),", isEmpty: ").concat(s)),s?console.log("Some form fields are empty."):a(e)},labelAlign:"left",children:[s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{align:"center",children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),e.premium_field?r?(0,c.jsx)(L.Z.Item,{name:e.field_name,children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s)}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>l(e.field_name,s)}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}):(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})})}):(0,c.jsx)(L.Z.Item,{name:e.field_name,className:"mb-0",valuePropName:"Boolean"===e.field_type?"checked":"value",children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s),className:"p-0"}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>{l(e.field_name,s),n.setFieldsValue({[e.field_name]:s})}}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>t(e.field_name,s),children:"Reset"})})]},s)),(0,c.jsx)("div",{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Update Settings"})})]})},lq=e=>{let{accessToken:s,premiumUser:l}=e,[t,a]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(0,y.RQ)(s).then(e=>{a(e)})},[s]),(0,c.jsx)(lR,{alertingSettings:t,handleInputChange:(e,s)=>{let l=t.map(l=>l.field_name===e?{...l,field_value:s}:l);console.log("updatedSettings: ".concat(JSON.stringify(l))),a(l)},handleResetField:(e,l)=>{if(s)try{let s=t.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:s.field_default_value}:s);a(s)}catch(e){console.log("ERROR OCCURRED!")}},handleSubmit:e=>{if(!s||(console.log("formValues: ".concat(e)),null==e||void 0==e))return;let l={};t.forEach(e=>{l[e.field_name]=e.field_value});let a={...e,...l};console.log("mergedFormValues: ".concat(JSON.stringify(a)));let{slack_alerting:r,...n}=a;console.log("slack_alerting: ".concat(r,", alertingArgs: ").concat(JSON.stringify(n)));try{(0,y.jA)(s,"alerting_args",n),"boolean"==typeof r&&(!0==r?(0,y.jA)(s,"alerting",["slack"]):(0,y.jA)(s,"alerting",[])),D.ZP.success("Wait 10s for proxy to update.")}catch(e){}},premiumUser:l})},lU=l(86582);let{Title:lz,Paragraph:lV}=es.default;console.log=function(){};var lK=e=>{let{accessToken:s,userRole:l,userID:t,premiumUser:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h]=L.Z.useForm(),[x,p]=(0,d.useState)(null),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)({}),[Z,N]=(0,d.useState)([]),[C,I]=(0,d.useState)(!1),[T,E]=(0,d.useState)([]),[P,F]=(0,d.useState)(null),[q,U]=(0,d.useState)([]),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)(null),H=e=>{Z.includes(e)?N(Z.filter(s=>s!==e)):N([...Z,e])},J={llm_exceptions:"LLM Exceptions",llm_too_slow:"LLM Responses Too Slow",llm_requests_hanging:"LLM Requests Hanging",budget_alerts:"Budget Alerts (API Keys, Users)",db_exceptions:"Database Exceptions (Read/Write)",daily_reports:"Weekly/Monthly Spend Reports",outage_alerts:"Outage Alerts",region_outage_alerts:"Region Outage Alerts"};(0,d.useEffect)(()=>{s&&l&&t&&(0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e),n(e.callbacks),E(e.available_callbacks);let s=e.alerts;if(console.log("alerts_data",s),s&&s.length>0){let e=s[0];console.log("_alert_info",e);let l=e.variables.SLACK_WEBHOOK_URL;console.log("catch_all_webhook",l),N(e.active_alerts),_(l),b(e.alerts_to_webhook)}o(s)})},[s,l,t]);let W=e=>Z&&Z.includes(e),G=()=>{if(!s)return;let e={};i.filter(e=>"email"===e.name).forEach(s=>{var l;Object.entries(null!==(l=s.variables)&&void 0!==l?l:{}).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));a&&a.value&&(e[l]=null==a?void 0:a.value)})}),console.log("updatedVariables",e);try{(0,y.K_)(s,{general_settings:{alerting:["email"]},environment_variables:e})}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Email settings updated successfully")},Y=async e=>{if(!s)return;let l={};Object.entries(e).forEach(e=>{let[s,t]=e;"callback"!==s&&(l[s]=t)});try{await (0,y.K_)(s,{environment_variables:l}),D.ZP.success("Callback added successfully"),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},$=async e=>{if(!s)return;let l=null==e?void 0:e.callback,t={};Object.entries(e).forEach(e=>{let[s,l]=e;"callback"!==s&&(t[s]=l)});try{await (0,y.K_)(s,{environment_variables:t,litellm_settings:{success_callback:[l]}}),D.ZP.success("Callback ".concat(l," added successfully")),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},X=e=>{console.log("inside handleSelectedCallbackChange",e),p(e.litellm_callback_name),console.log("all callbacks",T),e&&e.litellm_callback_params?(U(e.litellm_callback_params),console.log("selectedCallbackParams",q)):U([])};return s?(console.log("callbacks: ".concat(r)),(0,c.jsxs)("div",{className:"w-full mx-4",children:[(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Logging Callbacks"}),(0,c.jsx)(eR.Z,{value:"2",children:"Alerting Types"}),(0,c.jsx)(eR.Z,{value:"3",children:"Alerting Settings"}),(0,c.jsx)(eR.Z,{value:"4",children:"Email Alerts"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Active Logging Callbacks"}),(0,c.jsx)(w.Z,{numItems:2,children:(0,c.jsx)(eF.Z,{className:"max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eP.Z,{children:"Callback Name"})})}),(0,c.jsx)(eT.Z,{children:r.map((e,l)=>(0,c.jsxs)(eO.Z,{className:"flex justify-between",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.name})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"flex justify-between",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{B(e),V(!0)}}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,e.name),className:"ml-2",variant:"secondary",children:"Test Callback"})]})})]},l))})]})})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>I(!0),children:"Add Callback"})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(A.Z,{className:"my-2",children:["Alerts are only supported for Slack Webhook URLs. Get your webhook urls from"," ",(0,c.jsx)("a",{href:"https://api.slack.com/messaging/webhooks",target:"_blank",style:{color:"blue"},children:"here"})]}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{children:"Slack Webhook URL"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(J).map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:"region_outage_alerts"==l?a?(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)}):(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})}):(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:l,type:"password",defaultValue:v&&v[l]?v[l]:f})})]},s)})})]}),(0,c.jsx)(k.Z,{size:"xs",className:"mt-2",onClick:()=>{if(!s)return;let e={};Object.entries(J).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));console.log("key",l),console.log("webhookInput",a);let r=(null==a?void 0:a.value)||"";console.log("newWebhookValue",r),e[l]=r}),console.log("updatedAlertToWebhooks",e);let l={general_settings:{alert_to_webhook_url:e,alert_types:Z}};console.log("payload",l);try{(0,y.K_)(s,l)}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Alerts updated successfully")},children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"slack"),className:"mx-2",children:"Test Alerts"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lq,{accessToken:s,premiumUser:a})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Email Settings"}),(0,c.jsxs)(A.Z,{children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: email alerts"})," ",(0,c.jsx)("br",{})]}),(0,c.jsx)("div",{className:"flex w-full",children:i.filter(e=>"email"===e.name).map((e,s)=>{var l;return(0,c.jsx)(eA.Z,{children:(0,c.jsx)("ul",{children:(0,c.jsx)(w.Z,{numItems:2,children:Object.entries(null!==(l=e.variables)&&void 0!==l?l:{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("li",{className:"mx-2 my-2",children:[!0!=a&&("EMAIL_LOGO_URL"===s||"EMAIL_SUPPORT_CONTACT"===s)?(0,c.jsxs)("div",{children:[(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:(0,c.jsxs)(A.Z,{className:"mt-2",children:[" ","✨ ",s]})}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",disabled:!0,style:{width:"400px"}})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-2",children:s}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",style:{width:"400px"}})]}),(0,c.jsxs)("p",{style:{fontSize:"small",fontStyle:"italic"},children:["SMTP_HOST"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP host address, e.g. `smtp.resend.com`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PORT"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP port number, e.g. `587`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_USERNAME"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP username, e.g. `username`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PASSWORD"===s&&(0,c.jsx)("span",{style:{color:"red"},children:" Required * "}),"SMTP_SENDER_EMAIL"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the sender email address, e.g. `sender@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"TEST_EMAIL_ADDRESS"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Email Address to send `Test Email Alert` to. example: `info@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"EMAIL_LOGO_URL"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the Logo that appears in the email, pass a url to your logo"}),"EMAIL_SUPPORT_CONTACT"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the support email address that appears in the email. Default is support@berri.ai"})]})]},s)})})})},s)})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>G(),children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"email"),className:"mx-2",children:"Test Email Alerts"})]})})]})]})}),(0,c.jsxs)(M.Z,{title:"Add Logging Callback",visible:C,width:800,onCancel:()=>I(!1),footer:null,children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/logging",className:"mb-8 mt-4",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: Logging"}),(0,c.jsx)(L.Z,{form:h,onFinish:$,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(lU.Z,{label:"Callback",name:"callback",rules:[{required:!0,message:"Please select a callback"}],children:(0,c.jsx)(O.default,{onChange:e=>{let s=T[e];s&&(console.log(s.ui_callback_name),X(s))},children:T&&Object.values(T).map(e=>(0,c.jsx)(ee.Z,{value:e.litellm_callback_name,children:e.ui_callback_name},e.litellm_callback_name))})}),q&&q.map(e=>(0,c.jsx)(lU.Z,{label:e,name:e,rules:[{required:!0,message:"Please enter the value for "+e}],children:(0,c.jsx)(S.Z,{type:"password"})},e)),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]}),(0,c.jsx)(M.Z,{visible:z,width:800,title:"Edit ".concat(null==K?void 0:K.name," Settings"),onCancel:()=>V(!1),footer:null,children:(0,c.jsxs)(L.Z,{form:h,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(c.Fragment,{children:K&&K.variables&&Object.entries(K.variables).map(e=>{let[s,l]=e;return(0,c.jsx)(lU.Z,{label:s,name:s,children:(0,c.jsx)(S.Z,{type:"password",defaultValue:l})},s)})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]})):null},lB=l(92414),lH=l(46030);let{Option:lJ}=O.default;var lW=e=>{let{models:s,accessToken:l,routerSettings:t,setRouterSettings:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>i(!0),children:"+ Add Fallbacks"}),(0,c.jsx)(M.Z,{title:"Add Fallbacks",visible:n,width:800,footer:null,onOk:()=>{i(!1),r.resetFields()},onCancel:()=>{i(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:e=>{console.log(e);let{model_name:s,models:n}=e,o=[...t.fallbacks||[],{[s]:n}],c={...t,fallbacks:o};console.log(c);try{(0,y.K_)(l,{router_settings:c}),a(c)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully"),i(!1),r.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Public Model Name",name:"model_name",rules:[{required:!0,message:"Set the model to fallback for"}],help:"required",children:(0,c.jsx)(eD.Z,{defaultValue:o,children:s&&s.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>m(e),children:e},s))})}),(0,c.jsx)(L.Z.Item,{label:"Fallback Models",name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",children:(0,c.jsx)(lB.Z,{value:s,children:s&&s.filter(e=>e!=o).map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Fallbacks"})})]})})]})},lG=l(26433);async function lY(e,s){console.log=function(){},console.log("isLocal:",!1);let l=window.location.origin,t=new lG.ZP.OpenAI({apiKey:s,baseURL:l,dangerouslyAllowBrowser:!0});try{let s=await t.chat.completions.create({model:e,messages:[{role:"user",content:"Hi, this is a test message"}],mock_testing_fallbacks:!0});D.ZP.success((0,c.jsxs)("span",{children:["Test model=",(0,c.jsx)("strong",{children:e}),", received model=",(0,c.jsx)("strong",{children:s.model}),". See"," ",(0,c.jsx)("a",{href:"#",onClick:()=>window.open("https://docs.litellm.ai/docs/proxy/reliability","_blank"),style:{textDecoration:"underline",color:"blue"},children:"curl"})]}))}catch(e){D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20)}}let l$={ttl:3600,lowest_latency_buffer:0},lX=e=>{let{selectedStrategy:s,strategyArgs:l,paramExplanation:t}=e;return(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{className:"text-sm font-medium text-tremor-content-strong dark:text-dark-tremor-content-strong",children:"Routing Strategy Specific Args"}),(0,c.jsx)(I.Z,{children:"latency-based-routing"==s?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(l).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:t[s]})]}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]})}):(0,c.jsx)(A.Z,{children:"No specific settings"})})]})};var lQ=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)({}),[i,o]=(0,d.useState)({}),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(null),Z={routing_strategy_args:"(dict) Arguments to pass to the routing strategy",routing_strategy:"(string) Routing strategy to use",allowed_fails:"(int) Number of times a deployment can fail before being added to cooldown",cooldown_time:"(int) time in seconds to cooldown a deployment after failure",num_retries:"(int) Number of retries for failed requests. Defaults to 0.",timeout:"(float) Timeout for requests. Defaults to None.",retry_after:"(int) Minimum time to wait before retrying a failed request",ttl:"(int) Sliding window to look back over when calculating the average latency of a deployment. Default - 1 hour (in seconds).",lowest_latency_buffer:"(float) Shuffle between deployments within this % of the lowest latency. Default - 0 (i.e. always pick lowest latency)."};(0,d.useEffect)(()=>{s&&l&&t&&((0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e);let s=e.router_settings;"model_group_retry_policy"in s&&delete s.model_group_retry_policy,n(s)}),(0,y.YU)(s).then(e=>{u(e)}))},[s,l,t]);let C=async e=>{if(!s)return;console.log("received key: ".concat(e)),console.log("routerSettings['fallbacks']: ".concat(r.fallbacks));let l=r.fallbacks.map(s=>(e in s&&delete s[e],s)).filter(e=>Object.keys(e).length>0),t={...r,fallbacks:l};try{await (0,y.K_)(s,{router_settings:t}),n(t),D.ZP.success("Router settings updated successfully")}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}},I=(e,s)=>{u(m.map(l=>l.field_name===e?{...l,field_value:s}:l))},T=(e,l)=>{if(!s)return;let t=m[l].field_value;if(null!=t&&void 0!=t)try{(0,y.jA)(s,e,t);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:!0}:s);u(l)}catch(e){}},P=(e,l)=>{if(s)try{(0,y.ao)(s,e);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:null}:s);u(l)}catch(e){}},O=e=>{if(!s)return;console.log("router_settings",e);let l=Object.fromEntries(Object.entries(e).map(e=>{let[s,l]=e;if("routing_strategy_args"!==s&&"routing_strategy"!==s){var t;return[s,(null===(t=document.querySelector('input[name="'.concat(s,'"]')))||void 0===t?void 0:t.value)||l]}if("routing_strategy"==s)return[s,f];if("routing_strategy_args"==s&&"latency-based-routing"==f){let e={},s=document.querySelector('input[name="lowest_latency_buffer"]'),l=document.querySelector('input[name="ttl"]');return(null==s?void 0:s.value)&&(e.lowest_latency_buffer=Number(s.value)),(null==l?void 0:l.value)&&(e.ttl=Number(l.value)),console.log("setRoutingStrategyArgs: ".concat(e)),["routing_strategy_args",e]}return null}).filter(e=>null!=e));console.log("updatedVariables",l);try{(0,y.K_)(s,{router_settings:l})}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully")};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Loadbalancing"}),(0,c.jsx)(eR.Z,{value:"2",children:"Fallbacks"}),(0,c.jsx)(eR.Z,{value:"3",children:"General"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:[(0,c.jsx)(E.Z,{children:"Router Settings"}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(r).filter(e=>{let[s,l]=e;return"fallbacks"!=s&&"context_window_fallbacks"!=s&&"routing_strategy_args"!=s}).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:Z[s]})]}),(0,c.jsx)(eA.Z,{children:"routing_strategy"==s?(0,c.jsxs)(eD.Z,{defaultValue:l,className:"w-full max-w-md",onValueChange:_,children:[(0,c.jsx)(ee.Z,{value:"usage-based-routing",children:"usage-based-routing"}),(0,c.jsx)(ee.Z,{value:"latency-based-routing",children:"latency-based-routing"}),(0,c.jsx)(ee.Z,{value:"simple-shuffle",children:"simple-shuffle"})]}):(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]}),(0,c.jsx)(lX,{selectedStrategy:f,strategyArgs:r&&r.routing_strategy_args&&Object.keys(r.routing_strategy_args).length>0?r.routing_strategy_args:l$,paramExplanation:Z})]}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>O(r),children:"Save Changes"})})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Model Name"}),(0,c.jsx)(eP.Z,{children:"Fallbacks"})]})}),(0,c.jsx)(eT.Z,{children:r.fallbacks&&r.fallbacks.map((e,l)=>Object.entries(e).map(e=>{let[t,a]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:t}),(0,c.jsx)(eA.Z,{children:Array.isArray(a)?a.join(", "):a}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{onClick:()=>lY(t,s),children:"Test Fallback"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>C(t)})})]},l.toString()+t)}))})]}),(0,c.jsx)(lW,{models:(null==a?void 0:a.data)?a.data.map(e=>e.model_name):[],accessToken:s,routerSettings:r,setRouterSettings:n})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"}),(0,c.jsx)(eP.Z,{children:"Status"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:m.filter(e=>"TypedDictionary"!==e.field_type).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),(0,c.jsx)(eA.Z,{children:"Integer"==e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>I(e.field_name,s)}):null}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{onClick:()=>T(e.field_name,s),children:"Update"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>P(e.field_name,s),children:"Reset"})]})]},s))})]})})})]})]})}):null},l0=l(93142),l1=e=>{let{value:s={},onChange:l}=e,[t,a]=(0,d.useState)(Object.entries(s)),r=e=>{let s=t.filter((s,l)=>l!==e);a(s),null==l||l(Object.fromEntries(s))},n=(e,s,r)=>{let n=[...t];n[e]=[s,r],a(n),null==l||l(Object.fromEntries(n))};return(0,c.jsxs)("div",{children:[t.map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(l0.Z,{style:{display:"flex",marginBottom:8},align:"start",children:[(0,c.jsx)(S.Z,{placeholder:"Header Name",value:l,onChange:e=>n(s,e.target.value,t)}),(0,c.jsx)(S.Z,{placeholder:"Header Value",value:t,onChange:e=>n(s,l,e.target.value)}),(0,c.jsx)(sH.Z,{onClick:()=>r(s)})]},s)}),(0,c.jsx)(R.ZP,{type:"dashed",onClick:()=>{a([...t,["",""]])},icon:(0,c.jsx)(sJ.Z,{}),children:"Add Header"})]})};let{Option:l2}=O.default;var l4=e=>{let{accessToken:s,setPassThroughItems:l,passThroughItems:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>n(!0),children:"+ Add Pass-Through Endpoint"}),(0,c.jsx)(M.Z,{title:"Add Pass-Through Endpoint",visible:r,width:800,footer:null,onOk:()=>{n(!1),a.resetFields()},onCancel:()=>{n(!1),a.resetFields()},children:(0,c.jsxs)(L.Z,{form:a,onFinish:e=>{console.log(e);let r=[...t,{headers:e.headers,path:e.path,target:e.target}];try{(0,y.Vt)(s,e),l(r)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("Pass through endpoint successfully added"),n(!1),a.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Path",name:"path",rules:[{required:!0,message:"The route to be added to the LiteLLM Proxy Server."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Target",name:"target",rules:[{required:!0,message:"The URL to which requests for this path should be forwarded."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Headers",name:"headers",rules:[{required:!0,message:"Key-value pairs of headers to be forwarded with the request. You can set any key value pair here and it will be forwarded to your target endpoint"}],help:"required",children:(0,c.jsx)(l1,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Pass-Through Endpoint"})})]})})]})},l5=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&l&&t&&(0,y.mp)(s).then(e=>{n(e.endpoints)})},[s,l,t]);let i=(e,l)=>{if(s)try{(0,y.EG)(s,e);let l=r.filter(s=>s.path!==e);n(l),D.ZP.success("Endpoint deleted successfully.")}catch(e){}};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsx)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Path"}),(0,c.jsx)(eP.Z,{children:"Target"}),(0,c.jsx)(eP.Z,{children:"Headers"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:r.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.path})}),(0,c.jsx)(eA.Z,{children:e.target}),(0,c.jsx)(eA.Z,{children:JSON.stringify(e.headers)}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>i(e.path,s),children:"Reset"})})]},s))})]}),(0,c.jsx)(l4,{accessToken:s,setPassThroughItems:n,passThroughItems:r})]})})}):null},l3=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a}=e,[r]=L.Z.useForm(),n=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call");let s=await (0,y.Zr)(l,e);console.log("key create Response:",s),a(e=>e?[...e,s]:[s]),D.ZP.success("API Key Created"),r.resetFields()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Create Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),r.resetFields()},onCancel:()=>{t(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:n,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Budget"})})]})})},l6=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a,existingBudget:r,handleUpdateCall:n}=e;console.log("existingBudget",r);let[i]=L.Z.useForm();(0,d.useEffect)(()=>{i.setFieldsValue(r)},[r,i]);let o=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call"),t(!0);let s=await (0,y.qI)(l,e);a(e=>e?[...e,s]:[s]),D.ZP.success("Budget Updated"),i.resetFields(),n()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Edit Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),i.resetFields()},onCancel:()=>{t(!1),i.resetFields()},children:(0,c.jsxs)(L.Z,{form:i,onFinish:o,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:r,children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})},l8=l(17906),l7=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&(0,y.O3)(s).then(e=>{m(e)})},[s]);let u=async(e,l)=>{console.log("budget_id",e),null!=s&&(i(o.find(s=>s.budget_id===e)||null),r(!0))},h=async(e,l)=>{if(null==s)return;D.ZP.info("Request made"),await (0,y.NV)(s,e);let t=[...o];t.splice(l,1),m(t),D.ZP.success("Budget Deleted.")},x=async()=>{null!=s&&(0,y.O3)(s).then(e=>{m(e)})};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)(k.Z,{size:"sm",variant:"primary",className:"mb-2",onClick:()=>t(!0),children:"+ Create Budget"}),(0,c.jsx)(l3,{accessToken:s,isModalVisible:l,setIsModalVisible:t,setBudgetList:m}),n&&(0,c.jsx)(l6,{accessToken:s,isModalVisible:a,setIsModalVisible:r,setBudgetList:m,existingBudget:n,handleUpdateCall:x}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Create a budget to assign to customers."}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Budget ID"}),(0,c.jsx)(eP.Z,{children:"Max Budget"}),(0,c.jsx)(eP.Z,{children:"TPM"}),(0,c.jsx)(eP.Z,{children:"RPM"})]})}),(0,c.jsx)(eT.Z,{children:o.slice().sort((e,s)=>new Date(s.updated_at).getTime()-new Date(e.updated_at).getTime()).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.budget_id}),(0,c.jsx)(eA.Z,{children:e.max_budget?e.max_budget:"n/a"}),(0,c.jsx)(eA.Z,{children:e.tpm_limit?e.tpm_limit:"n/a"}),(0,c.jsx)(eA.Z,{children:e.rpm_limit?e.rpm_limit:"n/a"}),(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>u(e.budget_id,s)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>h(e.budget_id,s)})]},s))})]})]}),(0,c.jsxs)("div",{className:"mt-5",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"How to use budget id"}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Assign Budget to Customer"}),(0,c.jsx)(eR.Z,{children:"Test it (Curl)"}),(0,c.jsx)(eR.Z,{children:"Test it (OpenAI SDK)"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:"\ncurl -X POST --location '/end_user/new' \n-H 'Authorization: Bearer ' \n-H 'Content-Type: application/json' \n-d '{\"user_id\": \"my-customer-id', \"budget_id\": \"\"}' # \uD83D\uDC48 KEY CHANGE\n\n "})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:'\ncurl -X POST --location \'/chat/completions\' \n-H \'Authorization: Bearer \' \n-H \'Content-Type: application/json\' \n-d \'{\n "model": "gpt-3.5-turbo\', \n "messages":[{"role": "user", "content": "Hey, how\'s it going?"}],\n "user": "my-customer-id"\n}\' # \uD83D\uDC48 KEY CHANGE\n\n '})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'from openai import OpenAI\nclient = OpenAI(\n base_url="",\n api_key=""\n)\n\ncompletion = client.chat.completions.create(\n model="gpt-3.5-turbo",\n messages=[\n {"role": "system", "content": "You are a helpful assistant."},\n {"role": "user", "content": "Hello!"}\n ],\n user="my-customer-id"\n)\n\nprint(completion.choices[0].message)'})})]})]})]})]})},l9=l(77398),te=l.n(l9);async function ts(e){try{let s=await fetch("http://ip-api.com/json/".concat(e)),l=await s.json();console.log("ip lookup data",l);let t=l.countryCode?l.countryCode.toUpperCase().split("").map(e=>String.fromCodePoint(e.charCodeAt(0)+127397)).join(""):"";return l.country?"".concat(t," ").concat(l.country):"Unknown"}catch(e){return console.error("Error looking up IP:",e),"Unknown"}}let tl=e=>{let{ipAddress:s}=e,[l,t]=d.useState("-");return d.useEffect(()=>{if(!s)return;let e=!0;return ts(s).then(s=>{e&&t(s)}).catch(()=>{e&&t("-")}),()=>{e=!1}},[s]),(0,c.jsx)("span",{children:l})},tt=e=>{try{return new Date(e).toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0}).replace(",","")}catch(e){return"Error converting time"}},ta=e=>{let{utcTime:s}=e;return(0,c.jsx)("span",{style:{fontFamily:"monospace",width:"180px",display:"inline-block"},children:tt(s)})},tr=(e,s)=>{var l,t;return(null===(t=e.metadata)||void 0===t?void 0:null===(l=t.mcp_tool_call_metadata)||void 0===l?void 0:l.mcp_server_logo_url)?e.metadata.mcp_tool_call_metadata.mcp_server_logo_url:s?sn(s).logo:""},tn=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return(0,c.jsx)(()=>{let[e,l]=d.useState(s.getIsExpanded()),t=d.useCallback(()=>{l(e=>!e),s.getToggleExpandedHandler()()},[s]);return s.getCanExpand()?(0,c.jsx)("button",{onClick:t,style:{cursor:"pointer"},"aria-label":e?"Collapse row":"Expand row",className:"w-6 h-6 flex items-center justify-center focus:outline-none",children:(0,c.jsx)("svg",{className:"w-4 h-4 transform transition-transform duration-75 ".concat(e?"rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}):(0,c.jsx)("span",{className:"w-6 h-6 flex items-center justify-center",children:"●"})},{})}},{header:"Time",accessorKey:"startTime",cell:e=>(0,c.jsx)(ta,{utcTime:e.getValue()})},{header:"Status",accessorKey:"metadata.status",cell:e=>{let s="failure"!==(e.getValue()||"Success").toLowerCase();return(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat(s?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:s?"Success":"Failure"})}},{header:"Request ID",accessorKey:"request_id",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||""),children:(0,c.jsx)("span",{className:"font-mono text-xs max-w-[15ch] truncate block",children:String(e.getValue()||"")})})},{header:"Cost",accessorKey:"spend",cell:e=>(0,c.jsxs)("span",{children:["$",Number(e.getValue()||0).toFixed(6)]})},{header:"Country",accessorKey:"requester_ip_address",cell:e=>(0,c.jsx)(tl,{ipAddress:e.getValue()})},{header:"Team Name",accessorKey:"metadata.user_api_key_team_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Key Hash",accessorKey:"metadata.user_api_key",cell:e=>{let s=String(e.getValue()||"-"),l=e.row.original.onKeyHashClick;return(0,c.jsx)(W.Z,{title:s,children:(0,c.jsx)("span",{className:"font-mono max-w-[15ch] truncate block cursor-pointer hover:text-blue-600",onClick:()=>null==l?void 0:l(s),children:s})})}},{header:"Key Name",accessorKey:"metadata.user_api_key_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Model",accessorKey:"model",cell:e=>{let s=e.row.original,l=s.custom_llm_provider,t=String(e.getValue()||"");return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l&&(0,c.jsx)("img",{src:tr(s,l),alt:"",className:"w-4 h-4",onError:e=>{e.target.style.display="none"}}),(0,c.jsx)(W.Z,{title:t,children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:t})})]})}},{header:"Tokens",accessorKey:"total_tokens",cell:e=>{let s=e.row.original;return(0,c.jsxs)("span",{className:"text-sm",children:[String(s.total_tokens||"0"),(0,c.jsxs)("span",{className:"text-gray-400 text-xs ml-1",children:["(",String(s.prompt_tokens||"0"),"+",String(s.completion_tokens||"0"),")"]})]})}},{header:"Internal User",accessorKey:"user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"End User",accessorKey:"end_user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Tags",accessorKey:"request_tags",cell:e=>{let s=e.getValue();if(!s||0===Object.keys(s).length)return"-";let l=Object.entries(s),t=l[0],a=l.slice(1);return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:(0,c.jsx)(W.Z,{title:(0,c.jsx)("div",{className:"flex flex-col gap-1",children:l.map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{children:[s,": ",String(l)]},s)})}),children:(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[t[0],": ",String(t[1]),a.length>0&&" +".concat(a.length)]})})})}}],ti=async(e,s,l,t)=>{console.log("prefetchLogDetails called with",e.length,"logs");let a=e.map(e=>{if(e.request_id)return console.log("Prefetching details for request_id:",e.request_id),t.prefetchQuery({queryKey:["logDetails",e.request_id,s],queryFn:async()=>{console.log("Fetching details for",e.request_id);let t=await (0,y.qk)(l,e.request_id,s);return console.log("Received details for",e.request_id,":",t?"success":"failed"),t},staleTime:6e5,gcTime:6e5})});try{let e=await Promise.all(a);return console.log("All prefetch promises completed:",e.length),e}catch(e){throw console.error("Error in prefetchLogDetails:",e),e}},to=e=>{var s;let{errorInfo:l}=e,[t,a]=d.useState({}),[r,n]=d.useState(!1),i=e=>{a(s=>({...s,[e]:!s[e]}))},o=l.traceback&&(s=l.traceback)?Array.from(s.matchAll(/File "([^"]+)", line (\d+)/g)).map(e=>{let l=e[1],t=e[2],a=l.split("/").pop()||l,r=e.index||0,n=s.indexOf('File "',r+1),i=n>-1?s.substring(r,n).trim():s.substring(r).trim(),o=i.split("\n"),c="";return o.length>1&&(c=o[o.length-1].trim()),{filePath:l,fileName:a,lineNumber:t,code:c,inFunction:i.includes(" in ")?i.split(" in ")[1].split("\n")[0]:""}}):[];return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsxs)("h3",{className:"text-lg font-medium flex items-center text-red-600",children:[(0,c.jsx)("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),"Error Details"]})}),(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"bg-red-50 rounded-md p-4 mb-4",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Type:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_class||"Unknown Error"})]}),(0,c.jsxs)("div",{className:"flex mt-2",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Message:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_message||"Unknown error occurred"})]})]}),l.traceback&&(0,c.jsxs)("div",{className:"mt-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-2",children:[(0,c.jsx)("h4",{className:"font-medium",children:"Traceback"}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsx)("button",{onClick:()=>{let e=!r;if(n(e),o.length>0){let s={};o.forEach((l,t)=>{s[t]=e}),a(s)}},className:"text-gray-500 hover:text-gray-700 flex items-center text-sm",children:r?"Collapse All":"Expand All"}),(0,c.jsxs)("button",{onClick:()=>navigator.clipboard.writeText(l.traceback||""),className:"text-gray-500 hover:text-gray-700 flex items-center",title:"Copy traceback",children:[(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,c.jsx)("span",{className:"ml-1",children:"Copy"})]})]})]}),(0,c.jsx)("div",{className:"bg-white rounded-md border border-gray-200 overflow-hidden shadow-sm",children:o.map((e,s)=>(0,c.jsxs)("div",{className:"border-b border-gray-200 last:border-b-0",children:[(0,c.jsxs)("div",{className:"px-4 py-2 flex items-center justify-between cursor-pointer hover:bg-gray-50",onClick:()=>i(s),children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-gray-400 mr-2 w-12 text-right",children:e.lineNumber}),(0,c.jsx)("span",{className:"text-gray-600 font-medium",children:e.fileName}),(0,c.jsx)("span",{className:"text-gray-500 mx-1",children:"in"}),(0,c.jsx)("span",{className:"text-indigo-600 font-medium",children:e.inFunction||e.fileName})]}),(0,c.jsx)("svg",{className:"w-5 h-5 text-gray-500 transition-transform ".concat(t[s]?"transform rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),(t[s]||!1)&&e.code&&(0,c.jsx)("div",{className:"px-12 py-2 font-mono text-sm text-gray-800 bg-gray-50 overflow-x-auto border-t border-gray-100",children:e.code})]},s))})]})]})]})},tc=e=>{let{show:s}=e;return s?(0,c.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start",children:[(0,c.jsx)("div",{className:"text-blue-500 mr-3 flex-shrink-0 mt-0.5",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,c.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,c.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}),(0,c.jsxs)("div",{children:[(0,c.jsx)("h4",{className:"text-sm font-medium text-blue-800",children:"Request/Response Data Not Available"}),(0,c.jsxs)("p",{className:"text-sm text-blue-700 mt-1",children:["To view request and response details, enable prompt storage in your LiteLLM configuration by adding the following to your ",(0,c.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded",children:"proxy_config.yaml"})," file:"]}),(0,c.jsx)("pre",{className:"mt-2 bg-white p-3 rounded border border-blue-200 text-xs font-mono overflow-auto",children:"general_settings:\n store_model_in_db: true\n store_prompts_in_spend_logs: true"}),(0,c.jsx)("p",{className:"text-xs text-blue-700 mt-2",children:"Note: This will only affect new requests after the configuration change."})]})]}):null};function td(e){var s,l,t,a;let{accessToken:r,token:n,userRole:i,userID:o,allTeams:m}=e,[u,h]=(0,d.useState)(""),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(1),[b]=(0,d.useState)(50),Z=(0,d.useRef)(null),N=(0,d.useRef)(null),w=(0,d.useRef)(null),[k,S]=(0,d.useState)(te()().subtract(24,"hours").format("YYYY-MM-DDTHH:mm")),[C,I]=(0,d.useState)(te()().format("YYYY-MM-DDTHH:mm")),[T,A]=(0,d.useState)(!1),[E,P]=(0,d.useState)(!1),[O,L]=(0,d.useState)(""),[D,M]=(0,d.useState)(""),[F,R]=(0,d.useState)(""),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(null),[K,B]=(0,d.useState)(null),[H,J]=(0,d.useState)("Team ID"),[W,G]=(0,d.useState)(i&&eg.lo.includes(i)),[Y,$]=(0,d.useState)(null),X=(0,x.NL)();(0,d.useEffect)(()=>{(async()=>{if(K&&r){let e=await (0,y.t0)(r,K);console.log("keyData",e),V({...e.info,token:K,api_key:K})}})()},[K,r]),(0,d.useEffect)(()=>{function e(e){Z.current&&!Z.current.contains(e.target)&&f(!1),N.current&&!N.current.contains(e.target)&&g(!1),w.current&&!w.current.contains(e.target)&&P(!1)}return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{i&&eg.lo.includes(i)&&G(!0)},[i]);let Q=(0,e4.a)({queryKey:["logs","table",_,b,k,C,F,q,W?o:null],queryFn:async()=>{if(!r||!n||!i||!o)return console.log("Missing required auth parameters"),{data:[],total:0,page:1,page_size:b,total_pages:0};let e=te()(k).utc().format("YYYY-MM-DD HH:mm:ss"),s=T?te()(C).utc().format("YYYY-MM-DD HH:mm:ss"):te()().utc().format("YYYY-MM-DD HH:mm:ss"),l=await (0,y.h3)(r,q||void 0,F||void 0,void 0,e,s,_,b,W?o:void 0);return await ti(l.data,e,r,X),l.data=l.data.map(s=>{let l=X.getQueryData(["logDetails",s.request_id,e]);return(null==l?void 0:l.messages)&&(null==l?void 0:l.response)&&(s.messages=l.messages,s.response=l.response),s}),l},enabled:!!r&&!!n&&!!i&&!!o,refetchInterval:5e3,refetchIntervalInBackground:!0});if((0,d.useEffect)(()=>{var e;(null===(e=Q.data)||void 0===e?void 0:e.data)&&Y&&!Q.data.data.some(e=>e.request_id===Y)&&$(null)},[null===(s=Q.data)||void 0===s?void 0:s.data,Y]),!r||!n||!i||!o)return console.log("got None values for one of accessToken, token, userRole, userID"),null;let ee=(null===(t=Q.data)||void 0===t?void 0:null===(l=t.data)||void 0===l?void 0:l.filter(e=>!u||e.request_id.includes(u)||e.model.includes(u)||e.user&&e.user.includes(u)).map(e=>({...e,onKeyHashClick:e=>B(e)})))||[],es=()=>{if(T)return"".concat(te()(k).format("MMM D, h:mm A")," - ").concat(te()(C).format("MMM D, h:mm A"));let e=te()(),s=te()(k),l=e.diff(s,"minutes");if(l<=15)return"Last 15 Minutes";if(l<=60)return"Last Hour";let t=e.diff(s,"hours");return t<=4?"Last 4 Hours":t<=24?"Last 24 Hours":t<=168?"Last 7 Days":"".concat(s.format("MMM D")," - ").concat(e.format("MMM D"))};return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Request Logs"})}),z&&K&&z.api_key===K?(0,c.jsx)(eG,{keyId:K,keyData:z,accessToken:r,userID:o,userRole:i,teams:m,onClose:()=>B(null)}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between space-y-4 md:space-y-0",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by Request ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:u,onChange:e=>h(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"relative",ref:N,children:[(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>g(!p),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filter"]}),p&&(0,c.jsx)("div",{className:"absolute left-0 mt-2 w-[500px] bg-white rounded-lg shadow-lg border p-4 z-50",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsxs)("div",{className:"relative",children:[(0,c.jsxs)("button",{onClick:()=>f(!j),className:"px-3 py-1.5 border rounded-md bg-white text-sm min-w-[160px] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-left flex justify-between items-center",children:[H,(0,c.jsx)("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),j&&(0,c.jsx)("div",{className:"absolute left-0 mt-1 w-[160px] bg-white border rounded-md shadow-lg z-50",children:["Team ID","Key Hash"].map(e=>(0,c.jsxs)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2 ".concat(H===e?"bg-blue-50 text-blue-600":""),onClick:()=>{J(e),f(!1),"Team ID"===e?M(""):L("")},children:[H===e&&(0,c.jsx)("svg",{className:"h-4 w-4 text-blue-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e]},e))})]}),(0,c.jsx)("input",{type:"text",placeholder:"Enter value...",className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:"Team ID"===H?O:D,onChange:e=>{"Team ID"===H?L(e.target.value):M(e.target.value)}}),(0,c.jsx)("button",{className:"p-1 hover:bg-gray-100 rounded-md",onClick:()=>{L(""),M("")},children:(0,c.jsx)("span",{className:"text-gray-500",children:"\xd7"})})]}),(0,c.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm border rounded-md hover:bg-gray-50",onClick:()=>{L(""),M(""),g(!1)},children:"Cancel"}),(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{R(O),U(D),v(1),g(!1)},children:"Apply Filters"})]})]})})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsxs)("div",{className:"relative",ref:w,children:[(0,c.jsxs)("button",{onClick:()=>P(!E),className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"})}),es()]}),E&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border p-2 z-50",children:(0,c.jsxs)("div",{className:"space-y-1",children:[[{label:"Last 15 Minutes",value:15,unit:"minutes"},{label:"Last Hour",value:1,unit:"hours"},{label:"Last 4 Hours",value:4,unit:"hours"},{label:"Last 24 Hours",value:24,unit:"hours"},{label:"Last 7 Days",value:7,unit:"days"}].map(e=>(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(es()===e.label?"bg-blue-50 text-blue-600":""),onClick:()=>{I(te()().format("YYYY-MM-DDTHH:mm")),S(te()().subtract(e.value,e.unit).format("YYYY-MM-DDTHH:mm")),P(!1),A(!1)},children:e.label},e.label)),(0,c.jsx)("div",{className:"border-t my-2"}),(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(T?"bg-blue-50 text-blue-600":""),onClick:()=>A(!T),children:"Custom Range"})]})})]}),(0,c.jsxs)("button",{onClick:()=>{Q.refetch()},className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",title:"Refresh data",children:[(0,c.jsx)("svg",{className:"w-4 h-4 ".concat(Q.isFetching?"animate-spin":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),(0,c.jsx)("span",{children:"Refresh"})]})]}),T&&(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:k,onChange:e=>{S(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})}),(0,c.jsx)("span",{className:"text-gray-500",children:"to"}),(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:C,onChange:e=>{I(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})})]})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",Q.isLoading?"...":Q.data?(_-1)*b+1:0," ","-"," ",Q.isLoading?"...":Q.data?Math.min(_*b,Q.data.total):0," ","of"," ",Q.isLoading?"...":Q.data?Q.data.total:0," ","results"]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",Q.isLoading?"...":_," of"," ",Q.isLoading?"...":Q.data?Q.data.total_pages:1]}),(0,c.jsx)("button",{onClick:()=>v(e=>Math.max(1,e-1)),disabled:Q.isLoading||1===_,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>v(e=>{var s;return Math.min((null===(s=Q.data)||void 0===s?void 0:s.total_pages)||1,e+1)}),disabled:Q.isLoading||_===((null===(a=Q.data)||void 0===a?void 0:a.total_pages)||1),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})}),(0,c.jsx)(eL,{columns:tn,data:ee,renderSubComponent:tm,getRowCanExpand:()=>!0,onRowExpand:e=>{$(e)},expandedRequestId:Y})]})})]})}function tm(e){var s,l,t,a,r,n;let{row:i}=e,o=e=>{let s={...e};return"proxy_server_request"in s&&delete s.proxy_server_request,s},d=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},m=()=>{var e;return(null===(e=i.original.metadata)||void 0===e?void 0:e.proxy_server_request)?d(i.original.metadata.proxy_server_request):d(i.original.messages)},u=(null===(s=i.original.metadata)||void 0===s?void 0:s.status)==="failure",h=u?null===(l=i.original.metadata)||void 0===l?void 0:l.error_information:null,x=i.original.messages&&(Array.isArray(i.original.messages)?i.original.messages.length>0:Object.keys(i.original.messages).length>0),p=i.original.response&&Object.keys(d(i.original.response)).length>0,g=()=>u&&h?{error:{message:h.error_message||"An error occurred",type:h.error_class||"error",code:h.error_code||"unknown",param:null}}:d(i.original.response);return(0,c.jsxs)("div",{className:"p-6 bg-gray-50 space-y-6",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Details"})}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4 p-4",children:[(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Request ID:"}),(0,c.jsx)("span",{className:"font-mono text-sm",children:i.original.request_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model:"}),(0,c.jsx)("span",{children:i.original.model})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model ID:"}),(0,c.jsx)("span",{children:i.original.model_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Provider:"}),(0,c.jsx)("span",{children:i.original.custom_llm_provider||"-"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"API Base:"}),(0,c.jsx)(W.Z,{title:i.original.api_base||"-",children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:i.original.api_base||"-"})})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Start Time:"}),(0,c.jsx)("span",{children:i.original.startTime})]})]}),(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Tokens:"}),(0,c.jsxs)("span",{children:[i.original.total_tokens," (",i.original.prompt_tokens,"+",i.original.completion_tokens,")"]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cost:"}),(0,c.jsxs)("span",{children:["$",Number(i.original.spend||0).toFixed(6)]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cache Hit:"}),(0,c.jsx)("span",{children:i.original.cache_hit})]}),(null==i?void 0:null===(t=i.original)||void 0===t?void 0:t.requester_ip_address)&&(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"IP Address:"}),(0,c.jsx)("span",{children:null==i?void 0:null===(a=i.original)||void 0===a?void 0:a.requester_ip_address})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Status:"}),(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat("failure"!==((null===(r=i.original.metadata)||void 0===r?void 0:r.status)||"Success").toLowerCase()?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:"failure"!==((null===(n=i.original.metadata)||void 0===n?void 0:n.status)||"Success").toLowerCase()?"Success":"Failure"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"End Time:"}),(0,c.jsx)("span",{children:i.original.endTime})]})]})]})]}),(0,c.jsx)(tc,{show:!x&&!p}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request"}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(m(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy request",disabled:!x,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(m(),null,2)})})]}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsxs)("h3",{className:"text-lg font-medium",children:["Response",u&&(0,c.jsxs)("span",{className:"ml-2 text-sm text-red-600",children:["• HTTP code ",(null==h?void 0:h.error_code)||400]})]}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(g(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy response",disabled:!p,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96 bg-gray-50",children:p?(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(g(),null,2)}):(0,c.jsx)("div",{className:"text-gray-500 text-sm italic text-center py-4",children:"Response data not available"})})]})]}),u&&h&&(0,c.jsx)(to,{errorInfo:h}),i.original.request_tags&&Object.keys(i.original.request_tags).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"flex justify-between items-center p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Tags"})}),(0,c.jsx)("div",{className:"p-4",children:(0,c.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(i.original.request_tags).map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[s,": ",String(l)]},s)})})})]}),i.original.metadata&&Object.keys(i.original.metadata).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Metadata"}),(0,c.jsx)("button",{onClick:()=>{let e=o(i.original.metadata);navigator.clipboard.writeText(JSON.stringify(e,null,2))},className:"p-1 hover:bg-gray-200 rounded",title:"Copy metadata",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-64",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(o(i.original.metadata),null,2)})})]})]})}var tu=l(92699),th=l(14042);console.log=function(){};var tx=e=>{let{userID:s,userRole:l,accessToken:t,userSpend:a,userMaxBudget:r,selectedTeam:n}=e;console.log("userSpend: ".concat(a));let[i,o]=(0,d.useState)(null!==a?a:0),[m,u]=(0,d.useState)(n?n.max_budget:null);(0,d.useEffect)(()=>{if(n){if("Default Team"===n.team_alias)u(r);else{let e=!1;if(n.team_memberships)for(let l of n.team_memberships)l.user_id===s&&"max_budget"in l.litellm_budget_table&&null!==l.litellm_budget_table.max_budget&&(u(l.litellm_budget_table.max_budget),e=!0);e||u(n.max_budget)}}},[n,r]);let[h,x]=(0,d.useState)([]);(0,d.useEffect)(()=>{let e=async()=>{if(!t||!s||!l)return};(async()=>{try{if(null===s||null===l)return;if(null!==t){let e=(await (0,y.So)(t,s,l)).data.map(e=>e.id);console.log("available_model_names:",e),x(e)}}catch(e){console.error("Error fetching user models:",e)}})(),e()},[l,t,s]),(0,d.useEffect)(()=>{null!==a&&o(a)},[a]);let p=[];n&&n.models&&(p=n.models),p&&p.includes("all-proxy-models")?(console.log("user models:",h),p=h):p&&p.includes("all-team-models")?p=n.models:p&&0===p.length&&(p=h);let g=void 0!==i?i.toFixed(4):null;return console.log("spend in view user spend: ".concat(i)),(0,c.jsx)("div",{className:"flex items-center",children:(0,c.jsxs)("div",{className:"flex justify-between gap-x-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Total Spend"}),(0,c.jsxs)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:["$",g]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Max Budget"}),(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:null!==m?"$".concat(m," limit"):"No limit"})]})]})})};let tp=e=>{let{key:s,info:l}=e;return{token:s,...l}};var tg=e=>{let{topKeys:s,accessToken:l,userID:t,userRole:a,teams:r}=e,[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(void 0),[x,p]=(0,d.useState)("table"),g=async e=>{if(l)try{let s=await (0,y.t0)(l,e.api_key),t=tp(s);h(t),m(e.api_key),i(!0)}catch(e){console.error("Error fetching key info:",e)}},j=()=>{i(!1),m(null),h(void 0)};return d.useEffect(()=>{let e=e=>{"Escape"===e.key&&n&&j()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[n]),(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{className:"mb-4 flex justify-end items-center",children:(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>p("table"),className:"px-3 py-1 text-sm rounded-md ".concat("table"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Table View"}),(0,c.jsx)("button",{onClick:()=>p("chart"),className:"px-3 py-1 text-sm rounded-md ".concat("chart"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Chart View"})]})}),"chart"===x?(0,c.jsx)("div",{className:"relative",children:(0,c.jsx)(sw.Z,{className:"mt-4 h-40 cursor-pointer hover:opacity-90",data:s,index:"key_alias",categories:["spend"],colors:["cyan"],yAxisWidth:80,tickGap:5,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>e?"$".concat(e.toFixed(2)):"No Key Alias",onValueChange:e=>g(e),showTooltip:!0,customTooltip:e=>{var s,l,t;let a=null===(l=e.payload)||void 0===l?void 0:null===(s=l[0])||void 0===s?void 0:s.payload;return(0,c.jsx)("div",{className:"p-3 bg-black/90 shadow-lg rounded-lg text-white",children:(0,c.jsxs)("div",{className:"space-y-1.5",children:[(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Key: "}),(0,c.jsxs)("span",{className:"font-mono text-gray-100",children:[null==a?void 0:null===(t=a.api_key)||void 0===t?void 0:t.slice(0,10),"..."]})]}),(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Spend: "}),(0,c.jsxs)("span",{className:"text-white font-medium",children:["$",null==a?void 0:a.spend.toFixed(2)]})]})]})})}})}):(0,c.jsx)("div",{className:"border rounded-lg overflow-hidden",children:(0,c.jsx)(eL,{columns:[{header:"Key ID",accessorKey:"api_key",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>g(e.row.original),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>e.getValue()||"-"},{header:"Spend (USD)",accessorKey:"spend",cell:e=>"$".concat(Number(e.getValue()).toFixed(2))}],data:s,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{}),getRowCanExpand:()=>!1,isLoading:!1})}),n&&o&&u&&(console.log("Rendering modal with:",{isModalOpen:n,selectedKey:o,keyData:u}),(0,c.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e=>{e.target===e.currentTarget&&j()},children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-xl relative w-11/12 max-w-6xl max-h-[90vh] overflow-y-auto min-h-[750px]",children:[(0,c.jsx)("button",{onClick:j,className:"absolute top-4 right-4 text-gray-500 hover:text-gray-700 focus:outline-none","aria-label":"Close",children:(0,c.jsx)("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})}),(0,c.jsx)("div",{className:"p-6 h-full",children:(0,c.jsx)(eG,{keyId:o,onClose:j,keyData:u,accessToken:l,userID:t,userRole:a,teams:r})})]})}))]})},tj=l(44851);let tf=e=>{var s,l;let{modelName:t,metrics:a}=e;return(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:a.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:a.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:a.total_tokens.toLocaleString()}),(0,c.jsxs)(A.Z,{children:[Math.round(a.total_tokens/a.total_successful_requests)," avg per successful request"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",a.total_spend.toFixed(2)]}),(0,c.jsxs)(A.Z,{children:["$",(a.total_spend/a.total_successful_requests).toFixed(3)," per successful request"]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Requests per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.api_requests"],colors:["blue"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.spend"],colors:["green"],valueFormatter:e=>"$".concat(e.toFixed(2))})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Success vs Failed Requests"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Prompt Caching Metrics"}),(0,c.jsxs)("div",{className:"mb-2",children:[(0,c.jsxs)(A.Z,{children:["Cache Read: ",(null===(s=a.total_cache_read_input_tokens)||void 0===s?void 0:s.toLocaleString())||0," tokens"]}),(0,c.jsxs)(A.Z,{children:["Cache Creation: ",(null===(l=a.total_cache_creation_input_tokens)||void 0===l?void 0:l.toLocaleString())||0," tokens"]})]}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.cache_read_input_tokens","metrics.cache_creation_input_tokens"],colors:["cyan","purple"],valueFormatter:e=>e.toLocaleString()})]})]})]})},t_=e=>{let{modelMetrics:s}=e,l=Object.keys(s).sort((e,l)=>""===e?1:""===l?-1:s[l].total_spend-s[e].total_spend),t={total_requests:0,total_successful_requests:0,total_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:{}};Object.values(s).forEach(e=>{t.total_requests+=e.total_requests,t.total_successful_requests+=e.total_successful_requests,t.total_tokens+=e.total_tokens,t.total_spend+=e.total_spend,t.total_cache_read_input_tokens+=e.total_cache_read_input_tokens||0,t.total_cache_creation_input_tokens+=e.total_cache_creation_input_tokens||0,e.daily_data.forEach(e=>{t.daily_data[e.date]||(t.daily_data[e.date]={prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,spend:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),t.daily_data[e.date].prompt_tokens+=e.metrics.prompt_tokens,t.daily_data[e.date].completion_tokens+=e.metrics.completion_tokens,t.daily_data[e.date].total_tokens+=e.metrics.total_tokens,t.daily_data[e.date].api_requests+=e.metrics.api_requests,t.daily_data[e.date].spend+=e.metrics.spend,t.daily_data[e.date].successful_requests+=e.metrics.successful_requests,t.daily_data[e.date].failed_requests+=e.metrics.failed_requests,t.daily_data[e.date].cache_read_input_tokens+=e.metrics.cache_read_input_tokens||0,t.daily_data[e.date].cache_creation_input_tokens+=e.metrics.cache_creation_input_tokens||0})});let a=Object.entries(t.daily_data).map(e=>{let[s,l]=e;return{date:s,metrics:l}}).sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime());return(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{className:"border rounded-lg p-4",children:[(0,c.jsx)(E.Z,{children:"Overall Usage"}),(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4 mb-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:t.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:t.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:t.total_tokens.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",t.total_spend.toFixed(2)]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]})]})]}),(0,c.jsx)(tj.Z,{defaultActiveKey:l[0],children:l.map(e=>(0,c.jsx)(tj.Z.Panel,{header:(0,c.jsxs)("div",{className:"flex justify-between items-center w-full",children:[(0,c.jsx)(E.Z,{children:s[e].label||"Unknown Item"}),(0,c.jsxs)("div",{className:"flex space-x-4 text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["$",s[e].total_spend.toFixed(2)]}),(0,c.jsxs)("span",{children:[s[e].total_requests.toLocaleString()," requests"]})]})]}),children:(0,c.jsx)(tf,{modelName:e||"Unknown Model",metrics:s[e]})},e))})]})},ty=(e,s)=>{let l=e.metadata.key_alias||"key-hash-".concat(s),t=e.metadata.team_id;return t?"".concat(l," (team_id: ").concat(t,")"):l},tv=(e,s)=>{let l={};return e.results.forEach(e=>{Object.entries(e.breakdown[s]||{}).forEach(t=>{let[a,r]=t;l[a]||(l[a]={label:"api_keys"===s?ty(r,a):a,total_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0,prompt_tokens:0,completion_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:[]}),l[a].total_requests+=r.metrics.api_requests,l[a].prompt_tokens+=r.metrics.prompt_tokens,l[a].completion_tokens+=r.metrics.completion_tokens,l[a].total_tokens+=r.metrics.total_tokens,l[a].total_spend+=r.metrics.spend,l[a].total_successful_requests+=r.metrics.successful_requests,l[a].total_failed_requests+=r.metrics.failed_requests,l[a].total_cache_read_input_tokens+=r.metrics.cache_read_input_tokens||0,l[a].total_cache_creation_input_tokens+=r.metrics.cache_creation_input_tokens||0,l[a].daily_data.push({date:e.date,metrics:{prompt_tokens:r.metrics.prompt_tokens,completion_tokens:r.metrics.completion_tokens,total_tokens:r.metrics.total_tokens,api_requests:r.metrics.api_requests,spend:r.metrics.spend,successful_requests:r.metrics.successful_requests,failed_requests:r.metrics.failed_requests,cache_read_input_tokens:r.metrics.cache_read_input_tokens||0,cache_creation_input_tokens:r.metrics.cache_creation_input_tokens||0}})})}),Object.values(l).forEach(e=>{e.daily_data.sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime())}),l};var tb=e=>{let{accessToken:s,entityType:l,entityId:t,userID:a,userRole:r,entityList:n}=e,[i,o]=(0,d.useState)({results:[],metadata:{total_spend:0,total_api_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0}}),m=tv(i,"models"),u=tv(i,"api_keys"),[h,x]=(0,d.useState)([]),[p,g]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),j=async()=>{if(!s||!p.from||!p.to)return;let e=p.from,t=p.to;if("tag"===l)o(await (0,y.Z9)(s,e,t,1,h.length>0?h:null));else if("team"===l)o(await (0,y.ol)(s,e,t,1,h.length>0?h:null));else throw Error("Invalid entity type")};(0,d.useEffect)(()=>{j()},[s,p,t,h]);let f=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={provider:l,spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend,e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens}catch(e){console.log("Error processing provider ".concat(l,": ").concat(e))}})}),Object.values(e).filter(e=>e.spend>0).sort((e,s)=>s.spend-e.spend)},_=e=>0===h.length?e:e.filter(e=>h.includes(e.metadata.id)),v=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.entities||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{alias:t.metadata.team_alias||l,id:l}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.total_tokens+=t.metrics.total_tokens})}),_(Object.values(e).sort((e,s)=>s.metrics.spend-e.metrics.spend))};return(0,c.jsxs)("div",{style:{width:"100%"},children:[(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:p,onValueChange:g})]}),n&&n.length>0&&(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(A.Z,{children:["Filter by ","tag"===l?"Tags":"Teams"]}),(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},placeholder:"Select ".concat("tag"===l?"tags":"teams"," to filter..."),value:h,onChange:x,options:(()=>{if(n)return n})(),className:"mt-2",allowClear:!0})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["tag"===l?"Tag":"Team"," Spend Overview"]}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Spend"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",i.metadata.total_spend.toFixed(2)]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_api_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:i.metadata.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:i.metadata.total_failed_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_tokens.toLocaleString()})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...i.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:t}=e;if(!t||!(null==s?void 0:s[0]))return null;let a=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:a.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Total Spend: $",a.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",a.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",a.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",a.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Tokens: ",a.metrics.total_tokens]}),(0,c.jsxs)("div",{className:"mt-2 border-t pt-2",children:[(0,c.jsxs)("p",{className:"font-semibold",children:["Spend by ","tag"===l?"Tag":"Team",":"]}),Object.entries(a.breakdown.entities||{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[l.metadata.team_alias||s,": $",l.metrics.spend.toFixed(2)]},s)})]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-col space-y-2",children:[(0,c.jsxs)(E.Z,{children:["Spend Per ","tag"===l?"Tag":"Team"]}),(0,c.jsxs)("div",{className:"flex items-center text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["Get Started Tracking cost per ",l," "]}),(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tags",className:"text-blue-500 hover:text-blue-700 ml-1",children:"here"})]})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sw.Z,{className:"mt-4 h-52",data:v(),index:"metadata.alias",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(4)),layout:"vertical",showLegend:!1,yAxisWidth:100})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"tag"===l?"Tag":"Team"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:v().filter(e=>e.metrics.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.metadata.alias}),(0,c.jsxs)(eA.Z,{children:["$",e.metrics.spend.toFixed(4)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.metrics.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.metrics.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.metrics.total_tokens.toLocaleString()})]},e.metadata.id))})]})})]})]})})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:s,userID:a,userRole:r,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend}catch(e){console.log("Error adding spend for ".concat(l,": ").concat(e,", got metrics: ").concat(JSON.stringify(t)))}e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,...l}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsx)(E.Z,{children:"Provider Usage"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:f(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan","blue","indigo","violet","purple"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:f().map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:m})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:u})})]})]})]})},tZ=e=>{var s,l,t,a,r,n,i,o,m,u;let{accessToken:h,userRole:x,userID:p,teams:g}=e,[j,f]=(0,d.useState)({results:[],metadata:{}}),[_,v]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),[b,Z]=(0,d.useState)([]),k=async()=>{h&&Z(Object.values(await (0,y.UM)(h)).map(e=>({label:e.name,value:e.name})))};(0,d.useEffect)(()=>{k()},[h]);let S=(null===(s=j.metadata)||void 0===s?void 0:s.total_spend)||0,C=()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{provider:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}})},I=async()=>{if(!h||!_.from||!_.to)return;let e=_.from,s=_.to;try{let l=await (0,y.xX)(h,e,s);if(l.metadata.total_pages>10)throw Error("Too many pages of data (>10). Please select a smaller date range.");if(1===l.metadata.total_pages){f(l);return}let t=[...l.results];for(let a=2;a<=l.metadata.total_pages;a++){let l=await (0,y.xX)(h,e,s,a);t.push(...l.results)}f({results:t,metadata:l.metadata})}catch(e){throw console.error("Error fetching user spend data:",e),e}};(0,d.useEffect)(()=>{I()},[h,_]);let T=tv(j,"models"),P=tv(j,"api_keys");return(0,c.jsxs)("div",{style:{width:"100%"},className:"p-8",children:[(0,c.jsxs)(A.Z,{className:"text-sm text-gray-500 mb-4",children:["This is the new usage dashboard. ",(0,c.jsx)("br",{})," You may see empty data, as these use ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/blob/6de348125208dd4be81ff0e5813753df2fbe9735/schema.prisma#L320",className:"text-blue-500 hover:text-blue-700 ml-1",children:"new aggregate tables"})," to allow UI to work at 1M+ spend logs. To access the old dashboard, go to Experimental ",">"," Old Usage."]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Global Usage"}):(0,c.jsx)(eR.Z,{children:"Your Usage"}),(0,c.jsx)(eR.Z,{children:"Team Usage"}),eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Tag Usage"}):(0,c.jsx)(c.Fragment,{})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:_,onValueChange:e=>{v(e)}})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:p,userRole:x,accessToken:h,userSpend:S,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Usage Metrics"}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(t=j.metadata)||void 0===t?void 0:null===(l=t.total_api_requests)||void 0===l?void 0:l.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:(null===(r=j.metadata)||void 0===r?void 0:null===(a=r.total_successful_requests)||void 0===a?void 0:a.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:(null===(i=j.metadata)||void 0===i?void 0:null===(n=i.total_failed_requests)||void 0===n?void 0:n.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(m=j.metadata)||void 0===m?void 0:null===(o=m.total_tokens)||void 0===o?void 0:o.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Average Cost per Request"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",((S||0)/((null===(u=j.metadata)||void 0===u?void 0:u.total_api_requests)||1)).toFixed(4)]})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...j.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Requests: ",t.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",t.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",t.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.metrics.total_tokens]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:h,userID:p,userRole:x,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Top Models"})}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.key}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",t.requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-green-600",children:["Successful: ",t.successful_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-red-600",children:["Failed: ",t.failed_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.tokens.toLocaleString()]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Spend by Provider"})}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:C(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:C().filter(e=>e.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend<1e-5?"less than 0.00001":e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:T})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:P})})]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"team",userID:p,userRole:x,entityList:(null==g?void 0:g.map(e=>({label:e.team_alias,value:e.team_id})))||null})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"tag",userID:p,userRole:x,entityList:b})})]})]})]})},tN=e=>{let{proxySettings:s}=e,l="";return s&&s.PROXY_BASE_URL&&void 0!==s.PROXY_BASE_URL&&(l=s.PROXY_BASE_URL),(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(w.Z,{className:"gap-2 p-8 h-[80vh] w-full mt-2",children:(0,c.jsxs)("div",{className:"mb-5",children:[(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:"OpenAI Compatible Proxy: API Reference"}),(0,c.jsx)(A.Z,{className:"mt-2 mb-2",children:"LiteLLM is OpenAI Compatible. This means your API Key works with the OpenAI SDK. Just replace the base_url to point to your litellm proxy. Example Below "}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"OpenAI Python SDK"}),(0,c.jsx)(eR.Z,{children:"LlamaIndex"}),(0,c.jsx)(eR.Z,{children:"Langchain Py"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport openai\nclient = openai.OpenAI(\n api_key="your_api_key",\n base_url="'.concat(l,'" # LiteLLM Proxy is OpenAI compatible, Read More: https://docs.litellm.ai/docs/proxy/user_keys\n)\n\nresponse = client.chat.completions.create(\n model="gpt-3.5-turbo", # model to send to the proxy\n messages = [\n {\n "role": "user",\n "content": "this is a test request, write a short poem"\n }\n ]\n)\n\nprint(response)\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport os, dotenv\n\nfrom llama_index.llms import AzureOpenAI\nfrom llama_index.embeddings import AzureOpenAIEmbedding\nfrom llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext\n\nllm = AzureOpenAI(\n engine="azure-gpt-3.5", # model_name on litellm proxy\n temperature=0.0,\n azure_endpoint="'.concat(l,'", # litellm proxy endpoint\n api_key="sk-1234", # litellm proxy API Key\n api_version="2023-07-01-preview",\n)\n\nembed_model = AzureOpenAIEmbedding(\n deployment_name="azure-embedding-model",\n azure_endpoint="').concat(l,'",\n api_key="sk-1234",\n api_version="2023-07-01-preview",\n)\n\n\ndocuments = SimpleDirectoryReader("llama_index_data").load_data()\nservice_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context)\n\nquery_engine = index.as_query_engine()\nresponse = query_engine.query("What did the author do growing up?")\nprint(response)\n\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n)\nfrom langchain.schema import HumanMessage, SystemMessage\n\nchat = ChatOpenAI(\n openai_api_base="'.concat(l,'",\n model = "gpt-3.5-turbo",\n temperature=0.1\n)\n\nmessages = [\n SystemMessage(\n content="You are a helpful assistant that im using to make a test request to."\n ),\n HumanMessage(\n content="test from litellm. tell me why it\'s amazing in 1 sentence"\n ),\n]\nresponse = chat(messages)\n\nprint(response)\n\n ')})})]})]})]})})})},tw=l(243);async function tk(e,s,l,t,a,r,n,i,o){console.log=function(){},console.log("isLocal:",!1);let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t;let a=Date.now(),c=!1;for await(let _ of(await d.chat.completions.create({model:l,stream:!0,stream_options:{include_usage:!0},messages:e},{signal:r}))){var m,u,h,x,p,g,j,f;console.log("Stream chunk:",_);let e=null===(m=_.choices[0])||void 0===m?void 0:m.delta;if(console.log("Delta content:",null===(h=_.choices[0])||void 0===h?void 0:null===(u=h.delta)||void 0===u?void 0:u.content),console.log("Delta reasoning content:",null==e?void 0:e.reasoning_content),!c&&((null===(p=_.choices[0])||void 0===p?void 0:null===(x=p.delta)||void 0===x?void 0:x.content)||e&&e.reasoning_content)&&(c=!0,t=Date.now()-a,console.log("First token received! Time:",t,"ms"),i?(console.log("Calling onTimingData with:",t),i(t)):console.log("onTimingData callback is not defined!")),null===(j=_.choices[0])||void 0===j?void 0:null===(g=j.delta)||void 0===g?void 0:g.content){let e=_.choices[0].delta.content;s(e,_.model)}if(e&&e.reasoning_content){let s=e.reasoning_content;n&&n(s)}if(_.usage&&o){console.log("Usage data found:",_.usage);let e={completionTokens:_.usage.completion_tokens,promptTokens:_.usage.prompt_tokens,totalTokens:_.usage.total_tokens};(null===(f=_.usage.completion_tokens_details)||void 0===f?void 0:f.reasoning_tokens)&&(e.reasoningTokens=_.usage.completion_tokens_details.reasoning_tokens),o(e)}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Chat completion request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}async function tS(e,s,l,t,a,r){console.log=function(){},console.log("isLocal:",!1);let n=window.location.origin,i=new lG.ZP.OpenAI({apiKey:t,baseURL:n,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=await i.images.generate({model:l,prompt:e},{signal:r});if(console.log(t.data),t.data&&t.data[0]){if(t.data[0].url)s(t.data[0].url,l);else if(t.data[0].b64_json){let e=t.data[0].b64_json;s("data:image/png;base64,".concat(e),l)}else throw Error("No image data found in response")}else throw Error("Invalid response format")}catch(e){throw(null==r?void 0:r.aborted)?console.log("Image generation request was cancelled"):D.ZP.error("Error occurred while generating image. Please try again. Error: ".concat(e),20),e}}async function tC(e,s,l,t){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],r=arguments.length>5?arguments[5]:void 0,n=arguments.length>6?arguments[6]:void 0,i=arguments.length>7?arguments[7]:void 0,o=arguments.length>8?arguments[8]:void 0;if(!t)throw Error("API key is required");console.log=function(){};let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=Date.now(),a=!1,c=e.map(e=>({role:e.role,content:e.content,type:"message"}));for await(let e of(await d.responses.create({model:l,input:c,stream:!0},{signal:r})))if(console.log("Response event:",e),"object"==typeof e&&null!==e){if("response.role.delta"===e.type)continue;if("response.output_text.delta"===e.type&&"string"==typeof e.delta){let r=e.delta;if(console.log("Text delta",r),r.trim().length>0&&(s("assistant",r,l),!a)){a=!0;let e=Date.now()-t;console.log("First token received! Time:",e,"ms"),i&&i(e)}}if("response.reasoning.delta"===e.type&&"delta"in e){let s=e.delta;"string"==typeof s&&n&&n(s)}if("response.completed"===e.type&&"response"in e){let s=e.response.usage;if(console.log("Usage data:",s),s&&o){var m;console.log("Usage data:",s);let e={completionTokens:s.output_tokens,promptTokens:s.input_tokens,totalTokens:s.total_tokens};(null===(m=s.completion_tokens_details)||void 0===m?void 0:m.reasoning_tokens)&&(e.reasoningTokens=s.completion_tokens_details.reasoning_tokens),o(e)}}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Responses API request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}let tI=async e=>{try{let s=await (0,y.kn)(e);if(console.log("model_info:",s),(null==s?void 0:s.data.length)>0){let e=s.data.map(e=>({model_group:e.model_group,mode:null==e?void 0:e.mode}));return e.sort((e,s)=>e.model_group.localeCompare(s.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};(a=i||(i={})).IMAGE_GENERATION="image_generation",a.CHAT="chat",a.RESPONSES="responses",(r=o||(o={})).IMAGE="image",r.CHAT="chat",r.RESPONSES="responses";let tT={image_generation:"image",chat:"chat",responses:"responses"},tA=e=>{if(console.log("getEndpointType:",e),Object.values(i).includes(e)){let s=tT[e];return console.log("endpointType:",s),s}return"chat"};var tE=l(94263),tP=e=>{let{endpointType:s,onEndpointChange:l,className:t}=e,a=[{value:o.CHAT,label:"/v1/chat/completions"},{value:o.RESPONSES,label:"/v1/responses"},{value:o.IMAGE,label:"/v1/images/generations"}];return(0,c.jsxs)("div",{className:t,children:[(0,c.jsx)(A.Z,{children:"Endpoint Type:"}),(0,c.jsx)(O.default,{value:s,style:{width:"100%"},onChange:l,options:a,className:"rounded-md"})]})},tO=e=>{let{onChange:s,value:l,className:t,accessToken:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)(!1);return(0,d.useEffect)(()=>{(async()=>{if(a)try{let e=await (0,y.UM)(a);console.log("List tags response:",e),n(Object.values(e))}catch(e){console.error("Error fetching tags:",e)}})()},[]),(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select tags",onChange:s,value:l,loading:i,className:t,options:r.map(e=>({label:e.name,value:e.name,title:e.description||e.name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})};let tL=(e,s)=>{let l=s.find(s=>s.model_group===e);return(null==l?void 0:l.mode)?tA(l.mode):o.CHAT};var tD=l(83322),tM=l(70464),tF=l(77565),tR=e=>{let{reasoningContent:s}=e,[l,t]=(0,d.useState)(!0);return s?(0,c.jsxs)("div",{className:"reasoning-content mt-1 mb-2",children:[(0,c.jsxs)(R.ZP,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>t(!l),icon:(0,c.jsx)(tD.Z,{}),children:[l?"Hide reasoning":"Show reasoning",l?(0,c.jsx)(tM.Z,{className:"ml-1"}):(0,c.jsx)(tF.Z,{className:"ml-1"})]}),l&&(0,c.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700",children:(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),...r,children:a})}},children:s})})]}):null},tq=l(5540),tU=l(71282),tz=l(11741),tV=l(16601),tK=e=>{let{timeToFirstToken:s,usage:l}=e;return s||l?(0,c.jsxs)("div",{className:"response-metrics mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500 flex flex-wrap gap-3",children:[void 0!==s&&(0,c.jsx)(W.Z,{title:"Time to first token",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tq.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:[(s/1e3).toFixed(2),"s"]})]})}),(null==l?void 0:l.promptTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Prompt tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tU.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["In: ",l.promptTokens]})]})}),(null==l?void 0:l.completionTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Completion tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tz.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Out: ",l.completionTokens]})]})}),(null==l?void 0:l.reasoningTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Reasoning tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tD.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Reasoning: ",l.reasoningTokens]})]})}),(null==l?void 0:l.totalTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Total tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tV.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Total: ",l.totalTokens]})]})})]}):null},tB=l(61935),tH=l(69993),tJ=l(12660),tW=l(71891),tG=l(26430),tY=l(26349),t$=l(23907);let{TextArea:tX}=q.default;var tQ=e=>{let{accessToken:s,token:l,userRole:t,userID:a,disabledPersonalKeyCreation:r}=e,[n,i]=(0,d.useState)(r?"custom":"session"),[m,u]=(0,d.useState)(""),[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)([]),[f,_]=(0,d.useState)(void 0),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)([]),N=(0,d.useRef)(null),[w,C]=(0,d.useState)(o.CHAT),[I,T]=(0,d.useState)(!1),E=(0,d.useRef)(null),[P,L]=(0,d.useState)([]),M=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e="session"===n?s:m;if(!e||!l||!t||!a){console.log("userApiKey or token or userRole or userID is missing = ",e,l,t,a);return}(async()=>{try{if(!e){console.log("userApiKey is missing");return}let s=await tI(e);if(console.log("Fetched models:",s),s.length>0&&(Z(s),_(s[0].model_group),s[0].mode)){let e=tL(s[0].model_group,s);C(e)}}catch(e){console.error("Error fetching model info:",e)}})()},[s,a,t,n,m]),(0,d.useEffect)(()=>{M.current&&setTimeout(()=>{var e;null===(e=M.current)||void 0===e||e.scrollIntoView({behavior:"smooth",block:"end"})},100)},[p]);let F=(e,s,l)=>{console.log("updateTextUI called with:",e,s,l),g(t=>{let a=t[t.length-1];if(!a||a.role!==e||a.isImage)return[...t,{role:e,content:s,model:l}];{var r;let e={...a,content:a.content+s,model:null!==(r=a.model)&&void 0!==r?r:l};return[...t.slice(0,-1),e]}})},R=e=>{g(s=>{let l=s[s.length-1];return l&&"assistant"===l.role&&!l.isImage?[...s.slice(0,s.length-1),{...l,reasoningContent:(l.reasoningContent||"")+e}]:s.length>0&&"user"===s[s.length-1].role?[...s,{role:"assistant",content:"",reasoningContent:e}]:s})},q=e=>{console.log("updateTimingData called with:",e),g(s=>{let l=s[s.length-1];if(console.log("Current last message:",l),l&&"assistant"===l.role){console.log("Updating assistant message with timeToFirstToken:",e);let t=[...s.slice(0,s.length-1),{...l,timeToFirstToken:e}];return console.log("Updated chat history:",t),t}return l&&"user"===l.role?(console.log("Creating new assistant message with timeToFirstToken:",e),[...s,{role:"assistant",content:"",timeToFirstToken:e}]):(console.log("No appropriate message found to update timing"),s)})},U=e=>{console.log("Received usage data:",e),g(s=>{let l=s[s.length-1];if(l&&"assistant"===l.role){console.log("Updating message with usage data:",e);let t={...l,usage:e};return console.log("Updated message:",t),[...s.slice(0,s.length-1),t]}return s})},z=(e,s)=>{g(l=>[...l,{role:"assistant",content:e,model:s,isImage:!0}])},V=async()=>{if(""===h.trim()||!l||!t||!a)return;let e="session"===n?s:m;if(!e){D.ZP.error("Please provide an API key or select Current UI Session");return}E.current=new AbortController;let r=E.current.signal,i={role:"user",content:h};g([...p,i]),T(!0);try{if(f){if(w===o.CHAT){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tk(s,(e,s)=>F("assistant",e,s),f,e,P,r,R,q,U)}else if(w===o.IMAGE)await tS(h,(e,s)=>z(e,s),f,e,P,r);else if(w===o.RESPONSES){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tC(s,(e,s,l)=>F(e,s,l),f,e,P,r,R,q,U)}}}catch(e){r.aborted?console.log("Request was cancelled"):(console.error("Error fetching response",e),F("assistant","Error fetching response"))}finally{T(!1),E.current=null}x("")};if(t&&"Admin Viewer"===t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to test models"})]})}let K=(0,c.jsx)(tB.Z,{style:{fontSize:24},spin:!0});return(0,c.jsx)("div",{className:"w-full h-screen p-4 bg-white",children:(0,c.jsx)(eF.Z,{className:"w-full rounded-xl shadow-md overflow-hidden",children:(0,c.jsxs)("div",{className:"flex h-[80vh] w-full",children:[(0,c.jsx)("div",{className:"w-1/4 p-4 border-r border-gray-200 bg-gray-50",children:(0,c.jsx)("div",{className:"mb-6",children:(0,c.jsxs)("div",{className:"space-y-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(lE.Z,{className:"mr-2"})," API Key Source"]}),(0,c.jsx)(O.default,{disabled:r,defaultValue:"session",style:{width:"100%"},onChange:e=>i(e),options:[{value:"session",label:"Current UI Session"},{value:"custom",label:"Virtual Key"}],className:"rounded-md"}),"custom"===n&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom API key",type:"password",onValueChange:u,value:m,icon:lE.Z})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tH.Z,{className:"mr-2"})," Select Model"]}),(0,c.jsx)(O.default,{placeholder:"Select a Model",onChange:e=>{console.log("selected ".concat(e)),_(e),"custom"!==e&&C(tL(e,b)),v("custom"===e)},options:[...b.map(e=>({value:e.model_group,label:e.model_group})),{value:"custom",label:"Enter custom model"}],style:{width:"100%"},showSearch:!0,className:"rounded-md"}),y&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{_(e)},500)}})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tJ.Z,{className:"mr-2"})," Endpoint Type"]}),(0,c.jsx)(tP,{endpointType:w,onEndpointChange:e=>{C(e)},className:"mb-4"})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tW.Z,{className:"mr-2"})," Tags"]}),(0,c.jsx)(tO,{value:P,onChange:L,className:"mb-4",accessToken:s||""})]}),(0,c.jsx)(k.Z,{onClick:()=>{g([]),D.ZP.success("Chat history cleared.")},className:"w-full bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300 mt-4",icon:tG.Z,children:"Clear Chat"})]})})}),(0,c.jsxs)("div",{className:"w-3/4 flex flex-col bg-white",children:[(0,c.jsxs)("div",{className:"flex-1 overflow-auto p-4 pb-0",children:[0===p.length&&(0,c.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[(0,c.jsx)(tH.Z,{style:{fontSize:"48px",marginBottom:"16px"}}),(0,c.jsx)(A.Z,{children:"Start a conversation or generate an image"})]}),p.map((e,s)=>(0,c.jsx)("div",{className:"mb-4 ".concat("user"===e.role?"text-right":"text-left"),children:(0,c.jsxs)("div",{className:"inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4",style:{backgroundColor:"user"===e.role?"#f0f8ff":"#ffffff",border:"user"===e.role?"1px solid #e6f0fa":"1px solid #f0f0f0",textAlign:"left"},children:[(0,c.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full mr-1",style:{backgroundColor:"user"===e.role?"#e6f0fa":"#f5f5f5"},children:"user"===e.role?(0,c.jsx)(j.Z,{style:{fontSize:"12px",color:"#2563eb"}}):(0,c.jsx)(tH.Z,{style:{fontSize:"12px",color:"#4b5563"}})}),(0,c.jsx)("strong",{className:"text-sm capitalize",children:e.role}),"assistant"===e.role&&e.model&&(0,c.jsx)("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-normal",children:e.model})]}),e.reasoningContent&&(0,c.jsx)(tR,{reasoningContent:e.reasoningContent}),(0,c.jsxs)("div",{className:"whitespace-pre-wrap break-words max-w-full message-content",style:{wordWrap:"break-word",overflowWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},children:[e.isImage?(0,c.jsx)("img",{src:e.content,alt:"Generated image",className:"max-w-full rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"500px"}}):(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",wrapLines:!0,wrapLongLines:!0,...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),style:{wordBreak:"break-word"},...r,children:a})},pre:e=>{let{node:s,...l}=e;return(0,c.jsx)("pre",{style:{overflowX:"auto",maxWidth:"100%"},...l})}},children:e.content}),"assistant"===e.role&&(e.timeToFirstToken||e.usage)&&(0,c.jsx)(tK,{timeToFirstToken:e.timeToFirstToken,usage:e.usage})]})]})},s)),I&&(0,c.jsx)("div",{className:"flex justify-center items-center my-4",children:(0,c.jsx)(eY.Z,{indicator:K})}),(0,c.jsx)("div",{ref:M,style:{height:"1px"}})]}),(0,c.jsx)("div",{className:"p-4 border-t border-gray-200 bg-white",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tX,{value:h,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),V())},placeholder:w===o.CHAT||w===o.RESPONSES?"Type your message... (Shift+Enter for new line)":"Describe the image you want to generate...",disabled:I,className:"flex-1",autoSize:{minRows:1,maxRows:6},style:{resize:"none",paddingRight:"10px",paddingLeft:"10px"}}),I?(0,c.jsx)(k.Z,{onClick:()=>{E.current&&(E.current.abort(),E.current=null,T(!1),D.ZP.info("Request cancelled"))},className:"ml-2 bg-red-50 hover:bg-red-100 text-red-600 border-red-200",icon:tY.Z,children:"Cancel"}):(0,c.jsx)(k.Z,{onClick:V,className:"ml-2 text-white",icon:w===o.CHAT?t$.Z:tH.Z,children:w===o.CHAT?"Send":"Generate"})]})})]})]})})})},t0=l(19226),t1=l(45937),t2=l(28595),t4=l(68208),t5=l(9775),t3=l(41361),t6=l(37527),t8=l(88009),t7=l(48231),t9=l(41169),ae=l(44625),as=l(57400),al=l(58630),at=l(55322);let{Sider:aa}=t0.default;var ar=e=>{let{setPage:s,userRole:l,defaultSelectedKey:t}=e,a=[{key:"1",page:"api-keys",label:"Virtual Keys",icon:(0,c.jsx)(lE.Z,{})},{key:"3",page:"llm-playground",label:"Test Key",icon:(0,c.jsx)(t2.Z,{}),roles:eg.LQ},{key:"2",page:"models",label:"Models",icon:(0,c.jsx)(t4.Z,{}),roles:eg.LQ},{key:"12",page:"new_usage",label:"Usage",icon:(0,c.jsx)(t5.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"6",page:"teams",label:"Teams",icon:(0,c.jsx)(t3.Z,{})},{key:"17",page:"organizations",label:"Organizations",icon:(0,c.jsx)(t6.Z,{}),roles:eg.ZL},{key:"5",page:"users",label:"Internal Users",icon:(0,c.jsx)(j.Z,{}),roles:eg.ZL},{key:"14",page:"api_ref",label:"API Reference",icon:(0,c.jsx)(tJ.Z,{})},{key:"16",page:"model-hub",label:"Model Hub",icon:(0,c.jsx)(t8.Z,{})},{key:"15",page:"logs",label:"Logs",icon:(0,c.jsx)(t7.Z,{})},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,c.jsx)(t9.Z,{}),children:[{key:"9",page:"caching",label:"Caching",icon:(0,c.jsx)(ae.Z,{}),roles:eg.ZL},{key:"10",page:"budgets",label:"Budgets",icon:(0,c.jsx)(t6.Z,{}),roles:eg.ZL},{key:"11",page:"guardrails",label:"Guardrails",icon:(0,c.jsx)(as.Z,{}),roles:eg.ZL},{key:"4",page:"usage",label:"Old Usage",icon:(0,c.jsx)(t5.Z,{})},{key:"20",page:"transform-request",label:"API Playground",icon:(0,c.jsx)(tJ.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"18",page:"mcp-tools",label:"MCP Tools",icon:(0,c.jsx)(al.Z,{}),roles:eg.ZL},{key:"19",page:"tag-management",label:"Tag Management",icon:(0,c.jsx)(tW.Z,{}),roles:eg.ZL}]},{key:"settings",page:"settings",label:"Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL,children:[{key:"11",page:"general-settings",label:"Router Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"12",page:"pass-through-settings",label:"Pass-Through",icon:(0,c.jsx)(tJ.Z,{}),roles:eg.ZL},{key:"8",page:"settings",label:"Logging & Alerts",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"13",page:"admin-panel",label:"Admin Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL}]}],r=(e=>{let s=a.find(s=>s.page===e);if(s)return s.key;for(let s of a)if(s.children){let l=s.children.find(s=>s.page===e);if(l)return l.key}return"1"})(t),n=a.filter(e=>!!(!e.roles||e.roles.includes(l))&&(e.children&&(e.children=e.children.filter(e=>!e.roles||e.roles.includes(l))),!0));return(0,c.jsx)(t0.default,{style:{minHeight:"100vh"},children:(0,c.jsx)(aa,{theme:"light",width:220,children:(0,c.jsx)(t1.Z,{mode:"inline",selectedKeys:[r],style:{borderRight:0,backgroundColor:"transparent",fontSize:"14px"},items:n.map(e=>{var l;return{key:e.key,icon:e.icon,label:e.label,children:null===(l=e.children)||void 0===l?void 0:l.map(e=>({key:e.key,icon:e.icon,label:e.label,onClick:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}})),onClick:e.children?void 0:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}}})})})})},an=l(96889);console.log("process.env.NODE_ENV","production"),console.log=function(){};let ai=e=>null!==e&&("Admin"===e||"Admin Viewer"===e);var ao=e=>{let{accessToken:s,token:l,userRole:t,userID:a,keys:r,premiumUser:n}=e,i=new Date,[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)([]),[v,b]=(0,d.useState)([]),[Z,S]=(0,d.useState)([]),[C,I]=(0,d.useState)([]),[T,P]=(0,d.useState)([]),[O,L]=(0,d.useState)([]),[D,M]=(0,d.useState)({}),[F,R]=(0,d.useState)([]),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(["all-tags"]),[K,B]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(0),Y=new Date(i.getFullYear(),i.getMonth(),1),$=new Date(i.getFullYear(),i.getMonth()+1,0),X=er(Y),Q=er($);function es(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}console.log("keys in usage",r),console.log("premium user in usage",n);let el=async()=>{if(s)try{let e=await (0,y.g)(s);return console.log("usage tab: proxy_settings",e),e}catch(e){console.error("Error fetching proxy settings:",e)}};(0,d.useEffect)(()=>{ea(K.from,K.to)},[K,z]);let et=async(e,l,t)=>{if(!e||!l||!s)return;l.setHours(23,59,59,999),e.setHours(0,0,0,0),console.log("uiSelectedKey",t);let a=await (0,y.b1)(s,t,e.toISOString(),l.toISOString());console.log("End user data updated successfully",a),j(a)},ea=async(e,l)=>{if(!e||!l||!s)return;let t=await el();null!=t&&t.DISABLE_EXPENSIVE_DB_QUERIES||(l.setHours(23,59,59,999),e.setHours(0,0,0,0),b((await (0,y.J$)(s,e.toISOString(),l.toISOString(),0===z.length?void 0:z)).spend_per_tag),console.log("Tag spend data updated successfully"))};function er(e){let s=e.getFullYear(),l=e.getMonth()+1,t=e.getDate();return"".concat(s,"-").concat(l<10?"0"+l:l,"-").concat(t<10?"0"+t:t)}console.log("Start date is ".concat(X)),console.log("End date is ".concat(Q));let en=async(e,s,l)=>{try{let l=await e();s(l)}catch(e){console.error(l,e)}},ei=(e,s,l,t)=>{let a=[],r=new Date(s),n=e=>{if(e.includes("-"))return e;{let[s,l]=e.split(" ");return new Date(new Date().getFullYear(),new Date("".concat(s," 01 2024")).getMonth(),parseInt(l)).toISOString().split("T")[0]}},i=new Map(e.map(e=>{let s=n(e.date);return[s,{...e,date:s}]}));for(;r<=l;){let e=r.toISOString().split("T")[0];if(i.has(e))a.push(i.get(e));else{let s={date:e,api_requests:0,total_tokens:0};t.forEach(e=>{s[e]||(s[e]=0)}),a.push(s)}r.setDate(r.getDate()+1)}return a},eo=async()=>{if(s)try{let e=await (0,y.FC)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e,t,a,[]),n=Number(r.reduce((e,s)=>e+(s.spend||0),0).toFixed(2));G(n),m(r)}catch(e){console.error("Error fetching overall spend:",e)}},ec=()=>en(()=>s&&l?(0,y.OU)(s,l,X,Q):Promise.reject("No access token or token"),L,"Error fetching provider spend"),ed=async()=>{s&&await en(async()=>(await (0,y.tN)(s)).map(e=>({key:e.api_key.substring(0,10),api_key:e.api_key,key_alias:e.key_alias,spend:Number(e.total_spend.toFixed(2))})),h,"Error fetching top keys")},em=async()=>{s&&await en(async()=>(await (0,y.Au)(s)).map(e=>({key:e.model,spend:Number(e.total_spend.toFixed(2))})),p,"Error fetching top models")},eu=async()=>{s&&await en(async()=>{let e=await (0,y.mR)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0);return _(ei(e.daily_spend,t,a,e.teams)),I(e.teams),e.total_spend_per_team.map(e=>({name:e.team_id||"",value:Number(e.total_spend||0).toFixed(2)}))},P,"Error fetching team spend")},eh=()=>{s&&en(async()=>(await (0,y.X)(s)).tag_names,S,"Error fetching tag names")},ex=()=>{s&&en(()=>{var e,l;return(0,y.J$)(s,null===(e=K.from)||void 0===e?void 0:e.toISOString(),null===(l=K.to)||void 0===l?void 0:l.toISOString(),void 0)},e=>b(e.spend_per_tag),"Error fetching top tags")},ep=()=>{s&&en(()=>(0,y.b1)(s,null,void 0,void 0),j,"Error fetching top end users")},eg=async()=>{if(s)try{let e=await (0,y.wd)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e.daily_data||[],t,a,["api_requests","total_tokens"]);M({...e,daily_data:r})}catch(e){console.error("Error fetching global activity:",e)}},ej=async()=>{if(s)try{let e=await (0,y.xA)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=e.map(e=>({...e,daily_data:ei(e.daily_data||[],t,a,["api_requests","total_tokens"])}));R(r)}catch(e){console.error("Error fetching global activity per model:",e)}};return((0,d.useEffect)(()=>{(async()=>{if(s&&l&&t&&a){let e=await el();e&&(J(e),null!=e&&e.DISABLE_EXPENSIVE_DB_QUERIES)||(console.log("fetching data - valiue of proxySettings",H),eo(),ec(),ed(),em(),eg(),ej(),ai(t)&&(eu(),eh(),ex(),ep()))}})()},[s,l,t,a,X,Q]),null==H?void 0:H.DISABLE_EXPENSIVE_DB_QUERIES)?(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Database Query Limit Reached"}),(0,c.jsxs)(A.Z,{className:"mt-4",children:["SpendLogs in DB has ",H.NUM_SPEND_LOGS_ROWS," rows.",(0,c.jsx)("br",{}),"Please follow our guide to view usage when SpendLogs has more than 1M rows."]}),(0,c.jsx)(k.Z,{className:"mt-4",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/spending_monitoring",target:"_blank",children:"View Usage Guide"})})]})}):(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mt-2",children:[(0,c.jsx)(eR.Z,{children:"All Up"}),ai(t)?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(eR.Z,{children:"Team Based Usage"}),(0,c.jsx)(eR.Z,{children:"Customer Usage"}),(0,c.jsx)(eR.Z,{children:"Tag Based Usage"})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsx)("div",{})})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[100vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:a,userRole:t,accessToken:s,userSpend:W,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Monthly Spend"}),(0,c.jsx)(sw.Z,{data:o,index:"date",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$ ".concat(e.toFixed(2)),yAxisWidth:100,tickGap:5})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:u,accessToken:s,userID:a,userRole:t,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:x,index:"key",categories:["spend"],colors:["cyan"],yAxisWidth:200,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>"$".concat(e.toFixed(2))})]})}),(0,c.jsx)(N.Z,{numColSpan:1}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Spend by Provider"}),(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",variant:"pie",data:O,index:"provider",category:"spend",colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2))})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"})]})}),(0,c.jsx)(eT.Z,{children:O.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsx)(eA.Z,{children:1e-5>parseFloat(e.spend.toFixed(2))?"less than 0.00":e.spend.toFixed(2)})]},e.provider))})]})})]})})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"All Up"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(D.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["api_requests"],onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(D.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["total_tokens"],onValueChange:e=>console.log(e)})]})]})]}),(0,c.jsx)(c.Fragment,{children:F.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.model}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(e.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["api_requests"],valueFormatter:es,onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(e.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["total_tokens"],valueFormatter:es,onValueChange:e=>console.log(e)})]})]})]},s))})]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Total Spend Per Team"}),(0,c.jsx)(an.Z,{data:T})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend Per Team"}),(0,c.jsx)(sw.Z,{className:"h-72",data:f,showLegend:!0,index:"date",categories:C,yAxisWidth:80,stack:!0})]})]}),(0,c.jsx)(N.Z,{numColSpan:2})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:["Customers of your LLM API calls. Tracked when a `user` param is passed in your LLM calls ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/users",target:"_blank",children:"docs here"})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:K,onValueChange:e=>{B(e),et(e.from,e.to,null)}})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Key"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{et(K.from,K.to,null)},children:"All Keys"},"all-keys"),null==r?void 0:r.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{et(K.from,K.to,e.token)},children:e.key_alias},s):null)]})]})]}),(0,c.jsx)(eF.Z,{className:"mt-4",children:(0,c.jsxs)(eI.Z,{className:"max-h-[70vh] min-h-[500px]",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Customer"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Total Events"})]})}),(0,c.jsx)(eT.Z,{children:null==g?void 0:g.map((e,s)=>{var l;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.end_user}),(0,c.jsx)(eA.Z,{children:null===(l=e.total_spend)||void 0===l?void 0:l.toFixed(4)}),(0,c.jsx)(eA.Z,{children:e.total_count})]},s)})})]})})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sb.Z,{className:"mb-4",enableSelect:!0,value:K,onValueChange:e=>{B(e),ea(e.from,e.to)}})}),(0,c.jsx)(N.Z,{children:n?(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsx)(lH.Z,{value:String(e),children:e},e))]})}):(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsxs)(ee.Z,{value:String(e),disabled:!0,children:["✨ ",e," (Enterprise only Feature)"]},e))]})})})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full mb-4",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend Per Tag"}),(0,c.jsxs)(A.Z,{children:["Get Started Tracking cost per tag ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/cost_tracking",target:"_blank",children:"here"})]}),(0,c.jsx)(sw.Z,{className:"h-72",data:v,index:"name",categories:["spend"],colors:["cyan"]})]})}),(0,c.jsx)(N.Z,{numColSpan:2})]})]})]})]})})},ac=l(51853);let ad=e=>{let{responseTimeMs:s}=e;return null==s?null:(0,c.jsxs)("div",{className:"flex items-center space-x-1 text-xs text-gray-500 font-mono",children:[(0,c.jsx)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{d:"M12 6V12L16 14M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,c.jsxs)("span",{children:[s.toFixed(0),"ms"]})]})},am=e=>{let s=e;if("string"==typeof s)try{s=JSON.parse(s)}catch(e){}return s},au=e=>{let{label:s,value:l}=e,[t,a]=d.useState(!1),[r,n]=d.useState(!1),i=(null==l?void 0:l.toString())||"N/A",o=i.length>50?i.substring(0,50)+"...":i;return(0,c.jsx)("tr",{className:"hover:bg-gray-50",children:(0,c.jsx)("td",{className:"px-4 py-2 align-top",colSpan:2,children:(0,c.jsxs)("div",{className:"flex items-center justify-between group",children:[(0,c.jsxs)("div",{className:"flex items-center flex-1",children:[(0,c.jsx)("button",{onClick:()=>a(!t),className:"text-gray-400 hover:text-gray-600 mr-2",children:t?"▼":"▶"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("div",{className:"text-sm text-gray-600",children:s}),(0,c.jsx)("pre",{className:"mt-1 text-sm font-mono text-gray-800 whitespace-pre-wrap",children:t?i:o})]})]}),(0,c.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(i),n(!0),setTimeout(()=>n(!1),2e3)},className:"opacity-0 group-hover:opacity-100 text-gray-400 hover:text-gray-600",children:(0,c.jsx)(ac.Z,{className:"h-4 w-4"})})]})})})},ah=e=>{var s,l,t,a,r,n,i,o,d,m,u,h,x,p;let{response:g}=e,j=null,f={},_={};try{if(null==g?void 0:g.error)try{let e="string"==typeof g.error.message?JSON.parse(g.error.message):g.error.message;j={message:(null==e?void 0:e.message)||"Unknown error",traceback:(null==e?void 0:e.traceback)||"No traceback available",litellm_params:(null==e?void 0:e.litellm_cache_params)||{},health_check_cache_params:(null==e?void 0:e.health_check_cache_params)||{}},f=am(j.litellm_params)||{},_=am(j.health_check_cache_params)||{}}catch(e){console.warn("Error parsing error details:",e),j={message:String(g.error.message||"Unknown error"),traceback:"Error parsing details",litellm_params:{},health_check_cache_params:{}}}else f=am(null==g?void 0:g.litellm_cache_params)||{},_=am(null==g?void 0:g.health_check_cache_params)||{}}catch(e){console.warn("Error in response parsing:",e),f={},_={}}let y={redis_host:(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host)||(null==_?void 0:null===(i=_.connection_kwargs)||void 0===i?void 0:i.host)||(null==_?void 0:_.host)||"N/A",redis_port:(null==_?void 0:null===(m=_.redis_client)||void 0===m?void 0:null===(d=m.connection_pool)||void 0===d?void 0:null===(o=d.connection_kwargs)||void 0===o?void 0:o.port)||(null==_?void 0:null===(x=_.redis_async_client)||void 0===x?void 0:null===(h=x.connection_pool)||void 0===h?void 0:null===(u=h.connection_kwargs)||void 0===u?void 0:u.port)||(null==_?void 0:null===(p=_.connection_kwargs)||void 0===p?void 0:p.port)||(null==_?void 0:_.port)||"N/A",redis_version:(null==_?void 0:_.redis_version)||"N/A",startup_nodes:(()=>{try{var e,s,l,t,a,r,n,i,o,c,d,m,u;if(null==_?void 0:null===(e=_.redis_kwargs)||void 0===e?void 0:e.startup_nodes)return JSON.stringify(_.redis_kwargs.startup_nodes);let h=(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host),x=(null==_?void 0:null===(c=_.redis_client)||void 0===c?void 0:null===(o=c.connection_pool)||void 0===o?void 0:null===(i=o.connection_kwargs)||void 0===i?void 0:i.port)||(null==_?void 0:null===(u=_.redis_async_client)||void 0===u?void 0:null===(m=u.connection_pool)||void 0===m?void 0:null===(d=m.connection_kwargs)||void 0===d?void 0:d.port);return h&&x?JSON.stringify([{host:h,port:x}]):"N/A"}catch(e){return"N/A"}})(),namespace:(null==_?void 0:_.namespace)||"N/A"};return(0,c.jsx)("div",{className:"bg-white rounded-lg shadow",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"border-b border-gray-200 px-4",children:[(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Summary"}),(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Raw Response"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-6",children:[(null==g?void 0:g.status)==="healthy"?(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}):(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsxs)(A.Z,{className:"text-sm font-medium ".concat((null==g?void 0:g.status)==="healthy"?"text-green-500":"text-red-500"),children:["Cache Status: ",(null==g?void 0:g.status)||"unhealthy"]})]}),(0,c.jsx)("table",{className:"w-full border-collapse",children:(0,c.jsxs)("tbody",{children:[j&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold text-red-600",children:"Error Details"})}),(0,c.jsx)(au,{label:"Error Message",value:j.message}),(0,c.jsx)(au,{label:"Traceback",value:j.traceback})]}),(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Cache Details"})}),(0,c.jsx)(au,{label:"Cache Configuration",value:String(null==f?void 0:f.type)}),(0,c.jsx)(au,{label:"Ping Response",value:String(g.ping_response)}),(0,c.jsx)(au,{label:"Set Cache Response",value:g.set_cache_response||"N/A"}),(0,c.jsx)(au,{label:"litellm_settings.cache_params",value:JSON.stringify(f,null,2)}),(null==f?void 0:f.type)==="redis"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Redis Details"})}),(0,c.jsx)(au,{label:"Redis Host",value:y.redis_host||"N/A"}),(0,c.jsx)(au,{label:"Redis Port",value:y.redis_port||"N/A"}),(0,c.jsx)(au,{label:"Redis Version",value:y.redis_version||"N/A"}),(0,c.jsx)(au,{label:"Startup Nodes",value:y.startup_nodes||"N/A"}),(0,c.jsx)(au,{label:"Namespace",value:y.namespace||"N/A"})]})]})})]})}),(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsx)("div",{className:"bg-gray-50 rounded-md p-4 font-mono text-sm",children:(0,c.jsx)("pre",{className:"whitespace-pre-wrap break-words overflow-auto max-h-[500px]",children:(()=>{try{let e={...g,litellm_cache_params:f,health_check_cache_params:_},s=JSON.parse(JSON.stringify(e,(e,s)=>{if("string"==typeof s)try{return JSON.parse(s)}catch(e){}return s}));return JSON.stringify(s,null,2)}catch(e){return"Error formatting JSON: "+e.message}})()})})})]})]})})},ax=e=>{let{accessToken:s,healthCheckResponse:l,runCachingHealthCheck:t,responseTimeMs:a}=e,[r,n]=d.useState(null),[i,o]=d.useState(!1),m=async()=>{o(!0);let e=performance.now();await t(),n(performance.now()-e),o(!1)};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsx)(k.Z,{onClick:m,disabled:i,className:"bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white text-sm px-4 py-2 rounded-md",children:i?"Running Health Check...":"Run Health Check"}),(0,c.jsx)(ad,{responseTimeMs:r})]}),l&&(0,c.jsx)(ah,{response:l})]})},ap=e=>{if(e)return e.toISOString().split("T")[0]};function ag(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}var aj=e=>{let{accessToken:s,token:l,userRole:t,userID:a,premiumUser:r}=e,[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)("0"),[f,_]=(0,d.useState)("0"),[v,b]=(0,d.useState)("0"),[Z,k]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[S,C]=(0,d.useState)(""),[I,T]=(0,d.useState)("");(0,d.useEffect)(()=>{s&&Z&&((async()=>{p(await (0,y.zg)(s,ap(Z.from),ap(Z.to)))})(),C(new Date().toLocaleString()))},[s]);let E=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.api_key)&&void 0!==s?s:""}))),P=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.model)&&void 0!==s?s:""})));Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.call_type)&&void 0!==s?s:""})));let O=async(e,l)=>{e&&l&&s&&(l.setHours(23,59,59,999),e.setHours(0,0,0,0),p(await (0,y.zg)(s,ap(e),ap(l))))};(0,d.useEffect)(()=>{console.log("DATA IN CACHE DASHBOARD",x);let e=x;o.length>0&&(e=e.filter(e=>o.includes(e.api_key))),u.length>0&&(e=e.filter(e=>u.includes(e.model))),console.log("before processed data in cache dashboard",e);let s=0,l=0,t=0,a=e.reduce((e,a)=>{console.log("Processing item:",a),a.call_type||(console.log("Item has no call_type:",a),a.call_type="Unknown"),s+=(a.total_rows||0)-(a.cache_hit_true_rows||0),l+=a.cache_hit_true_rows||0,t+=a.cached_completion_tokens||0;let r=e.find(e=>e.name===a.call_type);return r?(r["LLM API requests"]+=(a.total_rows||0)-(a.cache_hit_true_rows||0),r["Cache hit"]+=a.cache_hit_true_rows||0,r["Cached Completion Tokens"]+=a.cached_completion_tokens||0,r["Generated Completion Tokens"]+=a.generated_completion_tokens||0):e.push({name:a.call_type,"LLM API requests":(a.total_rows||0)-(a.cache_hit_true_rows||0),"Cache hit":a.cache_hit_true_rows||0,"Cached Completion Tokens":a.cached_completion_tokens||0,"Generated Completion Tokens":a.generated_completion_tokens||0}),e},[]);j(ag(l)),_(ag(t));let r=l+s;r>0?b((l/r*100).toFixed(2)):b("0"),i(a),console.log("PROCESSED DATA IN CACHE DASHBOARD",a)},[o,u,Z,x]);let L=async()=>{try{D.ZP.info("Running cache health check..."),T("");let e=await (0,y.Tj)(null!==s?s:"");console.log("CACHING HEALTH CHECK RESPONSE",e),T(e)}catch(s){let e;if(console.error("Error running health check:",s),s&&s.message)try{let l=JSON.parse(s.message);l.error&&(l=l.error),e=l}catch(l){e={message:s.message}}else e={message:"Unknown error occurred"};T({error:e})}};return(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-full w-full mt-2 mb-8",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Cache Analytics"}),(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"Cache Health"})})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[S&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",S]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:()=>{C(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(w.Z,{numItems:3,className:"gap-4 mt-4",children:[(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select API Keys",value:o,onValueChange:m,children:E.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select Models",value:u,onValueChange:h,children:P.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(sb.Z,{enableSelect:!0,value:Z,onValueChange:e=>{k(e),O(e.from,e.to)},selectPlaceholder:"Select date range"})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hit Ratio"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsxs)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:[v,"%"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hits"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:g})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cached Tokens"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:f})})]})]}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cache Hits vs API Requests"}),(0,c.jsx)(sw.Z,{title:"Cache Hits vs API Requests",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["LLM API requests","Cache hit"],colors:["sky","teal"],yAxisWidth:48}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cached Completion Tokens vs Generated Completion Tokens"}),(0,c.jsx)(sw.Z,{className:"mt-6",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["Generated Completion Tokens","Cached Completion Tokens"],colors:["sky","teal"],yAxisWidth:48})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ax,{accessToken:s,healthCheckResponse:I,runCachingHealthCheck:L})})]})]})},af=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(async()=>{try{let e=await (0,y.t3)(s);console.log("guardrails: ".concat(JSON.stringify(e))),t(e.guardrails)}catch(e){console.error("Error fetching guardrails:",e)}})()},[s]),(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsxs)(A.Z,{className:"mb-4",children:["Configured guardrails and their current status. Setup guardrails in config.yaml."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Guardrail Name"}),(0,c.jsx)(eP.Z,{children:"Mode"}),(0,c.jsx)(eP.Z,{children:"Status"})]})}),(0,c.jsx)(eT.Z,{children:l&&0!==l.length?null==l?void 0:l.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.guardrail_name}),(0,c.jsx)(eA.Z,{children:e.litellm_params.mode}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"inline-flex rounded-full px-2 py-1 text-xs font-medium\n ".concat(e.litellm_params.default_on?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"),children:e.litellm_params.default_on?"Always On":"Per Request"})})]},s)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:3,className:"mt-4 text-gray-500 text-center py-4",children:"No guardrails configured"})})})]})})]})},a_=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)('{\n "model": "openai/gpt-4o",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n },\n {\n "role": "user",\n "content": "Explain quantum computing in simple terms"\n }\n ],\n "temperature": 0.7,\n "max_tokens": 500,\n "stream": true\n}'),[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(!1),o=(e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")},m=async()=>{i(!0);try{let e;try{e=JSON.parse(l)}catch(e){D.ZP.error("Invalid JSON in request body"),i(!1);return}let t={call_type:"completion",request_body:e};if(!s){D.ZP.error("No access token found"),i(!1);return}let a=await (0,y.Yo)(s,t);if(a.raw_request_api_base&&a.raw_request_body){let e=o(a.raw_request_api_base,a.raw_request_body,a.raw_request_headers||{});r(e),D.ZP.success("Request transformed successfully")}else{let e="string"==typeof a?a:JSON.stringify(a);r(e),D.ZP.info("Transformed request received in unexpected format")}}catch(e){console.error("Error transforming request:",e),D.ZP.error("Failed to transform request")}finally{i(!1)}};return(0,c.jsxs)("div",{className:"w-full m-2",style:{overflow:"hidden"},children:[(0,c.jsx)(E.Z,{children:"Playground"}),(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"See how LiteLLM transforms your request for the specified provider."}),(0,c.jsxs)("div",{style:{display:"flex",gap:"16px",width:"100%",minWidth:0,overflow:"hidden"},className:"mt-4",children:[(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"600px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Original Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"The request you would send to LiteLLM /chat/completions endpoint."})]}),(0,c.jsx)("textarea",{style:{flex:"1 1 auto",width:"100%",minHeight:"240px",padding:"16px",border:"1px solid #e8e8e8",borderRadius:"6px",fontFamily:"monospace",fontSize:"14px",resize:"none",marginBottom:"24px",overflow:"auto"},value:l,onChange:e=>t(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),m())},placeholder:"Press Cmd/Ctrl + Enter to transform"}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"auto"},children:(0,c.jsxs)(R.ZP,{type:"primary",style:{backgroundColor:"#000",display:"flex",alignItems:"center",gap:"8px"},onClick:m,loading:n,children:[(0,c.jsx)("span",{children:"Transform"}),(0,c.jsx)("span",{children:"→"})]})})]}),(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"800px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Transformed Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"How LiteLLM transforms your request for the specified provider."}),(0,c.jsx)("br",{}),(0,c.jsx)("p",{style:{color:"#666",margin:0},className:"text-xs",children:"Note: Sensitive headers are not shown."})]}),(0,c.jsxs)("div",{style:{position:"relative",backgroundColor:"#f5f5f5",borderRadius:"6px",flex:"1 1 auto",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,c.jsx)("pre",{style:{padding:"16px",fontFamily:"monospace",fontSize:"14px",margin:0,overflow:"auto",flex:"1 1 auto"},children:a||'curl -X POST \\\n https://api.openai.com/v1/chat/completions \\\n -H \'Authorization: Bearer sk-xxx\' \\\n -H \'Content-Type: application/json\' \\\n -d \'{\n "model": "gpt-4",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n }\n ],\n "temperature": 0.7\n }\''}),(0,c.jsx)(R.ZP,{type:"text",icon:(0,c.jsx)(s8.Z,{}),style:{position:"absolute",right:"8px",top:"8px"},size:"small",onClick:()=>{navigator.clipboard.writeText(a||""),D.ZP.success("Copied to clipboard")}})]})]})]}),(0,c.jsx)("div",{className:"mt-4 text-right w-full",children:(0,c.jsxs)("p",{className:"text-sm text-gray-500",children:["Found an error? File an issue ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/issues",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})]})},ay=l(21770);let av=[{accessorKey:"mcp_info.server_name",header:"Provider",cell:e=>{let{row:s}=e,l=s.original.mcp_info.server_name,t=s.original.mcp_info.logo_url;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[t&&(0,c.jsx)("img",{src:t,alt:"".concat(l," logo"),className:"h-5 w-5 object-contain"}),(0,c.jsx)("span",{className:"font-medium",children:l})]})}},{accessorKey:"name",header:"Tool Name",cell:e=>{let{row:s}=e,l=s.getValue("name");return(0,c.jsx)("div",{children:(0,c.jsx)("span",{className:"font-mono text-sm",children:l})})}},{accessorKey:"description",header:"Description",cell:e=>{let{row:s}=e,l=s.getValue("description");return(0,c.jsx)("div",{className:"max-w-md",children:(0,c.jsx)("span",{className:"text-sm text-gray-700",children:l})})}},{id:"actions",header:"Actions",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"flex items-center space-x-2",children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{"function"==typeof s.original.onToolSelect&&s.original.onToolSelect(l)},children:"Test Tool"})})}}];function ab(e){let{tool:s,onSubmit:l,isLoading:t,result:a,error:r,onClose:n}=e,[i,o]=d.useState({}),m=d.useMemo(()=>"string"==typeof s.inputSchema?{type:"object",properties:{input:{type:"string",description:"Input for this tool"}},required:["input"]}:s.inputSchema,[s.inputSchema]),u=(e,s)=>{o(l=>({...l,[e]:s}))};return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-lg border p-6 max-w-4xl w-full",children:[(0,c.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("h2",{className:"text-xl font-bold",children:["Test Tool: ",(0,c.jsx)("span",{className:"font-mono",children:s.name})]}),(0,c.jsx)("p",{className:"text-gray-600",children:s.description}),(0,c.jsxs)("p",{className:"text-sm text-gray-500 mt-1",children:["Provider: ",s.mcp_info.server_name]})]}),(0,c.jsx)("button",{onClick:n,className:"p-1 rounded-full hover:bg-gray-200",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,c.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Input Parameters"}),(0,c.jsxs)("form",{onSubmit:e=>{e.preventDefault(),l(i)},children:["string"==typeof s.inputSchema?(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:"This tool uses a dynamic input schema."}),(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Input ",(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),(0,c.jsx)("input",{type:"text",value:i.input||"",onChange:e=>u("input",e.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"})]})]}):Object.entries(m.properties).map(e=>{var s,l,t;let[a,r]=e;return(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[a," ",(null===(s=m.required)||void 0===s?void 0:s.includes(a))&&(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),r.description&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:r.description}),"string"===r.type&&(0,c.jsx)("input",{type:"text",value:i[a]||"",onChange:e=>u(a,e.target.value),required:null===(l=m.required)||void 0===l?void 0:l.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"number"===r.type&&(0,c.jsx)("input",{type:"number",value:i[a]||"",onChange:e=>u(a,parseFloat(e.target.value)),required:null===(t=m.required)||void 0===t?void 0:t.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"boolean"===r.type&&(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("input",{type:"checkbox",checked:i[a]||!1,onChange:e=>u(a,e.target.checked),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),(0,c.jsx)("span",{className:"ml-2 text-sm text-gray-600",children:"Enable"})]})]},a)}),(0,c.jsx)("div",{className:"mt-6",children:(0,c.jsx)(k.Z,{type:"submit",disabled:t,className:"w-full px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white",children:t?"Calling...":"Call Tool"})})]})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg overflow-auto max-h-[500px]",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Result"}),t&&(0,c.jsx)("div",{className:"flex justify-center items-center py-8",children:(0,c.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-700"})}),r&&(0,c.jsxs)("div",{className:"bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-md",children:[(0,c.jsx)("p",{className:"font-medium",children:"Error"}),(0,c.jsx)("pre",{className:"mt-2 text-xs overflow-auto whitespace-pre-wrap",children:r.message})]}),a&&!t&&!r&&(0,c.jsxs)("div",{children:[a.map((e,s)=>(0,c.jsxs)("div",{className:"mb-4",children:["text"===e.type&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.text})}),"image"===e.type&&e.url&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("img",{src:e.url,alt:"Tool result",className:"max-w-full h-auto rounded"})}),"embedded_resource"===e.type&&(0,c.jsxs)("div",{className:"bg-white border p-3 rounded-md",children:[(0,c.jsx)("p",{className:"text-sm font-medium",children:"Embedded Resource"}),(0,c.jsxs)("p",{className:"text-xs text-gray-500",children:["Type: ",e.resource_type]}),e.url&&(0,c.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline",children:"View Resource"})]})]},s)),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)("details",{className:"text-xs",children:[(0,c.jsx)("summary",{className:"cursor-pointer text-gray-500 hover:text-gray-700",children:"Raw JSON Response"}),(0,c.jsx)("pre",{className:"mt-2 bg-gray-100 p-2 rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(a,null,2)})]})})]}),!a&&!t&&!r&&(0,c.jsx)("div",{className:"text-center py-8 text-gray-500",children:(0,c.jsx)("p",{children:"The result will appear here after you call the tool."})})]})]})]})}function aZ(e){let{columns:s,data:l,isLoading:t}=e;return(0,c.jsx)(eL,{columns:s,data:l,isLoading:t,renderSubComponent:()=>(0,c.jsx)("div",{}),getRowCanExpand:()=>!1})}function aN(e){let{accessToken:s,userRole:l,userID:t}=e,[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),{data:x,isLoading:p}=(0,e4.a)({queryKey:["mcpTools"],queryFn:()=>{if(!s)throw Error("Access Token required");return(0,y.lU)(s)},enabled:!!s}),{mutate:g,isPending:j}=(0,ay.D)({mutationFn:e=>{if(!s)throw Error("Access Token required");return(0,y.tB)(s,e.tool.name,e.arguments)},onSuccess:e=>{m(e),h(null)},onError:e=>{h(e),m(null)}}),f=d.useMemo(()=>x?x.map(e=>({...e,onToolSelect:e=>{i(e),m(null),h(null)}})):[],[x]),_=d.useMemo(()=>f.filter(e=>{let s=a.toLowerCase();return e.name.toLowerCase().includes(s)||e.description.toLowerCase().includes(s)||e.mcp_info.server_name.toLowerCase().includes(s)}),[f,a]);return s&&l&&t?(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"MCP Tools"})}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search tools...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:a,onChange:e=>r(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"text-sm text-gray-500",children:[_.length," tool",1!==_.length?"s":""," available"]})]})}),(0,c.jsx)(aZ,{columns:av,data:_,isLoading:p})]}),n&&(0,c.jsx)("div",{className:"fixed inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center z-50 p-4",children:(0,c.jsx)(ab,{tool:n,onSubmit:e=>{n&&g({tool:n,arguments:e})},isLoading:j,result:o,error:u,onClose:()=>i(null)})})]}):(0,c.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Missing required authentication parameters."})}var aw=e=>{let{tagId:s,onClose:l,accessToken:t,is_admin:a,editTag:r}=e,[n]=L.Z.useForm(),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(r),[h,x]=(0,d.useState)([]),p=async()=>{if(t)try{let e=(await (0,y.mC)(t,[s]))[s];e&&(o(e),r&&n.setFieldsValue({name:e.name,description:e.description,models:e.models}))}catch(e){console.error("Error fetching tag details:",e),D.ZP.error("Error fetching tag details: "+e)}};(0,d.useEffect)(()=>{p()},[s,t]),(0,d.useEffect)(()=>{t&&eZ("dummy-user","Admin",t,x)},[t]);let g=async e=>{if(t)try{await (0,y.n9)(t,{name:e.name,description:e.description,models:e.models}),D.ZP.success("Tag updated successfully"),u(!1),p()}catch(e){console.error("Error updating tag:",e),D.ZP.error("Error updating tag: "+e)}};return i?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{onClick:l,className:"mb-4",children:"← Back to Tags"}),(0,c.jsxs)(E.Z,{children:["Tag Name: ",i.name]}),(0,c.jsx)(A.Z,{className:"text-gray-500",children:i.description||"No description"})]}),a&&!m&&(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Tag"})]}),m?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(L.Z,{form:n,onFinish:g,layout:"vertical",initialValues:i,children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(q.default,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed LLMs"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process this type of data",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:h.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))})}),(0,c.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,c.jsx)(k.Z,{onClick:()=>u(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]})}):(0,c.jsx)("div",{className:"space-y-6",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Tag Details"}),(0,c.jsxs)("div",{className:"space-y-4 mt-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Name"}),(0,c.jsx)(A.Z,{children:i.name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Description"}),(0,c.jsx)(A.Z,{children:i.description||"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Allowed LLMs"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-2",children:0===i.models.length?(0,c.jsx)(eM.Z,{color:"red",children:"All Models"}):i.models.map(e=>{var s;return(0,c.jsx)(eM.Z,{color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(null===(s=i.model_info)||void 0===s?void 0:s[e])||e})},e)})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:i.created_at?new Date(i.created_at).toLocaleString():"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:i.updated_at?new Date(i.updated_at).toLocaleString():"-"})]})]})]})})]}):(0,c.jsx)("div",{children:"Loading..."})},ak=e=>{let{data:s,onEdit:l,onDelete:t,onSelectTag:a}=e,[r,n]=d.useState([{id:"created_at",desc:!0}]),i=[{header:"Tag Name",accessorKey:"name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.name,children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5",onClick:()=>a(l.name),children:l.name})})})}},{header:"Description",accessorKey:"description",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.description,children:(0,c.jsx)("span",{className:"text-xs",children:l.description||"-"})})}},{header:"Allowed LLMs",accessorKey:"models",cell:e=>{var s,l;let{row:t}=e,a=t.original;return(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:(null==a?void 0:null===(s=a.models)||void 0===s?void 0:s.length)===0?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Models"}):null==a?void 0:null===(l=a.models)||void 0===l?void 0:l.map(e=>{var s;return(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(0,c.jsx)(A.Z,{children:(null===(s=a.model_info)||void 0===s?void 0:s[e])||e})})},e)})})}},{header:"Created",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:new Date(l.created_at).toLocaleDateString()})}},{id:"actions",header:"",cell:e=>{let{row:s}=e,a=s.original;return(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>l(a),className:"cursor-pointer"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(a.name),className:"cursor-pointer"})]})}}],o=(0,eS.b7)({data:s,columns:i,state:{sorting:r},onSortingChange:n,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0});return(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:i.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No tags found"})})})})})]})})})},aS=e=>{let{accessToken:s,userID:l,userRole:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v]=L.Z.useForm(),[b,Z]=(0,d.useState)([]),C=async()=>{if(s)try{let e=await (0,y.UM)(s);console.log("List tags response:",e),r(Object.values(e))}catch(e){console.error("Error fetching tags:",e),D.ZP.error("Error fetching tags: "+e)}},I=async e=>{if(s)try{await (0,y.mY)(s,{name:e.tag_name,description:e.description,models:e.allowed_llms}),D.ZP.success("Tag created successfully"),i(!1),v.resetFields(),C()}catch(e){console.error("Error creating tag:",e),D.ZP.error("Error creating tag: "+e)}},T=async e=>{j(e),p(!0)},E=async()=>{if(s&&g){try{await (0,y.fE)(s,g),D.ZP.success("Tag deleted successfully"),C()}catch(e){console.error("Error deleting tag:",e),D.ZP.error("Error deleting tag: "+e)}p(!1),j(null)}};return(0,d.useEffect)(()=>{l&&t&&s&&(async()=>{try{let e=await (0,y.AZ)(s,l,t);e&&e.data&&Z(e.data)}catch(e){console.error("Error fetching models:",e),D.ZP.error("Error fetching models: "+e)}})()},[s,l,t]),(0,d.useEffect)(()=>{C()},[s]),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:o?(0,c.jsx)(aw,{tagId:o,onClose:()=>{m(null),h(!1)},accessToken:s,is_admin:"Admin"===t,editTag:u}):(0,c.jsxs)("div",{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)("div",{className:"flex justify-between mt-2 w-full items-center mb-4",children:[(0,c.jsx)("h1",{children:"Tag Management"}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center cursor-pointer",onClick:()=>{C(),_(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(A.Z,{className:"mb-4",children:["Click on a tag name to view and edit its details.",(0,c.jsxs)("p",{children:["You can use tags to restrict the usage of certain LLMs based on tags passed in the request. Read more about tag routing ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tag_routing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})]}),(0,c.jsx)(k.Z,{className:"mb-4",onClick:()=>i(!0),children:"+ Create New Tag"}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(ak,{data:a,onEdit:e=>{m(e.name),h(!0)},onDelete:T,onSelectTag:m})})}),(0,c.jsx)(M.Z,{title:"Create New Tag",visible:n,width:800,footer:null,onCancel:()=>{i(!1),v.resetFields()},children:(0,c.jsxs)(L.Z,{form:v,onFinish:I,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"tag_name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed Models"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process requests from this tag",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_llms",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:b.map(e=>(0,c.jsx)(O.default.Option,{value:e.model_info.id,children:(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{children:e.model_name}),(0,c.jsxs)("span",{className:"text-gray-400 ml-2",children:["(",e.model_info.id,")"]})]})},e.model_info.id))})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Tag"})})]})}),x&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Tag"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this tag?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:E,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{p(!1),j(null)},children:"Cancel"})]})]})]})})]})})},aC=l(49096),aI=l(53335);let{cva:aT,cx:aA,compose:aE}=(0,aC.ZD)({hooks:{onComplete:e=>(0,aI.m6)(e)}});function aP(e){var s,l;let{className:t="",...a}=e,r=(0,d.useId)();return s=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),s=e.find(e=>{var s;return(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))===r}),l=e.find(e=>{var s;return e.effect instanceof KeyframeEffect&&(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))!==r});s&&l&&(s.currentTime=l.currentTime)},l=[r],(0,d.useLayoutEffect)(s,l),(0,c.jsxs)("svg",{"data-spinner-id":r,className:aA("pointer-events-none size-12 animate-spin text-current",t),fill:"none",viewBox:"0 0 24 24",...a,children:[(0,c.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,c.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}let aO=new h.S;function aL(){return(0,c.jsxs)("div",{className:aA("h-screen","flex items-center justify-center gap-4"),children:[(0,c.jsx)("div",{className:"text-lg font-medium py-2 pr-4 border-r border-r-gray-200",children:"\uD83D\uDE85 LiteLLM"}),(0,c.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,c.jsx)(aP,{className:"size-4"}),(0,c.jsx)("span",{className:"text-gray-600 text-sm",children:"Loading..."})]})]})}function aD(){let[e,s]=(0,d.useState)(""),[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,h]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[N,w]=(0,d.useState)({PROXY_BASE_URL:"",PROXY_LOGOUT_URL:""}),[k,S]=(0,d.useState)(!0),C=(0,m.useSearchParams)(),[I,T]=(0,d.useState)({data:[]}),[A,E]=(0,d.useState)(null),[P,O]=(0,d.useState)(!0),[L,D]=(0,d.useState)(null),M=C.get("invitation_id"),[F,R]=(0,d.useState)(()=>C.get("page")||"api-keys"),[q,U]=(0,d.useState)(null),z=!1===P&&null===A&&null===M;return((0,d.useEffect)(()=>{E(function(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token")),O(!1)},[]),(0,d.useEffect)(()=>{z&&(window.location.href=(y.H2||"")+"/sso/key/generate")},[A,P]),(0,d.useEffect)(()=>{if(!A)return;let e=(0,u.o)(A);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),U(e.key),r(e.disabled_non_admin_personal_key_creation),e.user_role){let l=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e.toLowerCase())),console.log("Received user role length: ".concat(e.toLowerCase().length)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"org_admin":return"Org Admin";case"internal_user":return"Internal User";case"internal_viewer":return"Internal Viewer";case"app_user":return"App User";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",l),s(l),"Admin Viewer"==l&&R("usage")}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e)),e.login_method?S("username_password"==e.login_method):console.log("User Email is not set ".concat(e)),e.premium_user&&t(e.premium_user),e.auth_header_name&&(0,y.K8)(e.auth_header_name),e.user_id&&D(e.user_id)}},[A]),(0,d.useEffect)(()=>{q&&L&&e&&eZ(L,e,q,v),q&&L&&e&&Z(q,L,e,null,h),q&&lw(q,f)},[q,L,e]),P)?(0,c.jsx)(aL,{}):(0,c.jsx)(d.Suspense,{fallback:(0,c.jsx)(aL,{}),children:(0,c.jsx)(x.aH,{client:aO,children:M?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):(0,c.jsxs)("div",{className:"flex flex-col min-h-screen",children:[(0,c.jsx)(b,{userID:L,userRole:e,premiumUser:l,userEmail:n,setProxySettings:w,proxySettings:N,accessToken:q}),(0,c.jsxs)("div",{className:"flex flex-1 overflow-auto",children:[(0,c.jsx)("div",{className:"mt-8",children:(0,c.jsx)(ar,{setPage:e=>{let s=new URLSearchParams(C);s.set("page",e),window.history.pushState(null,"","?".concat(s.toString())),R(e)},userRole:e,defaultSelectedKey:F})}),"api-keys"==F?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):"models"==F?(0,c.jsx)(lm,{userID:L,userRole:e,token:A,keys:p,accessToken:q,modelData:I,setModelData:T,premiumUser:l,teams:o}):"llm-playground"==F?(0,c.jsx)(tQ,{userID:L,userRole:e,token:A,accessToken:q,disabledPersonalKeyCreation:a}):"users"==F?(0,c.jsx)(l_,{userID:L,userRole:e,token:A,keys:p,teams:o,accessToken:q,setKeys:g}):"teams"==F?(0,c.jsx)(lZ,{teams:o,setTeams:h,searchParams:C,accessToken:q,userID:L,userRole:e,organizations:j}):"organizations"==F?(0,c.jsx)(lk,{organizations:j,setOrganizations:f,userModels:_,accessToken:q,userRole:e,premiumUser:l}):"admin-panel"==F?(0,c.jsx)(lM,{setTeams:h,searchParams:C,accessToken:q,showSSOBanner:k,premiumUser:l,proxySettings:N}):"api_ref"==F?(0,c.jsx)(tN,{proxySettings:N}):"settings"==F?(0,c.jsx)(lK,{userID:L,userRole:e,accessToken:q,premiumUser:l}):"budgets"==F?(0,c.jsx)(l7,{accessToken:q}):"guardrails"==F?(0,c.jsx)(af,{accessToken:q}):"transform-request"==F?(0,c.jsx)(a_,{accessToken:q}):"general-settings"==F?(0,c.jsx)(lQ,{userID:L,userRole:e,accessToken:q,modelData:I}):"model-hub"==F?(0,c.jsx)(tu.Z,{accessToken:q,publicPage:!1,premiumUser:l}):"caching"==F?(0,c.jsx)(aj,{userID:L,userRole:e,token:A,accessToken:q,premiumUser:l}):"pass-through-settings"==F?(0,c.jsx)(l5,{userID:L,userRole:e,accessToken:q,modelData:I}):"logs"==F?(0,c.jsx)(td,{userID:L,userRole:e,token:A,accessToken:q,allTeams:null!=o?o:[]}):"mcp-tools"==F?(0,c.jsx)(aN,{accessToken:q,userRole:e,userID:L}):"tag-management"==F?(0,c.jsx)(aS,{accessToken:q,userRole:e,userID:L}):"new_usage"==F?(0,c.jsx)(tZ,{userID:L,userRole:e,accessToken:q,teams:null!=o?o:[]}):(0,c.jsx)(ao,{userID:L,userRole:e,token:A,accessToken:q,keys:p,premiumUser:l})]})]})})})}},3914:function(e,s,l){"use strict";function t(){let e=window.location.hostname,s=["Lax","Strict","None"];["/","/ui"].forEach(l=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,";"),s.forEach(s=>{let t="None"===s?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; SameSite=").concat(s,";").concat(t),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,"; SameSite=").concat(s,";").concat(t)})}),console.log("After clearing cookies:",document.cookie)}function a(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}l.d(s,{b:function(){return t},e:function(){return a}})}},function(e){e.O(0,[665,990,42,261,899,466,250,699,971,117,744],function(){return e(e.s=36362)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/app/page-36914b80c40b5032.js b/litellm/proxy/_experimental/out/_next/static/chunks/app/page-36914b80c40b5032.js deleted file mode 100644 index eca8f272d7..0000000000 --- a/litellm/proxy/_experimental/out/_next/static/chunks/app/page-36914b80c40b5032.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{60497:function(e,s,l){Promise.resolve().then(l.bind(l,76737))},12011:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return y}});var t=l(57437),a=l(2265),r=l(99376),n=l(20831),i=l(94789),o=l(12514),c=l(49804),d=l(67101),m=l(84264),u=l(49566),h=l(96761),x=l(84566),p=l(19250),g=l(14474),j=l(13634),f=l(73002),_=l(3914);function y(){let[e]=j.Z.useForm(),s=(0,r.useSearchParams)();(0,_.e)("token");let l=s.get("invitation_id"),[y,v]=(0,a.useState)(null),[b,Z]=(0,a.useState)(""),[N,w]=(0,a.useState)(""),[k,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(""),[T,A]=(0,a.useState)("");return(0,a.useEffect)(()=>{l&&(0,p.W_)(l).then(e=>{let s=e.login_url;console.log("login_url:",s),I(s);let l=e.token,t=(0,g.o)(l);A(l),console.log("decoded:",t),v(t.key),console.log("decoded user email:",t.user_email),w(t.user_email),S(t.user_id)})},[l]),(0,t.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,t.jsxs)(o.Z,{children:[(0,t.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,t.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,t.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,t.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,t.jsxs)(d.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,t.jsx)(c.Z,{children:"SSO is under the Enterprise Tier."}),(0,t.jsx)(c.Z,{children:(0,t.jsx)(n.Z,{variant:"primary",className:"mb-2",children:(0,t.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,t.jsxs)(j.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",y,"token:",T,"formValues:",e),y&&T&&(e.user_email=N,k&&l&&(0,p.m_)(y,l,k,e.password).then(e=>{let s="/ui/";s+="?login=success",document.cookie="token="+T,console.log("redirecting to:",s),window.location.href=s}))},children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(j.Z.Item,{label:"Email Address",name:"user_email",children:(0,t.jsx)(u.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,t.jsx)(j.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,t.jsx)(u.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,t.jsx)("div",{className:"mt-10",children:(0,t.jsx)(f.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},76737:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return aD}});var t,a,r,n,i,o,c=l(57437),d=l(2265),m=l(99376),u=l(14474),h=l(21623),x=l(29827),p=l(27648),g=l(80795),j=l(15883),f=l(40428),_=l(3914),y=l(19250);let v=async e=>{if(!e)return null;try{return await (0,y.g)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};var b=e=>{let{userID:s,userEmail:l,userRole:t,premiumUser:a,proxySettings:r,setProxySettings:n,accessToken:i}=e,[o,m]=(0,d.useState)("");(0,d.useEffect)(()=>{(async()=>{if(i){let e=await v(i);console.log("response from fetchProxySettings",e),e&&n(e)}})()},[i]),(0,d.useEffect)(()=>{m((null==r?void 0:r.PROXY_LOGOUT_URL)||"")},[r]);let u=[{key:"1",label:(0,c.jsxs)("div",{className:"py-1",children:[(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Role: ",t]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Email: ",l||"Unknown"]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[(0,c.jsx)(j.Z,{})," ",s]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Premium User: ",String(a)]})]})},{key:"2",label:(0,c.jsxs)("p",{className:"text-sm hover:text-gray-900",onClick:()=>{(0,_.b)(),window.location.href=o},children:[(0,c.jsx)(f.Z,{})," Logout"]})}];return(0,c.jsx)("nav",{className:"bg-white border-b border-gray-200 sticky top-0 z-10",children:(0,c.jsx)("div",{className:"w-full",children:(0,c.jsxs)("div",{className:"flex items-center h-12 px-4",children:[(0,c.jsx)("div",{className:"flex items-center flex-shrink-0",children:(0,c.jsx)(p.default,{href:"/",className:"flex items-center",children:(0,c.jsx)("img",{src:"/get_image",alt:"LiteLLM Brand",className:"h-8 w-auto"})})}),(0,c.jsxs)("div",{className:"flex items-center space-x-5 ml-auto",children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/",target:"_blank",rel:"noopener noreferrer",className:"text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:"Docs"}),(0,c.jsx)(g.Z,{menu:{items:u,style:{padding:"4px",marginTop:"4px"}},children:(0,c.jsxs)("button",{className:"inline-flex items-center text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:["User",(0,c.jsx)("svg",{className:"ml-1 w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19 9l-7 7-7-7"})})]})})]})]})})})};let Z=async(e,s,l,t,a)=>{let r;r="Admin"!=l&&"Admin Viewer"!=l?await (0,y.It)(e,(null==t?void 0:t.organization_id)||null,s):await (0,y.It)(e,(null==t?void 0:t.organization_id)||null),console.log("givenTeams: ".concat(r)),a(r)};var N=l(49804),w=l(67101),k=l(20831),S=l(49566),C=l(87452),I=l(88829),T=l(72208),A=l(84264),E=l(96761),P=l(29233),O=l(52787),L=l(13634),D=l(41021),M=l(51369),F=l(29967),R=l(73002),q=l(56632),U=l(30150),z=e=>{let{step:s=.01,style:l={width:"100%"},placeholder:t="Enter a numerical value",min:a,max:r,onChange:n,...i}=e;return(0,c.jsx)(U.Z,{onWheel:e=>e.currentTarget.blur(),step:s,style:l,placeholder:t,min:a,max:r,onChange:n,...i})};let V=async(e,s,l)=>{try{if(null===e||null===s)return;if(null!==l){let t=(await (0,y.So)(l,e,s,!0)).data.map(e=>e.id),a=[],r=[];return t.forEach(e=>{e.endsWith("/*")?a.push(e):r.push(e)}),[...a,...r]}}catch(e){console.error("Error fetching user models:",e)}},K=e=>{if(e.endsWith("/*")){let s=e.replace("/*","");return"All ".concat(s," models")}return e},B=(e,s)=>{let l=[],t=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));t.push(...r),l.push(e)}else t.push(e)}),[...l,...t].filter((e,s,l)=>l.indexOf(e)===s)};var H=l(20577),J=l(15424),W=l(75957);let G=(e,s)=>["metadata","config","enforced_params","aliases"].includes(e)||"json"===s.format,Y=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch(e){return!1}},$=(e,s,l)=>{let t={max_budget:"Enter maximum budget in USD (e.g., 100.50)",budget_duration:"Select a time period for budget reset",tpm_limit:"Enter maximum tokens per minute (whole number)",rpm_limit:"Enter maximum requests per minute (whole number)",duration:"Enter duration (e.g., 30s, 24h, 7d)",metadata:'Enter JSON object with key-value pairs\nExample: {"team": "research", "project": "nlp"}',config:'Enter configuration as JSON object\nExample: {"setting": "value"}',permissions:"Enter comma-separated permission strings",enforced_params:'Enter parameters as JSON object\nExample: {"param": "value"}',blocked:"Enter true/false or specific block conditions",aliases:'Enter aliases as JSON object\nExample: {"alias1": "value1", "alias2": "value2"}',models:"Select one or more model names",key_alias:"Enter a unique identifier for this key",tags:"Enter comma-separated tag strings"}[e]||({string:"Text input",number:"Numeric input",integer:"Whole number input",boolean:"True/False value"})[l]||"Text input";return G(e,s)?"".concat(t,"\nMust be valid JSON format"):s.enum?"Select from available options\nAllowed values: ".concat(s.enum.join(", ")):t};var X=e=>{let{schemaComponent:s,excludedFields:l=[],form:t,overrideLabels:a={},overrideTooltips:r={},customValidation:n={},defaultValues:i={}}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null);(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.lP)()).components.schemas[s];if(!e)throw Error('Schema component "'.concat(s,'" not found'));m(e);let a={};Object.keys(e.properties).filter(e=>!l.includes(e)&&void 0!==i[e]).forEach(e=>{a[e]=i[e]}),t.setFieldsValue(a)}catch(e){console.error("Schema fetch error:",e),h(e instanceof Error?e.message:"Failed to fetch schema")}})()},[s,t,l]);let x=e=>{if(e.type)return e.type;if(e.anyOf){let s=e.anyOf.map(e=>e.type);if(s.includes("number")||s.includes("integer"))return"number";s.includes("string")}return"string"},p=(e,s)=>{var l;let t;let d=x(s),m=null==o?void 0:null===(l=o.required)||void 0===l?void 0:l.includes(e),u=a[e]||s.title||e,h=r[e]||s.description,p=[];m&&p.push({required:!0,message:"".concat(u," is required")}),n[e]&&p.push({validator:n[e]}),G(e,s)&&p.push({validator:async(e,s)=>{if(s&&!Y(s))throw Error("Please enter valid JSON")}});let g=h?(0,c.jsxs)("span",{children:[u," ",(0,c.jsx)(W.Z,{title:h,children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}):u;return t=G(e,s)?(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter as JSON",className:"font-mono"}):s.enum?(0,c.jsx)(O.default,{children:s.enum.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"number"===d||"integer"===d?(0,c.jsx)(H.Z,{style:{width:"100%"},precision:"integer"===d?0:void 0}):"duration"===e?(0,c.jsx)(S.Z,{placeholder:"eg: 30s, 30h, 30d"}):(0,c.jsx)(S.Z,{placeholder:h||""}),(0,c.jsx)(L.Z.Item,{label:g,name:e,className:"mt-8",rules:p,initialValue:i[e],help:(0,c.jsx)("div",{className:"text-xs text-gray-500",children:$(e,s,d)}),children:t},e)};return u?(0,c.jsxs)("div",{className:"text-red-500",children:["Error: ",u]}):(null==o?void 0:o.properties)?(0,c.jsx)("div",{children:Object.entries(o.properties).filter(e=>{let[s]=e;return!l.includes(s)}).map(e=>{let[s,l]=e;return p(s,l)})}):null},Q=e=>{let{teams:s,value:l,onChange:t}=e;return(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:t,filterOption:(e,s)=>{var l,t,a;return!!s&&((null===(a=s.children)||void 0===a?void 0:null===(t=a[0])||void 0===t?void 0:null===(l=t.props)||void 0===l?void 0:l.children)||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==s?void 0:s.map(e=>(0,c.jsxs)(O.default.Option,{value:e.team_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})},ee=l(57365),es=l(93192);function el(e){let{isInvitationLinkModalVisible:s,setIsInvitationLinkModalVisible:l,baseUrl:t,invitationLinkData:a}=e,{Title:r,Paragraph:n}=es.default,i=()=>(null==a?void 0:a.has_user_setup_sso)?new URL("/ui",t).toString():new URL("/ui?invitation_id=".concat(null==a?void 0:a.id),t).toString();return(0,c.jsxs)(M.Z,{title:"Invitation Link",visible:s,width:800,footer:null,onOk:()=>{l(!1)},onCancel:()=>{l(!1)},children:[(0,c.jsx)(n,{children:"Copy and send the generated link to onboard this user to the proxy."}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"User ID"}),(0,c.jsx)(A.Z,{children:null==a?void 0:a.user_id})]}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{children:"Invitation Link"}),(0,c.jsx)(A.Z,{children:(0,c.jsx)(A.Z,{children:i()})})]}),(0,c.jsx)("div",{className:"flex justify-end mt-5",children:(0,c.jsx)(P.CopyToClipboard,{text:i(),onCopy:()=>D.ZP.success("Copied!"),children:(0,c.jsx)(k.Z,{variant:"primary",children:"Copy invitation link"})})})]})}var et=l(77388),ea=l(1709),er=l(73879),en=l(3632),ei=l(15452),eo=l.n(ei),ec=l(71157),ed=l(44643),em=e=>{let{accessToken:s,teams:l,possibleUIRoles:t,onUsersCreated:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.g)(s);g(e)}catch(e){console.error("Error fetching UI settings:",e)}})(),f(new URL("/",window.location.href).toString())},[s]);let _=async()=>{u(!0);let e=i.map(e=>({...e,status:"pending"}));o(e);let l=!1;for(let a=0;ae.trim())),e.models&&"string"==typeof e.models&&(e.models=e.models.split(",").map(e=>e.trim())),e.max_budget&&""!==e.max_budget.toString().trim()&&(e.max_budget=parseFloat(e.max_budget.toString()));let r=await (0,y.Ov)(s,null,e);if(console.log("Full response:",r),r&&(r.key||r.user_id)){l=!0,console.log("Success case triggered");let e=(null===(t=r.data)||void 0===t?void 0:t.user_id)||r.user_id;try{if(null==p?void 0:p.SSO_ENABLED){let e=new URL("/ui",j).toString();o(s=>s.map((s,l)=>l===a?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let l=await (0,y.XO)(s,e),t=new URL("/ui?invitation_id=".concat(l.id),j).toString();o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,invitation_link:t}:e))}}catch(e){console.error("Error creating invitation:",e),o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=(null==r?void 0:r.error)||"Failed to create user";console.log("Error message:",e),o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=(null==s?void 0:null===(n=s.response)||void 0===n?void 0:null===(r=n.data)||void 0===r?void 0:r.error)||(null==s?void 0:s.message)||String(s);o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}u(!1),l&&a&&a()};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>n(!0),children:"+ Bulk Invite Users"}),(0,c.jsx)(M.Z,{title:"Bulk Invite Users",visible:r,width:800,onCancel:()=>n(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,c.jsx)("div",{className:"flex flex-col",children:0===i.length?(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,c.jsxs)("div",{className:"ml-11 mb-6",children:[(0,c.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,c.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,c.jsx)("li",{children:"Download our CSV template"}),(0,c.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,c.jsx)("li",{children:"Save the file and upload it here"}),(0,c.jsx)("li",{children:"After creation, download the results file containing the API keys for each user"})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,c.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_email"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_role"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_view_only", "internal_user", "internal_user_view_only")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"teams"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"models"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=new Blob([eo().unparse([["user_email","user_role","teams","max_budget","budget_duration","models"],["user@example.com","internal_user","team-id-1,team-id-2","100","30d","gpt-3.5-turbo,gpt-4"]])],{type:"text/csv"}),s=window.URL.createObjectURL(e),l=document.createElement("a");l.href=s,l.download="bulk_users_template.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(s)},size:"lg",className:"w-full md:w-auto",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download CSV Template"]})]}),(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,c.jsx)("div",{className:"ml-11",children:(0,c.jsx)(et.Z,{beforeUpload:e=>(x(null),eo().parse(e,{complete:e=>{let s=e.data[0],l=["user_email","user_role"].filter(e=>!s.includes(e));if(l.length>0){x("Your CSV is missing these required columns: ".concat(l.join(", "))),o([]);return}try{let l=e.data.slice(1).map((e,l)=>{var t,a,r,n,i,o;let c={user_email:(null===(t=e[s.indexOf("user_email")])||void 0===t?void 0:t.trim())||"",user_role:(null===(a=e[s.indexOf("user_role")])||void 0===a?void 0:a.trim())||"",teams:null===(r=e[s.indexOf("teams")])||void 0===r?void 0:r.trim(),max_budget:null===(n=e[s.indexOf("max_budget")])||void 0===n?void 0:n.trim(),budget_duration:null===(i=e[s.indexOf("budget_duration")])||void 0===i?void 0:i.trim(),models:null===(o=e[s.indexOf("models")])||void 0===o?void 0:o.trim(),rowNumber:l+2,isValid:!0,error:""},d=[];c.user_email||d.push("Email is required"),c.user_role||d.push("Role is required"),c.user_email&&!c.user_email.includes("@")&&d.push("Invalid email format");let m=["proxy_admin","proxy_admin_view_only","internal_user","internal_user_view_only"];return c.user_role&&!m.includes(c.user_role)&&d.push("Invalid role. Must be one of: ".concat(m.join(", "))),c.max_budget&&isNaN(parseFloat(c.max_budget.toString()))&&d.push("Max budget must be a number"),d.length>0&&(c.isValid=!1,c.error=d.join(", ")),c}),t=l.filter(e=>e.isValid);o(l),0===t.length?x("No valid users found in the CSV. Please check the errors below."):t.length{x("Failed to parse CSV file: ".concat(e.message)),o([])},header:!1}),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,c.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,c.jsx)(en.Z,{className:"text-3xl text-gray-400 mb-2"}),(0,c.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,c.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,c.jsx)(k.Z,{size:"sm",children:"Browse files"})]})})})]}):(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:i.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),h&&(0,c.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,c.jsx)(A.Z,{className:"text-red-600 font-medium",children:h})}),(0,c.jsxs)("div",{className:"ml-11",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,c.jsx)("div",{className:"flex items-center",children:i.some(e=>"success"===e.status||"failed"===e.status)?(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[i.filter(e=>"success"===e.status).length," Successful"]}),i.some(e=>"failed"===e.status)&&(0,c.jsxs)(A.Z,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[i.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[i.filter(e=>e.isValid).length," of ",i.length," users valid"]})]})}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex space-x-3",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]})]}),i.some(e=>"success"===e.status)&&(0,c.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"mr-3 mt-1",children:(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-blue-500"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,c.jsxs)(A.Z,{className:"block text-sm text-blue-700 mt-1",children:[(0,c.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing API keys and invitation links. Users will need these API keys to make LLM requests through LiteLLM."]})]})]})}),(0,c.jsx)(ea.Z,{dataSource:i,columns:[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,s)=>s.isValid?s.status&&"pending"!==s.status?"success"===s.status?(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}),(0,c.jsx)("span",{className:"text-green-500",children:"Success"})]}),s.invitation_link&&(0,c.jsx)("div",{className:"mt-1",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:s.invitation_link}),(0,c.jsx)(P.CopyToClipboard,{text:s.invitation_link,onCopy:()=>D.ZP.success("Invitation link copied!"),children:(0,c.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Failed"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(s.error)})]}):(0,c.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:s.error})]})}],size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]}),i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Start New Bulk Import"}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=i.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([eo().unparse(e)],{type:"text/csv"}),l=window.URL.createObjectURL(s),t=document.createElement("a");t.href=l,t.download="bulk_users_results.csv",document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(l)},variant:"primary",className:"flex items-center",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download User Credentials"]})]})]})]})})})]})};let{Option:eu}=O.default;var eh=e=>{let{userID:s,accessToken:l,teams:t,possibleUIRoles:a,onUserCreated:r,isEmbedded:n=!1}=e,[i,o]=(0,d.useState)(null),[u]=L.Z.useForm(),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),N=(0,m.useRouter)(),[w,P]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.So)(l,s,"any"),t=[];for(let s=0;s{N&&P(new URL("/",window.location.href).toString())},[N]);let F=async e=>{var t,a,o;try{D.ZP.info("Making API Call"),n||x(!0),e.models&&0!==e.models.length||(e.models=["no-default-models"]),console.log("formValues in create user:",e);let a=await (0,y.Ov)(l,null,e);console.log("user create Response:",a),g(!0);let o=(null===(t=a.data)||void 0===t?void 0:t.user_id)||a.user_id;if(r&&n){r(o),u.resetFields();return}if(null==i?void 0:i.SSO_ENABLED){let e={id:crypto.randomUUID(),user_id:o,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:s,updated_at:new Date,updated_by:s,has_user_setup_sso:!0};Z(e),v(!0)}else(0,y.XO)(l,o).then(e=>{e.has_user_setup_sso=!1,Z(e),v(!0)});D.ZP.success("API user Created"),u.resetFields(),localStorage.removeItem("userData"+s)}catch(s){let e=(null===(o=s.response)||void 0===o?void 0:null===(a=o.data)||void 0===a?void 0:a.detail)||(null==s?void 0:s.message)||"Error creating the user";D.ZP.error(e),console.error("Error creating the user:",s)}};return n?(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]}):(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>x(!0),children:"+ Invite User"}),(0,c.jsx)(em,{accessToken:l,teams:t,possibleUIRoles:a}),(0,c.jsxs)(M.Z,{title:"Invite User",visible:h,width:800,footer:null,onOk:()=>{x(!1),u.resetFields()},onCancel:()=>{x(!1),g(!1),u.resetFields()},children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Create a User who can own keys"}),(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Global Proxy Role"," ",(0,c.jsx)(W.Z,{title:"This is the role that the user will globally on the proxy. This role is independent of any team/org specific roles.",children:(0,c.jsx)(J.Z,{})})]}),name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{children:"Personal Key Creation"})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(L.Z.Item,{className:"gap-2",label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Models user has access to, outside of team scope.",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),j.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]})]}),p&&(0,c.jsx)(el,{isInvitationLinkModalVisible:_,setIsInvitationLinkModalVisible:v,baseUrl:w,invitationLinkData:b})]})},ex=l(7310),ep=l.n(ex),eg=l(20347);let{Option:ej}=O.default,ef=e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set";var e_=e=>{let{value:s,onChange:l,className:t="",style:a={}}=e;return(0,c.jsxs)(O.default,{style:{width:"100%",...a},value:s||void 0,onChange:l,className:t,placeholder:"n/a",children:[(0,c.jsx)(ej,{value:"24h",children:"daily"}),(0,c.jsx)(ej,{value:"7d",children:"weekly"}),(0,c.jsx)(ej,{value:"30d",children:"monthly"})]})};let{Option:ey}=O.default,ev=e=>{let s=[];if(console.log("data:",JSON.stringify(e)),e)for(let l of e)l.metadata&&l.metadata.tags&&s.push(...l.metadata.tags);let l=Array.from(new Set(s)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",l),l},eb=async(e,s,l,t)=>{try{if(null===e||null===s)return[];if(null!==l){let a=(await (0,y.So)(l,e,s,!0,t)).data.map(e=>e.id);return console.log("available_model_names:",a),a}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},eZ=async(e,s,l,t)=>{try{if(null===e||null===s)return;if(null!==l){let a=(await (0,y.So)(l,e,s)).data.map(e=>e.id);console.log("available_model_names:",a),t(a)}}catch(e){console.error("Error fetching user models:",e)}};var eN=e=>{let{userID:s,team:l,teams:t,userRole:a,accessToken:r,data:n,setData:i}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)("you"),[U,V]=(0,d.useState)(ev(n)),[B,H]=(0,d.useState)([]),[G,Y]=(0,d.useState)(l),[$,ee]=(0,d.useState)(!1),[es,el]=(0,d.useState)(null),[et,ea]=(0,d.useState)({}),[er,en]=(0,d.useState)([]),[ei,eo]=(0,d.useState)(!1),ec=()=>{u(!1),o.resetFields()},ed=()=>{u(!1),x(null),Y(null),o.resetFields()};(0,d.useEffect)(()=>{s&&a&&r&&eZ(s,a,r,f)},[r,s,a]),(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.t3)(r)).guardrails.map(e=>e.guardrail_name);H(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[r]),(0,d.useEffect)(()=>{(async()=>{try{if(r){let e=sessionStorage.getItem("possibleUserRoles");if(e)ea(JSON.parse(e));else{let e=await (0,y.lg)(r);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),ea(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[r]);let em=async e=>{try{var l,t,a;let c=null!==(l=null==e?void 0:e.key_alias)&&void 0!==l?l:"",d=null!==(t=null==e?void 0:e.team_id)&&void 0!==t?t:null;if((null!==(a=null==n?void 0:n.filter(e=>e.team_id===d).map(e=>e.key_alias))&&void 0!==a?a:[]).includes(c))throw Error("Key alias ".concat(c," already exists for team with ID ").concat(d,", please provide another key alias"));if(D.ZP.info("Making API Call"),u(!0),"you"===b&&(e.user_id=s),"service_account"===b){let s={};try{s=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}s.service_account_id=e.key_alias,e.metadata=JSON.stringify(s)}let m=await (0,y.wX)(r,s,e);console.log("key create Response:",m),i(e=>e?[...e,m]:[m]),window.addNewKeyToList&&window.addNewKeyToList(m),x(m.key),g(m.soft_budget),D.ZP.success("API Key Created"),o.resetFields(),localStorage.removeItem("userData"+s)}catch(e){console.log("error in create key:",e),D.ZP.error("Error creating the key: ".concat(e))}};(0,d.useEffect)(()=>{if(s&&a&&r){var e;eb(s,a,r,null!==(e=null==G?void 0:G.team_id)&&void 0!==e?e:null).then(e=>{var s;v(Array.from(new Set([...null!==(s=null==G?void 0:G.models)&&void 0!==s?s:[],...e])))})}o.setFieldValue("models",[])},[G,r,s,a]);let eu=async e=>{if(!e){en([]);return}eo(!0);try{let s=new URLSearchParams;if(s.append("user_email",e),null==r)return;let l=(await (0,y.u5)(r,s)).map(e=>({label:"".concat(e.user_email," (").concat(e.user_id,")"),value:e.user_id,user:e}));en(l)}catch(e){console.error("Error fetching users:",e),D.ZP.error("Failed to search for users")}finally{eo(!1)}},ex=(0,d.useCallback)(ep()(e=>eu(e),300),[r]),ej=(e,s)=>{let l=s.user;o.setFieldsValue({user_id:l.user_id})};return(0,c.jsxs)("div",{children:[a&&eg.LQ.includes(a)&&(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>u(!0),children:"+ Create New Key"}),(0,c.jsx)(M.Z,{visible:m,width:1e3,footer:null,onOk:ec,onCancel:ed,children:(0,c.jsxs)(L.Z,{form:o,onFinish:em,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Ownership"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Owned By"," ",(0,c.jsx)(W.Z,{title:"Select who will own this API key",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,c.jsxs)(F.ZP.Group,{onChange:e=>Z(e.target.value),value:b,children:[(0,c.jsx)(F.ZP,{value:"you",children:"You"}),(0,c.jsx)(F.ZP,{value:"service_account",children:"Service Account"}),"Admin"===a&&(0,c.jsx)(F.ZP,{value:"another_user",children:"Another User"})]})}),"another_user"===b&&(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["User ID"," ",(0,c.jsx)(W.Z,{title:"The user who will own this key and be responsible for its usage",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===b,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{ex(e)},onSelect:(e,s)=>ej(e,s),options:er,loading:ei,allowClear:!0,style:{width:"100%"},notFoundContent:ei?"Searching...":"No users found"}),(0,c.jsx)(R.ZP,{onClick:()=>ee(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,c.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Team"," ",(0,c.jsx)(W.Z,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:l?l.team_id:null,className:"mt-4",children:(0,c.jsx)(Q,{teams:t,onChange:e=>{Y((null==t?void 0:t.find(s=>s.team_id===e))||null)}})})]}),(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Details"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["you"===b||"another_user"===b?"Key Name":"Service Account ID"," ",(0,c.jsx)(W.Z,{title:"you"===b||"another_user"===b?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:"Please input a ".concat("you"===b?"key name":"service account ID")}],help:"required",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",className:"mt-4",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},onChange:e=>{e.includes("all-team-models")&&o.setFieldsValue({models:["all-team-models"]})},children:[(0,c.jsx)(ey,{value:"all-team-models",children:"All Team Models"},"all-team-models"),_.map(e=>(0,c.jsx)(ey,{value:e,children:K(e)},e))]})})]}),(0,c.jsx)("div",{className:"mb-8",children:(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{className:"m-0",children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Max Budget (USD)"," ",(0,c.jsx)(W.Z,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:"Budget cannot exceed team max budget: $".concat((null==l?void 0:l.max_budget)!==null&&(null==l?void 0:l.max_budget)!==void 0?null==l?void 0:l.max_budget:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.max_budget&&s>l.max_budget)throw Error("Budget cannot exceed team max budget: $".concat(l.max_budget))}}],children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Reset Budget"," ",(0,c.jsx)(W.Z,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:"Team Reset Budget: ".concat((null==l?void 0:l.budget_duration)!==null&&(null==l?void 0:l.budget_duration)!==void 0?null==l?void 0:l.budget_duration:"None"),children:(0,c.jsx)(e_,{onChange:e=>o.setFieldValue("budget_duration",e)})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:"TPM cannot exceed team TPM limit: ".concat((null==l?void 0:l.tpm_limit)!==null&&(null==l?void 0:l.tpm_limit)!==void 0?null==l?void 0:l.tpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.tpm_limit&&s>l.tpm_limit)throw Error("TPM limit cannot exceed team TPM limit: ".concat(l.tpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:"RPM cannot exceed team RPM limit: ".concat((null==l?void 0:l.rpm_limit)!==null&&(null==l?void 0:l.rpm_limit)!==void 0?null==l?void 0:l.rpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.rpm_limit&&s>l.rpm_limit)throw Error("RPM limit cannot exceed team RPM limit: ".concat(l.rpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Expire Key"," ",(0,c.jsx)(W.Z,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days)",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"duration",className:"mt-4",children:(0,c.jsx)(S.Z,{placeholder:"e.g., 30d"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:B.map(e=>({value:e,label:e}))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Metadata"," ",(0,c.jsx)(W.Z,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Tags"," ",(0,c.jsx)(W.Z,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:U})}),(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("b",{children:"Advanced Settings"}),(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,c.jsx)("a",{href:y.H2?"".concat(y.H2,"/#/key%20management/generate_key_fn_key_generate_post"):"/#/key%20management/generate_key_fn_key_generate_post",target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:"documentation"})]}),children:(0,c.jsx)(J.Z,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(X,{schemaComponent:"GenerateKeyRequest",form:o,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Key"})})]})}),$&&(0,c.jsx)(M.Z,{title:"Create New User",visible:$,onCancel:()=>ee(!1),footer:null,width:800,children:(0,c.jsx)(eh,{userID:s,accessToken:r,teams:t,possibleUIRoles:et,onUserCreated:e=>{el(e),o.setFieldsValue({user_id:e}),ee(!1)},isEmbedded:!0})}),h&&(0,c.jsx)(M.Z,{visible:m,onOk:ec,onCancel:ed,footer:null,children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Save your Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please save this secret key somewhere safe and accessible. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:null!=h?(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:h})}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>{D.ZP.success("API Key copied to clipboard")},children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]}):(0,c.jsx)(A.Z,{children:"Key being created, this might take 30s"})})]})})]})},ew=l(7366),ek=e=>{let{selectedTeam:s,currentOrg:l,selectedKeyAlias:t,accessToken:a,currentPage:r=1}=e,[n,i]=(0,d.useState)({keys:[],total_count:0,current_page:1,total_pages:0}),[o,c]=(0,d.useState)(!0),[m,u]=(0,d.useState)(null),h=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};try{if(console.log("calling fetchKeys"),!a){console.log("accessToken",a);return}c(!0);let r=await (0,y.OD)(a,(null==l?void 0:l.organization_id)||null,(null==s?void 0:s.team_id)||"",t,e.page||1,50);console.log("data",r),i(r),u(null)}catch(e){u(e instanceof Error?e:Error("An error occurred"))}finally{c(!1)}};return(0,d.useEffect)(()=>{h(),console.log("selectedTeam",s,"currentOrg",l,"accessToken",a,"selectedKeyAlias",t)},[s,l,a,t]),{keys:n.keys,isLoading:o,error:m,pagination:{currentPage:n.current_page,totalPages:n.total_pages,totalCount:n.total_count},refresh:h,setKeys:e=>{i(s=>{let l="function"==typeof e?e(s.keys):e;return{...s,keys:l}})}}},eS=l(71594),eC=l(24525),eI=l(21626),eT=l(97214),eA=l(28241),eE=l(58834),eP=l(69552),eO=l(71876);function eL(e){let{data:s=[],columns:l,getRowCanExpand:t,renderSubComponent:a,isLoading:r=!1,expandedRequestId:n,onRowExpand:i}=e,o=(0,eS.b7)({data:s,columns:l,getRowCanExpand:t,getCoreRowModel:(0,eC.sC)(),getExpandedRowModel:(0,eC.rV)(),state:{expanded:n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{}},onExpandedChange:e=>{if(!i)return;let l=n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{},t="function"==typeof e?e(l):e;if(0===Object.keys(t).length){i(null);return}let a=Object.keys(t)[0],r=void 0!==a?s[parseInt(a)]:null;i(r?r.request_id:null)}});return(0,c.jsx)("div",{className:"rounded-lg custom-border",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:r?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading logs..."})})})}):o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))}),e.getIsExpanded()&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:e.getVisibleCells().length,children:a({row:e})})})]},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No logs found"})})})})})]})})}var eD=l(27281),eM=l(41649),eF=l(12514),eR=l(12485),eq=l(18135),eU=l(35242),ez=l(29706),eV=l(77991),eK=l(10900),eB=l(23628),eH=l(74998);function eJ(e){var s,l;let{keyData:t,onCancel:a,onSubmit:r,teams:n,accessToken:i,userID:o,userRole:m}=e,[u]=L.Z.useForm(),[h,x]=(0,d.useState)([]),p=null==n?void 0:n.find(e=>e.team_id===t.team_id),[g,j]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(o&&m&&i)try{if(null===t.team_id){let e=(await (0,y.So)(i,o,m)).data.map(e=>e.id);j(e)}else if(null==p?void 0:p.team_id){let e=await eb(o,m,i,p.team_id);j(Array.from(new Set([...p.models,...e])))}}catch(e){console.error("Error fetching models:",e)}})()},[o,m,i,p,t.team_id]);let f={...t,budget_duration:(l=t.budget_duration)&&({"24h":"daily","7d":"weekly","30d":"monthly"})[l]||null,metadata:t.metadata?JSON.stringify(t.metadata,null,2):"",guardrails:(null===(s=t.metadata)||void 0===s?void 0:s.guardrails)||[]};return(0,c.jsxs)(L.Z,{form:u,onFinish:r,initialValues:f,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Key Alias",name:"key_alias",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[g.length>0&&(0,c.jsx)(O.default.Option,{value:"all-team-models",children:"All Team Models"}),g.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"daily",children:"Daily"}),(0,c.jsx)(O.default.Option,{value:"weekly",children:"Weekly"}),(0,c.jsx)(O.default.Option,{value:"monthly",children:"Monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Guardrails",name:"guardrails",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsx)(L.Z.Item,{name:"token",hidden:!0,children:(0,c.jsx)(q.default,{})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(k.Z,{variant:"light",onClick:a,children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]})}function eW(e){let{selectedToken:s,visible:l,onClose:t,accessToken:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(!1);(0,d.useEffect)(()=>{l&&s&&r.setFieldsValue({key_alias:s.key_alias,max_budget:s.max_budget,tpm_limit:s.tpm_limit,rpm_limit:s.rpm_limit,duration:s.duration||""})},[l,s,r]),(0,d.useEffect)(()=>{l||(i(null),p(!1),r.resetFields())},[l,r]),(0,d.useEffect)(()=>{(null==o?void 0:o.duration)?h((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString()}catch(e){return null}})(o.duration)):h(null)},[null==o?void 0:o.duration]);let g=async()=>{if(s&&a){p(!0);try{let e=await r.validateFields(),l=await (0,y.s0)(a,s.token,e);i(l.key),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key"),p(!1)}}},j=()=>{i(null),p(!1),r.resetFields(),t()};return(0,c.jsx)(M.Z,{title:"Regenerate API Key",open:l,onCancel:j,footer:n?[(0,c.jsx)(k.Z,{onClick:j,children:"Close"},"close")]:[(0,c.jsx)(k.Z,{onClick:j,className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:g,disabled:x,children:x?"Regenerating...":"Regenerate"},"regenerate")],children:n?(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:(null==s?void 0:s.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:n})}),(0,c.jsx)(P.CopyToClipboard,{text:n,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]}):(0,c.jsxs)(L.Z,{form:r,layout:"vertical",onValuesChange:e=>{"duration"in e&&m(s=>({...s,duration:e.duration}))},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",(null==s?void 0:s.expires)?new Date(s.expires).toLocaleString():"Never"]}),u&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",u]})]})})}function eG(e){var s,l;let{keyId:t,onClose:a,keyData:r,accessToken:n,userID:i,userRole:o,teams:m,onKeyDataUpdate:u,onDelete:h}=e,[x,p]=(0,d.useState)(!1),[g]=L.Z.useForm(),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1);if(!r)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(A.Z,{children:"Key not found"})]});let b=async e=>{try{var s,l;if(!n)return;let t=e.token;if(e.key=t,e.metadata&&"string"==typeof e.metadata)try{let l=JSON.parse(e.metadata);e.metadata={...l,...(null===(s=e.guardrails)||void 0===s?void 0:s.length)>0?{guardrails:e.guardrails}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),D.ZP.error("Invalid metadata JSON");return}else e.metadata={...e.metadata||{},...(null===(l=e.guardrails)||void 0===l?void 0:l.length)>0?{guardrails:e.guardrails}:{}};e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,y.Nc)(n,e);u&&u(a),D.ZP.success("Key updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update key"),console.error("Error updating key:",e)}},Z=async()=>{try{if(!n)return;await (0,y.I1)(n,r.token),D.ZP.success("Key deleted successfully"),h&&h(),a()}catch(e){console.error("Error deleting the key:",e),D.ZP.error("Failed to delete key")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(E.Z,{children:r.key_alias||"API Key"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:r.token})]}),o&&eg.LQ.includes(o)&&(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{icon:eB.Z,variant:"secondary",onClick:()=>v(!0),className:"flex items-center",children:"Regenerate Key"}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>f(!0),className:"flex items-center",children:"Delete Key"})]})]}),(0,c.jsx)(eW,{selectedToken:r,visible:_,onClose:()=>v(!1),accessToken:n}),j&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:Z,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>f(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number(r.spend).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",null!==r.max_budget?"$".concat(r.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Key Settings"}),!x&&o&&eg.LQ.includes(o)&&(0,c.jsx)(k.Z,{variant:"light",onClick:()=>p(!0),children:"Edit Settings"})]}),x?(0,c.jsx)(eJ,{keyData:r,onCancel:()=>p(!1),onSubmit:b,teams:m,accessToken:n,userID:i,userRole:o}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.token})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key Alias"}),(0,c.jsx)(A.Z,{children:r.key_alias||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Secret Key"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.key_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)(A.Z,{children:r.team_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),(0,c.jsx)(A.Z,{children:r.organization_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:new Date(r.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Expires"}),(0,c.jsx)(A.Z,{children:r.expires?new Date(r.expires).toLocaleString():"Never"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Spend"}),(0,c.jsxs)(A.Z,{children:["$",Number(r.spend).toFixed(4)," USD"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsx)(A.Z,{children:null!==r.max_budget?"$".concat(r.max_budget," USD"):"Unlimited"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",null!==r.max_parallel_requests?r.max_parallel_requests:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model TPM Limits: ",(null===(s=r.metadata)||void 0===s?void 0:s.model_tpm_limit)?JSON.stringify(r.metadata.model_tpm_limit):"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model RPM Limits: ",(null===(l=r.metadata)||void 0===l?void 0:l.model_rpm_limit)?JSON.stringify(r.metadata.model_rpm_limit):"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(r.metadata,null,2)})]})]})]})})]})]})]})}var eY=l(87908),e$=l(82422),eX=l(2356),eQ=l(44633),e0=l(86462),e1=l(3837),e2=e=>{var s;let{options:l,onApplyFilters:t,onResetFilters:a,initialValues:r={},buttonLabel:n="Filter"}=e,[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)((null===(s=l[0])||void 0===s?void 0:s.name)||""),[h,x]=(0,d.useState)(r),[p,j]=(0,d.useState)(r),[f,_]=(0,d.useState)(!1),[y,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),S=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=e=>{let s=e.target;!S.current||S.current.contains(s)||s.closest(".ant-dropdown")||s.closest(".ant-select-dropdown")||o(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{l.length>0&&l[0].isSearchable&&l[0].searchFn&&C(l[0])},[]);let C=async e=>{if(e.isSearchable&&e.searchFn){Z(!0);try{let s=await e.searchFn("");v(s)}catch(e){console.error("Error loading initial options:",e),v([])}finally{Z(!1)}}};(0,d.useEffect)(()=>{i&&(null==L?void 0:L.isSearchable)&&(null==L?void 0:L.searchFn)&&C(L)},[i,m]);let I=e=>{u(e),_(!1);let s=l.find(s=>s.name===e);(null==s?void 0:s.isSearchable)&&(null==s?void 0:s.searchFn)?C(s):v([])},T=(0,d.useCallback)(ep()(async(e,s)=>{if(s.isSearchable&&s.searchFn){Z(!0);try{let l=await s.searchFn(e);v(l)}catch(e){console.error("Error searching:",e),v([])}finally{Z(!1)}}},300),[]),A=e=>{j(s=>({...s,[m]:e}))},E=()=>{let e={};l.forEach(s=>{e[s.name]=""}),j(e)},P=l.map(e=>({key:e.name,label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[m===e.name&&(0,c.jsx)(e$.Z,{className:"h-4 w-4 text-blue-600"}),e.label||e.name]})})),L=l.find(e=>e.name===m);return(0,c.jsxs)("div",{className:"relative",ref:S,children:[(0,c.jsx)(k.Z,{icon:eX.Z,onClick:()=>o(!i),variant:"secondary",size:"xs",className:"flex items-center pr-2",children:n}),i&&(0,c.jsx)(eF.Z,{className:"absolute left-0 mt-2 w-[500px] z-50 border border-gray-200 shadow-lg",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsx)(g.Z,{menu:{items:P,onClick:e=>{let{key:s}=e;return I(s)},style:{minWidth:"200px"}},onOpenChange:_,open:f,trigger:["click"],children:(0,c.jsxs)(R.ZP,{className:"min-w-40 text-left flex justify-between items-center",children:[(null==L?void 0:L.label)||m,f?(0,c.jsx)(eQ.Z,{className:"h-4 w-4"}):(0,c.jsx)(e0.Z,{className:"h-4 w-4"})]})}),(null==L?void 0:L.isSearchable)?(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search ".concat(L.label||m,"..."),value:p[m]||void 0,onChange:e=>A(e),onSearch:e=>{w(e),T(e,L)},onInputKeyDown:e=>{"Enter"===e.key&&N&&(A(N),e.preventDefault())},filterOption:!1,className:"flex-1 w-full max-w-full truncate min-w-100",loading:b,options:y,allowClear:!0,notFoundContent:b?(0,c.jsx)(eY.Z,{size:"small"}):(0,c.jsx)("div",{className:"p-2",children:N&&(0,c.jsxs)(R.ZP,{type:"link",className:"p-0 mt-1",onClick:()=>{A(N);let e=document.activeElement;e&&e.blur()},children:["Use “",N,"” as filter value"]})})}):(0,c.jsx)(q.default,{placeholder:"Enter value...",value:p[m]||"",onChange:e=>A(e.target.value),className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",suffix:p[m]?(0,c.jsx)(e1.Z,{className:"h-4 w-4 cursor-pointer text-gray-400 hover:text-gray-500",onClick:e=>{e.stopPropagation(),A("")}}):null})]}),(0,c.jsxs)("div",{className:"flex gap-2 justify-end",children:[(0,c.jsx)(R.ZP,{onClick:()=>{E(),a(),o(!1)},children:"Reset"}),(0,c.jsx)(R.ZP,{onClick:()=>{x(p),t(p),o(!1)},children:"Apply Filters"})]})]})})]})},e4=l(16593);let e5=async e=>{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.OD)(e,null,"",null,l,100),r=a.keys.map(e=>e.key_alias).filter(Boolean);s=[...s,...r],l{if(!e)return[];try{let l=[],t=1,a=!0;for(;a;){let r=await (0,y.It)(e,s||null,null);l=[...l,...r.teams],t{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.r6)(e);s=[...s,...a.organizations],l{if(!s){g([]);return}let e=[...s];o["Team ID"]&&(e=e.filter(e=>e.team_id===o["Team ID"])),o["Organization ID"]&&(e=e.filter(e=>e.organization_id===o["Organization ID"])),g(e)},[s,o]),(0,d.useEffect)(()=>{let e=async()=>{let e=await e6(a);e.length>0&&u(e);let s=await e3(a);s.length>0&&x(s)};a&&e()},[a]);let j=(0,e4.a)({queryKey:["allKeys"],queryFn:async()=>{if(!a)throw Error("Access token required");return await e5(a)},enabled:!!a}).data||[];return(0,d.useEffect)(()=>{l&&l.length>0&&u(e=>e.length{t&&t.length>0&&x(e=>e.length{if(c({"Team ID":e["Team ID"]||"","Organization ID":e["Organization ID"]||"","Key Alias":e["Key Alias"]||""}),e["Team ID"]){let s=null==m?void 0:m.find(s=>s.team_id===e["Team ID"]);s&&r(s)}if(e["Organization ID"]){let s=null==h?void 0:h.find(s=>s.organization_id===e["Organization ID"]);s&&n(s)}let s=e["Key Alias"];i(s&&j.find(e=>e===s)||null)},handleFilterReset:()=>{c({"Team ID":"","Organization ID":"","Key Alias":""}),r(null),n(null)}}}({keys:s,teams:i,organizations:j,accessToken:x,setSelectedTeam:m,setCurrentOrg:f,setSelectedKeyAlias:h});(0,d.useEffect)(()=>{if(x){let e=s.map(e=>e.user_id).filter(e=>null!==e);(async()=>{N((await (0,y.Of)(x,e,1,100)).users)})()}},[x,s]),(0,d.useEffect)(()=>{if(_){let e=()=>{_()};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}},[_]);let P=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return s.getCanExpand()?(0,c.jsx)("button",{onClick:s.getToggleExpandedHandler(),style:{cursor:"pointer"},children:s.getIsExpanded()?"▼":"▶"}):null}},{header:"Key ID",accessorKey:"token",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>b(e.getValue()),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>{let s=e.getValue();return(0,c.jsx)(W.Z,{title:s,children:s?s.length>20?"".concat(s.slice(0,20),"..."):s:"-"})}},{header:"Secret Key",accessorKey:"key_name",cell:e=>(0,c.jsx)("span",{className:"font-mono text-xs",children:e.getValue()})},{header:"Team Alias",accessorKey:"team_id",cell:e=>{let{row:s,getValue:l}=e,t=l(),a=null==I?void 0:I.find(e=>e.team_id===t);return(null==a?void 0:a.team_alias)||"Unknown"}},{header:"Team ID",accessorKey:"team_id",cell:e=>(0,c.jsx)(W.Z,{title:e.getValue(),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})},{header:"Organization ID",accessorKey:"organization_id",cell:e=>e.getValue()?e.renderValue():"-"},{header:"User Email",accessorKey:"user_id",cell:e=>{let s=e.getValue(),l=Z.find(e=>e.user_id===s);return(null==l?void 0:l.user_email)?l.user_email:"-"}},{header:"User ID",accessorKey:"user_id",cell:e=>{let s=e.getValue();return s?(0,c.jsx)(W.Z,{title:s,children:(0,c.jsxs)("span",{children:[s.slice(0,7),"..."]})}):"-"}},{header:"Created At",accessorKey:"created_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"-"}},{header:"Created By",accessorKey:"created_by",cell:e=>e.getValue()||"Unknown"},{header:"Expires",accessorKey:"expires",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"Never"}},{header:"Spend (USD)",accessorKey:"spend",cell:e=>Number(e.getValue()).toFixed(4)},{header:"Budget (USD)",accessorKey:"max_budget",cell:e=>null!==e.getValue()&&void 0!==e.getValue()?e.getValue():"Unlimited"},{header:"Budget Reset",accessorKey:"budget_reset_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleString():"Never"}},{header:"Models",accessorKey:"models",cell:e=>{let s=e.getValue();return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:s&&s.length>0?s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):"-"})}},{header:"Rate Limits",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{children:["TPM: ",null!==l.tpm_limit?l.tpm_limit:"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",null!==l.rpm_limit?l.rpm_limit:"Unlimited"]})]})}}];return(0,c.jsx)("div",{className:"w-full h-full overflow-hidden",children:v?(0,c.jsx)(eG,{keyId:v,onClose:()=>b(null),keyData:s.find(e=>e.token===v),onKeyDataUpdate:e=>{l(s=>s.map(s=>s.token===e.token?e8(s,e):s))},onDelete:()=>{l(e=>e.filter(e=>e.token!==v))},accessToken:x,userID:p,userRole:g,teams:I}):(0,c.jsxs)("div",{className:"border-b py-4 flex-1 overflow-hidden",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between w-full mb-2",children:[(0,c.jsx)(e2,{options:[{name:"Team ID",label:"Team ID",isSearchable:!0,searchFn:async e=>I&&0!==I.length?I.filter(s=>s.team_id.toLowerCase().includes(e.toLowerCase())||s.team_alias&&s.team_alias.toLowerCase().includes(e.toLowerCase())).map(e=>({label:"".concat(e.team_alias||e.team_id," (").concat(e.team_id,")"),value:e.team_id})):[]},{name:"Organization ID",label:"Organization ID",isSearchable:!0,searchFn:async e=>T&&0!==T.length?T.filter(s=>{var l,t;return null!==(t=null===(l=s.organization_id)||void 0===l?void 0:l.toLowerCase().includes(e.toLowerCase()))&&void 0!==t&&t}).filter(e=>null!==e.organization_id&&void 0!==e.organization_id).map(e=>({label:"".concat(e.organization_id||"Unknown"," (").concat(e.organization_id,")"),value:e.organization_id})):[]},{name:"Key Alias",label:"Key Alias",isSearchable:!0,searchFn:async e=>C.filter(s=>s.toLowerCase().includes(e.toLowerCase())).map(e=>({label:e,value:e}))}],onApplyFilters:A,initialValues:w,onResetFilters:E}),(0,c.jsxs)("div",{className:"flex items-center gap-4",children:[(0,c.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:["Showing ",t?"...":"".concat((a.currentPage-1)*n+1," - ").concat(Math.min(a.currentPage*n,a.totalCount))," of ",t?"...":a.totalCount," results"]}),(0,c.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",t?"...":a.currentPage," of ",t?"...":a.totalPages]}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage-1),disabled:t||1===a.currentPage,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage+1),disabled:t||a.currentPage===a.totalPages,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]}),(0,c.jsx)("div",{className:"h-[75vh] overflow-auto",children:(0,c.jsx)(eL,{columns:P.filter(e=>"expander"!==e.id),data:S,isLoading:t,getRowCanExpand:()=>!1,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{})})})]})})}console.log=function(){};var e9=e=>{let{userID:s,userRole:l,accessToken:t,selectedTeam:a,setSelectedTeam:r,data:n,setData:i,teams:o,premiumUser:m,currentOrg:u,organizations:h,setCurrentOrg:x,selectedKeyAlias:p,setSelectedKeyAlias:g}=e,[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),[C,I]=(0,d.useState)(null),[T,O]=(0,d.useState)(null),[F,R]=(0,d.useState)((null==a?void 0:a.team_id)||""),[q,U]=(0,d.useState)("");(0,d.useEffect)(()=>{R((null==a?void 0:a.team_id)||"")},[a]);let{keys:z,isLoading:K,error:B,pagination:J,refresh:W,setKeys:G}=ek({selectedTeam:a,currentOrg:u,selectedKeyAlias:p,accessToken:t});window.refreshKeysList=W,window.addNewKeyToList=e=>{G(s=>[e,...s])};let[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(null),[el,et]=(0,d.useState)([]),ea=new Set,[er,en]=(0,d.useState)(!1),[ei,eo]=(0,d.useState)(!1),[ec,ed]=(0,d.useState)(null),[em,eu]=(0,d.useState)(null),[eh]=L.Z.useForm(),[ex,ep]=(0,d.useState)(null),[eg,ej]=(0,d.useState)(ea),[ef,e_]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("in calculateNewExpiryTime for selectedToken",ee),(null==em?void 0:em.duration)?ep((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString("en-US",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!0})}catch(e){return null}})(em.duration)):ep(null),console.log("calculateNewExpiryTime:",ex)},[ee,null==em?void 0:em.duration]),(0,d.useEffect)(()=>{(async()=>{try{if(null===s||null===l||null===t)return;let e=await V(s,l,t);e&&et(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,s,l]),(0,d.useEffect)(()=>{if(o){let e=new Set;o.forEach((s,l)=>{let t=s.team_id;e.add(t)}),ej(e)}},[o]);let ey=async()=>{if(null!=b&&null!=n){try{await (0,y.I1)(t,b);let e=n.filter(e=>e.token!==b);i(e)}catch(e){console.error("Error deleting the key:",e)}v(!1),Z(null)}},ev=(e,s)=>{eu(l=>({...l,[e]:s}))},eb=async()=>{if(!m){D.ZP.error("Regenerate API Key is an Enterprise feature. Please upgrade to use this feature.");return}if(null!=ee)try{let e=await eh.validateFields(),s=await (0,y.s0)(t,ee.token,e);if(ed(s.key),n){let l=n.map(l=>l.token===(null==ee?void 0:ee.token)?{...l,key_name:s.key_name,...e}:l);i(l)}eo(!1),eh.resetFields(),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key")}};return(0,c.jsxs)("div",{children:[(0,c.jsx)(e7,{keys:z,setKeys:G,isLoading:K,pagination:J,onPageChange:e=>{W({page:e})},pageSize:100,teams:o,selectedTeam:a,setSelectedTeam:r,accessToken:t,userID:s,userRole:l,organizations:h,setCurrentOrg:x,refresh:W,selectedKeyAlias:p,setSelectedKeyAlias:g}),_&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ey,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{v(!1),Z(null)},children:"Cancel"})]})]})]})}),(0,c.jsx)(M.Z,{title:"Regenerate API Key",visible:ei,onCancel:()=>{eo(!1),eh.resetFields()},footer:[(0,c.jsx)(k.Z,{onClick:()=>{eo(!1),eh.resetFields()},className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:eb,disabled:!m,children:m?"Regenerate":"Upgrade to Regenerate"},"regenerate")],children:m?(0,c.jsxs)(L.Z,{form:eh,layout:"vertical",onValuesChange:(e,s)=>{"duration"in e&&ev("duration",e.duration)},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry:"," ",(null==ee?void 0:ee.expires)!=null?new Date(ee.expires).toLocaleString():"Never"]}),ex&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",ex]})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to use this feature"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat",target:"_blank",children:"Get Free Trial"})})]})}),ec&&(0,c.jsx)(M.Z,{visible:!!ec,onCancel:()=>ed(null),footer:[(0,c.jsx)(k.Z,{onClick:()=>ed(null),children:"Close"},"close")],children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:(null==ee?void 0:ee.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:ec})}),(0,c.jsx)(P.CopyToClipboard,{text:ec,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]})})]})},se=l(12011);console.log=function(){},console.log("isLocal:",!1);var ss=e=>{let{userID:s,userRole:l,teams:t,keys:a,setUserRole:r,userEmail:n,setUserEmail:i,setTeams:o,setKeys:h,premiumUser:x,organizations:p}=e,[g,j]=(0,d.useState)(null),[f,v]=(0,d.useState)(null),b=(0,m.useSearchParams)(),k=function(e){console.log("COOKIES",document.cookie);let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token"),S=b.get("invitation_id"),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)(null),[E,P]=(0,d.useState)([]),[O,L]=(0,d.useState)(null),[D,M]=(0,d.useState)(null),[F,R]=(0,d.useState)(null);if(window.addEventListener("beforeunload",function(){sessionStorage.clear()}),(0,d.useEffect)(()=>{if(k){let e=(0,u.o)(k);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),I(e.key),e.user_role){let s=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"app_user":return"App User";case"internal_user":return"Internal User";case"internal_user_viewer":return"Internal Viewer";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",s),r(s)}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e))}}if(s&&C&&l&&!a&&!g){let e=sessionStorage.getItem("userModels"+s);e?P(JSON.parse(e)):(console.log("currentOrg: ".concat(JSON.stringify(f))),(async()=>{try{let e=await (0,y.g)(C);L(e);let t=await (0,y.Br)(C,s,l,!1,null,null);j(t.user_info),console.log("userSpendData: ".concat(JSON.stringify(g))),(null==t?void 0:t.teams[0].keys)?h(t.keys.concat(t.teams.filter(e=>"Admin"===l||e.user_id===s).flatMap(e=>e.keys))):h(t.keys),sessionStorage.setItem("userData"+s,JSON.stringify(t.keys)),sessionStorage.setItem("userSpendData"+s,JSON.stringify(t.user_info));let a=(await (0,y.So)(C,s,l)).data.map(e=>e.id);console.log("available_model_names:",a),P(a),console.log("userModels:",E),sessionStorage.setItem("userModels"+s,JSON.stringify(a))}catch(e){console.error("There was an error fetching the data",e)}})(),Z(C,s,l,f,o))}},[s,k,C,a,l]),(0,d.useEffect)(()=>{console.log("currentOrg: ".concat(JSON.stringify(f),", accessToken: ").concat(C,", userID: ").concat(s,", userRole: ").concat(l)),C&&(console.log("fetching teams"),Z(C,s,l,f,o))},[f]),(0,d.useEffect)(()=>{if(null!==a&&null!=D&&null!==D.team_id){let e=0;for(let s of(console.log("keys: ".concat(JSON.stringify(a))),a))D.hasOwnProperty("team_id")&&null!==s.team_id&&s.team_id===D.team_id&&(e+=s.spend);console.log("sum: ".concat(e)),A(e)}else if(null!==a){let e=0;for(let s of a)e+=s.spend;A(e)}},[D]),null!=S)return(0,c.jsx)(se.default,{});if(null==k){console.log("All cookies before redirect:",document.cookie),(0,_.b)();let e="/sso/key/generate";return console.log("Full URL:",e),window.location.href=e,null}if(null==C)return null;if(null==s)return(0,c.jsx)("h1",{children:"User ID is not set"});if(null==l&&r("App Owner"),l&&"Admin Viewer"==l){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to create keys"})]})}return console.log("inside user dashboard, selected team",D),console.log("All cookies after redirect:",document.cookie),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(N.Z,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,c.jsx)(eN,{userID:s,team:D,teams:t,userRole:l,accessToken:C,data:a,setData:h},D?D.team_id:null),(0,c.jsx)(e9,{userID:s,userRole:l,accessToken:C,selectedTeam:D||null,setSelectedTeam:M,selectedKeyAlias:F,setSelectedKeyAlias:R,data:a,setData:h,premiumUser:x,teams:t,currentOrg:f,setCurrentOrg:v,organizations:p})]})})})},sl=l(97765);(t=n||(n={})).OpenAI="OpenAI",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.Anthropic="Anthropic",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.Google_AI_Studio="Google AI Studio",t.Bedrock="Amazon Bedrock",t.Groq="Groq",t.MistralAI="Mistral AI",t.Deepseek="Deepseek",t.Cohere="Cohere",t.Databricks="Databricks",t.Ollama="Ollama",t.xAI="xAI",t.AssemblyAI="AssemblyAI",t.Cerebras="Cerebras",t.Sambanova="Sambanova",t.Perplexity="Perplexity",t.TogetherAI="TogetherAI",t.Openrouter="Openrouter",t.FireworksAI="Fireworks AI";let st={OpenAI:"openai",OpenAI_Text:"text-completion-openai",Azure:"azure",Azure_AI_Studio:"azure_ai",Anthropic:"anthropic",Google_AI_Studio:"gemini",Bedrock:"bedrock",Groq:"groq",MistralAI:"mistral",Cohere:"cohere_chat",OpenAI_Compatible:"openai",OpenAI_Text_Compatible:"text-completion-openai",Vertex_AI:"vertex_ai",Databricks:"databricks",xAI:"xai",Deepseek:"deepseek",Ollama:"ollama",AssemblyAI:"assemblyai",Cerebras:"cerebras",Sambanova:"sambanova",Perplexity:"perplexity",TogetherAI:"togetherai",Openrouter:"openrouter",FireworksAI:"fireworks_ai"},sa="/ui/assets/logos/",sr={Anthropic:"".concat(sa,"anthropic.svg"),AssemblyAI:"".concat(sa,"assemblyai_small.png"),Azure:"".concat(sa,"microsoft_azure.svg"),"Azure AI Foundry (Studio)":"".concat(sa,"microsoft_azure.svg"),"Amazon Bedrock":"".concat(sa,"bedrock.svg"),Cerebras:"".concat(sa,"cerebras.svg"),Cohere:"".concat(sa,"cohere.svg"),Databricks:"".concat(sa,"databricks.svg"),Deepseek:"".concat(sa,"deepseek.svg"),"Fireworks AI":"".concat(sa,"fireworks.svg"),Groq:"".concat(sa,"groq.svg"),"Google AI Studio":"".concat(sa,"google.svg"),"Mistral AI":"".concat(sa,"mistral.svg"),Ollama:"".concat(sa,"ollama.svg"),OpenAI:"".concat(sa,"openai_small.svg"),"OpenAI Text Completion":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Text Completion Models (Together AI, etc.)":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Endpoints (Together AI, etc.)":"".concat(sa,"openai_small.svg"),Openrouter:"".concat(sa,"openrouter.svg"),Perplexity:"".concat(sa,"perplexity-ai.svg"),Sambanova:"".concat(sa,"sambanova.svg"),TogetherAI:"".concat(sa,"togetherai.svg"),"Vertex AI (Anthropic, Gemini, etc.)":"".concat(sa,"google.svg"),xAI:"".concat(sa,"xai.svg")},sn=e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:sr[e],displayName:e}}let s=Object.keys(st).find(s=>st[s].toLowerCase()===e.toLowerCase());if(!s)return{logo:"",displayName:e};let l=n[s];return{logo:sr[l],displayName:l}},si=e=>"Vertex AI (Anthropic, Gemini, etc.)"===e?"gemini-pro":"Anthropic"==e||"Amazon Bedrock"==e?"claude-3-opus":"Google AI Studio"==e?"gemini-pro":"Azure AI Foundry (Studio)"==e?"azure_ai/command-r-plus":"Azure"==e?"azure/my-deployment":"gpt-3.5-turbo",so=(e,s)=>{console.log("Provider key: ".concat(e));let l=st[e];console.log("Provider mapped to: ".concat(l));let t=[];return e&&"object"==typeof s&&(Object.entries(s).forEach(e=>{let[s,a]=e;null!==a&&"object"==typeof a&&"litellm_provider"in a&&(a.litellm_provider===l||a.litellm_provider.includes(l))&&t.push(s)}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(s).forEach(e=>{let[s,l]=e;null!==l&&"object"==typeof l&&"litellm_provider"in l&&"cohere"===l.litellm_provider&&t.push(s)}))),t},sc=async(e,s,l)=>{try{console.log("handling submit for formValues:",e);let s=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let l=st[e.custom_llm_provider]+"/*";e.model_name=l,s.push({public_name:l,litellm_model:l}),e.model=l}let l=[];for(let t of s){let s={},a={},r=t.public_name;for(let[l,r]of(s.model=t.litellm_model,e.input_cost_per_token&&(e.input_cost_per_token=Number(e.input_cost_per_token)/1e6),e.output_cost_per_token&&(e.output_cost_per_token=Number(e.output_cost_per_token)/1e6),s.model=t.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==r&&"custom_pricing"!==l&&"pricing_model"!==l&&"cache_control"!==l){if("model_name"==l)s.model=r;else if("custom_llm_provider"==l){console.log("custom_llm_provider:",r);let e=st[r];s.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==l)continue;else if("base_model"===l)a[l]=r;else if("team_id"===l)a.team_id=r;else if("mode"==l)console.log("placing mode in modelInfo"),a.mode=r,delete s.mode;else if("custom_model_name"===l)s.model=r;else if("litellm_extra_params"==l){console.log("litellm_extra_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,t]of Object.entries(e))s[l]=t}}else if("model_info_params"==l){console.log("model_info_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[s,l]of Object.entries(e))a[s]=l}}else if("input_cost_per_token"===l||"output_cost_per_token"===l||"input_cost_per_second"===l){r&&(s[l]=Number(r));continue}else s[l]=r}l.push({litellmParamsObj:s,modelInfoObj:a,modelName:r})}return l}catch(e){D.ZP.error("Failed to create model: "+e,10)}},sd=async(e,s,l,t)=>{try{let a=await sc(e,s,l);if(!a||0===a.length)return;for(let e of a){let{litellmParamsObj:l,modelInfoObj:t,modelName:a}=e,r={model_name:a,litellm_params:l,model_info:t},n=await (0,y.kK)(s,r);console.log("response for model create call: ".concat(n.data))}t&&t(),l.resetFields()}catch(e){D.ZP.error("Failed to add model: "+e,10)}};var sm=l(53410),su=l(47451),sh=l(69410);let{Link:sx}=es.default,sp={[n.OpenAI]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Vertex_AI]:[{key:"vertex_project",label:"Vertex Project",placeholder:"adroit-cadet-1234..",required:!0},{key:"vertex_location",label:"Vertex Location",placeholder:"us-east-1",required:!0},{key:"vertex_credentials",label:"Vertex Credentials",required:!0,type:"upload"}],[n.AssemblyAI]:[{key:"api_base",label:"API Base",type:"select",required:!0,options:["https://api.assemblyai.com","https://api.eu.assemblyai.com"]},{key:"api_key",label:"AssemblyAI API Key",type:"password",required:!0}],[n.Azure]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_version",label:"API Version",placeholder:"2023-07-01-preview",tooltip:"By default litellm will use the latest version. If you want to use a different version, you can specify it here"},{key:"base_model",label:"Base Model",placeholder:"azure/gpt-3.5-turbo"},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.Azure_AI_Studio]:[{key:"api_base",label:"API Base",placeholder:"https://.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",tooltip:"Enter your full Target URI from Azure Foundry here. Example: https://litellm8397336933.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",required:!0},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.OpenAI_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Bedrock]:[{key:"aws_access_key_id",label:"AWS Access Key ID",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_secret_access_key",label:"AWS Secret Access Key",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_region_name",label:"AWS Region Name",placeholder:"us-east-1",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."}],[n.Ollama]:[],[n.Anthropic]:[{key:"api_key",label:"API Key",placeholder:"sk-",type:"password",required:!0}],[n.Google_AI_Studio]:[{key:"api_key",label:"API Key",placeholder:"aig-",type:"password",required:!0}],[n.Groq]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.MistralAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Deepseek]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cohere]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Databricks]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.xAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cerebras]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Sambanova]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Perplexity]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.TogetherAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Openrouter]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.FireworksAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}]};var sg=e=>{let{selectedProvider:s,uploadProps:l}=e,t=n[s],a=d.useMemo(()=>sp[t]||[],[t]);return(0,c.jsx)(c.Fragment,{children:a.map(e=>{var s;return(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:e.label,name:e.key,rules:e.required?[{required:!0,message:"Required"}]:void 0,tooltip:e.tooltip,className:"vertex_credentials"===e.key?"mb-0":void 0,children:"select"===e.type?(0,c.jsx)(O.default,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"upload"===e.type?(0,c.jsx)(et.Z,{...l,children:(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(en.Z,{}),children:"Click to Upload"})}):(0,c.jsx)(S.Z,{placeholder:e.placeholder,type:"password"===e.type?"password":"text"})}),"vertex_credentials"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Give litellm a gcp service account(.json file), so it can make the relevant calls"})})]}),"base_model"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,c.jsx)(sx,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key)})})};let{Title:sj,Link:sf}=es.default;var s_=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,onUpdateCredential:a,uploadProps:r,addOrEdit:i,existingCredential:o}=e,[m]=L.Z.useForm(),[u,h]=(0,d.useState)(n.OpenAI),[x,p]=(0,d.useState)(!1);return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(o))),(0,c.jsx)(M.Z,{title:"add"===i?"Add New Credential":"Edit Credential",visible:s,onCancel:()=>{l(),m.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:m,onFinish:e=>{"add"===i?t(e):a(e),m.resetFields()},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==o?void 0:o.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials",disabled:null!=o&&!!o.credential_name})}),(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,c.jsx)(O.default,{value:(null==o?void 0:o.credential_info.custom_llm_provider)||u,onChange:e=>{h(e)},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sg,{selectedProvider:u,uploadProps:r}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sf,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),m.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"add"===i?"Add Credential":"Update Credential"})]})]})]})})},sy=e=>{let{accessToken:s,uploadProps:l,credentialList:t,fetchCredentials:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)(null),[h]=L.Z.useForm();console.log("selectedCredential in credentials panel: ".concat(JSON.stringify(m)));let x=["credential_name","custom_llm_provider"],p=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.eZ)(s,e.credential_name,t);D.ZP.success("Credential updated successfully"),console.log("response: ".concat(JSON.stringify(r))),o(!1),a(s)},g=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.oC)(s,t);D.ZP.success("Credential added successfully"),console.log("response: ".concat(JSON.stringify(r))),n(!1),a(s)};(0,d.useEffect)(()=>{s&&a(s)},[s]);let j=e=>{let s={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"},l=s[e.toLowerCase()]||s.default;return(0,c.jsx)(eM.Z,{color:l,size:"xs",children:e})},f=async e=>{if(!s){console.error("No access token found");return}let l=await (0,y.gX)(s,e);console.log("response: ".concat(JSON.stringify(l))),D.ZP.success("Credential deleted successfully"),a(s)};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsxs)(A.Z,{children:["Configured credentials for different AI providers. Add and manage your API credentials."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/credentials",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]})}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Credential Name"}),(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Description"})]})}),(0,c.jsx)(eT.Z,{children:t&&0!==t.length?t.map((e,s)=>{var l,t;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.credential_name}),(0,c.jsx)(eA.Z,{children:j((null===(l=e.credential_info)||void 0===l?void 0:l.custom_llm_provider)||"-")}),(0,c.jsx)(eA.Z,{children:(null===(t=e.credential_info)||void 0===t?void 0:t.description)||"-"}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{icon:sm.Z,variant:"light",size:"sm",onClick:()=>{console.log("credential being set: ".concat(JSON.stringify(e))),u(e),o(!0)}}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"light",size:"sm",onClick:()=>f(e.credential_name)})]})]},s)}):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),className:"mt-4",children:"Add Credential"}),r&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:r,onCancel:()=>n(!1),uploadProps:l,addOrEdit:"add",onUpdateCredential:p,existingCredential:null}),i&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:i,existingCredential:m,onUpdateCredential:p,uploadProps:l,onCancel:()=>o(!1),addOrEdit:"edit"})]})};let sv=e=>{var s;return(null==e?void 0:null===(s=e.model_info)||void 0===s?void 0:s.team_public_model_name)?e.model_info.team_public_model_name:(null==e?void 0:e.model_name)||"-"};var sb=l(53003),sZ=l(47323),sN=l(75105),sw=l(40278),sk=l(14301),sS=l(59664),sC=e=>{let{modelMetrics:s,modelMetricsCategories:l,customTooltip:t,premiumUser:a}=e;return(0,c.jsx)(sS.Z,{title:"Time to First token (s)",className:"h-72",data:s,index:"date",showLegend:!1,categories:l,colors:["indigo","rose"],connectNulls:!0,customTooltip:t})},sI=e=>{let{teamData:s,canEditTeam:l,handleMemberDelete:t,setSelectedEditMember:a,setIsEditMemberModalVisible:r,setIsAddMemberModalVisible:n}=e;return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"User Email"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:s.team_info.members_with_roles.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_email})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.role})}),(0,c.jsx)(eA.Z,{children:l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{a(e),r(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(e)})]})})]},s))})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),children:"Add Member"})]})},sT=l(61994),sA=l(85180),sE=l(89245),sP=l(78355);let sO={"/key/generate":"Member can generate a virtual key for this team","/key/update":"Member can update a virtual key belonging to this team","/key/delete":"Member can delete a virtual key belonging to this team","/key/info":"Member can get info about a virtual key belonging to this team","/key/regenerate":"Member can regenerate a virtual key belonging to this team","/key/{key_id}/regenerate":"Member can regenerate a virtual key belonging to this team","/key/list":"Member can list virtual keys belonging to this team","/key/block":"Member can block a virtual key belonging to this team","/key/unblock":"Member can unblock a virtual key belonging to this team"},sL=e=>e.includes("/info")||e.includes("/list")?"GET":"POST",sD=e=>{let s=sL(e),l=sO[e];if(!l){for(let[s,t]of Object.entries(sO))if(e.includes(s)){l=t;break}}return l||(l="Access ".concat(e)),{method:s,endpoint:e,description:l,route:e}};var sM=e=>{let{teamId:s,accessToken:l,canEditTeam:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)(!0),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),g=async()=>{try{if(m(!0),!l)return;let e=await (0,y.aC)(l,s),t=e.all_available_permissions||[];r(t);let a=e.team_member_permissions||[];i(a),p(!1)}catch(e){D.ZP.error("Failed to load permissions"),console.error("Error fetching permissions:",e)}finally{m(!1)}};(0,d.useEffect)(()=>{g()},[s,l]);let j=(e,s)=>{i(s?[...n,e]:n.filter(s=>s!==e)),p(!0)},f=async()=>{try{if(!l)return;h(!0),await (0,y.TF)(l,s,n),D.ZP.success("Permissions updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update permissions"),console.error("Error updating permissions:",e)}finally{h(!1)}};if(o)return(0,c.jsx)("div",{className:"p-6 text-center",children:"Loading permissions..."});let _=a.length>0;return(0,c.jsxs)(eF.Z,{className:"bg-white shadow-md rounded-md p-6",children:[(0,c.jsxs)("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center border-b pb-4 mb-6",children:[(0,c.jsx)(E.Z,{className:"mb-2 sm:mb-0",children:"Member Permissions"}),t&&x&&(0,c.jsxs)("div",{className:"flex gap-3",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(sE.Z,{}),onClick:()=>{g()},children:"Reset"}),(0,c.jsxs)(k.Z,{onClick:f,loading:u,className:"flex items-center gap-2",children:[(0,c.jsx)(sP.Z,{})," Save Changes"]})]})]}),(0,c.jsx)(A.Z,{className:"mb-6 text-gray-600",children:"Control what team members can do when they are not team admins."}),_?(0,c.jsxs)(eI.Z,{className:"mt-4",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Method"}),(0,c.jsx)(eP.Z,{children:"Endpoint"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Access"})]})}),(0,c.jsx)(eT.Z,{children:a.map(e=>{let s=sD(e);return(0,c.jsxs)(eO.Z,{className:"hover:bg-gray-50 transition-colors",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"px-2 py-1 rounded text-xs font-medium ".concat("GET"===s.method?"bg-blue-100 text-blue-800":"bg-green-100 text-green-800"),children:s.method})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"font-mono text-sm text-gray-800",children:s.endpoint})}),(0,c.jsx)(eA.Z,{className:"text-gray-700",children:s.description}),(0,c.jsx)(eA.Z,{className:"text-right",children:(0,c.jsx)(sT.Z,{checked:n.includes(e),onChange:s=>j(e,s.target.checked),disabled:!t})})]},e)})})]}):(0,c.jsx)("div",{className:"py-12",children:(0,c.jsx)(sA.Z,{description:"No permissions available"})})]})},sF=e=>{var s,l,t;let{visible:a,onCancel:r,onSubmit:n,initialData:i,mode:o,config:m}=e,[u]=L.Z.useForm();console.log("Initial Data:",i),(0,d.useEffect)(()=>{if(a){if("edit"===o&&i)u.setFieldsValue({...i,role:i.role||m.defaultRole});else{var e;u.resetFields(),u.setFieldsValue({role:m.defaultRole||(null===(e=m.roleOptions[0])||void 0===e?void 0:e.value)})}}},[a,i,o,u,m.defaultRole,m.roleOptions]);let h=async e=>{try{let s=Object.entries(e).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:"string"==typeof t?t.trim():t}},{});n(s),u.resetFields(),D.ZP.success("Successfully ".concat("add"===o?"added":"updated"," member"))}catch(e){D.ZP.error("Failed to submit form"),console.error("Form submission error:",e)}},x=e=>{switch(e.type){case"input":return(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",onChange:e=>{e.target.value=e.target.value.trim()}});case"select":var s;return(0,c.jsx)(O.default,{children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))});default:return null}};return(0,c.jsx)(M.Z,{title:m.title||("add"===o?"Add Member":"Edit Member"),open:a,width:800,footer:null,onCancel:r,children:(0,c.jsxs)(L.Z,{form:u,onFinish:h,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[m.showEmail&&(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user@example.com",onChange:e=>{e.target.value=e.target.value.trim()}})}),m.showEmail&&m.showUserId&&(0,c.jsx)("div",{className:"text-center mb-4",children:(0,c.jsx)(A.Z,{children:"OR"})}),m.showUserId&&(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user_123",onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"Role"}),"edit"===o&&i&&(0,c.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(l=i.role,(null===(t=m.roleOptions.find(e=>e.value===l))||void 0===t?void 0:t.label)||l),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,c.jsx)(O.default,{children:"edit"===o&&i?[...m.roleOptions.filter(e=>e.value===i.role),...m.roleOptions.filter(e=>e.value!==i.role)].map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value)):m.roleOptions.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))})}),null===(s=m.additionalFields)||void 0===s?void 0:s.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:x(e)},e.name)),(0,c.jsxs)("div",{className:"text-right mt-6",children:[(0,c.jsx)(R.ZP,{onClick:r,className:"mr-2",children:"Cancel"}),(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"add"===o?"Add Member":"Save Changes"})]})]})})},sR=e=>{let{isVisible:s,onCancel:l,onSubmit:t,accessToken:a,title:r="Add Team Member",roles:n=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:i="user"}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)("user_email"),j=async(e,s)=>{if(!e){u([]);return}x(!0);try{let l=new URLSearchParams;if(l.append(s,e),null==a)return;let t=(await (0,y.u5)(a,l)).map(e=>({label:"user_email"===s?"".concat(e.user_email):"".concat(e.user_id),value:"user_email"===s?e.user_email:e.user_id,user:e}));u(t)}catch(e){console.error("Error fetching users:",e)}finally{x(!1)}},f=(0,d.useCallback)(ep()((e,s)=>j(e,s),300),[]),_=(e,s)=>{g(s),f(e,s)},v=(e,s)=>{let l=s.user;o.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:o.getFieldValue("role")})};return(0,c.jsx)(M.Z,{title:r,open:s,onCancel:()=>{o.resetFields(),u([]),l()},footer:null,width:800,children:(0,c.jsxs)(L.Z,{form:o,onFinish:t,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:i},children:[(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>_(e,"user_email"),onSelect:(e,s)=>v(e,s),options:"user_email"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>_(e,"user_id"),onSelect:(e,s)=>v(e,s),options:"user_id"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)(L.Z.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:i,children:n.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:(0,c.jsxs)(W.Z,{title:e.description,children:[(0,c.jsx)("span",{className:"font-medium",children:e.label}),(0,c.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,c.jsx)("div",{className:"text-right mt-4",children:(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"Add Member"})})]})})},sq=e=>{var s;let{teamId:l,onClose:t,accessToken:a,is_team_admin:r,is_proxy_admin:n,userModels:i,editTeam:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p,g]=(0,d.useState)(!1),[j]=L.Z.useForm(),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(null),[Z,N]=(0,d.useState)(!1);console.log("userModels in team info",i);let S=r||n,C=async()=>{try{if(x(!0),!a)return;let e=await (0,y.Xm)(a,l);u(e)}catch(e){D.ZP.error("Failed to load team information"),console.error("Error fetching team info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{C()},[l,a]);let I=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.cu)(a,l,s),D.ZP.success("Team member added successfully"),g(!1),j.resetFields(),C()}catch(e){D.ZP.error("Failed to add team member"),console.error("Error adding team member:",e)}},T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.sN)(a,l,s),D.ZP.success("Team member updated successfully"),_(!1),C()}catch(e){D.ZP.error("Failed to update team member"),console.error("Error updating team member:",e)}},P=async e=>{try{if(null==a)return;await (0,y.Lp)(a,l,e),D.ZP.success("Team member removed successfully"),C()}catch(e){D.ZP.error("Failed to remove team member"),console.error("Error removing team member:",e)}},M=async e=>{try{if(!a)return;let s={};try{s=e.metadata?JSON.parse(e.metadata):{}}catch(e){D.ZP.error("Invalid JSON in metadata field");return}let t={team_id:l,team_alias:e.team_alias,models:e.models,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration,metadata:{...s,guardrails:e.guardrails||[]}};await (0,y.Gh)(a,t),D.ZP.success("Team settings updated successfully"),N(!1),C()}catch(e){D.ZP.error("Failed to update team settings"),console.error("Error updating team:",e)}};if(h)return(0,c.jsx)("div",{className:"p-4",children:"Loading..."});if(!(null==m?void 0:m.team_info))return(0,c.jsx)("div",{className:"p-4",children:"Team not found"});let{team_info:F}=m;return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:F.team_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:F.team_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?3:0,children:[(0,c.jsx)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"},"overview"),...S?[(0,c.jsx)(eR.Z,{children:"Members"},"members"),(0,c.jsx)(eR.Z,{children:"Member Permissions"},"member-permissions"),(0,c.jsx)(eR.Z,{children:"Settings"},"settings")]:[]]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",F.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===F.max_budget?"Unlimited":"$".concat(F.max_budget)]}),F.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",F.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",F.rpm_limit||"Unlimited"]}),F.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",F.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sI,{teamData:m,canEditTeam:S,handleMemberDelete:P,setSelectedEditMember:b,setIsEditMemberModalVisible:_,setIsAddMemberModalVisible:g})}),S&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sM,{teamId:l,accessToken:a,canEditTeam:S})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Team Settings"}),S&&!Z&&(0,c.jsx)(k.Z,{onClick:()=>N(!0),children:"Edit Settings"})]}),Z?(0,c.jsxs)(L.Z,{form:j,onFinish:M,initialValues:{...F,team_alias:F.team_alias,models:F.models,tpm_limit:F.tpm_limit,rpm_limit:F.rpm_limit,max_budget:F.max_budget,budget_duration:F.budget_duration,guardrails:(null===(s=F.metadata)||void 0===s?void 0:s.guardrails)||[],metadata:F.metadata?JSON.stringify(F.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(q.default,{type:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map((e,s)=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},s))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>N(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team Name"}),(0,c.jsx)("div",{children:F.team_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"font-mono",children:F.team_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(F.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",F.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==F.max_budget?"$".concat(F.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",F.budget_duration||"Never"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Status"}),(0,c.jsx)(eM.Z,{color:F.blocked?"red":"green",children:F.blocked?"Blocked":"Active"})]})]})]})})]})]}),(0,c.jsx)(sF,{visible:f,onCancel:()=>_(!1),onSubmit:T,initialData:v,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Admin",value:"admin"},{label:"User",value:"user"}]}}),(0,c.jsx)(sR,{isVisible:p,onCancel:()=>g(!1),onSubmit:I,accessToken:a})]})},sU=l(45589);let{Title:sz,Link:sV}=es.default;var sK=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,existingCredential:a,setIsCredentialModalOpen:r}=e,[n]=L.Z.useForm();return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(a))),(0,c.jsx)(M.Z,{title:"Reuse Credentials",visible:s,onCancel:()=>{l(),n.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:n,onFinish:e=>{t(e),n.resetFields(),r(!1)},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==a?void 0:a.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries((null==a?void 0:a.credential_values)||{}).map(e=>{let[s,l]=e;return(0,c.jsx)(L.Z.Item,{label:s,name:s,initialValue:l,children:(0,c.jsx)(S.Z,{placeholder:"Enter ".concat(s),disabled:!0})},s)}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sV,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})},sB=l(63709),sH=l(45246),sJ=l(96473);let{Text:sW}=es.default;var sG=e=>{let{form:s,showCacheControl:l,onCacheControlChange:t}=e,a=e=>{let l=s.getFieldValue("litellm_extra_params");try{let t=l?JSON.parse(l):{};e.length>0?t.cache_control_injection_points=e:delete t.cache_control_injection_points,Object.keys(t).length>0?s.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):s.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Cache Control Injection Points",name:"cache_control",valuePropName:"checked",className:"mb-4",tooltip:"Tell litellm where to inject cache control checkpoints. You can specify either by role (to apply to all messages of that role) or by specific message index.",children:(0,c.jsx)(sB.Z,{onChange:t,className:"bg-gray-600"})}),l&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(sW,{className:"text-sm text-gray-500 block mb-4",children:"Providers like Anthropic, Bedrock API require users to specify where to inject cache control checkpoints, litellm can automatically add them for you as a cost saving feature."}),(0,c.jsx)(L.Z.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(e,l)=>{let{add:t,remove:r}=l;return(0,c.jsxs)(c.Fragment,{children:[e.map((l,t)=>(0,c.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,c.jsx)(L.Z.Item,{...l,label:"Type",name:[l.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,c.jsx)(O.default,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,c.jsx)(L.Z.Item,{...l,label:"Role",name:[l.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,c.jsx)(O.default,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),(0,c.jsx)(L.Z.Item,{...l,label:"Index",name:[l.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,c.jsx)(z,{type:"number",placeholder:"Optional",step:1,min:0,onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),e.length>1&&(0,c.jsx)(sH.Z,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{r(l.name),setTimeout(()=>{a(s.getFieldValue("cache_control_points"))},0)}})]},l.key)),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)("button",{type:"button",className:"flex items-center justify-center w-full border border-dashed border-gray-300 py-2 px-4 text-gray-600 hover:text-blue-600 hover:border-blue-300 transition-all rounded",onClick:()=>t(),children:[(0,c.jsx)(sJ.Z,{className:"mr-2"}),"Add Injection Point"]})})]})}})]})]})};function sY(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j,f,_,v,b,Z,N;let{modelId:C,onClose:I,modelData:T,accessToken:P,userID:O,userRole:F,editModel:q,setEditModalVisible:U,setSelectedModel:V,onModelUpdate:K}=e,[B]=L.Z.useForm(),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(!1),[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)(null),[en,ei]=(0,d.useState)(!1),eo="Admin"===F||T.model_info.created_by===O,ec=(null===(s=T.litellm_params)||void 0===s?void 0:s.litellm_credential_name)!=null&&(null===(l=T.litellm_params)||void 0===l?void 0:l.litellm_credential_name)!=void 0;console.log("usingExistingCredential, ",ec),console.log("modelData.litellm_params.litellm_credential_name, ",T.litellm_params.litellm_credential_name),(0,d.useEffect)(()=>{let e=async()=>{var e;if(!P)return;let s=await (0,y.ix)(P,C);console.log("modelInfoResponse, ",s);let l=s.data[0];J(l),(null==l?void 0:null===(e=l.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&ei(!0)};(async()=>{if(console.log("accessToken, ",P),!P||ec)return;let e=await (0,y.Qg)(P,null,C);console.log("existingCredentialResponse, ",e),er({credential_name:e.credential_name,credential_values:e.credential_values,credential_info:e.credential_info})})(),e()},[P,C]);let ed=async e=>{var s;if(console.log("values, ",e),!P)return;let l={credential_name:e.credential_name,model_id:C,credential_info:{custom_llm_provider:null===(s=H.litellm_params)||void 0===s?void 0:s.custom_llm_provider}};D.ZP.info("Storing credential.."),console.log("credentialResponse, ",await (0,y.oC)(P,l)),D.ZP.success("Credential stored successfully")},em=async e=>{try{var s;if(!P)return;es(!0);let l={...H.litellm_params,model:e.litellm_model_name,api_base:e.api_base,custom_llm_provider:e.custom_llm_provider,organization:e.organization,tpm:e.tpm,rpm:e.rpm,max_retries:e.max_retries,timeout:e.timeout,stream_timeout:e.stream_timeout,input_cost_per_token:e.input_cost/1e6,output_cost_per_token:e.output_cost/1e6};e.cache_control&&(null===(s=e.cache_control_injection_points)||void 0===s?void 0:s.length)>0?l.cache_control_injection_points=e.cache_control_injection_points:delete l.cache_control_injection_points;let t={model_name:e.model_name,litellm_params:l,model_info:{id:C}};await (0,y.um)(P,t);let a={...H,model_name:e.model_name,litellm_model_name:e.litellm_model_name,litellm_params:l};J(a),K&&K(a),D.ZP.success("Model settings updated successfully"),Q(!1),et(!1)}catch(e){console.error("Error updating model:",e),D.ZP.error("Failed to update model settings")}finally{es(!1)}};if(!T)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsx)(A.Z,{children:"Model not found"})]});let eu=async()=>{try{if(!P)return;await (0,y.Og)(P,C),D.ZP.success("Model deleted successfully"),K&&K({deleted:!0,model_info:{id:C}}),I()}catch(e){console.error("Error deleting the model:",e),D.ZP.error("Failed to delete model")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsxs)(E.Z,{children:["Public Model Name: ",sv(T)]}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:T.model_info.id})]}),(0,c.jsxs)("div",{className:"flex gap-2",children:["Admin"===F&&(0,c.jsx)(k.Z,{icon:sU.Z,variant:"secondary",onClick:()=>$(!0),className:"flex items-center",children:"Re-use Credentials"}),eo&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>G(!0),className:"flex items-center",children:"Delete Model"})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-6",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Raw JSON"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Provider"}),(0,c.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[T.provider&&(0,c.jsx)("img",{src:sn(T.provider).logo,alt:"".concat(T.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,l=s.parentElement;if(l){var t;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(t=T.provider)||void 0===t?void 0:t.charAt(0))||"-",l.replaceChild(e,s)}}}),(0,c.jsx)(E.Z,{children:T.provider||"Not Set"})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"LiteLLM Model"}),(0,c.jsx)("pre",{children:(0,c.jsx)(E.Z,{children:T.litellm_model_name||"Not Set"})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Pricing"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Input: $",T.input_cost,"/1M tokens"]}),(0,c.jsxs)(A.Z,{children:["Output: $",T.output_cost,"/1M tokens"]})]})]})]}),(0,c.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Created At ",T.model_info.created_at?new Date(T.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})}),"Created By ",T.model_info.created_by||"Not Set"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Model Settings"}),eo&&!el&&(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>et(!0),className:"flex items-center",children:"Edit Model"})]}),H?(0,c.jsx)(L.Z,{form:B,onFinish:em,initialValues:{model_name:H.model_name,litellm_model_name:H.litellm_model_name,api_base:H.litellm_params.api_base,custom_llm_provider:H.litellm_params.custom_llm_provider,organization:H.litellm_params.organization,tpm:H.litellm_params.tpm,rpm:H.litellm_params.rpm,max_retries:H.litellm_params.max_retries,timeout:H.litellm_params.timeout,stream_timeout:H.litellm_params.stream_timeout,input_cost:H.litellm_params.input_cost_per_token?1e6*H.litellm_params.input_cost_per_token:(null===(t=H.model_info)||void 0===t?void 0:t.input_cost_per_token)*1e6||null,output_cost:(null===(a=H.litellm_params)||void 0===a?void 0:a.output_cost_per_token)?1e6*H.litellm_params.output_cost_per_token:(null===(r=H.model_info)||void 0===r?void 0:r.output_cost_per_token)*1e6||null,cache_control:null!==(n=H.litellm_params)&&void 0!==n&&!!n.cache_control_injection_points,cache_control_injection_points:(null===(i=H.litellm_params)||void 0===i?void 0:i.cache_control_injection_points)||[]},layout:"vertical",onValuesChange:()=>Q(!0),children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"LiteLLM Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"litellm_model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter LiteLLM model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.litellm_model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"input_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter input cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(o=H.litellm_params)||void 0===o?void 0:o.input_cost_per_token)?((null===(m=H.litellm_params)||void 0===m?void 0:m.input_cost_per_token)*1e6).toFixed(4):(null==H?void 0:null===(u=H.model_info)||void 0===u?void 0:u.input_cost_per_token)?(1e6*H.model_info.input_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"output_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter output cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(h=H.litellm_params)||void 0===h?void 0:h.output_cost_per_token)?(1e6*H.litellm_params.output_cost_per_token).toFixed(4):(null==H?void 0:null===(x=H.model_info)||void 0===x?void 0:x.output_cost_per_token)?(1e6*H.model_info.output_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Base"}),el?(0,c.jsx)(L.Z.Item,{name:"api_base",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter API base"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(p=H.litellm_params)||void 0===p?void 0:p.api_base)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Custom LLM Provider"}),el?(0,c.jsx)(L.Z.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom LLM provider"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(g=H.litellm_params)||void 0===g?void 0:g.custom_llm_provider)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),el?(0,c.jsx)(L.Z.Item,{name:"organization",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter organization"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(j=H.litellm_params)||void 0===j?void 0:j.organization)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"TPM (Tokens per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"tpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter TPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(f=H.litellm_params)||void 0===f?void 0:f.tpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"RPM (Requests per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"rpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter RPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(_=H.litellm_params)||void 0===_?void 0:_.rpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Max Retries"}),el?(0,c.jsx)(L.Z.Item,{name:"max_retries",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter max retries"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(v=H.litellm_params)||void 0===v?void 0:v.max_retries)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(b=H.litellm_params)||void 0===b?void 0:b.timeout)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Stream Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"stream_timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter stream timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(Z=H.litellm_params)||void 0===Z?void 0:Z.stream_timeout)||"Not Set"})]}),el?(0,c.jsx)(sG,{form:B,showCacheControl:en,onCacheControlChange:e=>ei(e)}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Cache Control"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(N=H.litellm_params)||void 0===N?void 0:N.cache_control_injection_points)?(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{children:"Enabled"}),(0,c.jsx)("div",{className:"mt-2",children:H.litellm_params.cache_control_injection_points.map((e,s)=>(0,c.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,c.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,c.jsxs)("span",{children:[" Index: ",e.index]})]},s))})]}):"Disabled"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:T.model_info.team_id||"Not Set"})]})]}),el&&(0,c.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{B.resetFields(),Q(!1),et(!1)},children:"Cancel"}),(0,c.jsx)(k.Z,{variant:"primary",onClick:()=>B.submit(),loading:ee,children:"Save Changes"})]})]})}):(0,c.jsx)(A.Z,{children:"Loading..."})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(T,null,2)})})})]})]}),W&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Model"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this model?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(R.ZP,{onClick:eu,className:"ml-2",danger:!0,children:"Delete"}),(0,c.jsx)(R.ZP,{onClick:()=>G(!1),children:"Cancel"})]})]})]})}),Y&&!ec?(0,c.jsx)(sK,{isVisible:Y,onCancel:()=>$(!1),onAddCredential:ed,existingCredential:ea,setIsCredentialModalOpen:$}):(0,c.jsx)(M.Z,{open:Y,onCancel:()=>$(!1),title:"Using Existing Credential",children:(0,c.jsx)(A.Z,{children:T.litellm_params.litellm_credential_name})})]})}var s$=l(67960),sX=e=>{let{selectedProvider:s,providerModels:l,getPlaceholder:t}=e,a=L.Z.useFormInstance(),r=e=>{let s=e.target.value,l=(a.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:s,litellm_model:s}:e);a.setFieldsValue({model_mappings:l})};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)(L.Z.Item,{label:"LiteLLM Model Name(s)",tooltip:"Actual model name used for making litellm.completion() / litellm.embedding() call.",className:"mb-0",children:[(0,c.jsx)(L.Z.Item,{name:"model",rules:[{required:!0,message:"Please select at least one model."}],noStyle:!0,children:s===n.Azure||s===n.OpenAI_Compatible||s===n.Ollama?(0,c.jsx)(S.Z,{placeholder:t(s)}):l.length>0?(0,c.jsx)(O.default,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:e=>{let s=Array.isArray(e)?e:[e];if(s.includes("all-wildcard"))a.setFieldsValue({model_name:void 0,model_mappings:[]});else{let e=s.map(e=>({public_name:e,litellm_model:e}));a.setFieldsValue({model_mappings:e})}},optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:"All ".concat(s," Models (Wildcard)"),value:"all-wildcard"},...l.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,c.jsx)(S.Z,{placeholder:t(s)})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.model!==s.model,children:e=>{let{getFieldValue:s}=e,l=s("model")||[];return(Array.isArray(l)?l:[l]).includes("custom")&&(0,c.jsx)(L.Z.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom model name",onChange:r})})}})]}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Actual model name used for making litellm.completion() call. We loadbalance models with the same public name"})})]})]})},sQ=()=>{let e=L.Z.useFormInstance(),[s,l]=(0,d.useState)(0),t=L.Z.useWatch("model",e)||[],a=Array.isArray(t)?t:[t],r=L.Z.useWatch("custom_model_name",e),n=!a.includes("all-wildcard");if((0,d.useEffect)(()=>{if(r&&a.includes("custom")){let s=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:r,litellm_model:r}:e);e.setFieldValue("model_mappings",s),l(e=>e+1)}},[r,a,e]),(0,d.useEffect)(()=>{if(a.length>0&&!a.includes("all-wildcard")){let s=a.map(e=>"custom"===e&&r?{public_name:r,litellm_model:r}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",s),l(e=>e+1)}},[a,r,e]),!n)return null;let i=[{title:"Public Name",dataIndex:"public_name",key:"public_name",render:(s,l,t)=>(0,c.jsx)(S.Z,{value:s,onChange:s=>{let l=[...e.getFieldValue("model_mappings")];l[t].public_name=s.target.value,e.setFieldValue("model_mappings",l)}})},{title:"LiteLLM Model",dataIndex:"litellm_model",key:"litellm_model"}];return(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(L.Z.Item,{label:"Model Mappings",name:"model_mappings",tooltip:"Map public model names to LiteLLM model names for load balancing",labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",required:!0,children:(0,c.jsx)(ea.Z,{dataSource:e.getFieldValue("model_mappings"),columns:i,pagination:!1,size:"small"},s)})})},s0=l(90464);let{Link:s1}=es.default;var s2=e=>{let{showAdvancedSettings:s,setShowAdvancedSettings:l,teams:t}=e,[a]=L.Z.useForm(),[r,n]=d.useState(!1),[i,o]=d.useState("per_token"),[m,u]=d.useState(!1),h=(e,s)=>s&&(isNaN(Number(s))||0>Number(s))?Promise.reject("Please enter a valid positive number"):Promise.resolve(),x=(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject("Please enter valid JSON")}};return(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(C.Z,{className:"mt-2 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Advanced Settings"})}),(0,c.jsx)(I.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,c.jsx)(L.Z.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,c.jsx)(sB.Z,{onChange:e=>{n(e),e||a.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),r&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(L.Z.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:"per_token",onChange:e=>o(e),options:[{value:"per_token",label:"Per Million Tokens"},{value:"per_second",label:"Per Second"}]})}),"per_token"===i?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}):(0,c.jsx)(L.Z.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)(L.Z.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,c.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,c.jsx)(sB.Z,{onChange:e=>{let s=a.getFieldValue("litellm_extra_params");try{let l=s?JSON.parse(s):{};e?l.use_in_pass_through=!0:delete l.use_in_pass_through,Object.keys(l).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):a.setFieldValue("litellm_extra_params","")}catch(s){e?a.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):a.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,c.jsx)(sG,{form:a,showCacheControl:m,onCacheControlChange:e=>{if(u(e),!e){let e=a.getFieldValue("litellm_extra_params");try{let s=e?JSON.parse(e):{};delete s.cache_control_injection_points,Object.keys(s).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):a.setFieldValue("litellm_extra_params","")}catch(e){a.setFieldValue("litellm_extra_params","")}}}}),(0,c.jsx)(L.Z.Item,{label:"LiteLLM Params",name:"litellm_extra_params",tooltip:"Optional litellm params used for making a litellm.completion() call.",className:"mb-4 mt-4",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,c.jsxs)(su.Z,{className:"mb-4",children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,c.jsx)(L.Z.Item,{label:"Model Info",name:"model_info_params",tooltip:"Optional model info params. Returned when calling `/model/info` endpoint.",className:"mb-0",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})},s4=l(29),s5=l.n(s4),s6=l(23496),s3=l(35291),s8=l(23639);let{Text:s7}=es.default;var s9=e=>{let{formValues:s,accessToken:l,testMode:t,modelName:a="this model",onClose:r,onTestComplete:n}=e,[i,o]=d.useState(null),[m,u]=d.useState(null),[h,x]=d.useState(null),[p,g]=d.useState(!0),[j,f]=d.useState(!1),[_,v]=d.useState(!1),b=async()=>{g(!0),v(!1),o(null),u(null),x(null),f(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",s);let a=await sc(s,l,null);if(!a){console.log("No result from prepareModelAddRequest"),o("Failed to prepare model data. Please check your form inputs."),f(!1),g(!1);return}console.log("Result from prepareModelAddRequest:",a);let{litellmParamsObj:r,modelInfoObj:n,modelName:i}=a[0],c=await (0,y.Hx)(l,r,null==n?void 0:n.mode);if("success"===c.status)D.ZP.success("Connection test successful!"),o(null),f(!0);else{var e,t;let s=(null===(e=c.result)||void 0===e?void 0:e.error)||c.message||"Unknown error";o(s),u(r),x(null===(t=c.result)||void 0===t?void 0:t.raw_request_typed_dict),f(!1)}}catch(e){console.error("Test connection error:",e),o(e instanceof Error?e.message:String(e)),f(!1)}finally{g(!1),n&&n()}};d.useEffect(()=>{let e=setTimeout(()=>{b()},200);return()=>clearTimeout(e)},[]);let Z=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",N="string"==typeof i?Z(i):(null==i?void 0:i.message)?Z(i.message):"Unknown error",w=h?((e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")})(h.raw_request_api_base,h.raw_request_body,h.raw_request_headers||{}):"";return(0,c.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[p?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-776cdcbc0448e4ea",children:[(0,c.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-776cdcbc0448e4ea loading-spinner",children:(0,c.jsx)("div",{style:{border:"3px solid #f3f3f3",borderTop:"3px solid #1890ff",borderRadius:"50%",width:"30px",height:"30px",animation:"spin 1s linear infinite",margin:"0 auto"},className:"jsx-776cdcbc0448e4ea"})}),(0,c.jsxs)(s7,{style:{fontSize:"16px"},children:["Testing connection to ",a,"..."]}),(0,c.jsx)(s5(),{id:"776cdcbc0448e4ea",children:"@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);transform:rotate(0deg)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spin{0%{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}"})]}):j?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},children:[(0,c.jsx)("div",{style:{color:"#52c41a",fontSize:"32px",marginBottom:"16px"},children:(0,c.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,c.jsx)("path",{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"})})}),(0,c.jsxs)(s7,{type:"success",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," successful!"]})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,c.jsx)(s3.Z,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,c.jsxs)(s7,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," failed"]})]}),(0,c.jsxs)("div",{style:{backgroundColor:"#fff2f0",border:"1px solid #ffccc7",borderRadius:"8px",padding:"16px",marginBottom:"20px",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px"},children:"Error: "}),(0,c.jsx)(s7,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:N}),i&&(0,c.jsx)("div",{style:{marginTop:"12px"},children:(0,c.jsx)(R.ZP,{type:"link",onClick:()=>v(!_),style:{paddingLeft:0,height:"auto"},children:_?"Hide Details":"Show Details"})})]}),_&&(0,c.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"200px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:"string"==typeof i?i:JSON.stringify(i,null,2)})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:w||"No request data available"}),(0,c.jsx)(R.ZP,{style:{marginTop:"8px"},icon:(0,c.jsx)(s8.Z,{}),onClick:()=>{navigator.clipboard.writeText(w||""),D.ZP.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,c.jsx)(s6.Z,{style:{margin:"24px 0 16px"}}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,c.jsx)(R.ZP,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,c.jsx)(J.Z,{}),children:"View Documentation"})})]})};let le=[{value:"chat",label:"Chat - /chat/completions"},{value:"completion",label:"Completion - /completions"},{value:"embedding",label:"Embedding - /embeddings"},{value:"audio_speech",label:"Audio Speech - /audio/speech"},{value:"audio_transcription",label:"Audio Transcription - /audio/transcriptions"},{value:"image_generation",label:"Image Generation - /images/generations"},{value:"rerank",label:"Rerank - /rerank"},{value:"realtime",label:"Realtime - /realtime"}],{Title:ls,Link:ll}=es.default;var lt=e=>{let{form:s,handleOk:l,selectedProvider:t,setSelectedProvider:a,providerModels:r,setProviderModelsFn:i,getPlaceholder:o,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,credentials:p,accessToken:g,userRole:j}=e,[f,_]=(0,d.useState)("chat"),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),k=async()=>{Z(!0),w("test-".concat(Date.now())),v(!0)},S=eg.ZL.includes(j);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ls,{level:2,children:"Add new model"}),(0,c.jsx)(s$.Z,{children:(0,c.jsx)(L.Z,{form:s,onFinish:l,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"E.g. OpenAI, Azure OpenAI, Anthropic, Bedrock, etc.",labelCol:{span:10},labelAlign:"left",children:(0,c.jsx)(O.default,{showSearch:!0,value:t,onChange:e=>{a(e),i(e),s.setFieldsValue({model:[],model_name:void 0})},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sX,{selectedProvider:t,providerModels:r,getPlaceholder:o}),(0,c.jsx)(sQ,{}),(0,c.jsx)(L.Z.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,c.jsx)(O.default,{style:{width:"100%"},value:f,onChange:e=>_(e),options:le})}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-5 mt-1",children:[(0,c.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model ",(0,c.jsx)(ll,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,c.jsx)("div",{className:"mb-4",children:(0,c.jsx)(es.default.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,c.jsx)(L.Z.Item,{label:"Existing Credentials",name:"litellm_credential_name",children:(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{value:null,label:"None"},...p.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.litellm_credential_name!==s.litellm_credential_name||e.provider!==s.provider,children:e=>{let{getFieldValue:s}=e,l=s("litellm_credential_name");return(console.log("\uD83D\uDD11 Credential Name Changed:",l),l)?(0,c.jsx)("div",{className:"text-gray-500 text-sm text-center",children:"Using existing credentials - no additional provider fields needed"}):(0,c.jsx)(sg,{selectedProvider:t,uploadProps:m})}}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Team Settings"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{label:"Team",name:"team_id",className:"mb-4",tooltip:"Only keys for this team, will be able to call this model.",rules:[{required:!S,message:"Please select a team."}],children:(0,c.jsx)(Q,{teams:x})}),(0,c.jsx)(s2,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x}),(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(es.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{className:"space-x-2",children:[(0,c.jsx)(R.ZP,{onClick:k,loading:b,children:"Test Connect"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,c.jsx)(M.Z,{title:"Connection Test Results",open:y,onCancel:()=>{v(!1),Z(!1)},footer:[(0,c.jsx)(R.ZP,{onClick:()=>{v(!1),Z(!1)},children:"Close"},"close")],width:700,children:y&&(0,c.jsx)(s9,{formValues:s.getFieldsValue(),accessToken:g,testMode:f,modelName:s.getFieldValue("model_name")||s.getFieldValue("model"),onClose:()=>{v(!1),Z(!1)},onTestComplete:()=>Z(!1)},N)})]})},la=l(32986),lr=l(49084);function ln(e){let{data:s=[],columns:l,isLoading:t=!1}=e,[a,r]=d.useState([{id:"model_info.created_at",desc:!0}]),[n]=d.useState("onChange"),[i,o]=d.useState({}),[m,u]=d.useState({}),[h,x]=d.useState(!1),p=d.useRef(null);d.useEffect(()=>{let e=e=>{p.current&&!p.current.contains(e.target)&&x(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let g=(0,eS.b7)({data:s,columns:l,state:{sorting:a,columnSizing:i,columnVisibility:m},columnResizeMode:n,onSortingChange:r,onColumnSizingChange:o,onColumnVisibilityChange:u,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}}),j=e=>{if("string"==typeof e)return e;if("function"==typeof e){let s=e();if(s&&s.props&&s.props.children){let e=s.props.children;if("string"==typeof e)return e;if(e.props&&e.props.children)return e.props.children}}return""};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)("div",{className:"flex justify-end",children:(0,c.jsxs)("div",{className:"relative",ref:p,children:[(0,c.jsxs)("button",{onClick:()=>x(!h),className:"flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:[(0,c.jsx)(la.Z,{className:"h-4 w-4"}),"Columns"]}),h&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-56 bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50",children:(0,c.jsx)("div",{className:"py-1",children:g.getAllLeafColumns().map(e=>"actions"===e.id?null:(0,c.jsxs)("div",{className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer",onClick:()=>e.toggleVisibility(),children:[(0,c.jsx)("input",{type:"checkbox",checked:e.getIsVisible(),onChange:()=>e.toggleVisibility(),className:"h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,c.jsx)("span",{className:"ml-2",children:j(e.columnDef.header)})]},e.id))})})]})}),(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsx)("div",{className:"relative min-w-full",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1 w-full",children:[(0,c.jsx)(eE.Z,{children:g.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsxs)(eP.Z,{className:"py-1 h-8 relative ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getToggleSortingHandler(),children:[(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,c.jsx)("div",{onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:"absolute right-0 top-0 h-full w-2 cursor-col-resize select-none touch-none ".concat(e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200")})]},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading models..."})})})}):g.getRowModel().rows.length>0?g.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.column.id?120:e.column.getSize(),minWidth:"actions"===e.column.id?120:e.column.getSize(),maxWidth:"actions"===e.column.id?120:e.column.getSize(),position:"actions"===e.column.id?"sticky":"relative",right:"actions"===e.column.id?0:"auto"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No models found"})})})})})]})})})})]})}let li=(e,s,l,t,a,r,n,i,o)=>[{header:"Model ID",accessorKey:"model_info.id",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.model_info.id,children:(0,c.jsx)("div",{className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left w-full truncate whitespace-nowrap cursor-pointer",onClick:()=>t(l.model_info.id),children:l.model_info.id})})}},{header:"Public Model Name",accessorKey:"model_name",cell:e=>{let{row:s}=e,l=r(s.original)||"-";return(0,c.jsx)(W.Z,{title:l,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l})})}},{header:"Provider",accessorKey:"provider",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l.provider&&(0,c.jsx)("img",{src:sn(l.provider).logo,alt:"".concat(l.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,t=s.parentElement;if(t){var a;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(a=l.provider)||void 0===a?void 0:a.charAt(0))||"-",t.replaceChild(e,s)}}}),(0,c.jsx)("p",{className:"text-xs",children:l.provider||"-"})]})}},{header:"LiteLLM Model Name",accessorKey:"litellm_model_name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.litellm_model_name,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l.litellm_model_name||"-"})})}},{header:"Created At",accessorKey:"model_info.created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_at?new Date(l.model_info.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"model_info.updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.updated_at?new Date(l.model_info.updated_at).toLocaleDateString():"-"})}},{header:"Created By",accessorKey:"model_info.created_by",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_by||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Input Cost"})}),accessorKey:"input_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.input_cost||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Output Cost"})}),accessorKey:"output_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.output_cost||"-"})}},{header:"Team ID",accessorKey:"model_info.team_id",cell:e=>{let{row:s}=e,l=s.original;return l.model_info.team_id?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.model_info.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>a(l.model_info.team_id),children:[l.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:"Credentials",accessorKey:"litellm_credential_name",cell:e=>{let{row:s}=e,l=s.original;return l.litellm_params&&l.litellm_params.litellm_credential_name?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsxs)(W.Z,{title:l.litellm_params.litellm_credential_name,children:[l.litellm_params.litellm_credential_name.slice(0,7),"..."]})}):(0,c.jsx)("span",{className:"text-gray-400",children:"-"})}},{header:"Status",accessorKey:"model_info.db_model",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"\n inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium\n ".concat(l.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600","\n "),children:l.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:"",cell:l=>{var a;let{row:r}=l,n=r.original,i="Admin"===e||(null===(a=n.model_info)||void 0===a?void 0:a.created_by)===s;return(0,c.jsxs)("div",{className:"flex items-center justify-end gap-2 pr-4",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!0))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!1))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"})]})}}],{Title:lo,Link:lc}=es.default,ld={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"};var lm=e=>{let{accessToken:s,token:l,userRole:t,userID:a,modelData:r={data:[]},keys:i,setModelData:o,premiumUser:m,teams:u}=e,[h,x]=(0,d.useState)([]),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)([]);Object.values(n).filter(e=>isNaN(Number(e)));let[Z,N]=(0,d.useState)([]),[S,C]=(0,d.useState)(n.OpenAI),[I,T]=(0,d.useState)(""),[P,O]=(0,d.useState)(!1),[M,F]=(0,d.useState)(null),[R,q]=(0,d.useState)([]),[U,z]=(0,d.useState)([]),[V,K]=(0,d.useState)(null),[B,J]=(0,d.useState)([]),[W,G]=(0,d.useState)([]),[Y,$]=(0,d.useState)([]),[X,Q]=(0,d.useState)([]),[el,et]=(0,d.useState)([]),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)([]),[eo,ec]=(0,d.useState)([]),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[ex,ep]=(0,d.useState)(null),[ej,ef]=(0,d.useState)(0),[e_,ey]=(0,d.useState)({}),[ev,eb]=(0,d.useState)([]),[eZ,eN]=(0,d.useState)(!1),[ew,ek]=(0,d.useState)(null),[eS,eC]=(0,d.useState)(null),[eL,eM]=(0,d.useState)([]),[eK,eH]=(0,d.useState)([]),[eJ,eW]=(0,d.useState)(!1),[eG,eY]=(0,d.useState)(null),[e$,eQ]=(0,d.useState)(!1),[e0,e1]=(0,d.useState)(null),e2=async(e,l,r)=>{if(console.log("Updating model metrics for group:",e),!s||!a||!t||!l||!r)return;console.log("inside updateModelMetrics - startTime:",l,"endTime:",r),K(e);let n=null==ew?void 0:ew.token;void 0===n&&(n=null);let i=eS;void 0===i&&(i=null),l.setHours(0),l.setMinutes(0),l.setSeconds(0),r.setHours(23),r.setMinutes(59),r.setSeconds(59);try{let o=await (0,y.o6)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model metrics response:",o),G(o.data),$(o.all_api_bases);let c=await (0,y.Rg)(s,e,l.toISOString(),r.toISOString());Q(c.data),et(c.all_api_bases);let d=await (0,y.N8)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model exceptions response:",d),er(d.data),ei(d.exception_types);let m=await (0,y.fP)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);if(console.log("slowResponses:",m),em(m),e){let t=await (0,y.n$)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);ey(t);let a=await (0,y.v9)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);eb(a)}}catch(e){console.error("Failed to fetch model metrics",e)}},e4=async e=>{try{let s=await (0,y.N3)(e);console.log("credentials: ".concat(JSON.stringify(s))),eH(s.credentials)}catch(e){console.error("Error fetching credentials:",e)}};(0,d.useEffect)(()=>{e2(V,eu.from,eu.to)},[ew,eS]);let e5={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let s=new FileReader;s.onload=e=>{if(e.target){let s=e.target.result;p.setFieldsValue({vertex_credentials:s})}},s.readAsText(e)}return!1},onChange(e){"uploading"!==e.file.status&&console.log(e.file,e.fileList),"done"===e.file.status?D.ZP.success("".concat(e.file.name," file uploaded successfully")):"error"===e.file.status&&D.ZP.error("".concat(e.file.name," file upload failed."))}},e6=()=>{_(new Date().toLocaleString())},e3=async()=>{if(!s){console.error("Access token is missing");return}console.log("new modelGroupRetryPolicy:",ex);try{await (0,y.K_)(s,{router_settings:{model_group_retry_policy:ex}}),D.ZP.success("Retry settings saved successfully")}catch(e){console.error("Failed to save retry settings:",e),D.ZP.error("Failed to save retry settings")}};if((0,d.useEffect)(()=>{if(!s||!l||!t||!a)return;let e=async()=>{try{var e,l,r,n,i,c,d,m,u,h,x,p;let g=await (0,y.AZ)(s,a,t);console.log("Model data response:",g.data),o(g);let j=await (0,y.hy)(s);j&&N(j);let f=new Set;for(let e=0;e0&&(v=_[_.length-1],console.log("_initial_model_group:",v)),console.log("selectedModelGroup:",V);let b=await (0,y.o6)(s,a,t,v,null===(e=eu.from)||void 0===e?void 0:e.toISOString(),null===(l=eu.to)||void 0===l?void 0:l.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model metrics response:",b),G(b.data),$(b.all_api_bases);let Z=await (0,y.Rg)(s,v,null===(r=eu.from)||void 0===r?void 0:r.toISOString(),null===(n=eu.to)||void 0===n?void 0:n.toISOString());Q(Z.data),et(Z.all_api_bases);let w=await (0,y.N8)(s,a,t,v,null===(i=eu.from)||void 0===i?void 0:i.toISOString(),null===(c=eu.to)||void 0===c?void 0:c.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model exceptions response:",w),er(w.data),ei(w.exception_types);let k=await (0,y.fP)(s,a,t,v,null===(d=eu.from)||void 0===d?void 0:d.toISOString(),null===(m=eu.to)||void 0===m?void 0:m.toISOString(),null==ew?void 0:ew.token,eS),S=await (0,y.n$)(s,null===(u=eu.from)||void 0===u?void 0:u.toISOString().split("T")[0],null===(h=eu.to)||void 0===h?void 0:h.toISOString().split("T")[0],v);ey(S);let C=await (0,y.v9)(s,null===(x=eu.from)||void 0===x?void 0:x.toISOString().split("T")[0],null===(p=eu.to)||void 0===p?void 0:p.toISOString().split("T")[0],v);eb(C),console.log("dailyExceptions:",S),console.log("dailyExceptionsPerDeplyment:",C),console.log("slowResponses:",k),em(k);let I=await (0,y.j2)(s);eM(null==I?void 0:I.end_users);let T=(await (0,y.BL)(s,a,t)).router_settings;console.log("routerSettingsInfo:",T);let A=T.model_group_retry_policy,E=T.num_retries;console.log("model_group_retry_policy:",A),console.log("default_retries:",E),ep(A),ef(E)}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&t&&a&&e();let r=async()=>{let e=await (0,y.qm)(s);console.log("received model cost map data: ".concat(Object.keys(e))),j(e)};null==g&&r(),e6()},[s,l,t,a,g,f]),!r||!s||!l||!t||!a)return(0,c.jsx)("div",{children:"Loading..."});let e8=[],e7=[];for(let e=0;e(console.log("GET PROVIDER CALLED! - ".concat(g)),null!=g&&"object"==typeof g&&e in g)?g[e].litellm_provider:"openai";if(l){let e=l.split("/"),s=e[0];(n=t)||(n=1===e.length?u(l):s)}else n="-";a&&(i=null==a?void 0:a.input_cost_per_token,o=null==a?void 0:a.output_cost_per_token,c=null==a?void 0:a.max_tokens,d=null==a?void 0:a.max_input_tokens),(null==s?void 0:s.litellm_params)&&(m=Object.fromEntries(Object.entries(null==s?void 0:s.litellm_params).filter(e=>{let[s]=e;return"model"!==s&&"api_base"!==s}))),r.data[e].provider=n,r.data[e].input_cost=i,r.data[e].output_cost=o,r.data[e].litellm_model_name=l,e7.push(n),r.data[e].input_cost&&(r.data[e].input_cost=(1e6*Number(r.data[e].input_cost)).toFixed(2)),r.data[e].output_cost&&(r.data[e].output_cost=(1e6*Number(r.data[e].output_cost)).toFixed(2)),r.data[e].max_tokens=c,r.data[e].max_input_tokens=d,r.data[e].api_base=null==s?void 0:null===(ss=s.litellm_params)||void 0===ss?void 0:ss.api_base,r.data[e].cleanedLitellmParams=m,e8.push(s.model_name),console.log(r.data[e])}if(t&&"Admin Viewer"==t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to view all models"})]})}let sa=async()=>{try{D.ZP.info("Running health check..."),T("");let e=await (0,y.EY)(s);T(e)}catch(e){console.error("Error running health check:",e),T("Error running health check")}},sr=(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Select API Key Name"}),m?(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{ek(e)},children:e.key_alias},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>{eC(e)},children:e},s))]})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsxs)(ee.Z,{value:String(s),disabled:!0,onClick:()=>{ek(e)},children:["✨ ",e.key_alias," (Enterprise only Feature)"]},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsxs)(ee.Z,{value:e,disabled:!0,onClick:()=>{eC(e)},children:["✨ ",e," (Enterprise only Feature)"]},s))]})]})]}),sn=e=>{var s,l;let{payload:t,active:a}=e;if(!a||!t)return null;let r=null===(l=t[0])||void 0===l?void 0:null===(s=l.payload)||void 0===s?void 0:s.date,n=t.sort((e,s)=>s.value-e.value);if(n.length>5){let e=n.length-5;(n=n.slice(0,5)).push({dataKey:"".concat(e," other deployments"),value:t.slice(5).reduce((e,s)=>e+s.value,0),color:"gray"})}return(0,c.jsxs)("div",{className:"w-150 rounded-tremor-default border border-tremor-border bg-tremor-background p-2 text-tremor-default shadow-tremor-dropdown",children:[r&&(0,c.jsxs)("p",{className:"text-tremor-content-emphasis mb-2",children:["Date: ",r]}),n.map((e,s)=>{let l=parseFloat(e.value.toFixed(5)),t=0===l&&e.value>0?"<0.00001":l.toFixed(5);return(0,c.jsxs)("div",{className:"flex justify-between",children:[(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("div",{className:"w-2 h-2 mt-1 rounded-full bg-".concat(e.color,"-500")}),(0,c.jsx)("p",{className:"text-tremor-content",children:e.dataKey})]}),(0,c.jsx)("p",{className:"font-medium text-tremor-content-emphasis text-righ ml-2",children:t})]},s)})]})};console.log("selectedProvider: ".concat(S)),console.log("providerModels.length: ".concat(v.length));let sc=Object.keys(n).find(e=>n[e]===S);return(sc&&Z&&Z.find(e=>e.name===st[sc]),e0)?(0,c.jsx)("div",{className:"w-full h-full",children:(0,c.jsx)(sq,{teamId:e0,onClose:()=>e1(null),accessToken:s,is_team_admin:"Admin"===t,is_proxy_admin:"Proxy Admin"===t,userModels:e8,editTeam:!1,onUpdate:e6})}):(0,c.jsx)("div",{style:{width:"100%",height:"100%"},children:eG?(0,c.jsx)(sY,{modelId:eG,editModel:!0,onClose:()=>{eY(null),eQ(!1)},modelData:r.data.find(e=>e.model_info.id===eG),accessToken:s,userID:a,userRole:t,setEditModalVisible:O,setSelectedModel:F,onModelUpdate:e=>{o({...r,data:r.data.map(s=>s.model_info.id===e.model_info.id?e:s)}),e6()}}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[eg.ZL.includes(t)?(0,c.jsx)(eR.Z,{children:"All Models"}):(0,c.jsx)(eR.Z,{children:"Your Models"}),(0,c.jsx)(eR.Z,{children:"Add Model"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"LLM Credentials"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"/health Models"})}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Analytics"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Retry Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:e6})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(E.Z,{children:"Model Management"}),eg.ZL.includes(t)?(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add and manage models for the proxy"}):(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add models for teams you are an admin for."})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name:"}),(0,c.jsxs)(eD.Z,{className:"w-64",defaultValue:null!=V?V:"all",onValueChange:e=>K("all"===e?"all":e),value:null!=V?V:"all",children:[(0,c.jsx)(ee.Z,{value:"all",children:"All Models"}),R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))]})]})]}),(0,c.jsx)(ln,{columns:li(t,a,m,eY,e1,sv,e=>{F(e),O(!0)},e6,eQ),data:r.data.filter(e=>"all"===V||e.model_name===V||!V),isLoading:!1})]})}),(0,c.jsx)(ez.Z,{className:"h-full",children:(0,c.jsx)(lt,{form:p,handleOk:()=>{p.validateFields().then(e=>{sd(e,s,p,e6)}).catch(e=>{console.error("Validation failed:",e)})},selectedProvider:S,setSelectedProvider:C,providerModels:v,setProviderModelsFn:e=>{let s=so(e,g);b(s),console.log("providerModels: ".concat(s))},getPlaceholder:si,uploadProps:e5,showAdvancedSettings:eJ,setShowAdvancedSettings:eW,teams:u,credentials:eK,accessToken:s,userRole:t})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sy,{accessToken:s,uploadProps:e5,credentialList:eK,fetchCredentials:e4})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"`/health` will run a very small request through your models configured on litellm"}),(0,c.jsx)(k.Z,{onClick:sa,children:"Run `/health`"}),I&&(0,c.jsx)("pre",{children:JSON.stringify(I,null,2)})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:4,className:"mt-2 mb-2",children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:eu,className:"mr-2",onValueChange:e=>{eh(e),e2(V,e.from,e.to)}})]}),(0,c.jsxs)(sh.Z,{className:"ml-2",children:[(0,c.jsx)(A.Z,{children:"Select Model Group"}),(0,c.jsx)(eD.Z,{defaultValue:V||R[0],value:V||R[0],children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>e2(e,eu.from,eu.to),children:e},s))})]}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(sk.Z,{trigger:"click",content:sr,overlayStyle:{width:"20vw"},children:(0,c.jsx)(k.Z,{icon:eX.Z,size:"md",variant:"secondary",className:"mt-4 ml-2",style:{border:"none"},onClick:()=>eN(!0)})})})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"mr-2 max-h-[400px] min-h-[400px]",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Avg. Latency per Token"}),(0,c.jsx)(eR.Z,{value:"2",children:"Time to first token"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)("p",{className:"text-gray-500 italic",children:" (seconds/token)"}),(0,c.jsx)(A.Z,{className:"text-gray-500 italic mt-1 mb-1",children:"average Latency for successfull requests divided by the total tokens"}),W&&Y&&(0,c.jsx)(sN.Z,{title:"Model Latency",className:"h-72",data:W,showLegend:!1,index:"date",categories:Y,connectNulls:!0,customTooltip:sn})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sC,{modelMetrics:X,modelMetricsCategories:el,customTooltip:sn,premiumUser:m})})]})]})})}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"ml-2 max-h-[400px] min-h-[400px] overflow-y-auto",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Deployment"}),(0,c.jsx)(eP.Z,{children:"Success Responses"}),(0,c.jsxs)(eP.Z,{children:["Slow Responses ",(0,c.jsx)("p",{children:"Success Responses taking 600+s"})]})]})}),(0,c.jsx)(eT.Z,{children:ed.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.api_base}),(0,c.jsx)(eA.Z,{children:e.total_count}),(0,c.jsx)(eA.Z,{children:e.slow_count})]},s))})]})})})]}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Exceptions for ",V]}),(0,c.jsx)(sw.Z,{className:"h-60",data:ea,index:"model",categories:en,stack:!0,yAxisWidth:30})]})}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Up Rate Limit Errors (429) for ",V]}),(0,c.jsxs)(w.Z,{numItems:1,children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e_.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e_.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]}),(0,c.jsx)(sh.Z,{})]})]}),m?(0,c.jsx)(c.Fragment,{children:ev.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base?e.api_base:"Unknown API Base"}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors (429) ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]},s))}):(0,c.jsx)(c.Fragment,{children:ev&&ev.length>0&&ev.slice(0,1).map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"✨ Rate Limit Errors by Deployment"}),(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to see exceptions for all deployments"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]})]},s))})]})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name"}),(0,c.jsx)(eD.Z,{className:"mb-4 mt-2 ml-2 w-50",defaultValue:V||R[0],value:V||R[0],onValueChange:e=>K(e),children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))})]}),(0,c.jsxs)(E.Z,{children:["Retry Policy for ",V]}),(0,c.jsx)(A.Z,{className:"mb-6",children:"How many retries should be attempted based on the Exception"}),ld&&(0,c.jsx)("table",{children:(0,c.jsx)("tbody",{children:Object.entries(ld).map((e,s)=>{var l;let[t,a]=e,r=null==ex?void 0:null===(l=ex[V])||void 0===l?void 0:l[a];return null==r&&(r=ej),(0,c.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,c.jsx)("td",{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)("td",{children:(0,c.jsx)(H.Z,{className:"ml-5",value:r,min:0,step:1,onChange:e=>{ep(s=>{var l;let t=null!==(l=null==s?void 0:s[V])&&void 0!==l?l:{};return{...null!=s?s:{},[V]:{...t,[a]:e}}})}})})]},s)})})}),(0,c.jsx)(k.Z,{className:"mt-6 mr-8",onClick:e3,children:"Save"})]})]})]})})},lu=e=>{let{visible:s,possibleUIRoles:l,onCancel:t,user:a,onSubmit:r}=e,[n,i]=(0,d.useState)(a),[o]=L.Z.useForm();(0,d.useEffect)(()=>{o.resetFields()},[a]);let m=async()=>{o.resetFields(),t()},u=async e=>{r(e),o.resetFields(),t()};return a?(0,c.jsx)(M.Z,{visible:s,onCancel:m,footer:null,title:"Edit User "+a.user_id,width:1e3,children:(0,c.jsx)(L.Z,{form:o,onFinish:u,initialValues:a,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:l&&Object.entries(l).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Spend (USD)",name:"spend",tooltip:"(float) - Spend of all LLM calls completed by this user",help:"Across all keys (including keys with team_id).",children:(0,c.jsx)(H.Z,{min:0,step:.01})}),(0,c.jsx)(L.Z.Item,{label:"User Budget (USD)",name:"max_budget",tooltip:"(float) - Maximum budget of this user",help:"Maximum budget of this user.",children:(0,c.jsx)(z,{min:0,step:.01})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})}):null},lh=l(15731);let lx=(e,s,l)=>[{header:"User ID",accessorKey:"user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)(W.Z,{title:s.original.user_id,children:(0,c.jsx)("span",{className:"text-xs",children:s.original.user_id?"".concat(s.original.user_id.slice(0,7),"..."):"-"})})}},{header:"User Email",accessorKey:"user_email",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.user_email||"-"})}},{header:"Global Proxy Role",accessorKey:"user_role",cell:s=>{var l;let{row:t}=s;return(0,c.jsx)("span",{className:"text-xs",children:(null==e?void 0:null===(l=e[t.original.user_role])||void 0===l?void 0:l.ui_label)||"-"})}},{header:"User Spend ($ USD)",accessorKey:"spend",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.spend?s.original.spend.toFixed(2):"-"})}},{header:"User Max Budget ($ USD)",accessorKey:"max_budget",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.max_budget?s.original.max_budget:"Unlimited"})}},{header:()=>(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"SSO ID"}),(0,c.jsx)(W.Z,{title:"SSO ID is the ID of the user in the SSO provider. If the user is not using SSO, this will be null.",children:(0,c.jsx)(lh.Z,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.sso_user_id?s.original.sso_user_id:"-"})}},{header:"API Keys",accessorKey:"key_count",cell:e=>{let{row:s}=e;return(0,c.jsx)(w.Z,{numItems:2,children:s.original.key_count>0?(0,c.jsxs)(eM.Z,{size:"xs",color:"indigo",children:[s.original.key_count," Keys"]}):(0,c.jsx)(eM.Z,{size:"xs",color:"gray",children:"No Keys"})})}},{header:"Created At",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.created_at?new Date(s.original.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.updated_at?new Date(s.original.updated_at).toLocaleDateString():"-"})}},{id:"actions",header:"",cell:e=>{let{row:t}=e;return(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>s(t.original)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>l(t.original.user_id)})]})}}];function lp(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j;let{userId:f,onClose:_,accessToken:v,userRole:b,onDelete:Z}=e,[N,S]=(0,d.useState)(null),[C,I]=(0,d.useState)(!1),[T,P]=(0,d.useState)(!0);d.useEffect(()=>{console.log("userId: ".concat(f,", userRole: ").concat(b,", accessToken: ").concat(v)),(async()=>{try{if(!v)return;let e=await (0,y.Br)(v,f,b||"",!1,null,null,!0);S(e)}catch(e){console.error("Error fetching user data:",e),D.ZP.error("Failed to fetch user data")}finally{P(!1)}})()},[v,f,b]);let O=async()=>{try{if(!v)return;await (0,y.Eb)(v,[f]),D.ZP.success("User deleted successfully"),Z&&Z(),_()}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}};return T?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"Loading user data..."})]}):N?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(E.Z,{children:(null===(s=N.user_info)||void 0===s?void 0:s.user_email)||"User"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:N.user_id})]}),b&&eg.LQ.includes(b)&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>I(!0),className:"flex items-center",children:"Delete User"})]}),C&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:O,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>I(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Details"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number((null===(l=N.user_info)||void 0===l?void 0:l.spend)||0).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",(null===(t=N.user_info)||void 0===t?void 0:t.max_budget)!==null?"$".concat(N.user_info.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Teams"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(a=N.teams)||void 0===a?void 0:a.length)||0," teams"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"API Keys"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(r=N.keys)||void 0===r?void 0:r.length)||0," keys"]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"User ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:N.user_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Email"}),(0,c.jsx)(A.Z,{children:(null===(n=N.user_info)||void 0===n?void 0:n.user_email)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Role"}),(0,c.jsx)(A.Z,{children:(null===(i=N.user_info)||void 0===i?void 0:i.user_role)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:(null===(o=N.user_info)||void 0===o?void 0:o.created_at)?new Date(N.user_info.created_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:(null===(m=N.user_info)||void 0===m?void 0:m.updated_at)?new Date(N.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Teams"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(u=N.teams)||void 0===u?void 0:u.length)&&(null===(h=N.teams)||void 0===h?void 0:h.length)>0?null===(x=N.teams)||void 0===x?void 0:x.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e.team_alias||e.team_id},s)):(0,c.jsx)(A.Z,{children:"No teams"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Keys"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(p=N.keys)||void 0===p?void 0:p.length)&&(null===(g=N.keys)||void 0===g?void 0:g.length)>0?N.keys.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-green-100 rounded text-xs",children:e.key_alias||e.token},s)):(0,c.jsx)(A.Z,{children:"No API keys"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify((null===(j=N.user_info)||void 0===j?void 0:j.metadata)||{},null,2)})]})]})})})]})]})]}):(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"User not found"})]})}function lg(e){let{data:s=[],columns:l,isLoading:t=!1,onSortChange:a,currentSort:r,accessToken:n,userRole:i}=e,[o,m]=d.useState([{id:(null==r?void 0:r.sortBy)||"created_at",desc:(null==r?void 0:r.sortOrder)==="desc"}]),[u,h]=d.useState(null),x=(0,eS.b7)({data:s,columns:l,state:{sorting:o},onSortingChange:e=>{if(m(e),e.length>0){let s=e[0],l=s.id,t=s.desc?"desc":"asc";null==a||a(l,t)}},getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0}),p=e=>{h(e)};return(d.useEffect(()=>{r&&m([{id:r.sortBy,desc:"desc"===r.sortOrder}])},[r]),u)?(0,c.jsx)(lp,{userId:u,onClose:()=>{h(null)},accessToken:n,userRole:i}):(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:x.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading users..."})})})}):s.length>0?x.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:()=>{"user_id"===e.column.id&&p(e.getValue())},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No users found"})})})})})]})})})}var lj=l(67982),lf=e=>{var s;let{accessToken:l,possibleUIRoles:t,userID:a,userRole:r}=e,[n,i]=(0,d.useState)(!0),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)({}),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)([]),{Paragraph:v}=es.default,{Option:b}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){i(!1);return}try{let e=await (0,y.NL)(l);if(m(e),p(e.values||{}),l)try{let e=await (0,y.So)(l,a,r);if(e&&e.data){let s=e.data.map(e=>e.id);_(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),D.ZP.error("Failed to fetch SSO settings")}finally{i(!1)}})()},[l]);let Z=async()=>{if(l){j(!0);try{let e=await (0,y.nd)(l,x);m({...o,values:e.settings}),h(!1)}catch(e){console.error("Error updating SSO settings:",e),D.ZP.error("Failed to update settings")}finally{j(!1)}}},N=(e,s)=>{p(l=>({...l,[e]:s}))},w=(e,s,l)=>{var a;let r=s.type;return"user_role"===e&&t?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:Object.entries(t).filter(e=>{let[s]=e;return s.includes("internal_user")}).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(b,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{children:l}),(0,c.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:t})]})},s)})}):"budget_duration"===e?(0,c.jsx)(e_,{value:x[e]||null,onChange:s=>N(e,s),className:"mt-2"}):"boolean"===r?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!x[e],onChange:s=>N(e,s)})}):"array"===r&&(null===(a=s.items)||void 0===a?void 0:a.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:f.map(e=>(0,c.jsx)(b,{value:e,children:K(e)},e))}):"string"===r&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==x[e]?String(x[e]):"",onChange:s=>N(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},C=(e,s)=>{if(null==s)return(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"});if("user_role"===e&&t&&t[s]){let{ui_label:e,description:l}=t[s];return(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{className:"font-medium",children:e}),l&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:l})]})}return"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)})};return n?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):o?(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex justify-end items-center mb-4",children:!n&&o&&(u?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{h(!1),p(o.values||{})},disabled:g,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:Z,loading:g,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>h(!0),children:"Edit Settings"}))}),(null==o?void 0:null===(s=o.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(v,{className:"mb-4",children:o.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=o;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(v,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),u?(0,c.jsx)("div",{className:"mt-2",children:w(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:C(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No settings available or you do not have permission to view them."})})};console.log=function(){};var l_=e=>{let{accessToken:s,token:l,keys:t,userRole:a,userID:r,teams:n,setKeys:i}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(1),[g,j]=d.useState(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),[w,S]=(0,d.useState)(!1),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)({}),[E,P]=(0,d.useState)(""),[O,L]=(0,d.useState)("users"),[M,F]=(0,d.useState)({email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"}),[R,q]=(0,d.useState)(!1),[U,z]=(0,d.useState)(!1),[V,K]=(0,d.useState)("Email");(0,d.useRef)(null);let B=(0,d.useRef)(0);window.addEventListener("beforeunload",function(){sessionStorage.clear()});let H=(e,s)=>{let l={...M,[e]:s};F(l),console.log("called from handleFilterChange - newFilters:",JSON.stringify(l)),J(l)},J=(0,d.useCallback)(ep()(async e=>{if(!s||!l||!a||!r)return;let t=Date.now();B.current=t;try{let l=await (0,y.Of)(s,e.user_id?[e.user_id]:null,1,25,e.email||null,e.user_role||null,e.team||null,e.sso_user_id||null,e.sort_by,e.sort_order);t===B.current&&l&&(m(l),console.log("called from debouncedSearch filters:",JSON.stringify(e)),console.log("called from debouncedSearch data:",JSON.stringify(l)))}catch(e){console.error("Error searching users:",e)}},300),[s,l,a,r]);(0,d.useEffect)(()=>()=>{J.cancel()},[J]);let W=async()=>{if(C&&s)try{if(await (0,y.Eb)(s,[C]),D.ZP.success("User deleted successfully"),o){var e;let s=null===(e=o.users)||void 0===e?void 0:e.filter(e=>e.user_id!==C);m({...o,users:s||[]})}}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}S(!1),I(null)},G=async()=>{N(null),b(!1)},Y=async e=>{if(console.log("inside handleEditSubmit:",e),s&&l&&a&&r){try{await (0,y.pf)(s,e,null),D.ZP.success("User ".concat(e.user_id," updated successfully"))}catch(e){console.error("There was an error updating the user",e)}if(o){var t;let s=null===(t=o.users)||void 0===t?void 0:t.map(s=>s.user_id===e.user_id?e:s);m({...o,users:s||[]})}N(null),b(!1)}},$=async e=>{if(s&&l&&a&&r)try{let l=await (0,y.Of)(s,M.user_id?[M.user_id]:null,e,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(e),JSON.stringify(l)),m(l),p(e)}catch(e){console.error("Error changing page:",e)}};if((0,d.useEffect)(()=>{if(!s||!l||!a||!r)return;let e=async()=>{try{let e=sessionStorage.getItem("userList_".concat(x));if(e){let s=JSON.parse(e);m(s),console.log("called from useEffect")}else{let e=await (0,y.Of)(s,M.user_id?[M.user_id]:null,x,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(x),JSON.stringify(e)),m(e),console.log("called from useEffect 2")}let l=sessionStorage.getItem("possibleUserRoles");if(l)A(JSON.parse(l));else{let e=await (0,y.lg)(s);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),A(e)}}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&a&&r&&e()},[s,l,a,r]),!o||!s||!l||!a||!r)return(0,c.jsx)("div",{children:"Loading..."});let X=lx(T,e=>{N(e),b(!0)},e=>{I(e),S(!0)});return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Users"}),(0,c.jsx)("div",{className:"flex space-x-3",children:(0,c.jsx)(eh,{userID:r,accessToken:s,teams:n,possibleUIRoles:T})})]}),(0,c.jsxs)(eq.Z,{defaultIndex:0,onIndexChange:e=>L(0===e?"users":"settings"),children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Users"}),(0,c.jsx)(eR.Z,{children:"Default User Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by email...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.email,onChange:e=>H("email",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ".concat(R?"bg-gray-100":""),onClick:()=>q(!R),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filters",(M.user_id||M.user_role||M.team)&&(0,c.jsx)("span",{className:"w-2 h-2 rounded-full bg-blue-500"})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{F({email:"",user_id:"",user_role:"",team:"",sso_user_id:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"})},children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Reset Filters"]})]}),R&&(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Filter by User ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.user_id,onChange:e=>H("user_id",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})]}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.user_role,onValueChange:e=>H("user_role",e),placeholder:"Select Role",children:Object.entries(T).map(e=>{let[s,l]=e;return(0,c.jsx)(ee.Z,{value:s,children:l.ui_label},s)})})}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.team,onValueChange:e=>H("team",e),placeholder:"Select Team",children:null==n?void 0:n.map(e=>(0,c.jsx)(ee.Z,{value:e.team_id,children:e.team_alias||e.team_id},e.team_id))})}),(0,c.jsx)("div",{className:"relative w-64",children:(0,c.jsx)("input",{type:"text",placeholder:"Filter by SSO ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.sso_user_id,onChange:e=>H("sso_user_id",e.target.value)})})]}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",o&&o.users&&o.users.length>0?(o.page-1)*o.page_size+1:0," ","-"," ",o&&o.users?Math.min(o.page*o.page_size,o.total):0," ","of ",o?o.total:0," results"]}),(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>$(x-1),disabled:1===x,className:"px-3 py-1 text-sm border rounded-md ".concat(1===x?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),(0,c.jsx)("button",{onClick:()=>$(x+1),disabled:!o||x>=o.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(!o||x>=o.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})]})]})}),(0,c.jsx)(lg,{data:(null==o?void 0:o.users)||[],columns:X,isLoading:!o,accessToken:s,userRole:a,onSortChange:(e,s)=>{let l={...M,sort_by:e,sort_order:s};F(l),J(l)},currentSort:{sortBy:M.sort_by,sortOrder:M.sort_order}})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lf,{accessToken:s,possibleUIRoles:T,userID:r,userRole:a})})]})]}),(0,c.jsx)(lu,{visible:v,possibleUIRoles:T,onCancel:G,user:Z,onSubmit:Y}),w&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"}),(0,c.jsxs)("p",{className:"text-sm font-medium text-gray-900 mt-2",children:["User ID: ",C]})]})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:W,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{S(!1),I(null)},children:"Cancel"})]})]})]})})]})},ly=e=>{var s;let{accessToken:l,userID:t,userRole:a}=e,[r,n]=(0,d.useState)(!0),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)({}),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),{Paragraph:_}=es.default,{Option:v}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){n(!1);return}try{let e=await (0,y.EB)(l);if(o(e),x(e.values||{}),l)try{let e=await (0,y.So)(l,t,a);if(e&&e.data){let s=e.data.map(e=>e.id);f(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching team SSO settings:",e),D.ZP.error("Failed to fetch team settings")}finally{n(!1)}})()},[l]);let b=async()=>{if(l){g(!0);try{let e=await (0,y.r1)(l,h);o({...i,values:e.settings}),u(!1),D.ZP.success("Default team settings updated successfully")}catch(e){console.error("Error updating team settings:",e),D.ZP.error("Failed to update team settings")}finally{g(!1)}}},Z=(e,s)=>{x(l=>({...l,[e]:s}))},N=(e,s,l)=>{var t;let a=s.type;return"budget_duration"===e?(0,c.jsx)(e_,{value:h[e]||null,onChange:s=>Z(e,s),className:"mt-2"}):"boolean"===a?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!h[e],onChange:s=>Z(e,s)})}):"array"===a&&(null===(t=s.items)||void 0===t?void 0:t.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:j.map(e=>(0,c.jsx)(v,{value:e,children:K(e)},e))}):"string"===a&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:h[e]||"",onChange:s=>Z(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==h[e]?String(h[e]):"",onChange:s=>Z(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},w=(e,s)=>null==s?(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"}):"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)});return r?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):i?(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{className:"text-xl",children:"Default Team Settings"}),!r&&i&&(m?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{u(!1),x(i.values||{})},disabled:p,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:b,loading:p,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Settings"}))]}),(0,c.jsx)(A.Z,{children:"These settings will be applied by default when creating new teams."}),(null==i?void 0:null===(s=i.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(_,{className:"mb-4 mt-2",children:i.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=i;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(_,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),m?(0,c.jsx)("div",{className:"mt-2",children:N(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:w(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No team settings available or you do not have permission to view them."})})},lv=e=>{let{accessToken:s,userID:l}=e,[t,a]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(s&&l)try{let e=await (0,y.a6)(s);a(e)}catch(e){console.error("Error fetching available teams:",e)}})()},[s,l]);let r=async e=>{if(s&&l)try{await (0,y.cu)(s,e,{user_id:l,role:"user"}),D.ZP.success("Successfully joined team"),a(s=>s.filter(s=>s.team_id!==e))}catch(e){console.error("Error joining team:",e),D.ZP.error("Failed to join team")}};return(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{children:"Members"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsxs)(eT.Z,{children:[t.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.team_alias})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.description||"No description available"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[e.members_with_roles.length," members"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"flex flex-col",children:e.models&&0!==e.models.length?e.models.map((e,s)=>(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(e.slice(0,30),"..."):e})},s)):(0,c.jsx)(eM.Z,{size:"xs",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})})})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{size:"xs",variant:"secondary",onClick:()=>r(e.team_id),children:"Join Team"})})]},e.team_id)),0===t.length&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:5,className:"text-center",children:(0,c.jsx)(A.Z,{children:"No available teams to join"})})})]})]})})};console.log=function(){};let lb=(e,s)=>{let l=[];return e&&e.models.length>0?(console.log("organization.models: ".concat(e.models)),l=e.models):l=s,B(l,s)};var lZ=e=>{let{teams:s,searchParams:l,accessToken:t,setTeams:a,userID:r,userRole:n,organizations:i}=e,[o,m]=(0,d.useState)(""),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(null);(0,d.useEffect)(()=>{console.log("inside useeffect - ".concat(o)),t&&Z(t,r,n,u,a),ey()},[o]);let[g]=L.Z.useForm(),[j]=L.Z.useForm(),{Title:f,Paragraph:_}=es.default,[v,b]=(0,d.useState)(""),[E,P]=(0,d.useState)(!1),[F,U]=(0,d.useState)(null),[B,H]=(0,d.useState)(null),[G,Y]=(0,d.useState)(!1),[$,X]=(0,d.useState)(!1),[Q,ee]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)(!1),[eo,ec]=(0,d.useState)(null),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({}),[ex,ep]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("currentOrgForCreateTeam: ".concat(x));let e=lb(x,ea);console.log("models: ".concat(e)),em(e),g.setFieldValue("models",[])},[x,ea]),(0,d.useEffect)(()=>{(async()=>{try{if(null==t)return;let e=(await (0,y.t3)(t)).guardrails.map(e=>e.guardrail_name);ep(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[t]);let ej=async e=>{ec(e),ei(!0)},ef=async()=>{if(null!=eo&&null!=s&&null!=t){try{await (0,y.rs)(t,eo),Z(t,r,n,u,a)}catch(e){console.error("Error deleting the team:",e)}ei(!1),ec(null)}};(0,d.useEffect)(()=>{(async()=>{try{if(null===r||null===n||null===t)return;let e=await V(r,n,t);e&&er(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,r,n,s]);let e_=async e=>{try{if(console.log("formValues: ".concat(JSON.stringify(e))),null!=t){var l;let r=null==e?void 0:e.team_alias,n=null!==(l=null==s?void 0:s.map(e=>e.team_alias))&&void 0!==l?l:[],i=(null==e?void 0:e.organization_id)||(null==u?void 0:u.organization_id);if(""===i||"string"!=typeof i?e.organization_id=null:e.organization_id=i.trim(),n.includes(r))throw Error("Team alias ".concat(r," already exists, please pick another alias"));D.ZP.info("Creating Team");let o=await (0,y.hT)(t,e);null!==s?a([...s,o]):a([o]),console.log("response for team create call: ".concat(o)),D.ZP.success("Team created"),g.resetFields(),X(!1)}}catch(e){console.error("Error creating the team:",e),D.ZP.error("Error creating the team: "+e,20)}},ey=()=>{m(new Date().toLocaleString())};return(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:B?(0,c.jsx)(sq,{teamId:B,onUpdate:e=>{a(s=>null==s?s:s.map(s=>e.team_id===s.team_id?e8(s,e):s))},onClose:()=>{H(null),Y(!1)},accessToken:t,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let s=0;se.team_id===B)),is_proxy_admin:"Admin"==n,userModels:ea,editTeam:G}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Your Teams"}),(0,c.jsx)(eR.Z,{children:"Available Teams"}),(0,eg.tY)(n||"")&&(0,c.jsx)(eR.Z,{children:"Default Team Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[o&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",o]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:ey})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(A.Z,{children:["Click on “Team ID” to view team details ",(0,c.jsx)("b",{children:"and"})," manage team members."]}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Team ID"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Organization"}),(0,c.jsx)(eP.Z,{children:"Info"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.filter(e=>!u||e.organization_id===u.organization_id).sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{H(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.spend}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},children:Array.isArray(e.models)?(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)})},s))}):null}),(0,c.jsx)(eA.Z,{children:e.organization_id}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].keys&&eu[e.team_id].keys.length," ","Keys"]}),(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].members_with_roles&&eu[e.team_id].members_with_roles.length," ","Members"]})]}),(0,c.jsx)(eA.Z,{children:"Admin"==n?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{H(e.team_id),Y(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>ej(e.team_id),icon:eH.Z,size:"sm"})]}):null})]},e.team_id)):null})]}),en&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Team"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this team ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ef,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{ei(!1),ec(null)},children:"Cancel"})]})]})]})})]})}),"Admin"==n||"Org Admin"==n?(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>X(!0),children:"+ Create New Team"}),(0,c.jsx)(M.Z,{title:"Create Team",visible:$,width:800,footer:null,onOk:()=>{X(!1),g.resetFields()},onCancel:()=>{X(!1),g.resetFields()},children:(0,c.jsxs)(L.Z,{form:g,onFinish:e_,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Organization"," ",(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:u?u.organization_id:null,className:"mt-8",children:(0,c.jsx)(O.default,{showSearch:!0,allowClear:!0,placeholder:"Search or select an Organization",onChange:e=>{g.setFieldValue("organization_id",e),p((null==i?void 0:i.find(s=>s.organization_id===e))||null)},filterOption:(e,s)=>{var l;return!!s&&((null===(l=s.children)||void 0===l?void 0:l.toString())||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==i?void 0:i.map(e=>(0,c.jsxs)(O.default.Option,{value:e.organization_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"These are the models that your selected team has access to",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),ed.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Additional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,c.jsx)(S.Z,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:ex.map(e=>({value:e,label:e}))})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Team"})})]})})]}):null]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lv,{accessToken:t,userID:r})}),(0,eg.tY)(n||"")&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ly,{accessToken:t,userID:r||"",userRole:n||""})})]})]})})},lN=e=>{var s;let{organizationId:l,onClose:t,accessToken:a,is_org_admin:r,is_proxy_admin:n,userModels:i,editOrg:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),C=r||n,I=async()=>{try{if(x(!0),!a)return;let e=await (0,y.t$)(a,l);u(e)}catch(e){D.ZP.error("Failed to load organization information"),console.error("Error fetching organization info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{I()},[l,a]);let T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.vh)(a,l,s),D.ZP.success("Organization member added successfully"),_(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to add organization member"),console.error("Error adding organization member:",e)}},P=async e=>{try{if(!a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.LY)(a,l,s),D.ZP.success("Organization member updated successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to update organization member"),console.error("Error updating organization member:",e)}},M=async e=>{try{if(!a)return;await (0,y.Sb)(a,l,e.user_id),D.ZP.success("Organization member deleted successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to delete organization member"),console.error("Error deleting organization member:",e)}},F=async e=>{try{if(!a)return;let s={organization_id:l,organization_alias:e.organization_alias,models:e.models,litellm_budget_table:{tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration},metadata:e.metadata?JSON.parse(e.metadata):null};await (0,y.VA)(a,s),D.ZP.success("Organization settings updated successfully"),j(!1),I()}catch(e){D.ZP.error("Failed to update organization settings"),console.error("Error updating organization:",e)}};return h?(0,c.jsx)("div",{className:"p-4",children:"Loading..."}):m?(0,c.jsxs)("div",{className:"w-full h-screen p-4 bg-white",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:m.organization_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:m.organization_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?2:0,children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Members"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Organization Details"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Created: ",new Date(m.created_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Updated: ",new Date(m.updated_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Created By: ",m.created_by]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",m.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===m.litellm_budget_table.max_budget?"Unlimited":"$".concat(m.litellm_budget_table.max_budget)]}),m.litellm_budget_table.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",m.litellm_budget_table.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]}),m.litellm_budget_table.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",m.litellm_budget_table.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[75vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Created At"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:null===(s=m.members)||void 0===s?void 0:s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_role})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["$",e.spend.toFixed(6)]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:new Date(e.created_at).toLocaleString()})}),(0,c.jsx)(eA.Z,{children:C&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{N({role:e.user_role,user_email:e.user_email,user_id:e.user_id}),b(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{M(e)}})]})})]},s))})]})}),C&&(0,c.jsx)(k.Z,{onClick:()=>{_(!0)},children:"Add Member"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Organization Settings"}),C&&!g&&(0,c.jsx)(k.Z,{onClick:()=>j(!0),children:"Edit Settings"})]}),g?(0,c.jsxs)(L.Z,{form:p,onFinish:F,initialValues:{organization_alias:m.organization_alias,models:m.models,tpm_limit:m.litellm_budget_table.tpm_limit,rpm_limit:m.litellm_budget_table.rpm_limit,max_budget:m.litellm_budget_table.max_budget,budget_duration:m.litellm_budget_table.budget_duration,metadata:m.metadata?JSON.stringify(m.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>j(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization Name"}),(0,c.jsx)("div",{children:m.organization_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization ID"}),(0,c.jsx)("div",{className:"font-mono",children:m.organization_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(m.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==m.litellm_budget_table.max_budget?"$".concat(m.litellm_budget_table.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",m.litellm_budget_table.budget_duration||"Never"]})]})]})]})})]})]}),(0,c.jsx)(sR,{isVisible:f,onCancel:()=>_(!1),onSubmit:T,accessToken:a,title:"Add Organization Member",roles:[{label:"org_admin",value:"org_admin",description:"Can add and remove members, and change their roles."},{label:"internal_user",value:"internal_user",description:"Can view/create keys for themselves within organization."},{label:"internal_user_viewer",value:"internal_user_viewer",description:"Can only view their keys within organization."}],defaultRole:"internal_user"}),(0,c.jsx)(sF,{visible:v,onCancel:()=>b(!1),onSubmit:P,initialData:Z,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Org Admin",value:"org_admin"},{label:"Internal User",value:"internal_user"},{label:"Internal User Viewer",value:"internal_user_viewer"}]}})]}):(0,c.jsx)("div",{className:"p-4",children:"Organization not found"})};let lw=async(e,s)=>{s(await (0,y.r6)(e))};var lk=e=>{let{organizations:s,userRole:l,userModels:t,accessToken:a,lastRefreshed:r,handleRefreshClick:n,currentOrg:i,guardrailsList:o=[],setOrganizations:m,premiumUser:u}=e,[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(null),[b,Z]=(0,d.useState)(!1),[C]=L.Z.useForm();(0,d.useEffect)(()=>{0===s.length&&a&&lw(a,m)},[s,a]);let I=e=>{e&&(v(e),f(!0))},T=async()=>{if(_&&a)try{await (0,y.cq)(a,_),D.ZP.success("Organization deleted successfully"),f(!1),v(null),lw(a,m)}catch(e){console.error("Error deleting organization:",e)}},E=async e=>{try{if(!a)return;console.log("values in organizations new create call: ".concat(JSON.stringify(e))),await (0,y.H1)(a,e),Z(!1),C.resetFields(),lw(a,m)}catch(e){console.error("Error creating organization:",e)}};return u?h?(0,c.jsx)(lN,{organizationId:h,onClose:()=>{x(null),g(!1)},accessToken:a,is_org_admin:!0,is_proxy_admin:"Admin"===l,userModels:t,editOrg:p}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsx)("div",{className:"flex",children:(0,c.jsx)(eR.Z,{children:"Your Organizations"})}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[r&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",r]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:n})]})]}),(0,c.jsx)(eV.Z,{children:(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(A.Z,{children:"Click on “Organization ID” to view organization details."}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Organization ID"}),(0,c.jsx)(eP.Z,{children:"Organization Name"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"TPM / RPM Limits"}),(0,c.jsx)(eP.Z,{children:"Info"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>{var s,t,a,r,n,i,o,d,m;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.organization_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>x(e.organization_id),children:[null===(s=e.organization_id)||void 0===s?void 0:s.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{children:e.organization_alias}),(0,c.jsx)(eA.Z,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{children:e.spend}),(0,c.jsx)(eA.Z,{children:(null===(t=e.litellm_budget_table)||void 0===t?void 0:t.max_budget)!==null&&(null===(a=e.litellm_budget_table)||void 0===a?void 0:a.max_budget)!==void 0?null===(r=e.litellm_budget_table)||void 0===r?void 0:r.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{children:Array.isArray(e.models)&&(0,c.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)},s))})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["TPM: ",(null===(n=e.litellm_budget_table)||void 0===n?void 0:n.tpm_limit)?null===(i=e.litellm_budget_table)||void 0===i?void 0:i.tpm_limit:"Unlimited",(0,c.jsx)("br",{}),"RPM: ",(null===(o=e.litellm_budget_table)||void 0===o?void 0:o.rpm_limit)?null===(d=e.litellm_budget_table)||void 0===d?void 0:d.rpm_limit:"Unlimited"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[(null===(m=e.members)||void 0===m?void 0:m.length)||0," Members"]})}),(0,c.jsx)(eA.Z,{children:"Admin"===l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{x(e.organization_id),g(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>I(e.organization_id),icon:eH.Z,size:"sm"})]})})]},e.organization_id)}):null})]})})}),("Admin"===l||"Org Admin"===l)&&(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>Z(!0),children:"+ Create New Organization"}),(0,c.jsx)(M.Z,{title:"Create Organization",visible:b,width:800,footer:null,onCancel:()=>{Z(!1),C.resetFields()},children:(0,c.jsxs)(L.Z,{form:C,onFinish:E,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),t&&t.length>0&&t.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Organization"})})]})})]})]})]})}),j?(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Organization"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this organization?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:T,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{f(!1),v(null)},children:"Cancel"})]})]})]})}):(0,c.jsx)(c.Fragment,{})]}):(0,c.jsx)("div",{children:(0,c.jsxs)(A.Z,{children:["This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key ",(0,c.jsx)("a",{href:"https://litellm.ai/pricing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})},lS=l(94789);let lC={google:"https://artificialanalysis.ai/img/logos/google_small.svg",microsoft:"https://upload.wikimedia.org/wikipedia/commons/a/a8/Microsoft_Azure_Logo.svg",okta:"https://www.okta.com/sites/default/files/Okta_Logo_BrightBlue_Medium.png",generic:""},lI={google:{envVarMap:{google_client_id:"GOOGLE_CLIENT_ID",google_client_secret:"GOOGLE_CLIENT_SECRET"},fields:[{label:"GOOGLE CLIENT ID",name:"google_client_id"},{label:"GOOGLE CLIENT SECRET",name:"google_client_secret"}]},microsoft:{envVarMap:{microsoft_client_id:"MICROSOFT_CLIENT_ID",microsoft_client_secret:"MICROSOFT_CLIENT_SECRET",microsoft_tenant:"MICROSOFT_TENANT"},fields:[{label:"MICROSOFT CLIENT ID",name:"microsoft_client_id"},{label:"MICROSOFT CLIENT SECRET",name:"microsoft_client_secret"},{label:"MICROSOFT TENANT",name:"microsoft_tenant"}]},okta:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint",placeholder:"https://your-okta-domain/authorize"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint",placeholder:"https://your-okta-domain/token"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint",placeholder:"https://your-okta-domain/userinfo"}]},generic:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint"}]}};var lT=e=>{let{isAddSSOModalVisible:s,isInstructionsModalVisible:l,handleAddSSOOk:t,handleAddSSOCancel:a,handleShowInstructions:r,handleInstructionsOk:n,handleInstructionsCancel:i,form:o}=e,d=e=>{let s=lI[e];return s?s.fields.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,rules:[{required:!0,message:"Please enter the ".concat(e.label.toLowerCase())}],children:e.name.includes("client")?(0,c.jsx)(q.default.Password,{}):(0,c.jsx)(S.Z,{placeholder:e.placeholder})},e.name)):null};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(M.Z,{title:"Add SSO",visible:s,width:800,footer:null,onOk:t,onCancel:a,children:(0,c.jsxs)(L.Z,{form:o,onFinish:r,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,c.jsx)(O.default,{children:Object.entries(lC).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[l&&(0,c.jsx)("img",{src:l,alt:s,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,c.jsxs)("span",{children:[s.charAt(0).toUpperCase()+s.slice(1)," SSO"]})]})},s)})})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("sso_provider");return l?d(l):null}}),(0,c.jsx)(L.Z.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"PROXY BASE URL",name:"proxy_base_url",rules:[{required:!0,message:"Please enter the proxy base url"}],children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})}),(0,c.jsxs)(M.Z,{title:"SSO Setup Instructions",visible:l,width:800,footer:null,onOk:n,onCancel:i,children:[(0,c.jsx)("p",{children:"Follow these steps to complete the SSO setup:"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"1. DO NOT Exit this TAB"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"2. Open a new tab, visit your proxy base url"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"3. Confirm your SSO is configured correctly and you can login on the new Tab"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"4. If Step 3 is successful, you can close this tab"}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{onClick:n,children:"Done"})})]})]})},lA=l(62272),lE=l(92403),lP=l(29271),lO=l(34419),lL=e=>{let{accessToken:s,userID:l,proxySettings:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)("");(0,d.useEffect)(()=>{let e="";u(t&&t.PROXY_BASE_URL&&void 0!==t.PROXY_BASE_URL?t.PROXY_BASE_URL:window.location.origin)},[t]);let h="".concat(m,"/scim/v2"),x=async e=>{if(!s||!l){D.ZP.error("You need to be logged in to create a SCIM token");return}try{n(!0);let t={key_alias:e.key_alias||"SCIM Access Token",team_id:null,models:[],allowed_routes:["/scim/*"]},a=await (0,y.wX)(s,l,t);o(a),D.ZP.success("SCIM token created successfully")}catch(e){console.error("Error creating SCIM token:",e),D.ZP.error("Failed to create SCIM token")}finally{n(!1)}};return(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex items-center mb-4",children:(0,c.jsx)(E.Z,{children:"SCIM Configuration"})}),(0,c.jsx)(A.Z,{className:"text-gray-600",children:"System for Cross-domain Identity Management (SCIM) allows you to automatically provision and manage users and groups in LiteLLM."}),(0,c.jsx)(lj.Z,{}),(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"1"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lA.Z,{className:"h-5 w-5 mr-2"}),"SCIM Tenant URL"]})]}),(0,c.jsx)(A.Z,{className:"text-gray-600 mb-3",children:"Use this URL in your identity provider SCIM integration settings."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:h,disabled:!0,className:"flex-grow"}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>D.ZP.success("URL copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"ml-2 flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"2"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-5 w-5 mr-2"}),"Authentication Token"]})]}),(0,c.jsx)(lS.Z,{title:"Using SCIM",color:"blue",className:"mb-4",children:"You need a SCIM token to authenticate with the SCIM API. Create one below and use it in your SCIM provider configuration."}),i?(0,c.jsxs)(eF.Z,{className:"border border-yellow-300 bg-yellow-50",children:[(0,c.jsxs)("div",{className:"flex items-center mb-2 text-yellow-800",children:[(0,c.jsx)(lP.Z,{className:"h-5 w-5 mr-2"}),(0,c.jsx)(E.Z,{className:"text-lg text-yellow-800",children:"Your SCIM Token"})]}),(0,c.jsx)(A.Z,{className:"text-yellow-800 mb-4 font-medium",children:"Make sure to copy this token now. You will not be able to see it again."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:i.token,className:"flex-grow mr-2 bg-white",type:"password",disabled:!0}),(0,c.jsx)(P.CopyToClipboard,{text:i.token,onCopy:()=>D.ZP.success("Token copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]}),(0,c.jsxs)(k.Z,{className:"mt-4 flex items-center",variant:"secondary",onClick:()=>o(null),children:[(0,c.jsx)(lO.Z,{className:"h-4 w-4 mr-1"}),"Create Another Token"]})]}):(0,c.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,c.jsxs)(L.Z,{form:a,onFinish:x,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Token Name",rules:[{required:!0,message:"Please enter a name for your token"}],children:(0,c.jsx)(S.Z,{placeholder:"SCIM Access Token"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)(k.Z,{variant:"primary",type:"submit",loading:r,className:"flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-4 w-4 mr-1"}),"Create SCIM Token"]})})]})})]})]})]})})};let lD=()=>{let[e,s]=(0,d.useState)("http://localhost:4000");return(0,d.useEffect)(()=>{{let{protocol:e,host:l}=window.location;s("".concat(e,"//").concat(l))}},[]),e};var lM=e=>{let{searchParams:s,accessToken:l,showSSOBanner:t,premiumUser:a,proxySettings:r}=e,[n]=L.Z.useForm(),[i]=L.Z.useForm(),{Title:o,Paragraph:u}=es.default,[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)(null),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(!1),[S,C]=(0,d.useState)(!1),[I,T]=(0,d.useState)(!1),[A,E]=(0,d.useState)(!1),[P,O]=(0,d.useState)(!1),[F,U]=(0,d.useState)(!1),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)([]),[H,J]=(0,d.useState)(null);(0,m.useRouter)();let[W,G]=(0,d.useState)(null);console.log=function(){};let Y=lD(),$="All IP Addresses Allowed",X=Y;X+="/fallback/login";let Q=async()=>{try{if(!0!==a){D.ZP.error("This feature is only available for premium users. Please upgrade your account.");return}if(l){let e=await (0,y.PT)(l);B(e&&e.length>0?e:[$])}else B([$])}catch(e){console.error("Error fetching allowed IPs:",e),D.ZP.error("Failed to fetch allowed IPs ".concat(e)),B([$])}finally{!0===a&&O(!0)}},ee=async e=>{try{if(l){await (0,y.eH)(l,e.ip);let s=await (0,y.PT)(l);B(s),D.ZP.success("IP address added successfully")}}catch(e){console.error("Error adding IP:",e),D.ZP.error("Failed to add IP address ".concat(e))}finally{U(!1)}},el=async e=>{J(e),V(!0)},et=async()=>{if(H&&l)try{await (0,y.$I)(l,H);let e=await (0,y.PT)(l);B(e.length>0?e:[$]),D.ZP.success("IP address deleted successfully")}catch(e){console.error("Error deleting IP:",e),D.ZP.error("Failed to delete IP address ".concat(e))}finally{V(!1),J(null)}};(0,d.useEffect)(()=>{(async()=>{if(null!=l){let e=[],s=await (0,y.Xd)(l,"proxy_admin_viewer");console.log("proxy admin viewer response: ",s);let t=s.users;console.log("proxy viewers response: ".concat(t)),t.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy viewers: ".concat(t));let a=(await (0,y.Xd)(l,"proxy_admin")).users;a.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy admins: ".concat(a)),console.log("combinedList: ".concat(e)),g(e),G(await (0,y.lg)(l))}})()},[l]);let ea=async e=>{try{if(null!=l&&null!=p){var s;D.ZP.info("Making API Call"),e.user_email,e.user_id;let t=await (0,y.pf)(l,e,"proxy_admin"),a=(null===(s=t.data)||void 0===s?void 0:s.user_id)||t.user_id;(0,y.XO)(l,a).then(e=>{f(e),v(!0)}),console.log("response for team create call: ".concat(t));let r=p.findIndex(e=>(console.log("user.user_id=".concat(e.user_id,"; response.user_id=").concat(a)),e.user_id===t.user_id));console.log("foundIndex: ".concat(r)),-1==r&&(console.log("updates admin with new user"),p.push(t),g(p)),n.resetFields(),w(!1)}}catch(e){console.error("Error creating the key:",e)}},er=async e=>{if(null==l)return;let s=lI[e.sso_provider],t={PROXY_BASE_URL:e.proxy_base_url};s&&Object.entries(s.envVarMap).forEach(s=>{let[l,a]=s;e[l]&&(t[a]=e[l])}),(0,y.K_)(l,{environment_variables:t})};return console.log("admins: ".concat(null==p?void 0:p.length)),(0,c.jsxs)("div",{className:"w-full m-2 mt-2 p-8",children:[(0,c.jsx)(o,{level:4,children:"Admin Access "}),(0,c.jsx)(u,{children:"Go to 'Internal Users' page to add other admins."}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Security Settings"}),(0,c.jsx)(eR.Z,{children:"SCIM"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(o,{level:4,children:" ✨ Security Settings"}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem"},children:[(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:()=>!0===a?T(!0):D.ZP.error("Only premium users can add SSO"),children:"Add SSO"})}),(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:Q,children:"Allowed IPs"})})]})]}),(0,c.jsxs)("div",{className:"flex justify-start mb-4",children:[(0,c.jsx)(lT,{isAddSSOModalVisible:I,isInstructionsModalVisible:A,handleAddSSOOk:()=>{T(!1),n.resetFields()},handleAddSSOCancel:()=>{T(!1),n.resetFields()},handleShowInstructions:e=>{ea(e),er(e),T(!1),E(!0)},handleInstructionsOk:()=>{E(!1)},handleInstructionsCancel:()=>{E(!1)},form:n}),(0,c.jsx)(M.Z,{title:"Manage Allowed IP Addresses",width:800,visible:P,onCancel:()=>O(!1),footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>U(!0),children:"Add IP Address"},"add"),(0,c.jsx)(k.Z,{onClick:()=>O(!1),children:"Close"},"close")],children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"IP Address"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:K.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e}),(0,c.jsx)(eA.Z,{className:"text-right",children:e!==$&&(0,c.jsx)(k.Z,{onClick:()=>el(e),color:"red",size:"xs",children:"Delete"})})]},s))})]})}),(0,c.jsx)(M.Z,{title:"Add Allowed IP Address",visible:F,onCancel:()=>U(!1),footer:null,children:(0,c.jsxs)(L.Z,{onFinish:ee,children:[(0,c.jsx)(L.Z.Item,{name:"ip",rules:[{required:!0,message:"Please enter an IP address"}],children:(0,c.jsx)(q.default,{placeholder:"Enter IP address"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add IP Address"})})]})}),(0,c.jsx)(M.Z,{title:"Confirm Delete",visible:z,onCancel:()=>V(!1),onOk:et,footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>et(),children:"Yes"},"delete"),(0,c.jsx)(k.Z,{onClick:()=>V(!1),children:"Close"},"close")],children:(0,c.jsxs)("p",{children:["Are you sure you want to delete the IP address: ",H,"?"]})})]}),(0,c.jsxs)(lS.Z,{title:"Login without SSO",color:"teal",children:["If you need to login without sso, you can access"," ",(0,c.jsxs)("a",{href:X,target:"_blank",children:[(0,c.jsx)("b",{children:X})," "]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lL,{accessToken:l,userID:p&&p.length>0?p[0].user_id:null,proxySettings:r})})]})]})]})},lF=l(92858),lR=e=>{let{alertingSettings:s,handleInputChange:l,handleResetField:t,handleSubmit:a,premiumUser:r}=e,[n]=L.Z.useForm();return(0,c.jsxs)(L.Z,{form:n,onFinish:()=>{console.log("INSIDE ONFINISH");let e=n.getFieldsValue(),s=Object.entries(e).every(e=>{let[s,l]=e;return"boolean"!=typeof l&&(""===l||null==l)});console.log("formData: ".concat(JSON.stringify(e),", isEmpty: ").concat(s)),s?console.log("Some form fields are empty."):a(e)},labelAlign:"left",children:[s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{align:"center",children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),e.premium_field?r?(0,c.jsx)(L.Z.Item,{name:e.field_name,children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s)}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>l(e.field_name,s)}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}):(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})})}):(0,c.jsx)(L.Z.Item,{name:e.field_name,className:"mb-0",valuePropName:"Boolean"===e.field_type?"checked":"value",children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s),className:"p-0"}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>{l(e.field_name,s),n.setFieldsValue({[e.field_name]:s})}}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>t(e.field_name,s),children:"Reset"})})]},s)),(0,c.jsx)("div",{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Update Settings"})})]})},lq=e=>{let{accessToken:s,premiumUser:l}=e,[t,a]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(0,y.RQ)(s).then(e=>{a(e)})},[s]),(0,c.jsx)(lR,{alertingSettings:t,handleInputChange:(e,s)=>{let l=t.map(l=>l.field_name===e?{...l,field_value:s}:l);console.log("updatedSettings: ".concat(JSON.stringify(l))),a(l)},handleResetField:(e,l)=>{if(s)try{let s=t.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:s.field_default_value}:s);a(s)}catch(e){console.log("ERROR OCCURRED!")}},handleSubmit:e=>{if(!s||(console.log("formValues: ".concat(e)),null==e||void 0==e))return;let l={};t.forEach(e=>{l[e.field_name]=e.field_value});let a={...e,...l};console.log("mergedFormValues: ".concat(JSON.stringify(a)));let{slack_alerting:r,...n}=a;console.log("slack_alerting: ".concat(r,", alertingArgs: ").concat(JSON.stringify(n)));try{(0,y.jA)(s,"alerting_args",n),"boolean"==typeof r&&(!0==r?(0,y.jA)(s,"alerting",["slack"]):(0,y.jA)(s,"alerting",[])),D.ZP.success("Wait 10s for proxy to update.")}catch(e){}},premiumUser:l})},lU=l(86582);let{Title:lz,Paragraph:lV}=es.default;console.log=function(){};var lK=e=>{let{accessToken:s,userRole:l,userID:t,premiumUser:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h]=L.Z.useForm(),[x,p]=(0,d.useState)(null),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)({}),[Z,N]=(0,d.useState)([]),[C,I]=(0,d.useState)(!1),[T,E]=(0,d.useState)([]),[P,F]=(0,d.useState)(null),[q,U]=(0,d.useState)([]),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)(null),H=e=>{Z.includes(e)?N(Z.filter(s=>s!==e)):N([...Z,e])},J={llm_exceptions:"LLM Exceptions",llm_too_slow:"LLM Responses Too Slow",llm_requests_hanging:"LLM Requests Hanging",budget_alerts:"Budget Alerts (API Keys, Users)",db_exceptions:"Database Exceptions (Read/Write)",daily_reports:"Weekly/Monthly Spend Reports",outage_alerts:"Outage Alerts",region_outage_alerts:"Region Outage Alerts"};(0,d.useEffect)(()=>{s&&l&&t&&(0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e),n(e.callbacks),E(e.available_callbacks);let s=e.alerts;if(console.log("alerts_data",s),s&&s.length>0){let e=s[0];console.log("_alert_info",e);let l=e.variables.SLACK_WEBHOOK_URL;console.log("catch_all_webhook",l),N(e.active_alerts),_(l),b(e.alerts_to_webhook)}o(s)})},[s,l,t]);let W=e=>Z&&Z.includes(e),G=()=>{if(!s)return;let e={};i.filter(e=>"email"===e.name).forEach(s=>{var l;Object.entries(null!==(l=s.variables)&&void 0!==l?l:{}).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));a&&a.value&&(e[l]=null==a?void 0:a.value)})}),console.log("updatedVariables",e);try{(0,y.K_)(s,{general_settings:{alerting:["email"]},environment_variables:e})}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Email settings updated successfully")},Y=async e=>{if(!s)return;let l={};Object.entries(e).forEach(e=>{let[s,t]=e;"callback"!==s&&(l[s]=t)});try{await (0,y.K_)(s,{environment_variables:l}),D.ZP.success("Callback added successfully"),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},$=async e=>{if(!s)return;let l=null==e?void 0:e.callback,t={};Object.entries(e).forEach(e=>{let[s,l]=e;"callback"!==s&&(t[s]=l)});try{await (0,y.K_)(s,{environment_variables:t,litellm_settings:{success_callback:[l]}}),D.ZP.success("Callback ".concat(l," added successfully")),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},X=e=>{console.log("inside handleSelectedCallbackChange",e),p(e.litellm_callback_name),console.log("all callbacks",T),e&&e.litellm_callback_params?(U(e.litellm_callback_params),console.log("selectedCallbackParams",q)):U([])};return s?(console.log("callbacks: ".concat(r)),(0,c.jsxs)("div",{className:"w-full mx-4",children:[(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Logging Callbacks"}),(0,c.jsx)(eR.Z,{value:"2",children:"Alerting Types"}),(0,c.jsx)(eR.Z,{value:"3",children:"Alerting Settings"}),(0,c.jsx)(eR.Z,{value:"4",children:"Email Alerts"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Active Logging Callbacks"}),(0,c.jsx)(w.Z,{numItems:2,children:(0,c.jsx)(eF.Z,{className:"max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eP.Z,{children:"Callback Name"})})}),(0,c.jsx)(eT.Z,{children:r.map((e,l)=>(0,c.jsxs)(eO.Z,{className:"flex justify-between",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.name})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"flex justify-between",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{B(e),V(!0)}}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,e.name),className:"ml-2",variant:"secondary",children:"Test Callback"})]})})]},l))})]})})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>I(!0),children:"Add Callback"})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(A.Z,{className:"my-2",children:["Alerts are only supported for Slack Webhook URLs. Get your webhook urls from"," ",(0,c.jsx)("a",{href:"https://api.slack.com/messaging/webhooks",target:"_blank",style:{color:"blue"},children:"here"})]}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{children:"Slack Webhook URL"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(J).map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:"region_outage_alerts"==l?a?(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)}):(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})}):(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:l,type:"password",defaultValue:v&&v[l]?v[l]:f})})]},s)})})]}),(0,c.jsx)(k.Z,{size:"xs",className:"mt-2",onClick:()=>{if(!s)return;let e={};Object.entries(J).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));console.log("key",l),console.log("webhookInput",a);let r=(null==a?void 0:a.value)||"";console.log("newWebhookValue",r),e[l]=r}),console.log("updatedAlertToWebhooks",e);let l={general_settings:{alert_to_webhook_url:e,alert_types:Z}};console.log("payload",l);try{(0,y.K_)(s,l)}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Alerts updated successfully")},children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"slack"),className:"mx-2",children:"Test Alerts"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lq,{accessToken:s,premiumUser:a})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Email Settings"}),(0,c.jsxs)(A.Z,{children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: email alerts"})," ",(0,c.jsx)("br",{})]}),(0,c.jsx)("div",{className:"flex w-full",children:i.filter(e=>"email"===e.name).map((e,s)=>{var l;return(0,c.jsx)(eA.Z,{children:(0,c.jsx)("ul",{children:(0,c.jsx)(w.Z,{numItems:2,children:Object.entries(null!==(l=e.variables)&&void 0!==l?l:{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("li",{className:"mx-2 my-2",children:[!0!=a&&("EMAIL_LOGO_URL"===s||"EMAIL_SUPPORT_CONTACT"===s)?(0,c.jsxs)("div",{children:[(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:(0,c.jsxs)(A.Z,{className:"mt-2",children:[" ","✨ ",s]})}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",disabled:!0,style:{width:"400px"}})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-2",children:s}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",style:{width:"400px"}})]}),(0,c.jsxs)("p",{style:{fontSize:"small",fontStyle:"italic"},children:["SMTP_HOST"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP host address, e.g. `smtp.resend.com`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PORT"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP port number, e.g. `587`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_USERNAME"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP username, e.g. `username`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PASSWORD"===s&&(0,c.jsx)("span",{style:{color:"red"},children:" Required * "}),"SMTP_SENDER_EMAIL"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the sender email address, e.g. `sender@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"TEST_EMAIL_ADDRESS"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Email Address to send `Test Email Alert` to. example: `info@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"EMAIL_LOGO_URL"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the Logo that appears in the email, pass a url to your logo"}),"EMAIL_SUPPORT_CONTACT"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the support email address that appears in the email. Default is support@berri.ai"})]})]},s)})})})},s)})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>G(),children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"email"),className:"mx-2",children:"Test Email Alerts"})]})})]})]})}),(0,c.jsxs)(M.Z,{title:"Add Logging Callback",visible:C,width:800,onCancel:()=>I(!1),footer:null,children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/logging",className:"mb-8 mt-4",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: Logging"}),(0,c.jsx)(L.Z,{form:h,onFinish:$,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(lU.Z,{label:"Callback",name:"callback",rules:[{required:!0,message:"Please select a callback"}],children:(0,c.jsx)(O.default,{onChange:e=>{let s=T[e];s&&(console.log(s.ui_callback_name),X(s))},children:T&&Object.values(T).map(e=>(0,c.jsx)(ee.Z,{value:e.litellm_callback_name,children:e.ui_callback_name},e.litellm_callback_name))})}),q&&q.map(e=>(0,c.jsx)(lU.Z,{label:e,name:e,rules:[{required:!0,message:"Please enter the value for "+e}],children:(0,c.jsx)(S.Z,{type:"password"})},e)),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]}),(0,c.jsx)(M.Z,{visible:z,width:800,title:"Edit ".concat(null==K?void 0:K.name," Settings"),onCancel:()=>V(!1),footer:null,children:(0,c.jsxs)(L.Z,{form:h,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(c.Fragment,{children:K&&K.variables&&Object.entries(K.variables).map(e=>{let[s,l]=e;return(0,c.jsx)(lU.Z,{label:s,name:s,children:(0,c.jsx)(S.Z,{type:"password",defaultValue:l})},s)})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]})):null},lB=l(92414),lH=l(46030);let{Option:lJ}=O.default;var lW=e=>{let{models:s,accessToken:l,routerSettings:t,setRouterSettings:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>i(!0),children:"+ Add Fallbacks"}),(0,c.jsx)(M.Z,{title:"Add Fallbacks",visible:n,width:800,footer:null,onOk:()=>{i(!1),r.resetFields()},onCancel:()=>{i(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:e=>{console.log(e);let{model_name:s,models:n}=e,o=[...t.fallbacks||[],{[s]:n}],c={...t,fallbacks:o};console.log(c);try{(0,y.K_)(l,{router_settings:c}),a(c)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully"),i(!1),r.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Public Model Name",name:"model_name",rules:[{required:!0,message:"Set the model to fallback for"}],help:"required",children:(0,c.jsx)(eD.Z,{defaultValue:o,children:s&&s.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>m(e),children:e},s))})}),(0,c.jsx)(L.Z.Item,{label:"Fallback Models",name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",children:(0,c.jsx)(lB.Z,{value:s,children:s&&s.filter(e=>e!=o).map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Fallbacks"})})]})})]})},lG=l(26433);async function lY(e,s){console.log=function(){},console.log("isLocal:",!1);let l=window.location.origin,t=new lG.ZP.OpenAI({apiKey:s,baseURL:l,dangerouslyAllowBrowser:!0});try{let s=await t.chat.completions.create({model:e,messages:[{role:"user",content:"Hi, this is a test message"}],mock_testing_fallbacks:!0});D.ZP.success((0,c.jsxs)("span",{children:["Test model=",(0,c.jsx)("strong",{children:e}),", received model=",(0,c.jsx)("strong",{children:s.model}),". See"," ",(0,c.jsx)("a",{href:"#",onClick:()=>window.open("https://docs.litellm.ai/docs/proxy/reliability","_blank"),style:{textDecoration:"underline",color:"blue"},children:"curl"})]}))}catch(e){D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20)}}let l$={ttl:3600,lowest_latency_buffer:0},lX=e=>{let{selectedStrategy:s,strategyArgs:l,paramExplanation:t}=e;return(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{className:"text-sm font-medium text-tremor-content-strong dark:text-dark-tremor-content-strong",children:"Routing Strategy Specific Args"}),(0,c.jsx)(I.Z,{children:"latency-based-routing"==s?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(l).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:t[s]})]}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]})}):(0,c.jsx)(A.Z,{children:"No specific settings"})})]})};var lQ=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)({}),[i,o]=(0,d.useState)({}),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(null),Z={routing_strategy_args:"(dict) Arguments to pass to the routing strategy",routing_strategy:"(string) Routing strategy to use",allowed_fails:"(int) Number of times a deployment can fail before being added to cooldown",cooldown_time:"(int) time in seconds to cooldown a deployment after failure",num_retries:"(int) Number of retries for failed requests. Defaults to 0.",timeout:"(float) Timeout for requests. Defaults to None.",retry_after:"(int) Minimum time to wait before retrying a failed request",ttl:"(int) Sliding window to look back over when calculating the average latency of a deployment. Default - 1 hour (in seconds).",lowest_latency_buffer:"(float) Shuffle between deployments within this % of the lowest latency. Default - 0 (i.e. always pick lowest latency)."};(0,d.useEffect)(()=>{s&&l&&t&&((0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e);let s=e.router_settings;"model_group_retry_policy"in s&&delete s.model_group_retry_policy,n(s)}),(0,y.YU)(s).then(e=>{u(e)}))},[s,l,t]);let C=async e=>{if(!s)return;console.log("received key: ".concat(e)),console.log("routerSettings['fallbacks']: ".concat(r.fallbacks));let l=r.fallbacks.map(s=>(e in s&&delete s[e],s)).filter(e=>Object.keys(e).length>0),t={...r,fallbacks:l};try{await (0,y.K_)(s,{router_settings:t}),n(t),D.ZP.success("Router settings updated successfully")}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}},I=(e,s)=>{u(m.map(l=>l.field_name===e?{...l,field_value:s}:l))},T=(e,l)=>{if(!s)return;let t=m[l].field_value;if(null!=t&&void 0!=t)try{(0,y.jA)(s,e,t);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:!0}:s);u(l)}catch(e){}},P=(e,l)=>{if(s)try{(0,y.ao)(s,e);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:null}:s);u(l)}catch(e){}},O=e=>{if(!s)return;console.log("router_settings",e);let l=Object.fromEntries(Object.entries(e).map(e=>{let[s,l]=e;if("routing_strategy_args"!==s&&"routing_strategy"!==s){var t;return[s,(null===(t=document.querySelector('input[name="'.concat(s,'"]')))||void 0===t?void 0:t.value)||l]}if("routing_strategy"==s)return[s,f];if("routing_strategy_args"==s&&"latency-based-routing"==f){let e={},s=document.querySelector('input[name="lowest_latency_buffer"]'),l=document.querySelector('input[name="ttl"]');return(null==s?void 0:s.value)&&(e.lowest_latency_buffer=Number(s.value)),(null==l?void 0:l.value)&&(e.ttl=Number(l.value)),console.log("setRoutingStrategyArgs: ".concat(e)),["routing_strategy_args",e]}return null}).filter(e=>null!=e));console.log("updatedVariables",l);try{(0,y.K_)(s,{router_settings:l})}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully")};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Loadbalancing"}),(0,c.jsx)(eR.Z,{value:"2",children:"Fallbacks"}),(0,c.jsx)(eR.Z,{value:"3",children:"General"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:[(0,c.jsx)(E.Z,{children:"Router Settings"}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(r).filter(e=>{let[s,l]=e;return"fallbacks"!=s&&"context_window_fallbacks"!=s&&"routing_strategy_args"!=s}).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:Z[s]})]}),(0,c.jsx)(eA.Z,{children:"routing_strategy"==s?(0,c.jsxs)(eD.Z,{defaultValue:l,className:"w-full max-w-md",onValueChange:_,children:[(0,c.jsx)(ee.Z,{value:"usage-based-routing",children:"usage-based-routing"}),(0,c.jsx)(ee.Z,{value:"latency-based-routing",children:"latency-based-routing"}),(0,c.jsx)(ee.Z,{value:"simple-shuffle",children:"simple-shuffle"})]}):(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]}),(0,c.jsx)(lX,{selectedStrategy:f,strategyArgs:r&&r.routing_strategy_args&&Object.keys(r.routing_strategy_args).length>0?r.routing_strategy_args:l$,paramExplanation:Z})]}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>O(r),children:"Save Changes"})})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Model Name"}),(0,c.jsx)(eP.Z,{children:"Fallbacks"})]})}),(0,c.jsx)(eT.Z,{children:r.fallbacks&&r.fallbacks.map((e,l)=>Object.entries(e).map(e=>{let[t,a]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:t}),(0,c.jsx)(eA.Z,{children:Array.isArray(a)?a.join(", "):a}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{onClick:()=>lY(t,s),children:"Test Fallback"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>C(t)})})]},l.toString()+t)}))})]}),(0,c.jsx)(lW,{models:(null==a?void 0:a.data)?a.data.map(e=>e.model_name):[],accessToken:s,routerSettings:r,setRouterSettings:n})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"}),(0,c.jsx)(eP.Z,{children:"Status"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:m.filter(e=>"TypedDictionary"!==e.field_type).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),(0,c.jsx)(eA.Z,{children:"Integer"==e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>I(e.field_name,s)}):null}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{onClick:()=>T(e.field_name,s),children:"Update"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>P(e.field_name,s),children:"Reset"})]})]},s))})]})})})]})]})}):null},l0=l(93142),l1=e=>{let{value:s={},onChange:l}=e,[t,a]=(0,d.useState)(Object.entries(s)),r=e=>{let s=t.filter((s,l)=>l!==e);a(s),null==l||l(Object.fromEntries(s))},n=(e,s,r)=>{let n=[...t];n[e]=[s,r],a(n),null==l||l(Object.fromEntries(n))};return(0,c.jsxs)("div",{children:[t.map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(l0.Z,{style:{display:"flex",marginBottom:8},align:"start",children:[(0,c.jsx)(S.Z,{placeholder:"Header Name",value:l,onChange:e=>n(s,e.target.value,t)}),(0,c.jsx)(S.Z,{placeholder:"Header Value",value:t,onChange:e=>n(s,l,e.target.value)}),(0,c.jsx)(sH.Z,{onClick:()=>r(s)})]},s)}),(0,c.jsx)(R.ZP,{type:"dashed",onClick:()=>{a([...t,["",""]])},icon:(0,c.jsx)(sJ.Z,{}),children:"Add Header"})]})};let{Option:l2}=O.default;var l4=e=>{let{accessToken:s,setPassThroughItems:l,passThroughItems:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>n(!0),children:"+ Add Pass-Through Endpoint"}),(0,c.jsx)(M.Z,{title:"Add Pass-Through Endpoint",visible:r,width:800,footer:null,onOk:()=>{n(!1),a.resetFields()},onCancel:()=>{n(!1),a.resetFields()},children:(0,c.jsxs)(L.Z,{form:a,onFinish:e=>{console.log(e);let r=[...t,{headers:e.headers,path:e.path,target:e.target}];try{(0,y.Vt)(s,e),l(r)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("Pass through endpoint successfully added"),n(!1),a.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Path",name:"path",rules:[{required:!0,message:"The route to be added to the LiteLLM Proxy Server."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Target",name:"target",rules:[{required:!0,message:"The URL to which requests for this path should be forwarded."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Headers",name:"headers",rules:[{required:!0,message:"Key-value pairs of headers to be forwarded with the request. You can set any key value pair here and it will be forwarded to your target endpoint"}],help:"required",children:(0,c.jsx)(l1,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Pass-Through Endpoint"})})]})})]})},l5=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&l&&t&&(0,y.mp)(s).then(e=>{n(e.endpoints)})},[s,l,t]);let i=(e,l)=>{if(s)try{(0,y.EG)(s,e);let l=r.filter(s=>s.path!==e);n(l),D.ZP.success("Endpoint deleted successfully.")}catch(e){}};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsx)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Path"}),(0,c.jsx)(eP.Z,{children:"Target"}),(0,c.jsx)(eP.Z,{children:"Headers"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:r.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.path})}),(0,c.jsx)(eA.Z,{children:e.target}),(0,c.jsx)(eA.Z,{children:JSON.stringify(e.headers)}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>i(e.path,s),children:"Reset"})})]},s))})]}),(0,c.jsx)(l4,{accessToken:s,setPassThroughItems:n,passThroughItems:r})]})})}):null},l6=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a}=e,[r]=L.Z.useForm(),n=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call");let s=await (0,y.Zr)(l,e);console.log("key create Response:",s),a(e=>e?[...e,s]:[s]),D.ZP.success("API Key Created"),r.resetFields()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Create Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),r.resetFields()},onCancel:()=>{t(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:n,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Budget"})})]})})},l3=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a,existingBudget:r,handleUpdateCall:n}=e;console.log("existingBudget",r);let[i]=L.Z.useForm();(0,d.useEffect)(()=>{i.setFieldsValue(r)},[r,i]);let o=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call"),t(!0);let s=await (0,y.qI)(l,e);a(e=>e?[...e,s]:[s]),D.ZP.success("Budget Updated"),i.resetFields(),n()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Edit Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),i.resetFields()},onCancel:()=>{t(!1),i.resetFields()},children:(0,c.jsxs)(L.Z,{form:i,onFinish:o,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:r,children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})},l8=l(17906),l7=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&(0,y.O3)(s).then(e=>{m(e)})},[s]);let u=async(e,l)=>{console.log("budget_id",e),null!=s&&(i(o.find(s=>s.budget_id===e)||null),r(!0))},h=async(e,l)=>{if(null==s)return;D.ZP.info("Request made"),await (0,y.NV)(s,e);let t=[...o];t.splice(l,1),m(t),D.ZP.success("Budget Deleted.")},x=async()=>{null!=s&&(0,y.O3)(s).then(e=>{m(e)})};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)(k.Z,{size:"sm",variant:"primary",className:"mb-2",onClick:()=>t(!0),children:"+ Create Budget"}),(0,c.jsx)(l6,{accessToken:s,isModalVisible:l,setIsModalVisible:t,setBudgetList:m}),n&&(0,c.jsx)(l3,{accessToken:s,isModalVisible:a,setIsModalVisible:r,setBudgetList:m,existingBudget:n,handleUpdateCall:x}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Create a budget to assign to customers."}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Budget ID"}),(0,c.jsx)(eP.Z,{children:"Max Budget"}),(0,c.jsx)(eP.Z,{children:"TPM"}),(0,c.jsx)(eP.Z,{children:"RPM"})]})}),(0,c.jsx)(eT.Z,{children:o.slice().sort((e,s)=>new Date(s.updated_at).getTime()-new Date(e.updated_at).getTime()).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.budget_id}),(0,c.jsx)(eA.Z,{children:e.max_budget?e.max_budget:"n/a"}),(0,c.jsx)(eA.Z,{children:e.tpm_limit?e.tpm_limit:"n/a"}),(0,c.jsx)(eA.Z,{children:e.rpm_limit?e.rpm_limit:"n/a"}),(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>u(e.budget_id,s)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>h(e.budget_id,s)})]},s))})]})]}),(0,c.jsxs)("div",{className:"mt-5",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"How to use budget id"}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Assign Budget to Customer"}),(0,c.jsx)(eR.Z,{children:"Test it (Curl)"}),(0,c.jsx)(eR.Z,{children:"Test it (OpenAI SDK)"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:"\ncurl -X POST --location '/end_user/new' \n-H 'Authorization: Bearer ' \n-H 'Content-Type: application/json' \n-d '{\"user_id\": \"my-customer-id', \"budget_id\": \"\"}' # \uD83D\uDC48 KEY CHANGE\n\n "})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:'\ncurl -X POST --location \'/chat/completions\' \n-H \'Authorization: Bearer \' \n-H \'Content-Type: application/json\' \n-d \'{\n "model": "gpt-3.5-turbo\', \n "messages":[{"role": "user", "content": "Hey, how\'s it going?"}],\n "user": "my-customer-id"\n}\' # \uD83D\uDC48 KEY CHANGE\n\n '})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'from openai import OpenAI\nclient = OpenAI(\n base_url="",\n api_key=""\n)\n\ncompletion = client.chat.completions.create(\n model="gpt-3.5-turbo",\n messages=[\n {"role": "system", "content": "You are a helpful assistant."},\n {"role": "user", "content": "Hello!"}\n ],\n user="my-customer-id"\n)\n\nprint(completion.choices[0].message)'})})]})]})]})]})},l9=l(77398),te=l.n(l9);async function ts(e){try{let s=await fetch("http://ip-api.com/json/".concat(e)),l=await s.json();console.log("ip lookup data",l);let t=l.countryCode?l.countryCode.toUpperCase().split("").map(e=>String.fromCodePoint(e.charCodeAt(0)+127397)).join(""):"";return l.country?"".concat(t," ").concat(l.country):"Unknown"}catch(e){return console.error("Error looking up IP:",e),"Unknown"}}let tl=e=>{let{ipAddress:s}=e,[l,t]=d.useState("-");return d.useEffect(()=>{if(!s)return;let e=!0;return ts(s).then(s=>{e&&t(s)}).catch(()=>{e&&t("-")}),()=>{e=!1}},[s]),(0,c.jsx)("span",{children:l})},tt=e=>{try{return new Date(e).toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0}).replace(",","")}catch(e){return"Error converting time"}},ta=e=>{let{utcTime:s}=e;return(0,c.jsx)("span",{style:{fontFamily:"monospace",width:"180px",display:"inline-block"},children:tt(s)})},tr=(e,s)=>{var l,t;return(null===(t=e.metadata)||void 0===t?void 0:null===(l=t.mcp_tool_call_metadata)||void 0===l?void 0:l.mcp_server_logo_url)?e.metadata.mcp_tool_call_metadata.mcp_server_logo_url:s?sn(s).logo:""},tn=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return(0,c.jsx)(()=>{let[e,l]=d.useState(s.getIsExpanded()),t=d.useCallback(()=>{l(e=>!e),s.getToggleExpandedHandler()()},[s]);return s.getCanExpand()?(0,c.jsx)("button",{onClick:t,style:{cursor:"pointer"},"aria-label":e?"Collapse row":"Expand row",className:"w-6 h-6 flex items-center justify-center focus:outline-none",children:(0,c.jsx)("svg",{className:"w-4 h-4 transform transition-transform duration-75 ".concat(e?"rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}):(0,c.jsx)("span",{className:"w-6 h-6 flex items-center justify-center",children:"●"})},{})}},{header:"Time",accessorKey:"startTime",cell:e=>(0,c.jsx)(ta,{utcTime:e.getValue()})},{header:"Status",accessorKey:"metadata.status",cell:e=>{let s="failure"!==(e.getValue()||"Success").toLowerCase();return(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat(s?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:s?"Success":"Failure"})}},{header:"Request ID",accessorKey:"request_id",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||""),children:(0,c.jsx)("span",{className:"font-mono text-xs max-w-[15ch] truncate block",children:String(e.getValue()||"")})})},{header:"Cost",accessorKey:"spend",cell:e=>(0,c.jsxs)("span",{children:["$",Number(e.getValue()||0).toFixed(6)]})},{header:"Country",accessorKey:"requester_ip_address",cell:e=>(0,c.jsx)(tl,{ipAddress:e.getValue()})},{header:"Team Name",accessorKey:"metadata.user_api_key_team_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Key Hash",accessorKey:"metadata.user_api_key",cell:e=>{let s=String(e.getValue()||"-"),l=e.row.original.onKeyHashClick;return(0,c.jsx)(W.Z,{title:s,children:(0,c.jsx)("span",{className:"font-mono max-w-[15ch] truncate block cursor-pointer hover:text-blue-600",onClick:()=>null==l?void 0:l(s),children:s})})}},{header:"Key Name",accessorKey:"metadata.user_api_key_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Model",accessorKey:"model",cell:e=>{let s=e.row.original,l=s.custom_llm_provider,t=String(e.getValue()||"");return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l&&(0,c.jsx)("img",{src:tr(s,l),alt:"",className:"w-4 h-4",onError:e=>{e.target.style.display="none"}}),(0,c.jsx)(W.Z,{title:t,children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:t})})]})}},{header:"Tokens",accessorKey:"total_tokens",cell:e=>{let s=e.row.original;return(0,c.jsxs)("span",{className:"text-sm",children:[String(s.total_tokens||"0"),(0,c.jsxs)("span",{className:"text-gray-400 text-xs ml-1",children:["(",String(s.prompt_tokens||"0"),"+",String(s.completion_tokens||"0"),")"]})]})}},{header:"Internal User",accessorKey:"user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"End User",accessorKey:"end_user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Tags",accessorKey:"request_tags",cell:e=>{let s=e.getValue();if(!s||0===Object.keys(s).length)return"-";let l=Object.entries(s),t=l[0],a=l.slice(1);return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:(0,c.jsx)(W.Z,{title:(0,c.jsx)("div",{className:"flex flex-col gap-1",children:l.map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{children:[s,": ",String(l)]},s)})}),children:(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[t[0],": ",String(t[1]),a.length>0&&" +".concat(a.length)]})})})}}],ti=async(e,s,l,t)=>{console.log("prefetchLogDetails called with",e.length,"logs");let a=e.map(e=>{if(e.request_id)return console.log("Prefetching details for request_id:",e.request_id),t.prefetchQuery({queryKey:["logDetails",e.request_id,s],queryFn:async()=>{console.log("Fetching details for",e.request_id);let t=await (0,y.qk)(l,e.request_id,s);return console.log("Received details for",e.request_id,":",t?"success":"failed"),t},staleTime:6e5,gcTime:6e5})});try{let e=await Promise.all(a);return console.log("All prefetch promises completed:",e.length),e}catch(e){throw console.error("Error in prefetchLogDetails:",e),e}},to=e=>{var s;let{errorInfo:l}=e,[t,a]=d.useState({}),[r,n]=d.useState(!1),i=e=>{a(s=>({...s,[e]:!s[e]}))},o=l.traceback&&(s=l.traceback)?Array.from(s.matchAll(/File "([^"]+)", line (\d+)/g)).map(e=>{let l=e[1],t=e[2],a=l.split("/").pop()||l,r=e.index||0,n=s.indexOf('File "',r+1),i=n>-1?s.substring(r,n).trim():s.substring(r).trim(),o=i.split("\n"),c="";return o.length>1&&(c=o[o.length-1].trim()),{filePath:l,fileName:a,lineNumber:t,code:c,inFunction:i.includes(" in ")?i.split(" in ")[1].split("\n")[0]:""}}):[];return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsxs)("h3",{className:"text-lg font-medium flex items-center text-red-600",children:[(0,c.jsx)("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),"Error Details"]})}),(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"bg-red-50 rounded-md p-4 mb-4",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Type:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_class||"Unknown Error"})]}),(0,c.jsxs)("div",{className:"flex mt-2",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Message:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_message||"Unknown error occurred"})]})]}),l.traceback&&(0,c.jsxs)("div",{className:"mt-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-2",children:[(0,c.jsx)("h4",{className:"font-medium",children:"Traceback"}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsx)("button",{onClick:()=>{let e=!r;if(n(e),o.length>0){let s={};o.forEach((l,t)=>{s[t]=e}),a(s)}},className:"text-gray-500 hover:text-gray-700 flex items-center text-sm",children:r?"Collapse All":"Expand All"}),(0,c.jsxs)("button",{onClick:()=>navigator.clipboard.writeText(l.traceback||""),className:"text-gray-500 hover:text-gray-700 flex items-center",title:"Copy traceback",children:[(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,c.jsx)("span",{className:"ml-1",children:"Copy"})]})]})]}),(0,c.jsx)("div",{className:"bg-white rounded-md border border-gray-200 overflow-hidden shadow-sm",children:o.map((e,s)=>(0,c.jsxs)("div",{className:"border-b border-gray-200 last:border-b-0",children:[(0,c.jsxs)("div",{className:"px-4 py-2 flex items-center justify-between cursor-pointer hover:bg-gray-50",onClick:()=>i(s),children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-gray-400 mr-2 w-12 text-right",children:e.lineNumber}),(0,c.jsx)("span",{className:"text-gray-600 font-medium",children:e.fileName}),(0,c.jsx)("span",{className:"text-gray-500 mx-1",children:"in"}),(0,c.jsx)("span",{className:"text-indigo-600 font-medium",children:e.inFunction||e.fileName})]}),(0,c.jsx)("svg",{className:"w-5 h-5 text-gray-500 transition-transform ".concat(t[s]?"transform rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),(t[s]||!1)&&e.code&&(0,c.jsx)("div",{className:"px-12 py-2 font-mono text-sm text-gray-800 bg-gray-50 overflow-x-auto border-t border-gray-100",children:e.code})]},s))})]})]})]})},tc=e=>{let{show:s}=e;return s?(0,c.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start",children:[(0,c.jsx)("div",{className:"text-blue-500 mr-3 flex-shrink-0 mt-0.5",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,c.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,c.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}),(0,c.jsxs)("div",{children:[(0,c.jsx)("h4",{className:"text-sm font-medium text-blue-800",children:"Request/Response Data Not Available"}),(0,c.jsxs)("p",{className:"text-sm text-blue-700 mt-1",children:["To view request and response details, enable prompt storage in your LiteLLM configuration by adding the following to your ",(0,c.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded",children:"proxy_config.yaml"})," file:"]}),(0,c.jsx)("pre",{className:"mt-2 bg-white p-3 rounded border border-blue-200 text-xs font-mono overflow-auto",children:"general_settings:\n store_model_in_db: true\n store_prompts_in_spend_logs: true"}),(0,c.jsx)("p",{className:"text-xs text-blue-700 mt-2",children:"Note: This will only affect new requests after the configuration change."})]})]}):null};function td(e){var s,l,t,a;let{accessToken:r,token:n,userRole:i,userID:o,allTeams:m}=e,[u,h]=(0,d.useState)(""),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(1),[b]=(0,d.useState)(50),Z=(0,d.useRef)(null),N=(0,d.useRef)(null),w=(0,d.useRef)(null),[k,S]=(0,d.useState)(te()().subtract(24,"hours").format("YYYY-MM-DDTHH:mm")),[C,I]=(0,d.useState)(te()().format("YYYY-MM-DDTHH:mm")),[T,A]=(0,d.useState)(!1),[E,P]=(0,d.useState)(!1),[O,L]=(0,d.useState)(""),[D,M]=(0,d.useState)(""),[F,R]=(0,d.useState)(""),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(null),[K,B]=(0,d.useState)(null),[H,J]=(0,d.useState)("Team ID"),[W,G]=(0,d.useState)(i&&eg.lo.includes(i)),[Y,$]=(0,d.useState)(null),X=(0,x.NL)();(0,d.useEffect)(()=>{(async()=>{if(K&&r){let e=await (0,y.t0)(r,K);console.log("keyData",e),V({...e.info,token:K,api_key:K})}})()},[K,r]),(0,d.useEffect)(()=>{function e(e){Z.current&&!Z.current.contains(e.target)&&f(!1),N.current&&!N.current.contains(e.target)&&g(!1),w.current&&!w.current.contains(e.target)&&P(!1)}return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{i&&eg.lo.includes(i)&&G(!0)},[i]);let Q=(0,e4.a)({queryKey:["logs","table",_,b,k,C,F,q,W?o:null],queryFn:async()=>{if(!r||!n||!i||!o)return console.log("Missing required auth parameters"),{data:[],total:0,page:1,page_size:b,total_pages:0};let e=te()(k).utc().format("YYYY-MM-DD HH:mm:ss"),s=T?te()(C).utc().format("YYYY-MM-DD HH:mm:ss"):te()().utc().format("YYYY-MM-DD HH:mm:ss"),l=await (0,y.h3)(r,q||void 0,F||void 0,void 0,e,s,_,b,W?o:void 0);return await ti(l.data,e,r,X),l.data=l.data.map(s=>{let l=X.getQueryData(["logDetails",s.request_id,e]);return(null==l?void 0:l.messages)&&(null==l?void 0:l.response)&&(s.messages=l.messages,s.response=l.response),s}),l},enabled:!!r&&!!n&&!!i&&!!o,refetchInterval:5e3,refetchIntervalInBackground:!0});if((0,d.useEffect)(()=>{var e;(null===(e=Q.data)||void 0===e?void 0:e.data)&&Y&&!Q.data.data.some(e=>e.request_id===Y)&&$(null)},[null===(s=Q.data)||void 0===s?void 0:s.data,Y]),!r||!n||!i||!o)return console.log("got None values for one of accessToken, token, userRole, userID"),null;let ee=(null===(t=Q.data)||void 0===t?void 0:null===(l=t.data)||void 0===l?void 0:l.filter(e=>!u||e.request_id.includes(u)||e.model.includes(u)||e.user&&e.user.includes(u)).map(e=>({...e,onKeyHashClick:e=>B(e)})))||[],es=()=>{if(T)return"".concat(te()(k).format("MMM D, h:mm A")," - ").concat(te()(C).format("MMM D, h:mm A"));let e=te()(),s=te()(k),l=e.diff(s,"minutes");if(l<=15)return"Last 15 Minutes";if(l<=60)return"Last Hour";let t=e.diff(s,"hours");return t<=4?"Last 4 Hours":t<=24?"Last 24 Hours":t<=168?"Last 7 Days":"".concat(s.format("MMM D")," - ").concat(e.format("MMM D"))};return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Request Logs"})}),z&&K&&z.api_key===K?(0,c.jsx)(eG,{keyId:K,keyData:z,accessToken:r,userID:o,userRole:i,teams:m,onClose:()=>B(null)}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between space-y-4 md:space-y-0",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by Request ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:u,onChange:e=>h(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"relative",ref:N,children:[(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>g(!p),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filter"]}),p&&(0,c.jsx)("div",{className:"absolute left-0 mt-2 w-[500px] bg-white rounded-lg shadow-lg border p-4 z-50",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsxs)("div",{className:"relative",children:[(0,c.jsxs)("button",{onClick:()=>f(!j),className:"px-3 py-1.5 border rounded-md bg-white text-sm min-w-[160px] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-left flex justify-between items-center",children:[H,(0,c.jsx)("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),j&&(0,c.jsx)("div",{className:"absolute left-0 mt-1 w-[160px] bg-white border rounded-md shadow-lg z-50",children:["Team ID","Key Hash"].map(e=>(0,c.jsxs)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2 ".concat(H===e?"bg-blue-50 text-blue-600":""),onClick:()=>{J(e),f(!1),"Team ID"===e?M(""):L("")},children:[H===e&&(0,c.jsx)("svg",{className:"h-4 w-4 text-blue-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e]},e))})]}),(0,c.jsx)("input",{type:"text",placeholder:"Enter value...",className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:"Team ID"===H?O:D,onChange:e=>{"Team ID"===H?L(e.target.value):M(e.target.value)}}),(0,c.jsx)("button",{className:"p-1 hover:bg-gray-100 rounded-md",onClick:()=>{L(""),M("")},children:(0,c.jsx)("span",{className:"text-gray-500",children:"\xd7"})})]}),(0,c.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm border rounded-md hover:bg-gray-50",onClick:()=>{L(""),M(""),g(!1)},children:"Cancel"}),(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{R(O),U(D),v(1),g(!1)},children:"Apply Filters"})]})]})})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsxs)("div",{className:"relative",ref:w,children:[(0,c.jsxs)("button",{onClick:()=>P(!E),className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"})}),es()]}),E&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border p-2 z-50",children:(0,c.jsxs)("div",{className:"space-y-1",children:[[{label:"Last 15 Minutes",value:15,unit:"minutes"},{label:"Last Hour",value:1,unit:"hours"},{label:"Last 4 Hours",value:4,unit:"hours"},{label:"Last 24 Hours",value:24,unit:"hours"},{label:"Last 7 Days",value:7,unit:"days"}].map(e=>(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(es()===e.label?"bg-blue-50 text-blue-600":""),onClick:()=>{I(te()().format("YYYY-MM-DDTHH:mm")),S(te()().subtract(e.value,e.unit).format("YYYY-MM-DDTHH:mm")),P(!1),A(!1)},children:e.label},e.label)),(0,c.jsx)("div",{className:"border-t my-2"}),(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(T?"bg-blue-50 text-blue-600":""),onClick:()=>A(!T),children:"Custom Range"})]})})]}),(0,c.jsxs)("button",{onClick:()=>{Q.refetch()},className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",title:"Refresh data",children:[(0,c.jsx)("svg",{className:"w-4 h-4 ".concat(Q.isFetching?"animate-spin":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),(0,c.jsx)("span",{children:"Refresh"})]})]}),T&&(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:k,onChange:e=>{S(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})}),(0,c.jsx)("span",{className:"text-gray-500",children:"to"}),(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:C,onChange:e=>{I(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})})]})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",Q.isLoading?"...":Q.data?(_-1)*b+1:0," ","-"," ",Q.isLoading?"...":Q.data?Math.min(_*b,Q.data.total):0," ","of"," ",Q.isLoading?"...":Q.data?Q.data.total:0," ","results"]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",Q.isLoading?"...":_," of"," ",Q.isLoading?"...":Q.data?Q.data.total_pages:1]}),(0,c.jsx)("button",{onClick:()=>v(e=>Math.max(1,e-1)),disabled:Q.isLoading||1===_,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>v(e=>{var s;return Math.min((null===(s=Q.data)||void 0===s?void 0:s.total_pages)||1,e+1)}),disabled:Q.isLoading||_===((null===(a=Q.data)||void 0===a?void 0:a.total_pages)||1),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})}),(0,c.jsx)(eL,{columns:tn,data:ee,renderSubComponent:tm,getRowCanExpand:()=>!0,onRowExpand:e=>{$(e)},expandedRequestId:Y})]})})]})}function tm(e){var s,l,t,a,r,n;let{row:i}=e,o=e=>{let s={...e};return"proxy_server_request"in s&&delete s.proxy_server_request,s},d=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},m=()=>{var e;return(null===(e=i.original.metadata)||void 0===e?void 0:e.proxy_server_request)?d(i.original.metadata.proxy_server_request):d(i.original.messages)},u=(null===(s=i.original.metadata)||void 0===s?void 0:s.status)==="failure",h=u?null===(l=i.original.metadata)||void 0===l?void 0:l.error_information:null,x=i.original.messages&&(Array.isArray(i.original.messages)?i.original.messages.length>0:Object.keys(i.original.messages).length>0),p=i.original.response&&Object.keys(d(i.original.response)).length>0,g=()=>u&&h?{error:{message:h.error_message||"An error occurred",type:h.error_class||"error",code:h.error_code||"unknown",param:null}}:d(i.original.response);return(0,c.jsxs)("div",{className:"p-6 bg-gray-50 space-y-6",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Details"})}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4 p-4",children:[(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Request ID:"}),(0,c.jsx)("span",{className:"font-mono text-sm",children:i.original.request_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model:"}),(0,c.jsx)("span",{children:i.original.model})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model ID:"}),(0,c.jsx)("span",{children:i.original.model_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Provider:"}),(0,c.jsx)("span",{children:i.original.custom_llm_provider||"-"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"API Base:"}),(0,c.jsx)(W.Z,{title:i.original.api_base||"-",children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:i.original.api_base||"-"})})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Start Time:"}),(0,c.jsx)("span",{children:i.original.startTime})]})]}),(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Tokens:"}),(0,c.jsxs)("span",{children:[i.original.total_tokens," (",i.original.prompt_tokens,"+",i.original.completion_tokens,")"]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cost:"}),(0,c.jsxs)("span",{children:["$",Number(i.original.spend||0).toFixed(6)]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cache Hit:"}),(0,c.jsx)("span",{children:i.original.cache_hit})]}),(null==i?void 0:null===(t=i.original)||void 0===t?void 0:t.requester_ip_address)&&(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"IP Address:"}),(0,c.jsx)("span",{children:null==i?void 0:null===(a=i.original)||void 0===a?void 0:a.requester_ip_address})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Status:"}),(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat("failure"!==((null===(r=i.original.metadata)||void 0===r?void 0:r.status)||"Success").toLowerCase()?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:"failure"!==((null===(n=i.original.metadata)||void 0===n?void 0:n.status)||"Success").toLowerCase()?"Success":"Failure"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"End Time:"}),(0,c.jsx)("span",{children:i.original.endTime})]})]})]})]}),(0,c.jsx)(tc,{show:!x&&!p}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request"}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(m(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy request",disabled:!x,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(m(),null,2)})})]}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsxs)("h3",{className:"text-lg font-medium",children:["Response",u&&(0,c.jsxs)("span",{className:"ml-2 text-sm text-red-600",children:["• HTTP code ",(null==h?void 0:h.error_code)||400]})]}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(g(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy response",disabled:!p,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96 bg-gray-50",children:p?(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(g(),null,2)}):(0,c.jsx)("div",{className:"text-gray-500 text-sm italic text-center py-4",children:"Response data not available"})})]})]}),u&&h&&(0,c.jsx)(to,{errorInfo:h}),i.original.request_tags&&Object.keys(i.original.request_tags).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"flex justify-between items-center p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Tags"})}),(0,c.jsx)("div",{className:"p-4",children:(0,c.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(i.original.request_tags).map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[s,": ",String(l)]},s)})})})]}),i.original.metadata&&Object.keys(i.original.metadata).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Metadata"}),(0,c.jsx)("button",{onClick:()=>{let e=o(i.original.metadata);navigator.clipboard.writeText(JSON.stringify(e,null,2))},className:"p-1 hover:bg-gray-200 rounded",title:"Copy metadata",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-64",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(o(i.original.metadata),null,2)})})]})]})}var tu=l(92699),th=l(14042);console.log=function(){};var tx=e=>{let{userID:s,userRole:l,accessToken:t,userSpend:a,userMaxBudget:r,selectedTeam:n}=e;console.log("userSpend: ".concat(a));let[i,o]=(0,d.useState)(null!==a?a:0),[m,u]=(0,d.useState)(n?n.max_budget:null);(0,d.useEffect)(()=>{if(n){if("Default Team"===n.team_alias)u(r);else{let e=!1;if(n.team_memberships)for(let l of n.team_memberships)l.user_id===s&&"max_budget"in l.litellm_budget_table&&null!==l.litellm_budget_table.max_budget&&(u(l.litellm_budget_table.max_budget),e=!0);e||u(n.max_budget)}}},[n,r]);let[h,x]=(0,d.useState)([]);(0,d.useEffect)(()=>{let e=async()=>{if(!t||!s||!l)return};(async()=>{try{if(null===s||null===l)return;if(null!==t){let e=(await (0,y.So)(t,s,l)).data.map(e=>e.id);console.log("available_model_names:",e),x(e)}}catch(e){console.error("Error fetching user models:",e)}})(),e()},[l,t,s]),(0,d.useEffect)(()=>{null!==a&&o(a)},[a]);let p=[];n&&n.models&&(p=n.models),p&&p.includes("all-proxy-models")?(console.log("user models:",h),p=h):p&&p.includes("all-team-models")?p=n.models:p&&0===p.length&&(p=h);let g=void 0!==i?i.toFixed(4):null;return console.log("spend in view user spend: ".concat(i)),(0,c.jsx)("div",{className:"flex items-center",children:(0,c.jsxs)("div",{className:"flex justify-between gap-x-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Total Spend"}),(0,c.jsxs)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:["$",g]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Max Budget"}),(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:null!==m?"$".concat(m," limit"):"No limit"})]})]})})};let tp=e=>{let{key:s,info:l}=e;return{token:s,...l}};var tg=e=>{let{topKeys:s,accessToken:l,userID:t,userRole:a,teams:r}=e,[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(void 0),[x,p]=(0,d.useState)("table"),g=async e=>{if(l)try{let s=await (0,y.t0)(l,e.api_key),t=tp(s);h(t),m(e.api_key),i(!0)}catch(e){console.error("Error fetching key info:",e)}},j=()=>{i(!1),m(null),h(void 0)};return d.useEffect(()=>{let e=e=>{"Escape"===e.key&&n&&j()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[n]),(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{className:"mb-4 flex justify-end items-center",children:(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>p("table"),className:"px-3 py-1 text-sm rounded-md ".concat("table"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Table View"}),(0,c.jsx)("button",{onClick:()=>p("chart"),className:"px-3 py-1 text-sm rounded-md ".concat("chart"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Chart View"})]})}),"chart"===x?(0,c.jsx)("div",{className:"relative",children:(0,c.jsx)(sw.Z,{className:"mt-4 h-40 cursor-pointer hover:opacity-90",data:s,index:"key_alias",categories:["spend"],colors:["cyan"],yAxisWidth:80,tickGap:5,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>e?"$".concat(e.toFixed(2)):"No Key Alias",onValueChange:e=>g(e),showTooltip:!0,customTooltip:e=>{var s,l,t;let a=null===(l=e.payload)||void 0===l?void 0:null===(s=l[0])||void 0===s?void 0:s.payload;return(0,c.jsx)("div",{className:"p-3 bg-black/90 shadow-lg rounded-lg text-white",children:(0,c.jsxs)("div",{className:"space-y-1.5",children:[(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Key: "}),(0,c.jsxs)("span",{className:"font-mono text-gray-100",children:[null==a?void 0:null===(t=a.api_key)||void 0===t?void 0:t.slice(0,10),"..."]})]}),(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Spend: "}),(0,c.jsxs)("span",{className:"text-white font-medium",children:["$",null==a?void 0:a.spend.toFixed(2)]})]})]})})}})}):(0,c.jsx)("div",{className:"border rounded-lg overflow-hidden",children:(0,c.jsx)(eL,{columns:[{header:"Key ID",accessorKey:"api_key",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>g(e.row.original),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>e.getValue()||"-"},{header:"Spend (USD)",accessorKey:"spend",cell:e=>"$".concat(Number(e.getValue()).toFixed(2))}],data:s,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{}),getRowCanExpand:()=>!1,isLoading:!1})}),n&&o&&u&&(console.log("Rendering modal with:",{isModalOpen:n,selectedKey:o,keyData:u}),(0,c.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e=>{e.target===e.currentTarget&&j()},children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-xl relative w-11/12 max-w-6xl max-h-[90vh] overflow-y-auto min-h-[750px]",children:[(0,c.jsx)("button",{onClick:j,className:"absolute top-4 right-4 text-gray-500 hover:text-gray-700 focus:outline-none","aria-label":"Close",children:(0,c.jsx)("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})}),(0,c.jsx)("div",{className:"p-6 h-full",children:(0,c.jsx)(eG,{keyId:o,onClose:j,keyData:u,accessToken:l,userID:t,userRole:a,teams:r})})]})}))]})},tj=l(44851);let tf=e=>{var s,l;let{modelName:t,metrics:a}=e;return(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:a.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:a.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:a.total_tokens.toLocaleString()}),(0,c.jsxs)(A.Z,{children:[Math.round(a.total_tokens/a.total_successful_requests)," avg per successful request"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",a.total_spend.toFixed(2)]}),(0,c.jsxs)(A.Z,{children:["$",(a.total_spend/a.total_successful_requests).toFixed(3)," per successful request"]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Requests per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.api_requests"],colors:["blue"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.spend"],colors:["green"],valueFormatter:e=>"$".concat(e.toFixed(2))})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Success vs Failed Requests"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Prompt Caching Metrics"}),(0,c.jsxs)("div",{className:"mb-2",children:[(0,c.jsxs)(A.Z,{children:["Cache Read: ",(null===(s=a.total_cache_read_input_tokens)||void 0===s?void 0:s.toLocaleString())||0," tokens"]}),(0,c.jsxs)(A.Z,{children:["Cache Creation: ",(null===(l=a.total_cache_creation_input_tokens)||void 0===l?void 0:l.toLocaleString())||0," tokens"]})]}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.cache_read_input_tokens","metrics.cache_creation_input_tokens"],colors:["cyan","purple"],valueFormatter:e=>e.toLocaleString()})]})]})]})},t_=e=>{let{modelMetrics:s}=e,l=Object.keys(s).sort((e,l)=>""===e?1:""===l?-1:s[l].total_spend-s[e].total_spend),t={total_requests:0,total_successful_requests:0,total_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:{}};Object.values(s).forEach(e=>{t.total_requests+=e.total_requests,t.total_successful_requests+=e.total_successful_requests,t.total_tokens+=e.total_tokens,t.total_spend+=e.total_spend,t.total_cache_read_input_tokens+=e.total_cache_read_input_tokens||0,t.total_cache_creation_input_tokens+=e.total_cache_creation_input_tokens||0,e.daily_data.forEach(e=>{t.daily_data[e.date]||(t.daily_data[e.date]={prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,spend:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),t.daily_data[e.date].prompt_tokens+=e.metrics.prompt_tokens,t.daily_data[e.date].completion_tokens+=e.metrics.completion_tokens,t.daily_data[e.date].total_tokens+=e.metrics.total_tokens,t.daily_data[e.date].api_requests+=e.metrics.api_requests,t.daily_data[e.date].spend+=e.metrics.spend,t.daily_data[e.date].successful_requests+=e.metrics.successful_requests,t.daily_data[e.date].failed_requests+=e.metrics.failed_requests,t.daily_data[e.date].cache_read_input_tokens+=e.metrics.cache_read_input_tokens||0,t.daily_data[e.date].cache_creation_input_tokens+=e.metrics.cache_creation_input_tokens||0})});let a=Object.entries(t.daily_data).map(e=>{let[s,l]=e;return{date:s,metrics:l}}).sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime());return(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{className:"border rounded-lg p-4",children:[(0,c.jsx)(E.Z,{children:"Overall Usage"}),(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4 mb-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:t.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:t.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:t.total_tokens.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",t.total_spend.toFixed(2)]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]})]})]}),(0,c.jsx)(tj.Z,{defaultActiveKey:l[0],children:l.map(e=>(0,c.jsx)(tj.Z.Panel,{header:(0,c.jsxs)("div",{className:"flex justify-between items-center w-full",children:[(0,c.jsx)(E.Z,{children:s[e].label||"Unknown Item"}),(0,c.jsxs)("div",{className:"flex space-x-4 text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["$",s[e].total_spend.toFixed(2)]}),(0,c.jsxs)("span",{children:[s[e].total_requests.toLocaleString()," requests"]})]})]}),children:(0,c.jsx)(tf,{modelName:e||"Unknown Model",metrics:s[e]})},e))})]})},ty=(e,s)=>{let l=e.metadata.key_alias||"key-hash-".concat(s),t=e.metadata.team_id;return t?"".concat(l," (team_id: ").concat(t,")"):l},tv=(e,s)=>{let l={};return e.results.forEach(e=>{Object.entries(e.breakdown[s]||{}).forEach(t=>{let[a,r]=t;l[a]||(l[a]={label:"api_keys"===s?ty(r,a):a,total_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0,prompt_tokens:0,completion_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:[]}),l[a].total_requests+=r.metrics.api_requests,l[a].prompt_tokens+=r.metrics.prompt_tokens,l[a].completion_tokens+=r.metrics.completion_tokens,l[a].total_tokens+=r.metrics.total_tokens,l[a].total_spend+=r.metrics.spend,l[a].total_successful_requests+=r.metrics.successful_requests,l[a].total_failed_requests+=r.metrics.failed_requests,l[a].total_cache_read_input_tokens+=r.metrics.cache_read_input_tokens||0,l[a].total_cache_creation_input_tokens+=r.metrics.cache_creation_input_tokens||0,l[a].daily_data.push({date:e.date,metrics:{prompt_tokens:r.metrics.prompt_tokens,completion_tokens:r.metrics.completion_tokens,total_tokens:r.metrics.total_tokens,api_requests:r.metrics.api_requests,spend:r.metrics.spend,successful_requests:r.metrics.successful_requests,failed_requests:r.metrics.failed_requests,cache_read_input_tokens:r.metrics.cache_read_input_tokens||0,cache_creation_input_tokens:r.metrics.cache_creation_input_tokens||0}})})}),Object.values(l).forEach(e=>{e.daily_data.sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime())}),l};var tb=e=>{let{accessToken:s,entityType:l,entityId:t,userID:a,userRole:r,entityList:n}=e,[i,o]=(0,d.useState)({results:[],metadata:{total_spend:0,total_api_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0}}),m=tv(i,"models"),u=tv(i,"api_keys"),[h,x]=(0,d.useState)([]),[p,g]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),j=async()=>{if(!s||!p.from||!p.to)return;let e=p.from,t=p.to;if("tag"===l)o(await (0,y.Z9)(s,e,t,1,h.length>0?h:null));else if("team"===l)o(await (0,y.ol)(s,e,t,1,h.length>0?h:null));else throw Error("Invalid entity type")};(0,d.useEffect)(()=>{j()},[s,p,t,h]);let f=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={provider:l,spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend,e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens}catch(e){console.log("Error processing provider ".concat(l,": ").concat(e))}})}),Object.values(e).filter(e=>e.spend>0).sort((e,s)=>s.spend-e.spend)},_=e=>0===h.length?e:e.filter(e=>h.includes(e.metadata.id)),v=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.entities||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{alias:t.metadata.team_alias||l,id:l}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.total_tokens+=t.metrics.total_tokens})}),_(Object.values(e).sort((e,s)=>s.metrics.spend-e.metrics.spend))};return(0,c.jsxs)("div",{style:{width:"100%"},children:[(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:p,onValueChange:g})]}),n&&n.length>0&&(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(A.Z,{children:["Filter by ","tag"===l?"Tags":"Teams"]}),(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},placeholder:"Select ".concat("tag"===l?"tags":"teams"," to filter..."),value:h,onChange:x,options:(()=>{if(n)return n})(),className:"mt-2",allowClear:!0})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["tag"===l?"Tag":"Team"," Spend Overview"]}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Spend"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",i.metadata.total_spend.toFixed(2)]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_api_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:i.metadata.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:i.metadata.total_failed_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_tokens.toLocaleString()})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...i.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:t}=e;if(!t||!(null==s?void 0:s[0]))return null;let a=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:a.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Total Spend: $",a.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",a.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",a.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",a.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Tokens: ",a.metrics.total_tokens]}),(0,c.jsxs)("div",{className:"mt-2 border-t pt-2",children:[(0,c.jsxs)("p",{className:"font-semibold",children:["Spend by ","tag"===l?"Tag":"Team",":"]}),Object.entries(a.breakdown.entities||{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[l.metadata.team_alias||s,": $",l.metrics.spend.toFixed(2)]},s)})]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-col space-y-2",children:[(0,c.jsxs)(E.Z,{children:["Spend Per ","tag"===l?"Tag":"Team"]}),(0,c.jsxs)("div",{className:"flex items-center text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["Get Started Tracking cost per ",l," "]}),(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tags",className:"text-blue-500 hover:text-blue-700 ml-1",children:"here"})]})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sw.Z,{className:"mt-4 h-52",data:v(),index:"metadata.alias",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(4)),layout:"vertical",showLegend:!1,yAxisWidth:100})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"tag"===l?"Tag":"Team"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:v().filter(e=>e.metrics.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.metadata.alias}),(0,c.jsxs)(eA.Z,{children:["$",e.metrics.spend.toFixed(4)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.metrics.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.metrics.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.metrics.total_tokens.toLocaleString()})]},e.metadata.id))})]})})]})]})})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:s,userID:a,userRole:r,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend}catch(e){console.log("Error adding spend for ".concat(l,": ").concat(e,", got metrics: ").concat(JSON.stringify(t)))}e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,...l}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsx)(E.Z,{children:"Provider Usage"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:f(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan","blue","indigo","violet","purple"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:f().map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:m})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:u})})]})]})]})},tZ=e=>{var s,l,t,a,r,n,i,o,m,u;let{accessToken:h,userRole:x,userID:p,teams:g}=e,[j,f]=(0,d.useState)({results:[],metadata:{}}),[_,v]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),[b,Z]=(0,d.useState)([]),k=async()=>{h&&Z(Object.values(await (0,y.UM)(h)).map(e=>({label:e.name,value:e.name})))};(0,d.useEffect)(()=>{k()},[h]);let S=(null===(s=j.metadata)||void 0===s?void 0:s.total_spend)||0,C=()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{provider:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}})},I=async()=>{if(!h||!_.from||!_.to)return;let e=_.from,s=_.to;try{let l=await (0,y.xX)(h,e,s);if(l.metadata.total_pages>10)throw Error("Too many pages of data (>10). Please select a smaller date range.");if(1===l.metadata.total_pages){f(l);return}let t=[...l.results];for(let a=2;a<=l.metadata.total_pages;a++){let l=await (0,y.xX)(h,e,s,a);t.push(...l.results)}f({results:t,metadata:l.metadata})}catch(e){throw console.error("Error fetching user spend data:",e),e}};(0,d.useEffect)(()=>{I()},[h,_]);let T=tv(j,"models"),P=tv(j,"api_keys");return(0,c.jsxs)("div",{style:{width:"100%"},className:"p-8",children:[(0,c.jsxs)(A.Z,{className:"text-sm text-gray-500 mb-4",children:["This is the new usage dashboard. ",(0,c.jsx)("br",{})," You may see empty data, as these use ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/blob/6de348125208dd4be81ff0e5813753df2fbe9735/schema.prisma#L320",className:"text-blue-500 hover:text-blue-700 ml-1",children:"new aggregate tables"})," to allow UI to work at 1M+ spend logs. To access the old dashboard, go to Experimental ",">"," Old Usage."]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Global Usage"}):(0,c.jsx)(eR.Z,{children:"Your Usage"}),(0,c.jsx)(eR.Z,{children:"Team Usage"}),eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Tag Usage"}):(0,c.jsx)(c.Fragment,{})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:_,onValueChange:e=>{v(e)}})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:p,userRole:x,accessToken:h,userSpend:S,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Usage Metrics"}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(t=j.metadata)||void 0===t?void 0:null===(l=t.total_api_requests)||void 0===l?void 0:l.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:(null===(r=j.metadata)||void 0===r?void 0:null===(a=r.total_successful_requests)||void 0===a?void 0:a.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:(null===(i=j.metadata)||void 0===i?void 0:null===(n=i.total_failed_requests)||void 0===n?void 0:n.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(m=j.metadata)||void 0===m?void 0:null===(o=m.total_tokens)||void 0===o?void 0:o.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Average Cost per Request"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",((S||0)/((null===(u=j.metadata)||void 0===u?void 0:u.total_api_requests)||1)).toFixed(4)]})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...j.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Requests: ",t.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",t.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",t.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.metrics.total_tokens]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:h,userID:p,userRole:x,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Top Models"})}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.key}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",t.requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-green-600",children:["Successful: ",t.successful_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-red-600",children:["Failed: ",t.failed_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.tokens.toLocaleString()]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Spend by Provider"})}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:C(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:C().filter(e=>e.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend<1e-5?"less than 0.00001":e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:T})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:P})})]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"team",userID:p,userRole:x,entityList:(null==g?void 0:g.map(e=>({label:e.team_alias,value:e.team_id})))||null})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"tag",userID:p,userRole:x,entityList:b})})]})]})]})},tN=e=>{let{proxySettings:s}=e,l="";return s&&s.PROXY_BASE_URL&&void 0!==s.PROXY_BASE_URL&&(l=s.PROXY_BASE_URL),(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(w.Z,{className:"gap-2 p-8 h-[80vh] w-full mt-2",children:(0,c.jsxs)("div",{className:"mb-5",children:[(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:"OpenAI Compatible Proxy: API Reference"}),(0,c.jsx)(A.Z,{className:"mt-2 mb-2",children:"LiteLLM is OpenAI Compatible. This means your API Key works with the OpenAI SDK. Just replace the base_url to point to your litellm proxy. Example Below "}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"OpenAI Python SDK"}),(0,c.jsx)(eR.Z,{children:"LlamaIndex"}),(0,c.jsx)(eR.Z,{children:"Langchain Py"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport openai\nclient = openai.OpenAI(\n api_key="your_api_key",\n base_url="'.concat(l,'" # LiteLLM Proxy is OpenAI compatible, Read More: https://docs.litellm.ai/docs/proxy/user_keys\n)\n\nresponse = client.chat.completions.create(\n model="gpt-3.5-turbo", # model to send to the proxy\n messages = [\n {\n "role": "user",\n "content": "this is a test request, write a short poem"\n }\n ]\n)\n\nprint(response)\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport os, dotenv\n\nfrom llama_index.llms import AzureOpenAI\nfrom llama_index.embeddings import AzureOpenAIEmbedding\nfrom llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext\n\nllm = AzureOpenAI(\n engine="azure-gpt-3.5", # model_name on litellm proxy\n temperature=0.0,\n azure_endpoint="'.concat(l,'", # litellm proxy endpoint\n api_key="sk-1234", # litellm proxy API Key\n api_version="2023-07-01-preview",\n)\n\nembed_model = AzureOpenAIEmbedding(\n deployment_name="azure-embedding-model",\n azure_endpoint="').concat(l,'",\n api_key="sk-1234",\n api_version="2023-07-01-preview",\n)\n\n\ndocuments = SimpleDirectoryReader("llama_index_data").load_data()\nservice_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context)\n\nquery_engine = index.as_query_engine()\nresponse = query_engine.query("What did the author do growing up?")\nprint(response)\n\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n)\nfrom langchain.schema import HumanMessage, SystemMessage\n\nchat = ChatOpenAI(\n openai_api_base="'.concat(l,'",\n model = "gpt-3.5-turbo",\n temperature=0.1\n)\n\nmessages = [\n SystemMessage(\n content="You are a helpful assistant that im using to make a test request to."\n ),\n HumanMessage(\n content="test from litellm. tell me why it\'s amazing in 1 sentence"\n ),\n]\nresponse = chat(messages)\n\nprint(response)\n\n ')})})]})]})]})})})},tw=l(243);async function tk(e,s,l,t,a,r,n,i,o){console.log=function(){},console.log("isLocal:",!1);let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t;let a=Date.now(),c=!1;for await(let _ of(await d.chat.completions.create({model:l,stream:!0,stream_options:{include_usage:!0},messages:e},{signal:r}))){var m,u,h,x,p,g,j,f;console.log("Stream chunk:",_);let e=null===(m=_.choices[0])||void 0===m?void 0:m.delta;if(console.log("Delta content:",null===(h=_.choices[0])||void 0===h?void 0:null===(u=h.delta)||void 0===u?void 0:u.content),console.log("Delta reasoning content:",null==e?void 0:e.reasoning_content),!c&&((null===(p=_.choices[0])||void 0===p?void 0:null===(x=p.delta)||void 0===x?void 0:x.content)||e&&e.reasoning_content)&&(c=!0,t=Date.now()-a,console.log("First token received! Time:",t,"ms"),i?(console.log("Calling onTimingData with:",t),i(t)):console.log("onTimingData callback is not defined!")),null===(j=_.choices[0])||void 0===j?void 0:null===(g=j.delta)||void 0===g?void 0:g.content){let e=_.choices[0].delta.content;s(e,_.model)}if(e&&e.reasoning_content){let s=e.reasoning_content;n&&n(s)}if(_.usage&&o){console.log("Usage data found:",_.usage);let e={completionTokens:_.usage.completion_tokens,promptTokens:_.usage.prompt_tokens,totalTokens:_.usage.total_tokens};(null===(f=_.usage.completion_tokens_details)||void 0===f?void 0:f.reasoning_tokens)&&(e.reasoningTokens=_.usage.completion_tokens_details.reasoning_tokens),o(e)}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Chat completion request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}async function tS(e,s,l,t,a,r){console.log=function(){},console.log("isLocal:",!1);let n=window.location.origin,i=new lG.ZP.OpenAI({apiKey:t,baseURL:n,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=await i.images.generate({model:l,prompt:e},{signal:r});if(console.log(t.data),t.data&&t.data[0]){if(t.data[0].url)s(t.data[0].url,l);else if(t.data[0].b64_json){let e=t.data[0].b64_json;s("data:image/png;base64,".concat(e),l)}else throw Error("No image data found in response")}else throw Error("Invalid response format")}catch(e){throw(null==r?void 0:r.aborted)?console.log("Image generation request was cancelled"):D.ZP.error("Error occurred while generating image. Please try again. Error: ".concat(e),20),e}}async function tC(e,s,l,t){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],r=arguments.length>5?arguments[5]:void 0,n=arguments.length>6?arguments[6]:void 0,i=arguments.length>7?arguments[7]:void 0,o=arguments.length>8?arguments[8]:void 0;if(!t)throw Error("API key is required");console.log=function(){};let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=Date.now(),a=!1,c=e.map(e=>({role:e.role,content:e.content,type:"message"}));for await(let e of(await d.responses.create({model:l,input:c,stream:!0},{signal:r})))if(console.log("Response event:",e),"object"==typeof e&&null!==e){if("response.role.delta"===e.type)continue;if("response.output_text.delta"===e.type&&"string"==typeof e.delta){let r=e.delta;if(console.log("Text delta",r),r.trim().length>0&&(s("assistant",r,l),!a)){a=!0;let e=Date.now()-t;console.log("First token received! Time:",e,"ms"),i&&i(e)}}if("response.reasoning.delta"===e.type&&"delta"in e){let s=e.delta;"string"==typeof s&&n&&n(s)}if("response.completed"===e.type&&"response"in e){let s=e.response.usage;if(console.log("Usage data:",s),s&&o){var m;console.log("Usage data:",s);let e={completionTokens:s.output_tokens,promptTokens:s.input_tokens,totalTokens:s.total_tokens};(null===(m=s.completion_tokens_details)||void 0===m?void 0:m.reasoning_tokens)&&(e.reasoningTokens=s.completion_tokens_details.reasoning_tokens),o(e)}}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Responses API request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}let tI=async e=>{try{let s=await (0,y.kn)(e);if(console.log("model_info:",s),(null==s?void 0:s.data.length)>0){let e=s.data.map(e=>({model_group:e.model_group,mode:null==e?void 0:e.mode}));return e.sort((e,s)=>e.model_group.localeCompare(s.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};(a=i||(i={})).IMAGE_GENERATION="image_generation",a.CHAT="chat",a.RESPONSES="responses",(r=o||(o={})).IMAGE="image",r.CHAT="chat",r.RESPONSES="responses";let tT={image_generation:"image",chat:"chat",responses:"responses"},tA=e=>{if(console.log("getEndpointType:",e),Object.values(i).includes(e)){let s=tT[e];return console.log("endpointType:",s),s}return"chat"};var tE=l(94263),tP=e=>{let{endpointType:s,onEndpointChange:l,className:t}=e,a=[{value:o.CHAT,label:"/v1/chat/completions"},{value:o.RESPONSES,label:"/v1/responses"},{value:o.IMAGE,label:"/v1/images/generations"}];return(0,c.jsxs)("div",{className:t,children:[(0,c.jsx)(A.Z,{children:"Endpoint Type:"}),(0,c.jsx)(O.default,{value:s,style:{width:"100%"},onChange:l,options:a,className:"rounded-md"})]})},tO=e=>{let{onChange:s,value:l,className:t,accessToken:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)(!1);return(0,d.useEffect)(()=>{(async()=>{if(a)try{let e=await (0,y.UM)(a);console.log("List tags response:",e),n(Object.values(e))}catch(e){console.error("Error fetching tags:",e)}})()},[]),(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select tags",onChange:s,value:l,loading:i,className:t,options:r.map(e=>({label:e.name,value:e.name,title:e.description||e.name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})};let tL=(e,s)=>{let l=s.find(s=>s.model_group===e);return(null==l?void 0:l.mode)?tA(l.mode):o.CHAT};var tD=l(83322),tM=l(70464),tF=l(77565),tR=e=>{let{reasoningContent:s}=e,[l,t]=(0,d.useState)(!0);return s?(0,c.jsxs)("div",{className:"reasoning-content mt-1 mb-2",children:[(0,c.jsxs)(R.ZP,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>t(!l),icon:(0,c.jsx)(tD.Z,{}),children:[l?"Hide reasoning":"Show reasoning",l?(0,c.jsx)(tM.Z,{className:"ml-1"}):(0,c.jsx)(tF.Z,{className:"ml-1"})]}),l&&(0,c.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700",children:(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),...r,children:a})}},children:s})})]}):null},tq=l(5540),tU=l(71282),tz=l(11741),tV=l(16601),tK=e=>{let{timeToFirstToken:s,usage:l}=e;return s||l?(0,c.jsxs)("div",{className:"response-metrics mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500 flex flex-wrap gap-3",children:[void 0!==s&&(0,c.jsx)(W.Z,{title:"Time to first token",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tq.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:[(s/1e3).toFixed(2),"s"]})]})}),(null==l?void 0:l.promptTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Prompt tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tU.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["In: ",l.promptTokens]})]})}),(null==l?void 0:l.completionTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Completion tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tz.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Out: ",l.completionTokens]})]})}),(null==l?void 0:l.reasoningTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Reasoning tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tD.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Reasoning: ",l.reasoningTokens]})]})}),(null==l?void 0:l.totalTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Total tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tV.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Total: ",l.totalTokens]})]})})]}):null},tB=l(61935),tH=l(69993),tJ=l(12660),tW=l(71891),tG=l(26430),tY=l(26349),t$=l(23907);let{TextArea:tX}=q.default;var tQ=e=>{let{accessToken:s,token:l,userRole:t,userID:a,disabledPersonalKeyCreation:r}=e,[n,i]=(0,d.useState)(r?"custom":"session"),[m,u]=(0,d.useState)(""),[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)([]),[f,_]=(0,d.useState)(void 0),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)([]),N=(0,d.useRef)(null),[w,C]=(0,d.useState)(o.CHAT),[I,T]=(0,d.useState)(!1),E=(0,d.useRef)(null),[P,L]=(0,d.useState)([]),M=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e="session"===n?s:m;if(!e||!l||!t||!a){console.log("userApiKey or token or userRole or userID is missing = ",e,l,t,a);return}(async()=>{try{if(!e){console.log("userApiKey is missing");return}let s=await tI(e);if(console.log("Fetched models:",s),s.length>0&&(Z(s),_(s[0].model_group),s[0].mode)){let e=tL(s[0].model_group,s);C(e)}}catch(e){console.error("Error fetching model info:",e)}})()},[s,a,t,n,m]),(0,d.useEffect)(()=>{M.current&&setTimeout(()=>{var e;null===(e=M.current)||void 0===e||e.scrollIntoView({behavior:"smooth",block:"end"})},100)},[p]);let F=(e,s,l)=>{console.log("updateTextUI called with:",e,s,l),g(t=>{let a=t[t.length-1];if(!a||a.role!==e||a.isImage)return[...t,{role:e,content:s,model:l}];{var r;let e={...a,content:a.content+s,model:null!==(r=a.model)&&void 0!==r?r:l};return[...t.slice(0,-1),e]}})},R=e=>{g(s=>{let l=s[s.length-1];return l&&"assistant"===l.role&&!l.isImage?[...s.slice(0,s.length-1),{...l,reasoningContent:(l.reasoningContent||"")+e}]:s.length>0&&"user"===s[s.length-1].role?[...s,{role:"assistant",content:"",reasoningContent:e}]:s})},q=e=>{console.log("updateTimingData called with:",e),g(s=>{let l=s[s.length-1];if(console.log("Current last message:",l),l&&"assistant"===l.role){console.log("Updating assistant message with timeToFirstToken:",e);let t=[...s.slice(0,s.length-1),{...l,timeToFirstToken:e}];return console.log("Updated chat history:",t),t}return l&&"user"===l.role?(console.log("Creating new assistant message with timeToFirstToken:",e),[...s,{role:"assistant",content:"",timeToFirstToken:e}]):(console.log("No appropriate message found to update timing"),s)})},U=e=>{console.log("Received usage data:",e),g(s=>{let l=s[s.length-1];if(l&&"assistant"===l.role){console.log("Updating message with usage data:",e);let t={...l,usage:e};return console.log("Updated message:",t),[...s.slice(0,s.length-1),t]}return s})},z=(e,s)=>{g(l=>[...l,{role:"assistant",content:e,model:s,isImage:!0}])},V=async()=>{if(""===h.trim()||!l||!t||!a)return;let e="session"===n?s:m;if(!e){D.ZP.error("Please provide an API key or select Current UI Session");return}E.current=new AbortController;let r=E.current.signal,i={role:"user",content:h};g([...p,i]),T(!0);try{if(f){if(w===o.CHAT){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tk(s,(e,s)=>F("assistant",e,s),f,e,P,r,R,q,U)}else if(w===o.IMAGE)await tS(h,(e,s)=>z(e,s),f,e,P,r);else if(w===o.RESPONSES){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tC(s,(e,s,l)=>F(e,s,l),f,e,P,r,R,q,U)}}}catch(e){r.aborted?console.log("Request was cancelled"):(console.error("Error fetching response",e),F("assistant","Error fetching response"))}finally{T(!1),E.current=null}x("")};if(t&&"Admin Viewer"===t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to test models"})]})}let K=(0,c.jsx)(tB.Z,{style:{fontSize:24},spin:!0});return(0,c.jsx)("div",{className:"w-full h-screen p-4 bg-white",children:(0,c.jsx)(eF.Z,{className:"w-full rounded-xl shadow-md overflow-hidden",children:(0,c.jsxs)("div",{className:"flex h-[80vh] w-full",children:[(0,c.jsx)("div",{className:"w-1/4 p-4 border-r border-gray-200 bg-gray-50",children:(0,c.jsx)("div",{className:"mb-6",children:(0,c.jsxs)("div",{className:"space-y-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(lE.Z,{className:"mr-2"})," API Key Source"]}),(0,c.jsx)(O.default,{disabled:r,defaultValue:"session",style:{width:"100%"},onChange:e=>i(e),options:[{value:"session",label:"Current UI Session"},{value:"custom",label:"Virtual Key"}],className:"rounded-md"}),"custom"===n&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom API key",type:"password",onValueChange:u,value:m,icon:lE.Z})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tH.Z,{className:"mr-2"})," Select Model"]}),(0,c.jsx)(O.default,{placeholder:"Select a Model",onChange:e=>{console.log("selected ".concat(e)),_(e),"custom"!==e&&C(tL(e,b)),v("custom"===e)},options:[...b.map(e=>({value:e.model_group,label:e.model_group})),{value:"custom",label:"Enter custom model"}],style:{width:"100%"},showSearch:!0,className:"rounded-md"}),y&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{_(e)},500)}})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tJ.Z,{className:"mr-2"})," Endpoint Type"]}),(0,c.jsx)(tP,{endpointType:w,onEndpointChange:e=>{C(e)},className:"mb-4"})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tW.Z,{className:"mr-2"})," Tags"]}),(0,c.jsx)(tO,{value:P,onChange:L,className:"mb-4",accessToken:s||""})]}),(0,c.jsx)(k.Z,{onClick:()=>{g([]),D.ZP.success("Chat history cleared.")},className:"w-full bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300 mt-4",icon:tG.Z,children:"Clear Chat"})]})})}),(0,c.jsxs)("div",{className:"w-3/4 flex flex-col bg-white",children:[(0,c.jsxs)("div",{className:"flex-1 overflow-auto p-4 pb-0",children:[0===p.length&&(0,c.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[(0,c.jsx)(tH.Z,{style:{fontSize:"48px",marginBottom:"16px"}}),(0,c.jsx)(A.Z,{children:"Start a conversation or generate an image"})]}),p.map((e,s)=>(0,c.jsx)("div",{className:"mb-4 ".concat("user"===e.role?"text-right":"text-left"),children:(0,c.jsxs)("div",{className:"inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4",style:{backgroundColor:"user"===e.role?"#f0f8ff":"#ffffff",border:"user"===e.role?"1px solid #e6f0fa":"1px solid #f0f0f0",textAlign:"left"},children:[(0,c.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full mr-1",style:{backgroundColor:"user"===e.role?"#e6f0fa":"#f5f5f5"},children:"user"===e.role?(0,c.jsx)(j.Z,{style:{fontSize:"12px",color:"#2563eb"}}):(0,c.jsx)(tH.Z,{style:{fontSize:"12px",color:"#4b5563"}})}),(0,c.jsx)("strong",{className:"text-sm capitalize",children:e.role}),"assistant"===e.role&&e.model&&(0,c.jsx)("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-normal",children:e.model})]}),e.reasoningContent&&(0,c.jsx)(tR,{reasoningContent:e.reasoningContent}),(0,c.jsxs)("div",{className:"whitespace-pre-wrap break-words max-w-full message-content",style:{wordWrap:"break-word",overflowWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},children:[e.isImage?(0,c.jsx)("img",{src:e.content,alt:"Generated image",className:"max-w-full rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"500px"}}):(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",wrapLines:!0,wrapLongLines:!0,...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),style:{wordBreak:"break-word"},...r,children:a})},pre:e=>{let{node:s,...l}=e;return(0,c.jsx)("pre",{style:{overflowX:"auto",maxWidth:"100%"},...l})}},children:e.content}),"assistant"===e.role&&(e.timeToFirstToken||e.usage)&&(0,c.jsx)(tK,{timeToFirstToken:e.timeToFirstToken,usage:e.usage})]})]})},s)),I&&(0,c.jsx)("div",{className:"flex justify-center items-center my-4",children:(0,c.jsx)(eY.Z,{indicator:K})}),(0,c.jsx)("div",{ref:M,style:{height:"1px"}})]}),(0,c.jsx)("div",{className:"p-4 border-t border-gray-200 bg-white",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tX,{value:h,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),V())},placeholder:w===o.CHAT||w===o.RESPONSES?"Type your message... (Shift+Enter for new line)":"Describe the image you want to generate...",disabled:I,className:"flex-1",autoSize:{minRows:1,maxRows:6},style:{resize:"none",paddingRight:"10px",paddingLeft:"10px"}}),I?(0,c.jsx)(k.Z,{onClick:()=>{E.current&&(E.current.abort(),E.current=null,T(!1),D.ZP.info("Request cancelled"))},className:"ml-2 bg-red-50 hover:bg-red-100 text-red-600 border-red-200",icon:tY.Z,children:"Cancel"}):(0,c.jsx)(k.Z,{onClick:V,className:"ml-2 text-white",icon:w===o.CHAT?t$.Z:tH.Z,children:w===o.CHAT?"Send":"Generate"})]})})]})]})})})},t0=l(19226),t1=l(45937),t2=l(28595),t4=l(68208),t5=l(9775),t6=l(41361),t3=l(37527),t8=l(88009),t7=l(48231),t9=l(41169),ae=l(44625),as=l(57400),al=l(58630),at=l(55322);let{Sider:aa}=t0.default;var ar=e=>{let{setPage:s,userRole:l,defaultSelectedKey:t}=e,a=[{key:"1",page:"api-keys",label:"Virtual Keys",icon:(0,c.jsx)(lE.Z,{})},{key:"3",page:"llm-playground",label:"Test Key",icon:(0,c.jsx)(t2.Z,{}),roles:eg.LQ},{key:"2",page:"models",label:"Models",icon:(0,c.jsx)(t4.Z,{}),roles:eg.LQ},{key:"12",page:"new_usage",label:"Usage",icon:(0,c.jsx)(t5.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"6",page:"teams",label:"Teams",icon:(0,c.jsx)(t6.Z,{})},{key:"17",page:"organizations",label:"Organizations",icon:(0,c.jsx)(t3.Z,{}),roles:eg.ZL},{key:"5",page:"users",label:"Internal Users",icon:(0,c.jsx)(j.Z,{}),roles:eg.ZL},{key:"14",page:"api_ref",label:"API Reference",icon:(0,c.jsx)(tJ.Z,{})},{key:"16",page:"model-hub",label:"Model Hub",icon:(0,c.jsx)(t8.Z,{})},{key:"15",page:"logs",label:"Logs",icon:(0,c.jsx)(t7.Z,{})},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,c.jsx)(t9.Z,{}),children:[{key:"9",page:"caching",label:"Caching",icon:(0,c.jsx)(ae.Z,{}),roles:eg.ZL},{key:"10",page:"budgets",label:"Budgets",icon:(0,c.jsx)(t3.Z,{}),roles:eg.ZL},{key:"11",page:"guardrails",label:"Guardrails",icon:(0,c.jsx)(as.Z,{}),roles:eg.ZL},{key:"4",page:"usage",label:"Old Usage",icon:(0,c.jsx)(t5.Z,{})},{key:"20",page:"transform-request",label:"API Playground",icon:(0,c.jsx)(tJ.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"18",page:"mcp-tools",label:"MCP Tools",icon:(0,c.jsx)(al.Z,{}),roles:eg.ZL},{key:"19",page:"tag-management",label:"Tag Management",icon:(0,c.jsx)(tW.Z,{}),roles:eg.ZL}]},{key:"settings",page:"settings",label:"Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL,children:[{key:"11",page:"general-settings",label:"Router Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"12",page:"pass-through-settings",label:"Pass-Through",icon:(0,c.jsx)(tJ.Z,{}),roles:eg.ZL},{key:"8",page:"settings",label:"Logging & Alerts",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"13",page:"admin-panel",label:"Admin Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL}]}],r=(e=>{let s=a.find(s=>s.page===e);if(s)return s.key;for(let s of a)if(s.children){let l=s.children.find(s=>s.page===e);if(l)return l.key}return"1"})(t),n=a.filter(e=>!!(!e.roles||e.roles.includes(l))&&(e.children&&(e.children=e.children.filter(e=>!e.roles||e.roles.includes(l))),!0));return(0,c.jsx)(t0.default,{style:{minHeight:"100vh"},children:(0,c.jsx)(aa,{theme:"light",width:220,children:(0,c.jsx)(t1.Z,{mode:"inline",selectedKeys:[r],style:{borderRight:0,backgroundColor:"transparent",fontSize:"14px"},items:n.map(e=>{var l;return{key:e.key,icon:e.icon,label:e.label,children:null===(l=e.children)||void 0===l?void 0:l.map(e=>({key:e.key,icon:e.icon,label:e.label,onClick:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}})),onClick:e.children?void 0:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}}})})})})},an=l(96889);console.log("process.env.NODE_ENV","production"),console.log=function(){};let ai=e=>null!==e&&("Admin"===e||"Admin Viewer"===e);var ao=e=>{let{accessToken:s,token:l,userRole:t,userID:a,keys:r,premiumUser:n}=e,i=new Date,[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)([]),[v,b]=(0,d.useState)([]),[Z,S]=(0,d.useState)([]),[C,I]=(0,d.useState)([]),[T,P]=(0,d.useState)([]),[O,L]=(0,d.useState)([]),[D,M]=(0,d.useState)({}),[F,R]=(0,d.useState)([]),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(["all-tags"]),[K,B]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(0),Y=new Date(i.getFullYear(),i.getMonth(),1),$=new Date(i.getFullYear(),i.getMonth()+1,0),X=er(Y),Q=er($);function es(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}console.log("keys in usage",r),console.log("premium user in usage",n);let el=async()=>{if(s)try{let e=await (0,y.g)(s);return console.log("usage tab: proxy_settings",e),e}catch(e){console.error("Error fetching proxy settings:",e)}};(0,d.useEffect)(()=>{ea(K.from,K.to)},[K,z]);let et=async(e,l,t)=>{if(!e||!l||!s)return;l.setHours(23,59,59,999),e.setHours(0,0,0,0),console.log("uiSelectedKey",t);let a=await (0,y.b1)(s,t,e.toISOString(),l.toISOString());console.log("End user data updated successfully",a),j(a)},ea=async(e,l)=>{if(!e||!l||!s)return;let t=await el();null!=t&&t.DISABLE_EXPENSIVE_DB_QUERIES||(l.setHours(23,59,59,999),e.setHours(0,0,0,0),b((await (0,y.J$)(s,e.toISOString(),l.toISOString(),0===z.length?void 0:z)).spend_per_tag),console.log("Tag spend data updated successfully"))};function er(e){let s=e.getFullYear(),l=e.getMonth()+1,t=e.getDate();return"".concat(s,"-").concat(l<10?"0"+l:l,"-").concat(t<10?"0"+t:t)}console.log("Start date is ".concat(X)),console.log("End date is ".concat(Q));let en=async(e,s,l)=>{try{let l=await e();s(l)}catch(e){console.error(l,e)}},ei=(e,s,l,t)=>{let a=[],r=new Date(s),n=e=>{if(e.includes("-"))return e;{let[s,l]=e.split(" ");return new Date(new Date().getFullYear(),new Date("".concat(s," 01 2024")).getMonth(),parseInt(l)).toISOString().split("T")[0]}},i=new Map(e.map(e=>{let s=n(e.date);return[s,{...e,date:s}]}));for(;r<=l;){let e=r.toISOString().split("T")[0];if(i.has(e))a.push(i.get(e));else{let s={date:e,api_requests:0,total_tokens:0};t.forEach(e=>{s[e]||(s[e]=0)}),a.push(s)}r.setDate(r.getDate()+1)}return a},eo=async()=>{if(s)try{let e=await (0,y.FC)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e,t,a,[]),n=Number(r.reduce((e,s)=>e+(s.spend||0),0).toFixed(2));G(n),m(r)}catch(e){console.error("Error fetching overall spend:",e)}},ec=()=>en(()=>s&&l?(0,y.OU)(s,l,X,Q):Promise.reject("No access token or token"),L,"Error fetching provider spend"),ed=async()=>{s&&await en(async()=>(await (0,y.tN)(s)).map(e=>({key:e.api_key.substring(0,10),api_key:e.api_key,key_alias:e.key_alias,spend:Number(e.total_spend.toFixed(2))})),h,"Error fetching top keys")},em=async()=>{s&&await en(async()=>(await (0,y.Au)(s)).map(e=>({key:e.model,spend:Number(e.total_spend.toFixed(2))})),p,"Error fetching top models")},eu=async()=>{s&&await en(async()=>{let e=await (0,y.mR)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0);return _(ei(e.daily_spend,t,a,e.teams)),I(e.teams),e.total_spend_per_team.map(e=>({name:e.team_id||"",value:Number(e.total_spend||0).toFixed(2)}))},P,"Error fetching team spend")},eh=()=>{s&&en(async()=>(await (0,y.X)(s)).tag_names,S,"Error fetching tag names")},ex=()=>{s&&en(()=>{var e,l;return(0,y.J$)(s,null===(e=K.from)||void 0===e?void 0:e.toISOString(),null===(l=K.to)||void 0===l?void 0:l.toISOString(),void 0)},e=>b(e.spend_per_tag),"Error fetching top tags")},ep=()=>{s&&en(()=>(0,y.b1)(s,null,void 0,void 0),j,"Error fetching top end users")},eg=async()=>{if(s)try{let e=await (0,y.wd)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e.daily_data||[],t,a,["api_requests","total_tokens"]);M({...e,daily_data:r})}catch(e){console.error("Error fetching global activity:",e)}},ej=async()=>{if(s)try{let e=await (0,y.xA)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=e.map(e=>({...e,daily_data:ei(e.daily_data||[],t,a,["api_requests","total_tokens"])}));R(r)}catch(e){console.error("Error fetching global activity per model:",e)}};return((0,d.useEffect)(()=>{(async()=>{if(s&&l&&t&&a){let e=await el();e&&(J(e),null!=e&&e.DISABLE_EXPENSIVE_DB_QUERIES)||(console.log("fetching data - valiue of proxySettings",H),eo(),ec(),ed(),em(),eg(),ej(),ai(t)&&(eu(),eh(),ex(),ep()))}})()},[s,l,t,a,X,Q]),null==H?void 0:H.DISABLE_EXPENSIVE_DB_QUERIES)?(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Database Query Limit Reached"}),(0,c.jsxs)(A.Z,{className:"mt-4",children:["SpendLogs in DB has ",H.NUM_SPEND_LOGS_ROWS," rows.",(0,c.jsx)("br",{}),"Please follow our guide to view usage when SpendLogs has more than 1M rows."]}),(0,c.jsx)(k.Z,{className:"mt-4",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/spending_monitoring",target:"_blank",children:"View Usage Guide"})})]})}):(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mt-2",children:[(0,c.jsx)(eR.Z,{children:"All Up"}),ai(t)?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(eR.Z,{children:"Team Based Usage"}),(0,c.jsx)(eR.Z,{children:"Customer Usage"}),(0,c.jsx)(eR.Z,{children:"Tag Based Usage"})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsx)("div",{})})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[100vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:a,userRole:t,accessToken:s,userSpend:W,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Monthly Spend"}),(0,c.jsx)(sw.Z,{data:o,index:"date",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$ ".concat(e.toFixed(2)),yAxisWidth:100,tickGap:5})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:u,accessToken:s,userID:a,userRole:t,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:x,index:"key",categories:["spend"],colors:["cyan"],yAxisWidth:200,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>"$".concat(e.toFixed(2))})]})}),(0,c.jsx)(N.Z,{numColSpan:1}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Spend by Provider"}),(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",variant:"pie",data:O,index:"provider",category:"spend",colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2))})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"})]})}),(0,c.jsx)(eT.Z,{children:O.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsx)(eA.Z,{children:1e-5>parseFloat(e.spend.toFixed(2))?"less than 0.00":e.spend.toFixed(2)})]},e.provider))})]})})]})})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"All Up"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(D.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["api_requests"],onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(D.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["total_tokens"],onValueChange:e=>console.log(e)})]})]})]}),(0,c.jsx)(c.Fragment,{children:F.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.model}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(e.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["api_requests"],valueFormatter:es,onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(e.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["total_tokens"],valueFormatter:es,onValueChange:e=>console.log(e)})]})]})]},s))})]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Total Spend Per Team"}),(0,c.jsx)(an.Z,{data:T})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend Per Team"}),(0,c.jsx)(sw.Z,{className:"h-72",data:f,showLegend:!0,index:"date",categories:C,yAxisWidth:80,stack:!0})]})]}),(0,c.jsx)(N.Z,{numColSpan:2})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:["Customers of your LLM API calls. Tracked when a `user` param is passed in your LLM calls ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/users",target:"_blank",children:"docs here"})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:K,onValueChange:e=>{B(e),et(e.from,e.to,null)}})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Key"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{et(K.from,K.to,null)},children:"All Keys"},"all-keys"),null==r?void 0:r.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{et(K.from,K.to,e.token)},children:e.key_alias},s):null)]})]})]}),(0,c.jsx)(eF.Z,{className:"mt-4",children:(0,c.jsxs)(eI.Z,{className:"max-h-[70vh] min-h-[500px]",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Customer"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Total Events"})]})}),(0,c.jsx)(eT.Z,{children:null==g?void 0:g.map((e,s)=>{var l;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.end_user}),(0,c.jsx)(eA.Z,{children:null===(l=e.total_spend)||void 0===l?void 0:l.toFixed(4)}),(0,c.jsx)(eA.Z,{children:e.total_count})]},s)})})]})})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sb.Z,{className:"mb-4",enableSelect:!0,value:K,onValueChange:e=>{B(e),ea(e.from,e.to)}})}),(0,c.jsx)(N.Z,{children:n?(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsx)(lH.Z,{value:String(e),children:e},e))]})}):(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsxs)(ee.Z,{value:String(e),disabled:!0,children:["✨ ",e," (Enterprise only Feature)"]},e))]})})})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full mb-4",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend Per Tag"}),(0,c.jsxs)(A.Z,{children:["Get Started Tracking cost per tag ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/cost_tracking",target:"_blank",children:"here"})]}),(0,c.jsx)(sw.Z,{className:"h-72",data:v,index:"name",categories:["spend"],colors:["cyan"]})]})}),(0,c.jsx)(N.Z,{numColSpan:2})]})]})]})]})})},ac=l(51853);let ad=e=>{let{responseTimeMs:s}=e;return null==s?null:(0,c.jsxs)("div",{className:"flex items-center space-x-1 text-xs text-gray-500 font-mono",children:[(0,c.jsx)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{d:"M12 6V12L16 14M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,c.jsxs)("span",{children:[s.toFixed(0),"ms"]})]})},am=e=>{let s=e;if("string"==typeof s)try{s=JSON.parse(s)}catch(e){}return s},au=e=>{let{label:s,value:l}=e,[t,a]=d.useState(!1),[r,n]=d.useState(!1),i=(null==l?void 0:l.toString())||"N/A",o=i.length>50?i.substring(0,50)+"...":i;return(0,c.jsx)("tr",{className:"hover:bg-gray-50",children:(0,c.jsx)("td",{className:"px-4 py-2 align-top",colSpan:2,children:(0,c.jsxs)("div",{className:"flex items-center justify-between group",children:[(0,c.jsxs)("div",{className:"flex items-center flex-1",children:[(0,c.jsx)("button",{onClick:()=>a(!t),className:"text-gray-400 hover:text-gray-600 mr-2",children:t?"▼":"▶"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("div",{className:"text-sm text-gray-600",children:s}),(0,c.jsx)("pre",{className:"mt-1 text-sm font-mono text-gray-800 whitespace-pre-wrap",children:t?i:o})]})]}),(0,c.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(i),n(!0),setTimeout(()=>n(!1),2e3)},className:"opacity-0 group-hover:opacity-100 text-gray-400 hover:text-gray-600",children:(0,c.jsx)(ac.Z,{className:"h-4 w-4"})})]})})})},ah=e=>{var s,l,t,a,r,n,i,o,d,m,u,h,x,p;let{response:g}=e,j=null,f={},_={};try{if(null==g?void 0:g.error)try{let e="string"==typeof g.error.message?JSON.parse(g.error.message):g.error.message;j={message:(null==e?void 0:e.message)||"Unknown error",traceback:(null==e?void 0:e.traceback)||"No traceback available",litellm_params:(null==e?void 0:e.litellm_cache_params)||{},health_check_cache_params:(null==e?void 0:e.health_check_cache_params)||{}},f=am(j.litellm_params)||{},_=am(j.health_check_cache_params)||{}}catch(e){console.warn("Error parsing error details:",e),j={message:String(g.error.message||"Unknown error"),traceback:"Error parsing details",litellm_params:{},health_check_cache_params:{}}}else f=am(null==g?void 0:g.litellm_cache_params)||{},_=am(null==g?void 0:g.health_check_cache_params)||{}}catch(e){console.warn("Error in response parsing:",e),f={},_={}}let y={redis_host:(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host)||(null==_?void 0:null===(i=_.connection_kwargs)||void 0===i?void 0:i.host)||(null==_?void 0:_.host)||"N/A",redis_port:(null==_?void 0:null===(m=_.redis_client)||void 0===m?void 0:null===(d=m.connection_pool)||void 0===d?void 0:null===(o=d.connection_kwargs)||void 0===o?void 0:o.port)||(null==_?void 0:null===(x=_.redis_async_client)||void 0===x?void 0:null===(h=x.connection_pool)||void 0===h?void 0:null===(u=h.connection_kwargs)||void 0===u?void 0:u.port)||(null==_?void 0:null===(p=_.connection_kwargs)||void 0===p?void 0:p.port)||(null==_?void 0:_.port)||"N/A",redis_version:(null==_?void 0:_.redis_version)||"N/A",startup_nodes:(()=>{try{var e,s,l,t,a,r,n,i,o,c,d,m,u;if(null==_?void 0:null===(e=_.redis_kwargs)||void 0===e?void 0:e.startup_nodes)return JSON.stringify(_.redis_kwargs.startup_nodes);let h=(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host),x=(null==_?void 0:null===(c=_.redis_client)||void 0===c?void 0:null===(o=c.connection_pool)||void 0===o?void 0:null===(i=o.connection_kwargs)||void 0===i?void 0:i.port)||(null==_?void 0:null===(u=_.redis_async_client)||void 0===u?void 0:null===(m=u.connection_pool)||void 0===m?void 0:null===(d=m.connection_kwargs)||void 0===d?void 0:d.port);return h&&x?JSON.stringify([{host:h,port:x}]):"N/A"}catch(e){return"N/A"}})(),namespace:(null==_?void 0:_.namespace)||"N/A"};return(0,c.jsx)("div",{className:"bg-white rounded-lg shadow",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"border-b border-gray-200 px-4",children:[(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Summary"}),(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Raw Response"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-6",children:[(null==g?void 0:g.status)==="healthy"?(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}):(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsxs)(A.Z,{className:"text-sm font-medium ".concat((null==g?void 0:g.status)==="healthy"?"text-green-500":"text-red-500"),children:["Cache Status: ",(null==g?void 0:g.status)||"unhealthy"]})]}),(0,c.jsx)("table",{className:"w-full border-collapse",children:(0,c.jsxs)("tbody",{children:[j&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold text-red-600",children:"Error Details"})}),(0,c.jsx)(au,{label:"Error Message",value:j.message}),(0,c.jsx)(au,{label:"Traceback",value:j.traceback})]}),(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Cache Details"})}),(0,c.jsx)(au,{label:"Cache Configuration",value:String(null==f?void 0:f.type)}),(0,c.jsx)(au,{label:"Ping Response",value:String(g.ping_response)}),(0,c.jsx)(au,{label:"Set Cache Response",value:g.set_cache_response||"N/A"}),(0,c.jsx)(au,{label:"litellm_settings.cache_params",value:JSON.stringify(f,null,2)}),(null==f?void 0:f.type)==="redis"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Redis Details"})}),(0,c.jsx)(au,{label:"Redis Host",value:y.redis_host||"N/A"}),(0,c.jsx)(au,{label:"Redis Port",value:y.redis_port||"N/A"}),(0,c.jsx)(au,{label:"Redis Version",value:y.redis_version||"N/A"}),(0,c.jsx)(au,{label:"Startup Nodes",value:y.startup_nodes||"N/A"}),(0,c.jsx)(au,{label:"Namespace",value:y.namespace||"N/A"})]})]})})]})}),(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsx)("div",{className:"bg-gray-50 rounded-md p-4 font-mono text-sm",children:(0,c.jsx)("pre",{className:"whitespace-pre-wrap break-words overflow-auto max-h-[500px]",children:(()=>{try{let e={...g,litellm_cache_params:f,health_check_cache_params:_},s=JSON.parse(JSON.stringify(e,(e,s)=>{if("string"==typeof s)try{return JSON.parse(s)}catch(e){}return s}));return JSON.stringify(s,null,2)}catch(e){return"Error formatting JSON: "+e.message}})()})})})]})]})})},ax=e=>{let{accessToken:s,healthCheckResponse:l,runCachingHealthCheck:t,responseTimeMs:a}=e,[r,n]=d.useState(null),[i,o]=d.useState(!1),m=async()=>{o(!0);let e=performance.now();await t(),n(performance.now()-e),o(!1)};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsx)(k.Z,{onClick:m,disabled:i,className:"bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white text-sm px-4 py-2 rounded-md",children:i?"Running Health Check...":"Run Health Check"}),(0,c.jsx)(ad,{responseTimeMs:r})]}),l&&(0,c.jsx)(ah,{response:l})]})},ap=e=>{if(e)return e.toISOString().split("T")[0]};function ag(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}var aj=e=>{let{accessToken:s,token:l,userRole:t,userID:a,premiumUser:r}=e,[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)("0"),[f,_]=(0,d.useState)("0"),[v,b]=(0,d.useState)("0"),[Z,k]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[S,C]=(0,d.useState)(""),[I,T]=(0,d.useState)("");(0,d.useEffect)(()=>{s&&Z&&((async()=>{p(await (0,y.zg)(s,ap(Z.from),ap(Z.to)))})(),C(new Date().toLocaleString()))},[s]);let E=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.api_key)&&void 0!==s?s:""}))),P=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.model)&&void 0!==s?s:""})));Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.call_type)&&void 0!==s?s:""})));let O=async(e,l)=>{e&&l&&s&&(l.setHours(23,59,59,999),e.setHours(0,0,0,0),p(await (0,y.zg)(s,ap(e),ap(l))))};(0,d.useEffect)(()=>{console.log("DATA IN CACHE DASHBOARD",x);let e=x;o.length>0&&(e=e.filter(e=>o.includes(e.api_key))),u.length>0&&(e=e.filter(e=>u.includes(e.model))),console.log("before processed data in cache dashboard",e);let s=0,l=0,t=0,a=e.reduce((e,a)=>{console.log("Processing item:",a),a.call_type||(console.log("Item has no call_type:",a),a.call_type="Unknown"),s+=(a.total_rows||0)-(a.cache_hit_true_rows||0),l+=a.cache_hit_true_rows||0,t+=a.cached_completion_tokens||0;let r=e.find(e=>e.name===a.call_type);return r?(r["LLM API requests"]+=(a.total_rows||0)-(a.cache_hit_true_rows||0),r["Cache hit"]+=a.cache_hit_true_rows||0,r["Cached Completion Tokens"]+=a.cached_completion_tokens||0,r["Generated Completion Tokens"]+=a.generated_completion_tokens||0):e.push({name:a.call_type,"LLM API requests":(a.total_rows||0)-(a.cache_hit_true_rows||0),"Cache hit":a.cache_hit_true_rows||0,"Cached Completion Tokens":a.cached_completion_tokens||0,"Generated Completion Tokens":a.generated_completion_tokens||0}),e},[]);j(ag(l)),_(ag(t));let r=l+s;r>0?b((l/r*100).toFixed(2)):b("0"),i(a),console.log("PROCESSED DATA IN CACHE DASHBOARD",a)},[o,u,Z,x]);let L=async()=>{try{D.ZP.info("Running cache health check..."),T("");let e=await (0,y.Tj)(null!==s?s:"");console.log("CACHING HEALTH CHECK RESPONSE",e),T(e)}catch(s){let e;if(console.error("Error running health check:",s),s&&s.message)try{let l=JSON.parse(s.message);l.error&&(l=l.error),e=l}catch(l){e={message:s.message}}else e={message:"Unknown error occurred"};T({error:e})}};return(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-full w-full mt-2 mb-8",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Cache Analytics"}),(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"Cache Health"})})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[S&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",S]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:()=>{C(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(w.Z,{numItems:3,className:"gap-4 mt-4",children:[(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select API Keys",value:o,onValueChange:m,children:E.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select Models",value:u,onValueChange:h,children:P.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(sb.Z,{enableSelect:!0,value:Z,onValueChange:e=>{k(e),O(e.from,e.to)},selectPlaceholder:"Select date range"})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hit Ratio"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsxs)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:[v,"%"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hits"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:g})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cached Tokens"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:f})})]})]}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cache Hits vs API Requests"}),(0,c.jsx)(sw.Z,{title:"Cache Hits vs API Requests",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["LLM API requests","Cache hit"],colors:["sky","teal"],yAxisWidth:48}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cached Completion Tokens vs Generated Completion Tokens"}),(0,c.jsx)(sw.Z,{className:"mt-6",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["Generated Completion Tokens","Cached Completion Tokens"],colors:["sky","teal"],yAxisWidth:48})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ax,{accessToken:s,healthCheckResponse:I,runCachingHealthCheck:L})})]})]})},af=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(async()=>{try{let e=await (0,y.t3)(s);console.log("guardrails: ".concat(JSON.stringify(e))),t(e.guardrails)}catch(e){console.error("Error fetching guardrails:",e)}})()},[s]),(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsxs)(A.Z,{className:"mb-4",children:["Configured guardrails and their current status. Setup guardrails in config.yaml."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Guardrail Name"}),(0,c.jsx)(eP.Z,{children:"Mode"}),(0,c.jsx)(eP.Z,{children:"Status"})]})}),(0,c.jsx)(eT.Z,{children:l&&0!==l.length?null==l?void 0:l.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.guardrail_name}),(0,c.jsx)(eA.Z,{children:e.litellm_params.mode}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"inline-flex rounded-full px-2 py-1 text-xs font-medium\n ".concat(e.litellm_params.default_on?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"),children:e.litellm_params.default_on?"Always On":"Per Request"})})]},s)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:3,className:"mt-4 text-gray-500 text-center py-4",children:"No guardrails configured"})})})]})})]})},a_=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)('{\n "model": "openai/gpt-4o",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n },\n {\n "role": "user",\n "content": "Explain quantum computing in simple terms"\n }\n ],\n "temperature": 0.7,\n "max_tokens": 500,\n "stream": true\n}'),[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(!1),o=(e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")},m=async()=>{i(!0);try{let e;try{e=JSON.parse(l)}catch(e){D.ZP.error("Invalid JSON in request body"),i(!1);return}let t={call_type:"completion",request_body:e};if(!s){D.ZP.error("No access token found"),i(!1);return}let a=await (0,y.Yo)(s,t);if(a.raw_request_api_base&&a.raw_request_body){let e=o(a.raw_request_api_base,a.raw_request_body,a.raw_request_headers||{});r(e),D.ZP.success("Request transformed successfully")}else{let e="string"==typeof a?a:JSON.stringify(a);r(e),D.ZP.info("Transformed request received in unexpected format")}}catch(e){console.error("Error transforming request:",e),D.ZP.error("Failed to transform request")}finally{i(!1)}};return(0,c.jsxs)("div",{className:"w-full m-2",style:{overflow:"hidden"},children:[(0,c.jsx)(E.Z,{children:"Playground"}),(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"See how LiteLLM transforms your request for the specified provider."}),(0,c.jsxs)("div",{style:{display:"flex",gap:"16px",width:"100%",minWidth:0,overflow:"hidden"},className:"mt-4",children:[(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"600px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Original Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"The request you would send to LiteLLM /chat/completions endpoint."})]}),(0,c.jsx)("textarea",{style:{flex:"1 1 auto",width:"100%",minHeight:"240px",padding:"16px",border:"1px solid #e8e8e8",borderRadius:"6px",fontFamily:"monospace",fontSize:"14px",resize:"none",marginBottom:"24px",overflow:"auto"},value:l,onChange:e=>t(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),m())},placeholder:"Press Cmd/Ctrl + Enter to transform"}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"auto"},children:(0,c.jsxs)(R.ZP,{type:"primary",style:{backgroundColor:"#000",display:"flex",alignItems:"center",gap:"8px"},onClick:m,loading:n,children:[(0,c.jsx)("span",{children:"Transform"}),(0,c.jsx)("span",{children:"→"})]})})]}),(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"800px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Transformed Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"How LiteLLM transforms your request for the specified provider."}),(0,c.jsx)("br",{}),(0,c.jsx)("p",{style:{color:"#666",margin:0},className:"text-xs",children:"Note: Sensitive headers are not shown."})]}),(0,c.jsxs)("div",{style:{position:"relative",backgroundColor:"#f5f5f5",borderRadius:"6px",flex:"1 1 auto",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,c.jsx)("pre",{style:{padding:"16px",fontFamily:"monospace",fontSize:"14px",margin:0,overflow:"auto",flex:"1 1 auto"},children:a||'curl -X POST \\\n https://api.openai.com/v1/chat/completions \\\n -H \'Authorization: Bearer sk-xxx\' \\\n -H \'Content-Type: application/json\' \\\n -d \'{\n "model": "gpt-4",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n }\n ],\n "temperature": 0.7\n }\''}),(0,c.jsx)(R.ZP,{type:"text",icon:(0,c.jsx)(s8.Z,{}),style:{position:"absolute",right:"8px",top:"8px"},size:"small",onClick:()=>{navigator.clipboard.writeText(a||""),D.ZP.success("Copied to clipboard")}})]})]})]}),(0,c.jsx)("div",{className:"mt-4 text-right w-full",children:(0,c.jsxs)("p",{className:"text-sm text-gray-500",children:["Found an error? File an issue ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/issues",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})]})},ay=l(21770);let av=[{accessorKey:"mcp_info.server_name",header:"Provider",cell:e=>{let{row:s}=e,l=s.original.mcp_info.server_name,t=s.original.mcp_info.logo_url;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[t&&(0,c.jsx)("img",{src:t,alt:"".concat(l," logo"),className:"h-5 w-5 object-contain"}),(0,c.jsx)("span",{className:"font-medium",children:l})]})}},{accessorKey:"name",header:"Tool Name",cell:e=>{let{row:s}=e,l=s.getValue("name");return(0,c.jsx)("div",{children:(0,c.jsx)("span",{className:"font-mono text-sm",children:l})})}},{accessorKey:"description",header:"Description",cell:e=>{let{row:s}=e,l=s.getValue("description");return(0,c.jsx)("div",{className:"max-w-md",children:(0,c.jsx)("span",{className:"text-sm text-gray-700",children:l})})}},{id:"actions",header:"Actions",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"flex items-center space-x-2",children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{"function"==typeof s.original.onToolSelect&&s.original.onToolSelect(l)},children:"Test Tool"})})}}];function ab(e){let{tool:s,onSubmit:l,isLoading:t,result:a,error:r,onClose:n}=e,[i,o]=d.useState({}),m=d.useMemo(()=>"string"==typeof s.inputSchema?{type:"object",properties:{input:{type:"string",description:"Input for this tool"}},required:["input"]}:s.inputSchema,[s.inputSchema]),u=(e,s)=>{o(l=>({...l,[e]:s}))};return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-lg border p-6 max-w-4xl w-full",children:[(0,c.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("h2",{className:"text-xl font-bold",children:["Test Tool: ",(0,c.jsx)("span",{className:"font-mono",children:s.name})]}),(0,c.jsx)("p",{className:"text-gray-600",children:s.description}),(0,c.jsxs)("p",{className:"text-sm text-gray-500 mt-1",children:["Provider: ",s.mcp_info.server_name]})]}),(0,c.jsx)("button",{onClick:n,className:"p-1 rounded-full hover:bg-gray-200",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,c.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Input Parameters"}),(0,c.jsxs)("form",{onSubmit:e=>{e.preventDefault(),l(i)},children:["string"==typeof s.inputSchema?(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:"This tool uses a dynamic input schema."}),(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Input ",(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),(0,c.jsx)("input",{type:"text",value:i.input||"",onChange:e=>u("input",e.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"})]})]}):Object.entries(m.properties).map(e=>{var s,l,t;let[a,r]=e;return(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[a," ",(null===(s=m.required)||void 0===s?void 0:s.includes(a))&&(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),r.description&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:r.description}),"string"===r.type&&(0,c.jsx)("input",{type:"text",value:i[a]||"",onChange:e=>u(a,e.target.value),required:null===(l=m.required)||void 0===l?void 0:l.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"number"===r.type&&(0,c.jsx)("input",{type:"number",value:i[a]||"",onChange:e=>u(a,parseFloat(e.target.value)),required:null===(t=m.required)||void 0===t?void 0:t.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"boolean"===r.type&&(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("input",{type:"checkbox",checked:i[a]||!1,onChange:e=>u(a,e.target.checked),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),(0,c.jsx)("span",{className:"ml-2 text-sm text-gray-600",children:"Enable"})]})]},a)}),(0,c.jsx)("div",{className:"mt-6",children:(0,c.jsx)(k.Z,{type:"submit",disabled:t,className:"w-full px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white",children:t?"Calling...":"Call Tool"})})]})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg overflow-auto max-h-[500px]",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Result"}),t&&(0,c.jsx)("div",{className:"flex justify-center items-center py-8",children:(0,c.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-700"})}),r&&(0,c.jsxs)("div",{className:"bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-md",children:[(0,c.jsx)("p",{className:"font-medium",children:"Error"}),(0,c.jsx)("pre",{className:"mt-2 text-xs overflow-auto whitespace-pre-wrap",children:r.message})]}),a&&!t&&!r&&(0,c.jsxs)("div",{children:[a.map((e,s)=>(0,c.jsxs)("div",{className:"mb-4",children:["text"===e.type&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.text})}),"image"===e.type&&e.url&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("img",{src:e.url,alt:"Tool result",className:"max-w-full h-auto rounded"})}),"embedded_resource"===e.type&&(0,c.jsxs)("div",{className:"bg-white border p-3 rounded-md",children:[(0,c.jsx)("p",{className:"text-sm font-medium",children:"Embedded Resource"}),(0,c.jsxs)("p",{className:"text-xs text-gray-500",children:["Type: ",e.resource_type]}),e.url&&(0,c.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline",children:"View Resource"})]})]},s)),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)("details",{className:"text-xs",children:[(0,c.jsx)("summary",{className:"cursor-pointer text-gray-500 hover:text-gray-700",children:"Raw JSON Response"}),(0,c.jsx)("pre",{className:"mt-2 bg-gray-100 p-2 rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(a,null,2)})]})})]}),!a&&!t&&!r&&(0,c.jsx)("div",{className:"text-center py-8 text-gray-500",children:(0,c.jsx)("p",{children:"The result will appear here after you call the tool."})})]})]})]})}function aZ(e){let{columns:s,data:l,isLoading:t}=e;return(0,c.jsx)(eL,{columns:s,data:l,isLoading:t,renderSubComponent:()=>(0,c.jsx)("div",{}),getRowCanExpand:()=>!1})}function aN(e){let{accessToken:s,userRole:l,userID:t}=e,[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),{data:x,isLoading:p}=(0,e4.a)({queryKey:["mcpTools"],queryFn:()=>{if(!s)throw Error("Access Token required");return(0,y.lU)(s)},enabled:!!s}),{mutate:g,isPending:j}=(0,ay.D)({mutationFn:e=>{if(!s)throw Error("Access Token required");return(0,y.tB)(s,e.tool.name,e.arguments)},onSuccess:e=>{m(e),h(null)},onError:e=>{h(e),m(null)}}),f=d.useMemo(()=>x?x.map(e=>({...e,onToolSelect:e=>{i(e),m(null),h(null)}})):[],[x]),_=d.useMemo(()=>f.filter(e=>{let s=a.toLowerCase();return e.name.toLowerCase().includes(s)||e.description.toLowerCase().includes(s)||e.mcp_info.server_name.toLowerCase().includes(s)}),[f,a]);return s&&l&&t?(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"MCP Tools"})}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search tools...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:a,onChange:e=>r(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"text-sm text-gray-500",children:[_.length," tool",1!==_.length?"s":""," available"]})]})}),(0,c.jsx)(aZ,{columns:av,data:_,isLoading:p})]}),n&&(0,c.jsx)("div",{className:"fixed inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center z-50 p-4",children:(0,c.jsx)(ab,{tool:n,onSubmit:e=>{n&&g({tool:n,arguments:e})},isLoading:j,result:o,error:u,onClose:()=>i(null)})})]}):(0,c.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Missing required authentication parameters."})}var aw=e=>{let{tagId:s,onClose:l,accessToken:t,is_admin:a,editTag:r}=e,[n]=L.Z.useForm(),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(r),[h,x]=(0,d.useState)([]),p=async()=>{if(t)try{let e=(await (0,y.mC)(t,[s]))[s];e&&(o(e),r&&n.setFieldsValue({name:e.name,description:e.description,models:e.models}))}catch(e){console.error("Error fetching tag details:",e),D.ZP.error("Error fetching tag details: "+e)}};(0,d.useEffect)(()=>{p()},[s,t]),(0,d.useEffect)(()=>{t&&eZ("dummy-user","Admin",t,x)},[t]);let g=async e=>{if(t)try{await (0,y.n9)(t,{name:e.name,description:e.description,models:e.models}),D.ZP.success("Tag updated successfully"),u(!1),p()}catch(e){console.error("Error updating tag:",e),D.ZP.error("Error updating tag: "+e)}};return i?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{onClick:l,className:"mb-4",children:"← Back to Tags"}),(0,c.jsxs)(E.Z,{children:["Tag Name: ",i.name]}),(0,c.jsx)(A.Z,{className:"text-gray-500",children:i.description||"No description"})]}),a&&!m&&(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Tag"})]}),m?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(L.Z,{form:n,onFinish:g,layout:"vertical",initialValues:i,children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(q.default,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed LLMs"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process this type of data",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:h.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))})}),(0,c.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,c.jsx)(k.Z,{onClick:()=>u(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]})}):(0,c.jsx)("div",{className:"space-y-6",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Tag Details"}),(0,c.jsxs)("div",{className:"space-y-4 mt-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Name"}),(0,c.jsx)(A.Z,{children:i.name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Description"}),(0,c.jsx)(A.Z,{children:i.description||"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Allowed LLMs"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-2",children:0===i.models.length?(0,c.jsx)(eM.Z,{color:"red",children:"All Models"}):i.models.map(e=>{var s;return(0,c.jsx)(eM.Z,{color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(null===(s=i.model_info)||void 0===s?void 0:s[e])||e})},e)})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:i.created_at?new Date(i.created_at).toLocaleString():"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:i.updated_at?new Date(i.updated_at).toLocaleString():"-"})]})]})]})})]}):(0,c.jsx)("div",{children:"Loading..."})},ak=e=>{let{data:s,onEdit:l,onDelete:t,onSelectTag:a}=e,[r,n]=d.useState([{id:"created_at",desc:!0}]),i=[{header:"Tag Name",accessorKey:"name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.name,children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5",onClick:()=>a(l.name),children:l.name})})})}},{header:"Description",accessorKey:"description",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.description,children:(0,c.jsx)("span",{className:"text-xs",children:l.description||"-"})})}},{header:"Allowed LLMs",accessorKey:"models",cell:e=>{var s,l;let{row:t}=e,a=t.original;return(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:(null==a?void 0:null===(s=a.models)||void 0===s?void 0:s.length)===0?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Models"}):null==a?void 0:null===(l=a.models)||void 0===l?void 0:l.map(e=>{var s;return(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(0,c.jsx)(A.Z,{children:(null===(s=a.model_info)||void 0===s?void 0:s[e])||e})})},e)})})}},{header:"Created",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:new Date(l.created_at).toLocaleDateString()})}},{id:"actions",header:"",cell:e=>{let{row:s}=e,a=s.original;return(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>l(a),className:"cursor-pointer"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(a.name),className:"cursor-pointer"})]})}}],o=(0,eS.b7)({data:s,columns:i,state:{sorting:r},onSortingChange:n,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0});return(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:i.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No tags found"})})})})})]})})})},aS=e=>{let{accessToken:s,userID:l,userRole:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v]=L.Z.useForm(),[b,Z]=(0,d.useState)([]),C=async()=>{if(s)try{let e=await (0,y.UM)(s);console.log("List tags response:",e),r(Object.values(e))}catch(e){console.error("Error fetching tags:",e),D.ZP.error("Error fetching tags: "+e)}},I=async e=>{if(s)try{await (0,y.mY)(s,{name:e.tag_name,description:e.description,models:e.allowed_llms}),D.ZP.success("Tag created successfully"),i(!1),v.resetFields(),C()}catch(e){console.error("Error creating tag:",e),D.ZP.error("Error creating tag: "+e)}},T=async e=>{j(e),p(!0)},E=async()=>{if(s&&g){try{await (0,y.fE)(s,g),D.ZP.success("Tag deleted successfully"),C()}catch(e){console.error("Error deleting tag:",e),D.ZP.error("Error deleting tag: "+e)}p(!1),j(null)}};return(0,d.useEffect)(()=>{l&&t&&s&&(async()=>{try{let e=await (0,y.AZ)(s,l,t);e&&e.data&&Z(e.data)}catch(e){console.error("Error fetching models:",e),D.ZP.error("Error fetching models: "+e)}})()},[s,l,t]),(0,d.useEffect)(()=>{C()},[s]),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:o?(0,c.jsx)(aw,{tagId:o,onClose:()=>{m(null),h(!1)},accessToken:s,is_admin:"Admin"===t,editTag:u}):(0,c.jsxs)("div",{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)("div",{className:"flex justify-between mt-2 w-full items-center mb-4",children:[(0,c.jsx)("h1",{children:"Tag Management"}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center cursor-pointer",onClick:()=>{C(),_(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(A.Z,{className:"mb-4",children:["Click on a tag name to view and edit its details.",(0,c.jsxs)("p",{children:["You can use tags to restrict the usage of certain LLMs based on tags passed in the request. Read more about tag routing ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tag_routing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})]}),(0,c.jsx)(k.Z,{className:"mb-4",onClick:()=>i(!0),children:"+ Create New Tag"}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(ak,{data:a,onEdit:e=>{m(e.name),h(!0)},onDelete:T,onSelectTag:m})})}),(0,c.jsx)(M.Z,{title:"Create New Tag",visible:n,width:800,footer:null,onCancel:()=>{i(!1),v.resetFields()},children:(0,c.jsxs)(L.Z,{form:v,onFinish:I,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"tag_name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed Models"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process requests from this tag",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_llms",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:b.map(e=>(0,c.jsx)(O.default.Option,{value:e.model_info.id,children:(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{children:e.model_name}),(0,c.jsxs)("span",{className:"text-gray-400 ml-2",children:["(",e.model_info.id,")"]})]})},e.model_info.id))})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Tag"})})]})}),x&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Tag"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this tag?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:E,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{p(!1),j(null)},children:"Cancel"})]})]})]})})]})})},aC=l(49096),aI=l(53335);let{cva:aT,cx:aA,compose:aE}=(0,aC.ZD)({hooks:{onComplete:e=>(0,aI.m6)(e)}});function aP(e){var s,l;let{className:t="",...a}=e,r=(0,d.useId)();return s=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),s=e.find(e=>{var s;return(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))===r}),l=e.find(e=>{var s;return e.effect instanceof KeyframeEffect&&(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))!==r});s&&l&&(s.currentTime=l.currentTime)},l=[r],(0,d.useLayoutEffect)(s,l),(0,c.jsxs)("svg",{"data-spinner-id":r,className:aA("pointer-events-none size-12 animate-spin text-current",t),fill:"none",viewBox:"0 0 24 24",...a,children:[(0,c.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,c.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}let aO=new h.S;function aL(){return(0,c.jsxs)("div",{className:aA("h-screen","flex items-center justify-center gap-4"),children:[(0,c.jsx)("div",{className:"text-lg font-medium py-2 pr-4 border-r border-r-gray-200",children:"\uD83D\uDE85 LiteLLM"}),(0,c.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,c.jsx)(aP,{className:"size-4"}),(0,c.jsx)("span",{className:"text-gray-600 text-sm",children:"Loading..."})]})]})}function aD(){let[e,s]=(0,d.useState)(""),[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,h]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[N,w]=(0,d.useState)({PROXY_BASE_URL:"",PROXY_LOGOUT_URL:""}),[k,S]=(0,d.useState)(!0),C=(0,m.useSearchParams)(),[I,T]=(0,d.useState)({data:[]}),[A,E]=(0,d.useState)(null),[P,O]=(0,d.useState)(!0),[L,D]=(0,d.useState)(null),M=C.get("invitation_id"),[F,R]=(0,d.useState)(()=>C.get("page")||"api-keys"),[q,U]=(0,d.useState)(null);return((0,d.useEffect)(()=>{E(function(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token")),O(!1)},[]),(0,d.useEffect)(()=>{!1===P&&null===A&&(window.location.href=(y.H2||"")+"/sso/key/generate")},[A,P]),(0,d.useEffect)(()=>{if(!A)return;let e=(0,u.o)(A);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),U(e.key),r(e.disabled_non_admin_personal_key_creation),e.user_role){let l=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e.toLowerCase())),console.log("Received user role length: ".concat(e.toLowerCase().length)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"org_admin":return"Org Admin";case"internal_user":return"Internal User";case"internal_viewer":return"Internal Viewer";case"app_user":return"App User";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",l),s(l),"Admin Viewer"==l&&R("usage")}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e)),e.login_method?S("username_password"==e.login_method):console.log("User Email is not set ".concat(e)),e.premium_user&&t(e.premium_user),e.auth_header_name&&(0,y.K8)(e.auth_header_name),e.user_id&&D(e.user_id)}},[A]),(0,d.useEffect)(()=>{q&&L&&e&&eZ(L,e,q,v),q&&L&&e&&Z(q,L,e,null,h),q&&lw(q,f)},[q,L,e]),P||!1==P&&null===A)?(0,c.jsx)(aL,{}):(0,c.jsx)(d.Suspense,{fallback:(0,c.jsx)(aL,{}),children:(0,c.jsx)(x.aH,{client:aO,children:M?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):(0,c.jsxs)("div",{className:"flex flex-col min-h-screen",children:[(0,c.jsx)(b,{userID:L,userRole:e,premiumUser:l,userEmail:n,setProxySettings:w,proxySettings:N,accessToken:q}),(0,c.jsxs)("div",{className:"flex flex-1 overflow-auto",children:[(0,c.jsx)("div",{className:"mt-8",children:(0,c.jsx)(ar,{setPage:e=>{let s=new URLSearchParams(C);s.set("page",e),window.history.pushState(null,"","?".concat(s.toString())),R(e)},userRole:e,defaultSelectedKey:F})}),"api-keys"==F?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):"models"==F?(0,c.jsx)(lm,{userID:L,userRole:e,token:A,keys:p,accessToken:q,modelData:I,setModelData:T,premiumUser:l,teams:o}):"llm-playground"==F?(0,c.jsx)(tQ,{userID:L,userRole:e,token:A,accessToken:q,disabledPersonalKeyCreation:a}):"users"==F?(0,c.jsx)(l_,{userID:L,userRole:e,token:A,keys:p,teams:o,accessToken:q,setKeys:g}):"teams"==F?(0,c.jsx)(lZ,{teams:o,setTeams:h,searchParams:C,accessToken:q,userID:L,userRole:e,organizations:j}):"organizations"==F?(0,c.jsx)(lk,{organizations:j,setOrganizations:f,userModels:_,accessToken:q,userRole:e,premiumUser:l}):"admin-panel"==F?(0,c.jsx)(lM,{setTeams:h,searchParams:C,accessToken:q,showSSOBanner:k,premiumUser:l,proxySettings:N}):"api_ref"==F?(0,c.jsx)(tN,{proxySettings:N}):"settings"==F?(0,c.jsx)(lK,{userID:L,userRole:e,accessToken:q,premiumUser:l}):"budgets"==F?(0,c.jsx)(l7,{accessToken:q}):"guardrails"==F?(0,c.jsx)(af,{accessToken:q}):"transform-request"==F?(0,c.jsx)(a_,{accessToken:q}):"general-settings"==F?(0,c.jsx)(lQ,{userID:L,userRole:e,accessToken:q,modelData:I}):"model-hub"==F?(0,c.jsx)(tu.Z,{accessToken:q,publicPage:!1,premiumUser:l}):"caching"==F?(0,c.jsx)(aj,{userID:L,userRole:e,token:A,accessToken:q,premiumUser:l}):"pass-through-settings"==F?(0,c.jsx)(l5,{userID:L,userRole:e,accessToken:q,modelData:I}):"logs"==F?(0,c.jsx)(td,{userID:L,userRole:e,token:A,accessToken:q,allTeams:null!=o?o:[]}):"mcp-tools"==F?(0,c.jsx)(aN,{accessToken:q,userRole:e,userID:L}):"tag-management"==F?(0,c.jsx)(aS,{accessToken:q,userRole:e,userID:L}):"new_usage"==F?(0,c.jsx)(tZ,{userID:L,userRole:e,accessToken:q,teams:null!=o?o:[]}):(0,c.jsx)(ao,{userID:L,userRole:e,token:A,accessToken:q,keys:p,premiumUser:l})]})]})})})}},3914:function(e,s,l){"use strict";function t(){let e=window.location.hostname,s=["Lax","Strict","None"];["/","/ui"].forEach(l=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,";"),s.forEach(s=>{let t="None"===s?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; SameSite=").concat(s,";").concat(t),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,"; SameSite=").concat(s,";").concat(t)})}),console.log("After clearing cookies:",document.cookie)}function a(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}l.d(s,{b:function(){return t},e:function(){return a}})}},function(e){e.O(0,[665,990,42,261,899,466,250,699,971,117,744],function(){return e(e.s=60497)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/main-app-2b16cdb7ff4e1af7.js b/litellm/proxy/_experimental/out/_next/static/chunks/main-app-4f7318ae681a6d94.js similarity index 54% rename from litellm/proxy/_experimental/out/_next/static/chunks/main-app-2b16cdb7ff4e1af7.js rename to litellm/proxy/_experimental/out/_next/static/chunks/main-app-4f7318ae681a6d94.js index 33781e7a63..04cf9b1105 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/main-app-2b16cdb7ff4e1af7.js +++ b/litellm/proxy/_experimental/out/_next/static/chunks/main-app-4f7318ae681a6d94.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{35618:function(e,n,t){Promise.resolve().then(t.t.bind(t,12846,23)),Promise.resolve().then(t.t.bind(t,19107,23)),Promise.resolve().then(t.t.bind(t,61060,23)),Promise.resolve().then(t.t.bind(t,4707,23)),Promise.resolve().then(t.t.bind(t,80,23)),Promise.resolve().then(t.t.bind(t,36423,23))}},function(e){var n=function(n){return e(e.s=n)};e.O(0,[971,117],function(){return n(54278),n(35618)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{10264:function(e,n,t){Promise.resolve().then(t.t.bind(t,12846,23)),Promise.resolve().then(t.t.bind(t,19107,23)),Promise.resolve().then(t.t.bind(t,61060,23)),Promise.resolve().then(t.t.bind(t,4707,23)),Promise.resolve().then(t.t.bind(t,80,23)),Promise.resolve().then(t.t.bind(t,36423,23))}},function(e){var n=function(n){return e(e.s=n)};e.O(0,[971,117],function(){return n(54278),n(10264)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/index.html b/litellm/proxy/_experimental/out/index.html index fe18b9be80..d46d2b1454 100644 --- a/litellm/proxy/_experimental/out/index.html +++ b/litellm/proxy/_experimental/out/index.html @@ -1 +1 @@ -LiteLLM Dashboard \ No newline at end of file +LiteLLM Dashboard \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/index.txt b/litellm/proxy/_experimental/out/index.txt index 0f27cbf775..a83c327f95 100644 --- a/litellm/proxy/_experimental/out/index.txt +++ b/litellm/proxy/_experimental/out/index.txt @@ -1,7 +1,7 @@ 2:I[19107,[],"ClientPageRoot"] -3:I[76737,["665","static/chunks/3014691f-b7b79b78e27792f3.js","990","static/chunks/13b76428-ebdf3012af0e4489.js","42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","899","static/chunks/899-57685cedd1dcbc78.js","466","static/chunks/466-65538e7f331af98e.js","250","static/chunks/250-7d480872c0e251dc.js","699","static/chunks/699-2176ba2273e4676d.js","931","static/chunks/app/page-36914b80c40b5032.js"],"default",1] +3:I[76737,["665","static/chunks/3014691f-b7b79b78e27792f3.js","990","static/chunks/13b76428-ebdf3012af0e4489.js","42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","899","static/chunks/899-57685cedd1dcbc78.js","466","static/chunks/466-65538e7f331af98e.js","250","static/chunks/250-85fb4e9c2fdebf3e.js","699","static/chunks/699-907a1bb245b7369a.js","931","static/chunks/app/page-225a364dd94a768d.js"],"default",1] 4:I[4707,[],""] 5:I[36423,[],""] -0:["fzhvjOFL6KeNsWYrLD4ya",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] +0:["TGdu5EOOYr2m-EAOFIND0",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"LiteLLM Dashboard"}],["$","meta","3",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","4",{"rel":"icon","href":"/ui/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]] 1:null diff --git a/litellm/proxy/_experimental/out/model_hub.txt b/litellm/proxy/_experimental/out/model_hub.txt index 3bdb89cd19..14962120fd 100644 --- a/litellm/proxy/_experimental/out/model_hub.txt +++ b/litellm/proxy/_experimental/out/model_hub.txt @@ -1,7 +1,7 @@ 2:I[19107,[],"ClientPageRoot"] -3:I[52829,["42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","250","static/chunks/250-7d480872c0e251dc.js","699","static/chunks/699-2176ba2273e4676d.js","418","static/chunks/app/model_hub/page-a965e43ba9638156.js"],"default",1] +3:I[52829,["42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","250","static/chunks/250-85fb4e9c2fdebf3e.js","699","static/chunks/699-907a1bb245b7369a.js","418","static/chunks/app/model_hub/page-3d2c374ee41b38e5.js"],"default",1] 4:I[4707,[],""] 5:I[36423,[],""] -0:["fzhvjOFL6KeNsWYrLD4ya",[[["",{"children":["model_hub",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["model_hub",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","model_hub","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] +0:["TGdu5EOOYr2m-EAOFIND0",[[["",{"children":["model_hub",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["model_hub",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","model_hub","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"LiteLLM Dashboard"}],["$","meta","3",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","4",{"rel":"icon","href":"/ui/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]] 1:null diff --git a/litellm/proxy/_experimental/out/onboarding.html b/litellm/proxy/_experimental/out/onboarding.html index 9b3880cffd..085f63f727 100644 --- a/litellm/proxy/_experimental/out/onboarding.html +++ b/litellm/proxy/_experimental/out/onboarding.html @@ -1 +1 @@ -LiteLLM Dashboard \ No newline at end of file +LiteLLM Dashboard \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/onboarding.txt b/litellm/proxy/_experimental/out/onboarding.txt index 4e77654a7b..9ef840aba3 100644 --- a/litellm/proxy/_experimental/out/onboarding.txt +++ b/litellm/proxy/_experimental/out/onboarding.txt @@ -1,7 +1,7 @@ 2:I[19107,[],"ClientPageRoot"] -3:I[12011,["665","static/chunks/3014691f-b7b79b78e27792f3.js","42","static/chunks/42-69f5b4e6a9942a9f.js","899","static/chunks/899-57685cedd1dcbc78.js","250","static/chunks/250-7d480872c0e251dc.js","461","static/chunks/app/onboarding/page-9598003bc1e91371.js"],"default",1] +3:I[12011,["665","static/chunks/3014691f-b7b79b78e27792f3.js","42","static/chunks/42-69f5b4e6a9942a9f.js","899","static/chunks/899-57685cedd1dcbc78.js","250","static/chunks/250-85fb4e9c2fdebf3e.js","461","static/chunks/app/onboarding/page-339a46b35fba4423.js"],"default",1] 4:I[4707,[],""] 5:I[36423,[],""] -0:["fzhvjOFL6KeNsWYrLD4ya",[[["",{"children":["onboarding",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["onboarding",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","onboarding","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] +0:["TGdu5EOOYr2m-EAOFIND0",[[["",{"children":["onboarding",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["onboarding",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","onboarding","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"LiteLLM Dashboard"}],["$","meta","3",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","4",{"rel":"icon","href":"/ui/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]] 1:null diff --git a/ui/litellm-dashboard/out/404.html b/ui/litellm-dashboard/out/404.html index 269a2f4068..3808300736 100644 --- a/ui/litellm-dashboard/out/404.html +++ b/ui/litellm-dashboard/out/404.html @@ -1 +1 @@ -404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file +404: This page could not be found.LiteLLM Dashboard

404

This page could not be found.

\ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_buildManifest.js b/ui/litellm-dashboard/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_buildManifest.js similarity index 100% rename from ui/litellm-dashboard/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_buildManifest.js rename to ui/litellm-dashboard/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_buildManifest.js diff --git a/ui/litellm-dashboard/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_ssgManifest.js b/ui/litellm-dashboard/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_ssgManifest.js similarity index 100% rename from ui/litellm-dashboard/out/_next/static/fzhvjOFL6KeNsWYrLD4ya/_ssgManifest.js rename to ui/litellm-dashboard/out/_next/static/TGdu5EOOYr2m-EAOFIND0/_ssgManifest.js diff --git a/ui/litellm-dashboard/out/_next/static/chunks/250-7d480872c0e251dc.js b/ui/litellm-dashboard/out/_next/static/chunks/250-7d480872c0e251dc.js deleted file mode 100644 index 3fb93afc11..0000000000 --- a/ui/litellm-dashboard/out/_next/static/chunks/250-7d480872c0e251dc.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[250],{19250:function(e,t,o){o.d(t,{$I:function(){return K},AZ:function(){return D},Au:function(){return em},BL:function(){return eU},Br:function(){return b},E9:function(){return eZ},EB:function(){return te},EG:function(){return eX},EY:function(){return eK},Eb:function(){return C},FC:function(){return ei},Gh:function(){return eO},H1:function(){return v},H2:function(){return n},Hx:function(){return eg},I1:function(){return j},It:function(){return x},J$:function(){return ea},K8:function(){return d},K_:function(){return eY},LY:function(){return eI},Lp:function(){return eG},N3:function(){return eN},N8:function(){return ee},NL:function(){return e1},NV:function(){return f},Nc:function(){return ex},O3:function(){return eV},OD:function(){return e_},OU:function(){return eh},Of:function(){return S},Og:function(){return y},Ov:function(){return E},PT:function(){return X},Qg:function(){return eS},RQ:function(){return _},Rg:function(){return Q},Sb:function(){return eJ},So:function(){return et},TF:function(){return ta},Tj:function(){return e$},UM:function(){return e7},VA:function(){return G},Vt:function(){return eD},W_:function(){return V},X:function(){return er},XO:function(){return k},Xd:function(){return eT},Xm:function(){return F},YU:function(){return eL},Yo:function(){return J},Z9:function(){return R},Zr:function(){return m},a6:function(){return O},aC:function(){return to},ao:function(){return eq},b1:function(){return ed},cq:function(){return A},cu:function(){return eP},eH:function(){return Y},eZ:function(){return eF},fE:function(){return e8},fP:function(){return W},g:function(){return eQ},gX:function(){return eb},h3:function(){return es},hT:function(){return ej},hy:function(){return u},ix:function(){return H},j2:function(){return en},jA:function(){return eH},jE:function(){return ez},kK:function(){return p},kn:function(){return q},lP:function(){return h},lU:function(){return e4},lg:function(){return eE},mC:function(){return e9},mR:function(){return eo},mY:function(){return e5},m_:function(){return U},mp:function(){return eM},n$:function(){return ey},n9:function(){return e6},nd:function(){return e3},o6:function(){return $},oC:function(){return eC},ol:function(){return z},pf:function(){return eR},qI:function(){return g},qk:function(){return e0},qm:function(){return w},r1:function(){return tt},r6:function(){return B},rs:function(){return N},s0:function(){return L},sN:function(){return ev},t$:function(){return P},t0:function(){return ek},t3:function(){return eW},tB:function(){return e2},tN:function(){return el},u5:function(){return ec},um:function(){return eB},v9:function(){return ef},vh:function(){return eA},wX:function(){return T},wd:function(){return ew},xA:function(){return eu},xX:function(){return I},zg:function(){return ep}});var a=o(20347),r=o(41021);let n=null;console.log=function(){};let c=0,s=e=>new Promise(t=>setTimeout(t,e)),i=async e=>{let t=Date.now();t-c>6e4?(e.includes("Authentication Error - Expired Key")&&(r.ZP.info("UI Session Expired. Logging out."),c=t,await s(3e3),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",window.location.href="/"),c=t):console.log("Error suppressed to prevent spam:",e)},l="Authorization";function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Authorization";console.log("setGlobalLitellmHeaderName: ".concat(e)),l=e}let h=async()=>{let e=n?"".concat(n,"/openapi.json"):"/openapi.json",t=await fetch(e);return await t.json()},w=async e=>{try{let t=n?"".concat(n,"/get/litellm_model_cost_map"):"/get/litellm_model_cost_map",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}}),a=await o.json();return console.log("received litellm model cost data: ".concat(a)),a}catch(e){throw console.error("Failed to get model cost map:",e),e}},p=async(e,t)=>{try{let o=n?"".concat(n,"/model/new"):"/model/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text()||"Network response was not ok";throw r.ZP.error(e),Error(e)}let c=await a.json();return console.log("API Response:",c),r.ZP.destroy(),r.ZP.success("Model ".concat(t.model_name," created successfully"),2),c}catch(e){throw console.error("Failed to create key:",e),e}},u=async e=>{try{let t=n?"".concat(n,"/model/settings"):"/model/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){console.error("Failed to get model settings:",e)}},y=async(e,t)=>{console.log("model_id in model delete call: ".concat(t));try{let o=n?"".concat(n,"/model/delete"):"/model/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},f=async(e,t)=>{if(console.log("budget_id in budget delete call: ".concat(t)),null!=e)try{let o=n?"".concat(n,"/budget/delete"):"/budget/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},m=async(e,t)=>{try{console.log("Form Values in budgetCreateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/new"):"/budget/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},g=async(e,t)=>{try{console.log("Form Values in budgetUpdateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/update"):"/budget/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},k=async(e,t)=>{try{let o=n?"".concat(n,"/invitation/new"):"/invitation/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},_=async e=>{try{let t=n?"".concat(n,"/alerting/settings"):"/alerting/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},T=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/key/generate"):"/key/generate",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},E=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.auto_create_key=!1,o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/user/new"):"/user/new",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},j=async(e,t)=>{try{let o=n?"".concat(n,"/key/delete"):"/key/delete";console.log("in keyDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},C=async(e,t)=>{try{let o=n?"".concat(n,"/user/delete"):"/user/delete";console.log("in userDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_ids:t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete user(s):",e),e}},N=async(e,t)=>{try{let o=n?"".concat(n,"/team/delete"):"/team/delete";console.log("in teamDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},S=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,h=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null,w=arguments.length>9&&void 0!==arguments[9]?arguments[9]:null;try{let p=n?"".concat(n,"/user/list"):"/user/list";console.log("in userListCall");let u=new URLSearchParams;if(t&&t.length>0){let e=t.join(",");u.append("user_ids",e)}o&&u.append("page",o.toString()),a&&u.append("page_size",a.toString()),r&&u.append("user_email",r),c&&u.append("role",c),s&&u.append("team",s),d&&u.append("sso_user_ids",d),h&&u.append("sort_by",h),w&&u.append("sort_order",w);let y=u.toString();y&&(p+="?".concat(y));let f=await fetch(p,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!f.ok){let e=await f.text();throw i(e),Error("Network response was not ok")}let m=await f.json();return console.log("/user/list API Response:",m),m}catch(e){throw console.error("Failed to create key:",e),e}},b=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,c=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];console.log("userInfoCall: ".concat(t,", ").concat(o,", ").concat(a,", ").concat(r,", ").concat(c,", ").concat(s));try{let d;if(a){d=n?"".concat(n,"/user/list"):"/user/list";let e=new URLSearchParams;null!=r&&e.append("page",r.toString()),null!=c&&e.append("page_size",c.toString()),d+="?".concat(e.toString())}else d=n?"".concat(n,"/user/info"):"/user/info",("Admin"!==o&&"Admin Viewer"!==o||s)&&t&&(d+="?user_id=".concat(t));console.log("Requesting user data from:",d);let h=await fetch(d,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}let w=await h.json();return console.log("API Response:",w),w}catch(e){throw console.error("Failed to fetch user data:",e),e}},F=async(e,t)=>{try{let o=n?"".concat(n,"/team/info"):"/team/info";t&&(o="".concat(o,"?team_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},x=async function(e,t){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;try{let a=n?"".concat(n,"/team/list"):"/team/list";console.log("in teamInfoCall");let r=new URLSearchParams;o&&r.append("user_id",o.toString()),t&&r.append("organization_id",t.toString());let c=r.toString();c&&(a+="?".concat(c));let s=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log("/team/list API Response:",d),d}catch(e){throw console.error("Failed to create key:",e),e}},O=async e=>{try{let t=n?"".concat(n,"/team/available"):"/team/available";console.log("in availableTeamListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/team/available_teams API Response:",a),a}catch(e){throw e}},B=async e=>{try{let t=n?"".concat(n,"/organization/list"):"/organization/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},P=async(e,t)=>{try{let o=n?"".concat(n,"/organization/info"):"/organization/info";t&&(o="".concat(o,"?organization_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},v=async(e,t)=>{try{if(console.log("Form Values in organizationCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw console.error("Failed to parse metadata:",e),Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/organization/new"):"/organization/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},G=async(e,t)=>{try{console.log("Form Values in organizationUpdateCall:",t);let o=n?"".concat(n,"/organization/update"):"/organization/update",a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},A=async(e,t)=>{try{let o=n?"".concat(n,"/organization/delete"):"/organization/delete",a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Error deleting organization: ".concat(e))}return await a.json()}catch(e){throw console.error("Failed to delete organization:",e),e}},J=async(e,t)=>{try{let o=n?"".concat(n,"/utils/transform_request"):"/utils/transform_request",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},I=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;try{let r=n?"".concat(n,"/user/daily/activity"):"/user/daily/activity",c=new URLSearchParams;c.append("start_date",t.toISOString()),c.append("end_date",o.toISOString()),c.append("page_size","1000"),c.append("page",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}return await d.json()}catch(e){throw console.error("Failed to create key:",e),e}},R=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/tag/daily/activity"):"/tag/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("tags",r.join(","));let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},z=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/team/daily/activity"):"/team/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("team_ids",r.join(",")),s.append("exclude_team_ids","litellm-dashboard");let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},V=async e=>{try{let t=n?"".concat(n,"/onboarding/get_token"):"/onboarding/get_token";t+="?invite_link=".concat(e);let o=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},U=async(e,t,o,a)=>{let r=n?"".concat(n,"/onboarding/claim_token"):"/onboarding/claim_token";try{let n=await fetch(r,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({invitation_link:t,user_id:o,password:a})});if(!n.ok){let e=await n.text();throw i(e),Error("Network response was not ok")}let c=await n.json();return console.log(c),c}catch(e){throw console.error("Failed to delete key:",e),e}},L=async(e,t,o)=>{try{let a=n?"".concat(n,"/key/").concat(t,"/regenerate"):"/key/".concat(t,"/regenerate"),r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Regenerate key Response:",c),c}catch(e){throw console.error("Failed to regenerate key:",e),e}},M=!1,Z=null,D=async(e,t,o)=>{try{console.log("modelInfoCall:",e,t,o);let c=n?"".concat(n,"/v2/model/info"):"/v2/model/info";a.ZL.includes(o)||(c+="?user_models_only=true");let s=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw e+="error shown=".concat(M),M||(e.includes("No model list passed")&&(e="No Models Exist. Click Add Model to get started."),r.ZP.info(e,10),M=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{M=!1},1e4)),Error("Network response was not ok")}let i=await s.json();return console.log("modelInfoCall:",i),i}catch(e){throw console.error("Failed to create key:",e),e}},H=async(e,t)=>{try{let o=n?"".concat(n,"/v1/model/info"):"/v1/model/info";o+="?litellm_model_id=".concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");let r=await a.json();return console.log("modelInfoV1Call:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},q=async e=>{try{let t=n?"".concat(n,"/model_group/info"):"/model_group/info",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("modelHubCall:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},X=async e=>{try{let t=n?"".concat(n,"/get/allowed_ips"):"/get/allowed_ips",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw Error("Network response was not ok: ".concat(e))}let a=await o.json();return console.log("getAllowedIPs:",a),a.data}catch(e){throw console.error("Failed to get allowed IPs:",e),e}},Y=async(e,t)=>{try{let o=n?"".concat(n,"/add/allowed_ip"):"/add/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("addAllowedIP:",r),r}catch(e){throw console.error("Failed to add allowed IP:",e),e}},K=async(e,t)=>{try{let o=n?"".concat(n,"/delete/allowed_ip"):"/delete/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("deleteAllowedIP:",r),r}catch(e){throw console.error("Failed to delete allowed IP:",e),e}},$=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics"):"/model/metrics";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},Q=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/model/streaming_metrics"):"/model/streaming_metrics";t&&(r="".concat(r,"?_selected_model_group=").concat(t,"&startTime=").concat(o,"&endTime=").concat(a));let c=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},W=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/slow_responses"):"/model/metrics/slow_responses";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},ee=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/exceptions"):"/model/metrics/exceptions";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},et=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;console.log("in /models calls, globalLitellmHeaderName",l);try{let t=n?"".concat(n,"/models"):"/models",o=new URLSearchParams;!0===a&&o.append("return_wildcard_routes","True"),r&&o.append("team_id",r.toString()),o.toString()&&(t+="?".concat(o.toString()));let c=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},eo=async e=>{try{let t=n?"".concat(n,"/global/spend/teams"):"/global/spend/teams";console.log("in teamSpendLogsCall:",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ea=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/tags"):"/global/spend/tags";t&&o&&(r="".concat(r,"?start_date=").concat(t,"&end_date=").concat(o)),a&&(r+="".concat(r,"&tags=").concat(a.join(","))),console.log("in tagsSpendLogsCall:",r);let c=await fetch("".concat(r),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to create key:",e),e}},er=async e=>{try{let t=n?"".concat(n,"/global/spend/all_tag_names"):"/global/spend/all_tag_names";console.log("in global/spend/all_tag_names call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},en=async e=>{try{let t=n?"".concat(n,"/global/all_end_users"):"/global/all_end_users";console.log("in global/all_end_users call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ec=async(e,t)=>{try{let o=n?"".concat(n,"/user/filter/ui"):"/user/filter/ui";t.get("user_email")&&(o+="?user_email=".concat(t.get("user_email"))),t.get("user_id")&&(o+="?user_id=".concat(t.get("user_id")));let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},es=async(e,t,o,a,r,c,s,d,h)=>{try{let w=n?"".concat(n,"/spend/logs/ui"):"/spend/logs/ui",p=new URLSearchParams;t&&p.append("api_key",t),o&&p.append("team_id",o),a&&p.append("request_id",a),r&&p.append("start_date",r),c&&p.append("end_date",c),s&&p.append("page",s.toString()),d&&p.append("page_size",d.toString()),h&&p.append("user_id",h);let u=p.toString();u&&(w+="?".concat(u));let y=await fetch(w,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!y.ok){let e=await y.text();throw i(e),Error("Network response was not ok")}let f=await y.json();return console.log("Spend Logs Response:",f),f}catch(e){throw console.error("Failed to fetch spend logs:",e),e}},ei=async e=>{try{let t=n?"".concat(n,"/global/spend/logs"):"/global/spend/logs",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},el=async e=>{try{let t=n?"".concat(n,"/global/spend/keys?limit=5"):"/global/spend/keys?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ed=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/end_users"):"/global/spend/end_users",c="";c=t?JSON.stringify({api_key:t,startTime:o,endTime:a}):JSON.stringify({startTime:o,endTime:a});let s={method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:c},d=await fetch(r,s);if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log(h),h}catch(e){throw console.error("Failed to create key:",e),e}},eh=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/provider"):"/global/spend/provider";o&&a&&(r+="?start_date=".concat(o,"&end_date=").concat(a)),t&&(r+="&api_key=".concat(t));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log(d),d}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ew=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity"):"/global/activity";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ep=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/cache_hits"):"/global/activity/cache_hits";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},eu=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/model"):"/global/activity/model";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ey=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions"):"/global/activity/exceptions";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ef=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions/deployment"):"/global/activity/exceptions/deployment";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},em=async e=>{try{let t=n?"".concat(n,"/global/spend/models?limit=5"):"/global/spend/models?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},eg=async(e,t,o)=>{try{console.log("Sending model connection test request:",JSON.stringify(t));let r=n?"".concat(n,"/health/test_connection"):"/health/test_connection",c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",[l]:"Bearer ".concat(e)},body:JSON.stringify({litellm_params:t,mode:o})}),s=c.headers.get("content-type");if(!s||!s.includes("application/json")){let e=await c.text();throw console.error("Received non-JSON response:",e),Error("Received non-JSON response (".concat(c.status,": ").concat(c.statusText,"). Check network tab for details."))}let i=await c.json();if(!c.ok||"error"===i.status){if("error"===i.status);else{var a;return{status:"error",message:(null===(a=i.error)||void 0===a?void 0:a.message)||"Connection test failed: ".concat(c.status," ").concat(c.statusText)}}}return i}catch(e){throw console.error("Model connection test error:",e),e}},ek=async(e,t)=>{try{console.log("entering keyInfoV1Call");let o=n?"".concat(n,"/key/info"):"/key/info";o="".concat(o,"?key=").concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(console.log("response",a),!a.ok){let e=await a.text();i(e),r.ZP.error("Failed to fetch key info - "+e)}let c=await a.json();return console.log("data",c),c}catch(e){throw console.error("Failed to fetch key info:",e),e}},e_=async(e,t,o,a,r,c)=>{try{let s=n?"".concat(n,"/key/list"):"/key/list";console.log("in keyListCall");let d=new URLSearchParams;o&&d.append("team_id",o.toString()),t&&d.append("organization_id",t.toString()),a&&d.append("key_alias",a),r&&d.append("page",r.toString()),c&&d.append("size",c.toString()),d.append("return_full_object","true"),d.append("include_team_keys","true");let h=d.toString();h&&(s+="?".concat(h));let w=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!w.ok){let e=await w.text();throw i(e),Error("Network response was not ok")}let p=await w.json();return console.log("/team/list API Response:",p),p}catch(e){throw console.error("Failed to create key:",e),e}},eT=async(e,t)=>{try{let o=n?"".concat(n,"/user/get_users?role=").concat(t):"/user/get_users?role=".concat(t);console.log("in userGetAllUsersCall:",o);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to get requested models:",e),e}},eE=async e=>{try{let t=n?"".concat(n,"/user/available_roles"):"/user/available_roles",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("response from user/available_role",a),a}catch(e){throw e}},ej=async(e,t)=>{try{if(console.log("Form Values in teamCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/team/new"):"/team/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eC=async(e,t)=>{try{if(console.log("Form Values in credentialCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/credentials"):"/credentials",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eN=async e=>{try{let t=n?"".concat(n,"/credentials"):"/credentials";console.log("in credentialListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/credentials API Response:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},eS=async(e,t,o)=>{try{let a=n?"".concat(n,"/credentials"):"/credentials";t?a+="/by_name/".concat(t):o&&(a+="/by_model/".concat(o)),console.log("in credentialListCall");let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("/credentials API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eb=async(e,t)=>{try{let o=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t);console.log("in credentialDeleteCall:",t);let a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},eF=async(e,t,o)=>{try{if(console.log("Form Values in credentialUpdateCall:",o),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let a=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t),r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ex=async(e,t)=>{try{if(console.log("Form Values in keyUpdateCall:",t),t.model_tpm_limit){console.log("formValues.model_tpm_limit:",t.model_tpm_limit);try{t.model_tpm_limit=JSON.parse(t.model_tpm_limit)}catch(e){throw Error("Failed to parse model_tpm_limit: "+e)}}if(t.model_rpm_limit){console.log("formValues.model_rpm_limit:",t.model_rpm_limit);try{t.model_rpm_limit=JSON.parse(t.model_rpm_limit)}catch(e){throw Error("Failed to parse model_rpm_limit: "+e)}}let o=n?"".concat(n,"/key/update"):"/key/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update key Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eO=async(e,t)=>{try{console.log("Form Values in teamUpateCall:",t);let o=n?"".concat(n,"/team/update"):"/team/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eB=async(e,t)=>{try{console.log("Form Values in modelUpateCall:",t);let o=n?"".concat(n,"/model/update"):"/model/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error update from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update model Response:",r),r}catch(e){throw console.error("Failed to update model:",e),e}},eP=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_add"):"/team/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},ev=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_update"):"/team/member_update",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,role:o.role,user_id:o.user_id})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eG=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_delete"):"/team/member_delete",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,...void 0!==o.user_email&&{user_email:o.user_email},...void 0!==o.user_id&&{user_id:o.user_id}})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eA=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/organization/member_add"):"/organization/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create organization member:",e),e}},eJ=async(e,t,o)=>{try{console.log("Form Values in organizationMemberDeleteCall:",o);let a=n?"".concat(n,"/organization/member_delete"):"/organization/member_delete",r=await fetch(a,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,user_id:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to delete organization member:",e),e}},eI=async(e,t,o)=>{try{console.log("Form Values in organizationMemberUpdateCall:",o);let a=n?"".concat(n,"/organization/member_update"):"/organization/member_update",r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to update organization member:",e),e}},eR=async(e,t,o)=>{try{console.log("Form Values in userUpdateUserCall:",t);let a=n?"".concat(n,"/user/update"):"/user/update",r={...t};null!==o&&(r.user_role=o),r=JSON.stringify(r);let c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:r});if(!c.ok){let e=await c.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let s=await c.json();return console.log("API Response:",s),s}catch(e){throw console.error("Failed to create key:",e),e}},ez=async(e,t)=>{try{let o=n?"".concat(n,"/health/services?service=").concat(t):"/health/services?service=".concat(t);console.log("Checking Slack Budget Alerts service health");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error(e)}let c=await a.json();return r.ZP.success("Test request to ".concat(t," made - check logs/alerts on ").concat(t," to verify")),c}catch(e){throw console.error("Failed to perform health check:",e),e}},eV=async e=>{try{let t=n?"".concat(n,"/budget/list"):"/budget/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eU=async(e,t,o)=>{try{let t=n?"".concat(n,"/get/config/callbacks"):"/get/config/callbacks",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eL=async e=>{try{let t=n?"".concat(n,"/config/list?config_type=general_settings"):"/config/list?config_type=general_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eM=async e=>{try{let t=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eZ=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/info?field_name=").concat(t):"/config/field/info?field_name=".concat(t),a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eD=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eH=async(e,t,o)=>{try{let a=n?"".concat(n,"/config/field/update"):"/config/field/update",c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,field_value:o,config_type:"general_settings"})});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}let s=await c.json();return r.ZP.success("Successfully updated value!"),s}catch(e){throw console.error("Failed to set callbacks:",e),e}},eq=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/delete"):"/config/field/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,config_type:"general_settings"})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return r.ZP.success("Field reset on proxy"),c}catch(e){throw console.error("Failed to get callbacks:",e),e}},eX=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint?endpoint_id=").concat(t):"/config/pass_through_endpoint".concat(t),a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eY=async(e,t)=>{try{let o=n?"".concat(n,"/config/update"):"/config/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eK=async e=>{try{let t=n?"".concat(n,"/health"):"/health",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to call /health:",e),e}},e$=async e=>{try{let t=n?"".concat(n,"/cache/ping"):"/cache/ping",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error(e)}return await o.json()}catch(e){throw console.error("Failed to call /cache/ping:",e),e}},eQ=async e=>{try{let t=n?"".concat(n,"/sso/get/ui_settings"):"/sso/get/ui_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eW=async e=>{try{let t=n?"".concat(n,"/guardrails/list"):"/guardrails/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Guardrails list response:",a),a}catch(e){throw console.error("Failed to fetch guardrails list:",e),e}},e0=async(e,t,o)=>{try{let a=n?"".concat(n,"/spend/logs/ui/").concat(t,"?start_date=").concat(encodeURIComponent(o)):"/spend/logs/ui/".concat(t,"?start_date=").concat(encodeURIComponent(o));console.log("Fetching log details from:",a);let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Fetched log details:",c),c}catch(e){throw console.error("Failed to fetch log details:",e),e}},e1=async e=>{try{let t=n?"".concat(n,"/get/internal_user_settings"):"/get/internal_user_settings";console.log("Fetching SSO settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched SSO settings:",a),a}catch(e){throw console.error("Failed to fetch SSO settings:",e),e}},e3=async(e,t)=>{try{let o=n?"".concat(n,"/update/internal_user_settings"):"/update/internal_user_settings";console.log("Updating internal user settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated internal user settings:",c),r.ZP.success("Internal user settings updated successfully"),c}catch(e){throw console.error("Failed to update internal user settings:",e),e}},e4=async e=>{try{let t=n?"".concat(n,"/mcp/tools/list"):"/mcp/tools/list";console.log("Fetching MCP tools from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched MCP tools:",a),a}catch(e){throw console.error("Failed to fetch MCP tools:",e),e}},e2=async(e,t,o)=>{try{let a=n?"".concat(n,"/mcp/tools/call"):"/mcp/tools/call";console.log("Calling MCP tool:",t,"with arguments:",o);let r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("MCP tool call response:",c),c}catch(e){throw console.error("Failed to call MCP tool:",e),e}},e5=async(e,t)=>{try{let o=n?"".concat(n,"/tag/new"):"/tag/new",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error creating tag:",e),e}},e6=async(e,t)=>{try{let o=n?"".concat(n,"/tag/update"):"/tag/update",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error updating tag:",e),e}},e9=async(e,t)=>{try{let o=n?"".concat(n,"/tag/info"):"/tag/info",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({names:t})});if(!a.ok){let e=await a.text();return await i(e),{}}return await a.json()}catch(e){throw console.error("Error getting tag info:",e),e}},e7=async e=>{try{let t=n?"".concat(n,"/tag/list"):"/tag/list",o=await fetch(t,{method:"GET",headers:{Authorization:"Bearer ".concat(e)}});if(!o.ok){let e=await o.text();return await i(e),{}}return await o.json()}catch(e){throw console.error("Error listing tags:",e),e}},e8=async(e,t)=>{try{let o=n?"".concat(n,"/tag/delete"):"/tag/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({name:t})});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error deleting tag:",e),e}},te=async e=>{try{let t=n?"".concat(n,"/get/default_team_settings"):"/get/default_team_settings";console.log("Fetching default team settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched default team settings:",a),a}catch(e){throw console.error("Failed to fetch default team settings:",e),e}},tt=async(e,t)=>{try{let o=n?"".concat(n,"/update/default_team_settings"):"/update/default_team_settings";console.log("Updating default team settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated default team settings:",c),r.ZP.success("Default team settings updated successfully"),c}catch(e){throw console.error("Failed to update default team settings:",e),e}},to=async(e,t)=>{try{let o=n?"".concat(n,"/team/permissions_list?team_id=").concat(t):"/team/permissions_list?team_id=".concat(t),a=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("Team permissions response:",r),r}catch(e){throw console.error("Failed to get team permissions:",e),e}},ta=async(e,t,o)=>{try{let a=n?"".concat(n,"/team/permissions_update"):"/team/permissions_update",r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({team_id:t,team_member_permissions:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Team permissions response:",c),c}catch(e){throw console.error("Failed to update team permissions:",e),e}}},20347:function(e,t,o){o.d(t,{LQ:function(){return n},ZL:function(){return a},lo:function(){return r},tY:function(){return c}});let a=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],r=["Internal User","Internal Viewer"],n=["Internal User","Admin"],c=e=>a.includes(e)}}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js b/ui/litellm-dashboard/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js new file mode 100644 index 0000000000..d058e3dd01 --- /dev/null +++ b/ui/litellm-dashboard/out/_next/static/chunks/250-85fb4e9c2fdebf3e.js @@ -0,0 +1 @@ +"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[250],{19250:function(e,t,o){o.d(t,{$I:function(){return K},AZ:function(){return D},Au:function(){return em},BL:function(){return eL},Br:function(){return b},E9:function(){return eD},EB:function(){return tt},EG:function(){return eY},EY:function(){return e$},Eb:function(){return C},FC:function(){return ei},Gh:function(){return eB},H1:function(){return v},H2:function(){return n},Hx:function(){return ek},I1:function(){return j},It:function(){return x},J$:function(){return ea},K8:function(){return d},K_:function(){return eK},LY:function(){return eR},Lp:function(){return eA},N3:function(){return eS},N8:function(){return ee},NL:function(){return e3},NV:function(){return f},Nc:function(){return eO},O3:function(){return eU},OD:function(){return eT},OU:function(){return eh},Of:function(){return S},Og:function(){return y},Ov:function(){return E},PT:function(){return X},Qg:function(){return eb},RQ:function(){return _},Rg:function(){return Q},Sb:function(){return eI},So:function(){return et},TF:function(){return tr},Tj:function(){return eQ},UM:function(){return e8},VA:function(){return G},Vt:function(){return eH},W_:function(){return V},X:function(){return er},XO:function(){return k},Xd:function(){return eE},Xm:function(){return F},YU:function(){return eM},Yo:function(){return J},Z9:function(){return R},Zr:function(){return m},a6:function(){return O},aC:function(){return ta},ao:function(){return eX},b1:function(){return ed},cq:function(){return A},cu:function(){return ev},e2:function(){return eg},eH:function(){return Y},eZ:function(){return ex},fE:function(){return te},fP:function(){return W},g:function(){return eW},gX:function(){return eF},h3:function(){return es},hT:function(){return eC},hy:function(){return u},ix:function(){return H},j2:function(){return en},jA:function(){return eq},jE:function(){return eV},kK:function(){return p},kn:function(){return q},lP:function(){return h},lU:function(){return e4},lg:function(){return ej},mC:function(){return e7},mR:function(){return eo},mY:function(){return e6},m_:function(){return U},mp:function(){return eZ},n$:function(){return ey},n9:function(){return e9},nd:function(){return e2},o6:function(){return $},oC:function(){return eN},ol:function(){return z},pf:function(){return ez},qI:function(){return g},qk:function(){return e1},qm:function(){return w},r1:function(){return to},r6:function(){return B},rs:function(){return N},s0:function(){return L},sN:function(){return eG},t$:function(){return P},t0:function(){return e_},t3:function(){return e0},tB:function(){return e5},tN:function(){return el},u5:function(){return ec},um:function(){return eP},v9:function(){return ef},vh:function(){return eJ},wX:function(){return T},wd:function(){return ew},xA:function(){return eu},xX:function(){return I},zg:function(){return ep}});var a=o(20347),r=o(41021);let n=null;console.log=function(){};let c=0,s=e=>new Promise(t=>setTimeout(t,e)),i=async e=>{let t=Date.now();t-c>6e4?(e.includes("Authentication Error - Expired Key")&&(r.ZP.info("UI Session Expired. Logging out."),c=t,await s(3e3),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",window.location.href="/"),c=t):console.log("Error suppressed to prevent spam:",e)},l="Authorization";function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Authorization";console.log("setGlobalLitellmHeaderName: ".concat(e)),l=e}let h=async()=>{let e=n?"".concat(n,"/openapi.json"):"/openapi.json",t=await fetch(e);return await t.json()},w=async e=>{try{let t=n?"".concat(n,"/get/litellm_model_cost_map"):"/get/litellm_model_cost_map",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}}),a=await o.json();return console.log("received litellm model cost data: ".concat(a)),a}catch(e){throw console.error("Failed to get model cost map:",e),e}},p=async(e,t)=>{try{let o=n?"".concat(n,"/model/new"):"/model/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text()||"Network response was not ok";throw r.ZP.error(e),Error(e)}let c=await a.json();return console.log("API Response:",c),r.ZP.destroy(),r.ZP.success("Model ".concat(t.model_name," created successfully"),2),c}catch(e){throw console.error("Failed to create key:",e),e}},u=async e=>{try{let t=n?"".concat(n,"/model/settings"):"/model/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){console.error("Failed to get model settings:",e)}},y=async(e,t)=>{console.log("model_id in model delete call: ".concat(t));try{let o=n?"".concat(n,"/model/delete"):"/model/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},f=async(e,t)=>{if(console.log("budget_id in budget delete call: ".concat(t)),null!=e)try{let o=n?"".concat(n,"/budget/delete"):"/budget/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},m=async(e,t)=>{try{console.log("Form Values in budgetCreateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/new"):"/budget/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},g=async(e,t)=>{try{console.log("Form Values in budgetUpdateCall:",t),console.log("Form Values after check:",t);let o=n?"".concat(n,"/budget/update"):"/budget/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},k=async(e,t)=>{try{let o=n?"".concat(n,"/invitation/new"):"/invitation/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},_=async e=>{try{let t=n?"".concat(n,"/alerting/settings"):"/alerting/settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},T=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/key/generate"):"/key/generate",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},E=async(e,t,o)=>{try{if(console.log("Form Values in keyCreateCall:",o),o.description&&(o.metadata||(o.metadata={}),o.metadata.description=o.description,delete o.description,o.metadata=JSON.stringify(o.metadata)),o.auto_create_key=!1,o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}console.log("Form Values after check:",o);let a=n?"".concat(n,"/user/new"):"/user/new",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},j=async(e,t)=>{try{let o=n?"".concat(n,"/key/delete"):"/key/delete";console.log("in keyDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},C=async(e,t)=>{try{let o=n?"".concat(n,"/user/delete"):"/user/delete";console.log("in userDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({user_ids:t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete user(s):",e),e}},N=async(e,t)=>{try{let o=n?"".concat(n,"/team/delete"):"/team/delete";console.log("in teamDeleteCall:",t);let a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},S=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null,c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:null,s=arguments.length>6&&void 0!==arguments[6]?arguments[6]:null,d=arguments.length>7&&void 0!==arguments[7]?arguments[7]:null,h=arguments.length>8&&void 0!==arguments[8]?arguments[8]:null,w=arguments.length>9&&void 0!==arguments[9]?arguments[9]:null;try{let p=n?"".concat(n,"/user/list"):"/user/list";console.log("in userListCall");let u=new URLSearchParams;if(t&&t.length>0){let e=t.join(",");u.append("user_ids",e)}o&&u.append("page",o.toString()),a&&u.append("page_size",a.toString()),r&&u.append("user_email",r),c&&u.append("role",c),s&&u.append("team",s),d&&u.append("sso_user_ids",d),h&&u.append("sort_by",h),w&&u.append("sort_order",w);let y=u.toString();y&&(p+="?".concat(y));let f=await fetch(p,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!f.ok){let e=await f.text();throw i(e),Error("Network response was not ok")}let m=await f.json();return console.log("/user/list API Response:",m),m}catch(e){throw console.error("Failed to create key:",e),e}},b=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4?arguments[4]:void 0,c=arguments.length>5?arguments[5]:void 0,s=arguments.length>6&&void 0!==arguments[6]&&arguments[6];console.log("userInfoCall: ".concat(t,", ").concat(o,", ").concat(a,", ").concat(r,", ").concat(c,", ").concat(s));try{let d;if(a){d=n?"".concat(n,"/user/list"):"/user/list";let e=new URLSearchParams;null!=r&&e.append("page",r.toString()),null!=c&&e.append("page_size",c.toString()),d+="?".concat(e.toString())}else d=n?"".concat(n,"/user/info"):"/user/info",("Admin"!==o&&"Admin Viewer"!==o||s)&&t&&(d+="?user_id=".concat(t));console.log("Requesting user data from:",d);let h=await fetch(d,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}let w=await h.json();return console.log("API Response:",w),w}catch(e){throw console.error("Failed to fetch user data:",e),e}},F=async(e,t)=>{try{let o=n?"".concat(n,"/team/info"):"/team/info";t&&(o="".concat(o,"?team_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},x=async function(e,t){let o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:null;try{let a=n?"".concat(n,"/team/list"):"/team/list";console.log("in teamInfoCall");let r=new URLSearchParams;o&&r.append("user_id",o.toString()),t&&r.append("organization_id",t.toString());let c=r.toString();c&&(a+="?".concat(c));let s=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log("/team/list API Response:",d),d}catch(e){throw console.error("Failed to create key:",e),e}},O=async e=>{try{let t=n?"".concat(n,"/team/available"):"/team/available";console.log("in availableTeamListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/team/available_teams API Response:",a),a}catch(e){throw e}},B=async e=>{try{let t=n?"".concat(n,"/organization/list"):"/organization/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},P=async(e,t)=>{try{let o=n?"".concat(n,"/organization/info"):"/organization/info";t&&(o="".concat(o,"?organization_id=").concat(t)),console.log("in teamInfoCall");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},v=async(e,t)=>{try{if(console.log("Form Values in organizationCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw console.error("Failed to parse metadata:",e),Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/organization/new"):"/organization/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},G=async(e,t)=>{try{console.log("Form Values in organizationUpdateCall:",t);let o=n?"".concat(n,"/organization/update"):"/organization/update",a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},A=async(e,t)=>{try{let o=n?"".concat(n,"/organization/delete"):"/organization/delete",a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_ids:[t]})});if(!a.ok){let e=await a.text();throw i(e),Error("Error deleting organization: ".concat(e))}return await a.json()}catch(e){throw console.error("Failed to delete organization:",e),e}},J=async(e,t)=>{try{let o=n?"".concat(n,"/utils/transform_request"):"/utils/transform_request",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},I=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;try{let r=n?"".concat(n,"/user/daily/activity"):"/user/daily/activity",c=new URLSearchParams;c.append("start_date",t.toISOString()),c.append("end_date",o.toISOString()),c.append("page_size","1000"),c.append("page",a.toString());let s=c.toString();s&&(r+="?".concat(s));let d=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}return await d.json()}catch(e){throw console.error("Failed to create key:",e),e}},R=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/tag/daily/activity"):"/tag/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("tags",r.join(","));let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},z=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;try{let c=n?"".concat(n,"/team/daily/activity"):"/team/daily/activity",s=new URLSearchParams;s.append("start_date",t.toISOString()),s.append("end_date",o.toISOString()),s.append("page_size","1000"),s.append("page",a.toString()),r&&s.append("team_ids",r.join(",")),s.append("exclude_team_ids","litellm-dashboard");let d=s.toString();d&&(c+="?".concat(d));let h=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!h.ok){let e=await h.text();throw i(e),Error("Network response was not ok")}return await h.json()}catch(e){throw console.error("Failed to create key:",e),e}},V=async e=>{try{let t=n?"".concat(n,"/onboarding/get_token"):"/onboarding/get_token";t+="?invite_link=".concat(e);let o=await fetch(t,{method:"GET",headers:{"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},U=async(e,t,o,a)=>{let r=n?"".concat(n,"/onboarding/claim_token"):"/onboarding/claim_token";try{let n=await fetch(r,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({invitation_link:t,user_id:o,password:a})});if(!n.ok){let e=await n.text();throw i(e),Error("Network response was not ok")}let c=await n.json();return console.log(c),c}catch(e){throw console.error("Failed to delete key:",e),e}},L=async(e,t,o)=>{try{let a=n?"".concat(n,"/key/").concat(t,"/regenerate"):"/key/".concat(t,"/regenerate"),r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(o)});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Regenerate key Response:",c),c}catch(e){throw console.error("Failed to regenerate key:",e),e}},M=!1,Z=null,D=async(e,t,o)=>{try{console.log("modelInfoCall:",e,t,o);let c=n?"".concat(n,"/v2/model/info"):"/v2/model/info";a.ZL.includes(o)||(c+="?user_models_only=true");let s=await fetch(c,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!s.ok){let e=await s.text();throw e+="error shown=".concat(M),M||(e.includes("No model list passed")&&(e="No Models Exist. Click Add Model to get started."),r.ZP.info(e,10),M=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{M=!1},1e4)),Error("Network response was not ok")}let i=await s.json();return console.log("modelInfoCall:",i),i}catch(e){throw console.error("Failed to create key:",e),e}},H=async(e,t)=>{try{let o=n?"".concat(n,"/v1/model/info"):"/v1/model/info";o+="?litellm_model_id=".concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");let r=await a.json();return console.log("modelInfoV1Call:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},q=async e=>{try{let t=n?"".concat(n,"/model_group/info"):"/model_group/info",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("modelHubCall:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},X=async e=>{try{let t=n?"".concat(n,"/get/allowed_ips"):"/get/allowed_ips",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw Error("Network response was not ok: ".concat(e))}let a=await o.json();return console.log("getAllowedIPs:",a),a.data}catch(e){throw console.error("Failed to get allowed IPs:",e),e}},Y=async(e,t)=>{try{let o=n?"".concat(n,"/add/allowed_ip"):"/add/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("addAllowedIP:",r),r}catch(e){throw console.error("Failed to add allowed IP:",e),e}},K=async(e,t)=>{try{let o=n?"".concat(n,"/delete/allowed_ip"):"/delete/allowed_ip",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({ip:t})});if(!a.ok){let e=await a.text();throw Error("Network response was not ok: ".concat(e))}let r=await a.json();return console.log("deleteAllowedIP:",r),r}catch(e){throw console.error("Failed to delete allowed IP:",e),e}},$=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics"):"/model/metrics";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},Q=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/model/streaming_metrics"):"/model/streaming_metrics";t&&(r="".concat(r,"?_selected_model_group=").concat(t,"&startTime=").concat(o,"&endTime=").concat(a));let c=await fetch(r,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},W=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/slow_responses"):"/model/metrics/slow_responses";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},ee=async(e,t,o,a,r,c,s,d)=>{try{let t=n?"".concat(n,"/model/metrics/exceptions"):"/model/metrics/exceptions";a&&(t="".concat(t,"?_selected_model_group=").concat(a,"&startTime=").concat(r,"&endTime=").concat(c,"&api_key=").concat(s,"&customer=").concat(d));let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to create key:",e),e}},et=async function(e,t,o){let a=arguments.length>3&&void 0!==arguments[3]&&arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:null;console.log("in /models calls, globalLitellmHeaderName",l);try{let t=n?"".concat(n,"/models"):"/models",o=new URLSearchParams;!0===a&&o.append("return_wildcard_routes","True"),r&&o.append("team_id",r.toString()),o.toString()&&(t+="?".concat(o.toString()));let c=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}return await c.json()}catch(e){throw console.error("Failed to create key:",e),e}},eo=async e=>{try{let t=n?"".concat(n,"/global/spend/teams"):"/global/spend/teams";console.log("in teamSpendLogsCall:",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ea=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/tags"):"/global/spend/tags";t&&o&&(r="".concat(r,"?start_date=").concat(t,"&end_date=").concat(o)),a&&(r+="".concat(r,"&tags=").concat(a.join(","))),console.log("in tagsSpendLogsCall:",r);let c=await fetch("".concat(r),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to create key:",e),e}},er=async e=>{try{let t=n?"".concat(n,"/global/spend/all_tag_names"):"/global/spend/all_tag_names";console.log("in global/spend/all_tag_names call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},en=async e=>{try{let t=n?"".concat(n,"/global/all_end_users"):"/global/all_end_users";console.log("in global/all_end_users call",t);let o=await fetch("".concat(t),{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ec=async(e,t)=>{try{let o=n?"".concat(n,"/user/filter/ui"):"/user/filter/ui";t.get("user_email")&&(o+="?user_email=".concat(t.get("user_email"))),t.get("user_id")&&(o+="?user_id=".concat(t.get("user_id")));let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to create key:",e),e}},es=async(e,t,o,a,r,c,s,d,h)=>{try{let w=n?"".concat(n,"/spend/logs/ui"):"/spend/logs/ui",p=new URLSearchParams;t&&p.append("api_key",t),o&&p.append("team_id",o),a&&p.append("request_id",a),r&&p.append("start_date",r),c&&p.append("end_date",c),s&&p.append("page",s.toString()),d&&p.append("page_size",d.toString()),h&&p.append("user_id",h);let u=p.toString();u&&(w+="?".concat(u));let y=await fetch(w,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!y.ok){let e=await y.text();throw i(e),Error("Network response was not ok")}let f=await y.json();return console.log("Spend Logs Response:",f),f}catch(e){throw console.error("Failed to fetch spend logs:",e),e}},ei=async e=>{try{let t=n?"".concat(n,"/global/spend/logs"):"/global/spend/logs",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},el=async e=>{try{let t=n?"".concat(n,"/global/spend/keys?limit=5"):"/global/spend/keys?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},ed=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/end_users"):"/global/spend/end_users",c="";c=t?JSON.stringify({api_key:t,startTime:o,endTime:a}):JSON.stringify({startTime:o,endTime:a});let s={method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:c},d=await fetch(r,s);if(!d.ok){let e=await d.text();throw i(e),Error("Network response was not ok")}let h=await d.json();return console.log(h),h}catch(e){throw console.error("Failed to create key:",e),e}},eh=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/spend/provider"):"/global/spend/provider";o&&a&&(r+="?start_date=".concat(o,"&end_date=").concat(a)),t&&(r+="&api_key=".concat(t));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok){let e=await s.text();throw i(e),Error("Network response was not ok")}let d=await s.json();return console.log(d),d}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ew=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity"):"/global/activity";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ep=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/cache_hits"):"/global/activity/cache_hits";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},eu=async(e,t,o)=>{try{let a=n?"".concat(n,"/global/activity/model"):"/global/activity/model";t&&o&&(a+="?start_date=".concat(t,"&end_date=").concat(o));let r={method:"GET",headers:{[l]:"Bearer ".concat(e)}},c=await fetch(a,r);if(!c.ok)throw await c.text(),Error("Network response was not ok");let s=await c.json();return console.log(s),s}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ey=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions"):"/global/activity/exceptions";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},ef=async(e,t,o,a)=>{try{let r=n?"".concat(n,"/global/activity/exceptions/deployment"):"/global/activity/exceptions/deployment";t&&o&&(r+="?start_date=".concat(t,"&end_date=").concat(o)),a&&(r+="&model_group=".concat(a));let c={method:"GET",headers:{[l]:"Bearer ".concat(e)}},s=await fetch(r,c);if(!s.ok)throw await s.text(),Error("Network response was not ok");let i=await s.json();return console.log(i),i}catch(e){throw console.error("Failed to fetch spend data:",e),e}},em=async e=>{try{let t=n?"".concat(n,"/global/spend/models?limit=5"):"/global/spend/models?limit=5",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log(a),a}catch(e){throw console.error("Failed to create key:",e),e}},eg=async(e,t)=>{try{let o=n?"".concat(n,"/v2/key/info"):"/v2/key/info",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({keys:t})});if(!a.ok){let e=await a.text();if(e.includes("Invalid proxy server token passed"))throw Error("Invalid proxy server token passed");throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to create key:",e),e}},ek=async(e,t,o)=>{try{console.log("Sending model connection test request:",JSON.stringify(t));let r=n?"".concat(n,"/health/test_connection"):"/health/test_connection",c=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",[l]:"Bearer ".concat(e)},body:JSON.stringify({litellm_params:t,mode:o})}),s=c.headers.get("content-type");if(!s||!s.includes("application/json")){let e=await c.text();throw console.error("Received non-JSON response:",e),Error("Received non-JSON response (".concat(c.status,": ").concat(c.statusText,"). Check network tab for details."))}let i=await c.json();if(!c.ok||"error"===i.status){if("error"===i.status);else{var a;return{status:"error",message:(null===(a=i.error)||void 0===a?void 0:a.message)||"Connection test failed: ".concat(c.status," ").concat(c.statusText)}}}return i}catch(e){throw console.error("Model connection test error:",e),e}},e_=async(e,t)=>{try{console.log("entering keyInfoV1Call");let o=n?"".concat(n,"/key/info"):"/key/info";o="".concat(o,"?key=").concat(t);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(console.log("response",a),!a.ok){let e=await a.text();i(e),r.ZP.error("Failed to fetch key info - "+e)}let c=await a.json();return console.log("data",c),c}catch(e){throw console.error("Failed to fetch key info:",e),e}},eT=async(e,t,o,a,r,c)=>{try{let s=n?"".concat(n,"/key/list"):"/key/list";console.log("in keyListCall");let d=new URLSearchParams;o&&d.append("team_id",o.toString()),t&&d.append("organization_id",t.toString()),a&&d.append("key_alias",a),r&&d.append("page",r.toString()),c&&d.append("size",c.toString()),d.append("return_full_object","true"),d.append("include_team_keys","true");let h=d.toString();h&&(s+="?".concat(h));let w=await fetch(s,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!w.ok){let e=await w.text();throw i(e),Error("Network response was not ok")}let p=await w.json();return console.log("/team/list API Response:",p),p}catch(e){throw console.error("Failed to create key:",e),e}},eE=async(e,t)=>{try{let o=n?"".concat(n,"/user/get_users?role=").concat(t):"/user/get_users?role=".concat(t);console.log("in userGetAllUsersCall:",o);let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to get requested models:",e),e}},ej=async e=>{try{let t=n?"".concat(n,"/user/available_roles"):"/user/available_roles",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");let a=await o.json();return console.log("response from user/available_role",a),a}catch(e){throw e}},eC=async(e,t)=>{try{if(console.log("Form Values in teamCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/team/new"):"/team/new",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eN=async(e,t)=>{try{if(console.log("Form Values in credentialCreateCall:",t),t.metadata){console.log("formValues.metadata:",t.metadata);try{t.metadata=JSON.parse(t.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let o=n?"".concat(n,"/credentials"):"/credentials",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("API Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eS=async e=>{try{let t=n?"".concat(n,"/credentials"):"/credentials";console.log("in credentialListCall");let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("/credentials API Response:",a),a}catch(e){throw console.error("Failed to create key:",e),e}},eb=async(e,t,o)=>{try{let a=n?"".concat(n,"/credentials"):"/credentials";t?a+="/by_name/".concat(t):o&&(a+="/by_model/".concat(o)),console.log("in credentialListCall");let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("/credentials API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eF=async(e,t)=>{try{let o=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t);console.log("in credentialDeleteCall:",t);let a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log(r),r}catch(e){throw console.error("Failed to delete key:",e),e}},ex=async(e,t,o)=>{try{if(console.log("Form Values in credentialUpdateCall:",o),o.metadata){console.log("formValues.metadata:",o.metadata);try{o.metadata=JSON.parse(o.metadata)}catch(e){throw Error("Failed to parse metadata: "+e)}}let a=n?"".concat(n,"/credentials/").concat(t):"/credentials/".concat(t),r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eO=async(e,t)=>{try{if(console.log("Form Values in keyUpdateCall:",t),t.model_tpm_limit){console.log("formValues.model_tpm_limit:",t.model_tpm_limit);try{t.model_tpm_limit=JSON.parse(t.model_tpm_limit)}catch(e){throw Error("Failed to parse model_tpm_limit: "+e)}}if(t.model_rpm_limit){console.log("formValues.model_rpm_limit:",t.model_rpm_limit);try{t.model_rpm_limit=JSON.parse(t.model_rpm_limit)}catch(e){throw Error("Failed to parse model_rpm_limit: "+e)}}let o=n?"".concat(n,"/key/update"):"/key/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update key Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eB=async(e,t)=>{try{console.log("Form Values in teamUpateCall:",t);let o=n?"".concat(n,"/team/update"):"/team/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update Team Response:",r),r}catch(e){throw console.error("Failed to create key:",e),e}},eP=async(e,t)=>{try{console.log("Form Values in modelUpateCall:",t);let o=n?"".concat(n,"/model/update"):"/model/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),console.error("Error update from the server:",e),Error("Network response was not ok")}let r=await a.json();return console.log("Update model Response:",r),r}catch(e){throw console.error("Failed to update model:",e),e}},ev=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_add"):"/team/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eG=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_update"):"/team/member_update",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,role:o.role,user_id:o.user_id})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eA=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/team/member_delete"):"/team/member_delete",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({team_id:t,...void 0!==o.user_email&&{user_email:o.user_email},...void 0!==o.user_id&&{user_id:o.user_id}})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create key:",e),e}},eJ=async(e,t,o)=>{try{console.log("Form Values in teamMemberAddCall:",o);let a=n?"".concat(n,"/organization/member_add"):"/organization/member_add",r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,member:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error(e)}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to create organization member:",e),e}},eI=async(e,t,o)=>{try{console.log("Form Values in organizationMemberDeleteCall:",o);let a=n?"".concat(n,"/organization/member_delete"):"/organization/member_delete",r=await fetch(a,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,user_id:o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to delete organization member:",e),e}},eR=async(e,t,o)=>{try{console.log("Form Values in organizationMemberUpdateCall:",o);let a=n?"".concat(n,"/organization/member_update"):"/organization/member_update",r=await fetch(a,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({organization_id:t,...o})});if(!r.ok){let e=await r.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let c=await r.json();return console.log("API Response:",c),c}catch(e){throw console.error("Failed to update organization member:",e),e}},ez=async(e,t,o)=>{try{console.log("Form Values in userUpdateUserCall:",t);let a=n?"".concat(n,"/user/update"):"/user/update",r={...t};null!==o&&(r.user_role=o),r=JSON.stringify(r);let c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:r});if(!c.ok){let e=await c.text();throw i(e),console.error("Error response from the server:",e),Error("Network response was not ok")}let s=await c.json();return console.log("API Response:",s),s}catch(e){throw console.error("Failed to create key:",e),e}},eV=async(e,t)=>{try{let o=n?"".concat(n,"/health/services?service=").concat(t):"/health/services?service=".concat(t);console.log("Checking Slack Budget Alerts service health");let a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error(e)}let c=await a.json();return r.ZP.success("Test request to ".concat(t," made - check logs/alerts on ").concat(t," to verify")),c}catch(e){throw console.error("Failed to perform health check:",e),e}},eU=async e=>{try{let t=n?"".concat(n,"/budget/list"):"/budget/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eL=async(e,t,o)=>{try{let t=n?"".concat(n,"/get/config/callbacks"):"/get/config/callbacks",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eM=async e=>{try{let t=n?"".concat(n,"/config/list?config_type=general_settings"):"/config/list?config_type=general_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eZ=async e=>{try{let t=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eD=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/info?field_name=").concat(t):"/config/field/info?field_name=".concat(t),a=await fetch(o,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok)throw await a.text(),Error("Network response was not ok");return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eH=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint"):"/config/pass_through_endpoint",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},eq=async(e,t,o)=>{try{let a=n?"".concat(n,"/config/field/update"):"/config/field/update",c=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,field_value:o,config_type:"general_settings"})});if(!c.ok){let e=await c.text();throw i(e),Error("Network response was not ok")}let s=await c.json();return r.ZP.success("Successfully updated value!"),s}catch(e){throw console.error("Failed to set callbacks:",e),e}},eX=async(e,t)=>{try{let o=n?"".concat(n,"/config/field/delete"):"/config/field/delete",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({field_name:t,config_type:"general_settings"})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return r.ZP.success("Field reset on proxy"),c}catch(e){throw console.error("Failed to get callbacks:",e),e}},eY=async(e,t)=>{try{let o=n?"".concat(n,"/config/pass_through_endpoint?endpoint_id=").concat(t):"/config/pass_through_endpoint".concat(t),a=await fetch(o,{method:"DELETE",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},eK=async(e,t)=>{try{let o=n?"".concat(n,"/config/update"):"/config/update",a=await fetch(o,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({...t})});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}return await a.json()}catch(e){throw console.error("Failed to set callbacks:",e),e}},e$=async e=>{try{let t=n?"".concat(n,"/health"):"/health",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}return await o.json()}catch(e){throw console.error("Failed to call /health:",e),e}},eQ=async e=>{try{let t=n?"".concat(n,"/cache/ping"):"/cache/ping",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error(e)}return await o.json()}catch(e){throw console.error("Failed to call /cache/ping:",e),e}},eW=async e=>{try{let t=n?"".concat(n,"/sso/get/ui_settings"):"/sso/get/ui_settings",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok)throw await o.text(),Error("Network response was not ok");return await o.json()}catch(e){throw console.error("Failed to get callbacks:",e),e}},e0=async e=>{try{let t=n?"".concat(n,"/guardrails/list"):"/guardrails/list",o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Guardrails list response:",a),a}catch(e){throw console.error("Failed to fetch guardrails list:",e),e}},e1=async(e,t,o)=>{try{let a=n?"".concat(n,"/spend/logs/ui/").concat(t,"?start_date=").concat(encodeURIComponent(o)):"/spend/logs/ui/".concat(t,"?start_date=").concat(encodeURIComponent(o));console.log("Fetching log details from:",a);let r=await fetch(a,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Fetched log details:",c),c}catch(e){throw console.error("Failed to fetch log details:",e),e}},e3=async e=>{try{let t=n?"".concat(n,"/get/internal_user_settings"):"/get/internal_user_settings";console.log("Fetching SSO settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched SSO settings:",a),a}catch(e){throw console.error("Failed to fetch SSO settings:",e),e}},e2=async(e,t)=>{try{let o=n?"".concat(n,"/update/internal_user_settings"):"/update/internal_user_settings";console.log("Updating internal user settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated internal user settings:",c),r.ZP.success("Internal user settings updated successfully"),c}catch(e){throw console.error("Failed to update internal user settings:",e),e}},e4=async e=>{try{let t=n?"".concat(n,"/mcp/tools/list"):"/mcp/tools/list";console.log("Fetching MCP tools from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched MCP tools:",a),a}catch(e){throw console.error("Failed to fetch MCP tools:",e),e}},e5=async(e,t,o)=>{try{let a=n?"".concat(n,"/mcp/tools/call"):"/mcp/tools/call";console.log("Calling MCP tool:",t,"with arguments:",o);let r=await fetch(a,{method:"POST",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify({name:t,arguments:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("MCP tool call response:",c),c}catch(e){throw console.error("Failed to call MCP tool:",e),e}},e6=async(e,t)=>{try{let o=n?"".concat(n,"/tag/new"):"/tag/new",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error creating tag:",e),e}},e9=async(e,t)=>{try{let o=n?"".concat(n,"/tag/update"):"/tag/update",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error updating tag:",e),e}},e7=async(e,t)=>{try{let o=n?"".concat(n,"/tag/info"):"/tag/info",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({names:t})});if(!a.ok){let e=await a.text();return await i(e),{}}return await a.json()}catch(e){throw console.error("Error getting tag info:",e),e}},e8=async e=>{try{let t=n?"".concat(n,"/tag/list"):"/tag/list",o=await fetch(t,{method:"GET",headers:{Authorization:"Bearer ".concat(e)}});if(!o.ok){let e=await o.text();return await i(e),{}}return await o.json()}catch(e){throw console.error("Error listing tags:",e),e}},te=async(e,t)=>{try{let o=n?"".concat(n,"/tag/delete"):"/tag/delete",a=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({name:t})});if(!a.ok){let e=await a.text();await i(e);return}return await a.json()}catch(e){throw console.error("Error deleting tag:",e),e}},tt=async e=>{try{let t=n?"".concat(n,"/get/default_team_settings"):"/get/default_team_settings";console.log("Fetching default team settings from:",t);let o=await fetch(t,{method:"GET",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"}});if(!o.ok){let e=await o.text();throw i(e),Error("Network response was not ok")}let a=await o.json();return console.log("Fetched default team settings:",a),a}catch(e){throw console.error("Failed to fetch default team settings:",e),e}},to=async(e,t)=>{try{let o=n?"".concat(n,"/update/default_team_settings"):"/update/default_team_settings";console.log("Updating default team settings:",t);let a=await fetch(o,{method:"PATCH",headers:{[l]:"Bearer ".concat(e),"Content-Type":"application/json"},body:JSON.stringify(t)});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let c=await a.json();return console.log("Updated default team settings:",c),r.ZP.success("Default team settings updated successfully"),c}catch(e){throw console.error("Failed to update default team settings:",e),e}},ta=async(e,t)=>{try{let o=n?"".concat(n,"/team/permissions_list?team_id=").concat(t):"/team/permissions_list?team_id=".concat(t),a=await fetch(o,{method:"GET",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)}});if(!a.ok){let e=await a.text();throw i(e),Error("Network response was not ok")}let r=await a.json();return console.log("Team permissions response:",r),r}catch(e){throw console.error("Failed to get team permissions:",e),e}},tr=async(e,t,o)=>{try{let a=n?"".concat(n,"/team/permissions_update"):"/team/permissions_update",r=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(e)},body:JSON.stringify({team_id:t,team_member_permissions:o})});if(!r.ok){let e=await r.text();throw i(e),Error("Network response was not ok")}let c=await r.json();return console.log("Team permissions response:",c),c}catch(e){throw console.error("Failed to update team permissions:",e),e}}},20347:function(e,t,o){o.d(t,{LQ:function(){return n},ZL:function(){return a},lo:function(){return r},tY:function(){return c}});let a=["Admin","Admin Viewer","proxy_admin","proxy_admin_viewer","org_admin"],r=["Internal User","Internal Viewer"],n=["Internal User","Admin"],c=e=>a.includes(e)}}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/699-2176ba2273e4676d.js b/ui/litellm-dashboard/out/_next/static/chunks/699-907a1bb245b7369a.js similarity index 100% rename from ui/litellm-dashboard/out/_next/static/chunks/699-2176ba2273e4676d.js rename to ui/litellm-dashboard/out/_next/static/chunks/699-907a1bb245b7369a.js diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js b/ui/litellm-dashboard/out/_next/static/chunks/app/layout-429ad74a94df7643.js similarity index 59% rename from litellm/proxy/_experimental/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js rename to ui/litellm-dashboard/out/_next/static/chunks/app/layout-429ad74a94df7643.js index 54014d8da6..b655a049db 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/app/layout-311f9b6ff79980ae.js +++ b/ui/litellm-dashboard/out/_next/static/chunks/app/layout-429ad74a94df7643.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{35677:function(n,e,t){Promise.resolve().then(t.t.bind(t,39974,23)),Promise.resolve().then(t.t.bind(t,2778,23))},2778:function(){},39974:function(n){n.exports={style:{fontFamily:"'__Inter_cf7686', '__Inter_Fallback_cf7686'",fontStyle:"normal"},className:"__className_cf7686"}}},function(n){n.O(0,[919,986,971,117,744],function(){return n(n.s=35677)}),_N_E=n.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[185],{96443:function(n,e,t){Promise.resolve().then(t.t.bind(t,39974,23)),Promise.resolve().then(t.t.bind(t,2778,23))},2778:function(){},39974:function(n){n.exports={style:{fontFamily:"'__Inter_cf7686', '__Inter_Fallback_cf7686'",fontStyle:"normal"},className:"__className_cf7686"}}},function(n){n.O(0,[919,986,971,117,744],function(){return n(n.s=96443)}),_N_E=n.O()}]); \ No newline at end of file diff --git a/litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js b/ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js similarity index 60% rename from litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js rename to ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js index e9399e4533..d78551c3fc 100644 --- a/litellm/proxy/_experimental/out/_next/static/chunks/app/model_hub/page-a965e43ba9638156.js +++ b/ui/litellm-dashboard/out/_next/static/chunks/app/model_hub/page-3d2c374ee41b38e5.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[418],{56668:function(e,n,u){Promise.resolve().then(u.bind(u,52829))},52829:function(e,n,u){"use strict";u.r(n),u.d(n,{default:function(){return f}});var t=u(57437),s=u(2265),r=u(99376),c=u(92699);function f(){let e=(0,r.useSearchParams)().get("key"),[n,u]=(0,s.useState)(null);return(0,s.useEffect)(()=>{e&&u(e)},[e]),(0,t.jsx)(c.Z,{accessToken:n,publicPage:!0,premiumUser:!1})}}},function(e){e.O(0,[42,261,250,699,971,117,744],function(){return e(e.s=56668)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[418],{21024:function(e,n,u){Promise.resolve().then(u.bind(u,52829))},52829:function(e,n,u){"use strict";u.r(n),u.d(n,{default:function(){return f}});var t=u(57437),s=u(2265),r=u(99376),c=u(92699);function f(){let e=(0,r.useSearchParams)().get("key"),[n,u]=(0,s.useState)(null);return(0,s.useEffect)(()=>{e&&u(e)},[e]),(0,t.jsx)(c.Z,{accessToken:n,publicPage:!0,premiumUser:!1})}}},function(e){e.O(0,[42,261,250,699,971,117,744],function(){return e(e.s=21024)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js b/ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js new file mode 100644 index 0000000000..a995e87291 --- /dev/null +++ b/ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-339a46b35fba4423.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[461],{8672:function(e,t,n){Promise.resolve().then(n.bind(n,12011))},12011:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return S}});var s=n(57437),o=n(2265),a=n(99376),c=n(20831),i=n(94789),l=n(12514),r=n(49804),u=n(67101),m=n(84264),d=n(49566),h=n(96761),x=n(84566),p=n(19250),f=n(14474),k=n(13634),g=n(73002),j=n(3914);function S(){let[e]=k.Z.useForm(),t=(0,a.useSearchParams)();(0,j.e)("token");let n=t.get("invitation_id"),[S,w]=(0,o.useState)(null),[Z,_]=(0,o.useState)(""),[N,b]=(0,o.useState)(""),[T,y]=(0,o.useState)(null),[E,v]=(0,o.useState)(""),[C,U]=(0,o.useState)("");return(0,o.useEffect)(()=>{n&&(0,p.W_)(n).then(e=>{let t=e.login_url;console.log("login_url:",t),v(t);let n=e.token,s=(0,f.o)(n);U(n),console.log("decoded:",s),w(s.key),console.log("decoded user email:",s.user_email),b(s.user_email),y(s.user_id)})},[n]),(0,s.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,s.jsxs)(l.Z,{children:[(0,s.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,s.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,s.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,s.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,s.jsxs)(u.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,s.jsx)(r.Z,{children:"SSO is under the Enterprise Tier."}),(0,s.jsx)(r.Z,{children:(0,s.jsx)(c.Z,{variant:"primary",className:"mb-2",children:(0,s.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,s.jsxs)(k.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",S,"token:",C,"formValues:",e),S&&C&&(e.user_email=N,T&&n&&(0,p.m_)(S,n,T,e.password).then(e=>{let t="/ui/";t+="?login=success",document.cookie="token="+C,console.log("redirecting to:",t),window.location.href=t}))},children:[(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Z.Item,{label:"Email Address",name:"user_email",children:(0,s.jsx)(d.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,s.jsx)(k.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,s.jsx)(d.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,s.jsx)("div",{className:"mt-10",children:(0,s.jsx)(g.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},3914:function(e,t,n){"use strict";function s(){let e=window.location.hostname,t=["Lax","Strict","None"];["/","/ui"].forEach(n=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,";"),t.forEach(t=>{let s="None"===t?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; SameSite=").concat(t,";").concat(s),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,"; SameSite=").concat(t,";").concat(s)})}),console.log("After clearing cookies:",document.cookie)}function o(e){let t=document.cookie.split("; ").find(t=>t.startsWith(e+"="));return t?t.split("=")[1]:null}n.d(t,{b:function(){return s},e:function(){return o}})}},function(e){e.O(0,[665,42,899,250,971,117,744],function(){return e(e.s=8672)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js b/ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js deleted file mode 100644 index 5e22c7e73d..0000000000 --- a/ui/litellm-dashboard/out/_next/static/chunks/app/onboarding/page-9598003bc1e91371.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[461],{23781:function(e,t,n){Promise.resolve().then(n.bind(n,12011))},12011:function(e,t,n){"use strict";n.r(t),n.d(t,{default:function(){return S}});var s=n(57437),o=n(2265),a=n(99376),c=n(20831),i=n(94789),l=n(12514),r=n(49804),u=n(67101),m=n(84264),d=n(49566),h=n(96761),x=n(84566),p=n(19250),f=n(14474),k=n(13634),g=n(73002),j=n(3914);function S(){let[e]=k.Z.useForm(),t=(0,a.useSearchParams)();(0,j.e)("token");let n=t.get("invitation_id"),[S,w]=(0,o.useState)(null),[Z,_]=(0,o.useState)(""),[N,b]=(0,o.useState)(""),[T,y]=(0,o.useState)(null),[E,v]=(0,o.useState)(""),[C,U]=(0,o.useState)("");return(0,o.useEffect)(()=>{n&&(0,p.W_)(n).then(e=>{let t=e.login_url;console.log("login_url:",t),v(t);let n=e.token,s=(0,f.o)(n);U(n),console.log("decoded:",s),w(s.key),console.log("decoded user email:",s.user_email),b(s.user_email),y(s.user_id)})},[n]),(0,s.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,s.jsxs)(l.Z,{children:[(0,s.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,s.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,s.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,s.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,s.jsxs)(u.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,s.jsx)(r.Z,{children:"SSO is under the Enterprise Tier."}),(0,s.jsx)(r.Z,{children:(0,s.jsx)(c.Z,{variant:"primary",className:"mb-2",children:(0,s.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,s.jsxs)(k.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",S,"token:",C,"formValues:",e),S&&C&&(e.user_email=N,T&&n&&(0,p.m_)(S,n,T,e.password).then(e=>{let t="/ui/";t+="?login=success",document.cookie="token="+C,console.log("redirecting to:",t),window.location.href=t}))},children:[(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(k.Z.Item,{label:"Email Address",name:"user_email",children:(0,s.jsx)(d.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,s.jsx)(k.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,s.jsx)(d.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,s.jsx)("div",{className:"mt-10",children:(0,s.jsx)(g.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},3914:function(e,t,n){"use strict";function s(){let e=window.location.hostname,t=["Lax","Strict","None"];["/","/ui"].forEach(n=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,";"),t.forEach(t=>{let s="None"===t?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; SameSite=").concat(t,";").concat(s),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(n,"; domain=").concat(e,"; SameSite=").concat(t,";").concat(s)})}),console.log("After clearing cookies:",document.cookie)}function o(e){let t=document.cookie.split("; ").find(t=>t.startsWith(e+"="));return t?t.split("=")[1]:null}n.d(t,{b:function(){return s},e:function(){return o}})}},function(e){e.O(0,[665,42,899,250,971,117,744],function(){return e(e.s=23781)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/app/page-225a364dd94a768d.js b/ui/litellm-dashboard/out/_next/static/chunks/app/page-225a364dd94a768d.js new file mode 100644 index 0000000000..3d3bf48015 --- /dev/null +++ b/ui/litellm-dashboard/out/_next/static/chunks/app/page-225a364dd94a768d.js @@ -0,0 +1 @@ +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{36362:function(e,s,l){Promise.resolve().then(l.bind(l,76737))},12011:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return y}});var t=l(57437),a=l(2265),r=l(99376),n=l(20831),i=l(94789),o=l(12514),c=l(49804),d=l(67101),m=l(84264),u=l(49566),h=l(96761),x=l(84566),p=l(19250),g=l(14474),j=l(13634),f=l(73002),_=l(3914);function y(){let[e]=j.Z.useForm(),s=(0,r.useSearchParams)();(0,_.e)("token");let l=s.get("invitation_id"),[y,v]=(0,a.useState)(null),[b,Z]=(0,a.useState)(""),[N,w]=(0,a.useState)(""),[k,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(""),[T,A]=(0,a.useState)("");return(0,a.useEffect)(()=>{l&&(0,p.W_)(l).then(e=>{let s=e.login_url;console.log("login_url:",s),I(s);let l=e.token,t=(0,g.o)(l);A(l),console.log("decoded:",t),v(t.key),console.log("decoded user email:",t.user_email),w(t.user_email),S(t.user_id)})},[l]),(0,t.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,t.jsxs)(o.Z,{children:[(0,t.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,t.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,t.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,t.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,t.jsxs)(d.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,t.jsx)(c.Z,{children:"SSO is under the Enterprise Tier."}),(0,t.jsx)(c.Z,{children:(0,t.jsx)(n.Z,{variant:"primary",className:"mb-2",children:(0,t.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,t.jsxs)(j.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",y,"token:",T,"formValues:",e),y&&T&&(e.user_email=N,k&&l&&(0,p.m_)(y,l,k,e.password).then(e=>{let s="/ui/";s+="?login=success",document.cookie="token="+T,console.log("redirecting to:",s),window.location.href=s}))},children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(j.Z.Item,{label:"Email Address",name:"user_email",children:(0,t.jsx)(u.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,t.jsx)(j.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,t.jsx)(u.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,t.jsx)("div",{className:"mt-10",children:(0,t.jsx)(f.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},76737:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return aD}});var t,a,r,n,i,o,c=l(57437),d=l(2265),m=l(99376),u=l(14474),h=l(21623),x=l(29827),p=l(27648),g=l(80795),j=l(15883),f=l(40428),_=l(3914),y=l(19250);let v=async e=>{if(!e)return null;try{return await (0,y.g)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};var b=e=>{let{userID:s,userEmail:l,userRole:t,premiumUser:a,proxySettings:r,setProxySettings:n,accessToken:i}=e,[o,m]=(0,d.useState)("");(0,d.useEffect)(()=>{(async()=>{if(i){let e=await v(i);console.log("response from fetchProxySettings",e),e&&n(e)}})()},[i]),(0,d.useEffect)(()=>{m((null==r?void 0:r.PROXY_LOGOUT_URL)||"")},[r]);let u=[{key:"1",label:(0,c.jsxs)("div",{className:"py-1",children:[(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Role: ",t]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Email: ",l||"Unknown"]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[(0,c.jsx)(j.Z,{})," ",s]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Premium User: ",String(a)]})]})},{key:"2",label:(0,c.jsxs)("p",{className:"text-sm hover:text-gray-900",onClick:()=>{(0,_.b)(),window.location.href=o},children:[(0,c.jsx)(f.Z,{})," Logout"]})}];return(0,c.jsx)("nav",{className:"bg-white border-b border-gray-200 sticky top-0 z-10",children:(0,c.jsx)("div",{className:"w-full",children:(0,c.jsxs)("div",{className:"flex items-center h-12 px-4",children:[(0,c.jsx)("div",{className:"flex items-center flex-shrink-0",children:(0,c.jsx)(p.default,{href:"/",className:"flex items-center",children:(0,c.jsx)("img",{src:"/get_image",alt:"LiteLLM Brand",className:"h-8 w-auto"})})}),(0,c.jsxs)("div",{className:"flex items-center space-x-5 ml-auto",children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/",target:"_blank",rel:"noopener noreferrer",className:"text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:"Docs"}),(0,c.jsx)(g.Z,{menu:{items:u,style:{padding:"4px",marginTop:"4px"}},children:(0,c.jsxs)("button",{className:"inline-flex items-center text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:["User",(0,c.jsx)("svg",{className:"ml-1 w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19 9l-7 7-7-7"})})]})})]})]})})})};let Z=async(e,s,l,t,a)=>{let r;r="Admin"!=l&&"Admin Viewer"!=l?await (0,y.It)(e,(null==t?void 0:t.organization_id)||null,s):await (0,y.It)(e,(null==t?void 0:t.organization_id)||null),console.log("givenTeams: ".concat(r)),a(r)};var N=l(49804),w=l(67101),k=l(20831),S=l(49566),C=l(87452),I=l(88829),T=l(72208),A=l(84264),E=l(96761),P=l(29233),O=l(52787),L=l(13634),D=l(41021),M=l(51369),F=l(29967),R=l(73002),q=l(56632),U=l(30150),z=e=>{let{step:s=.01,style:l={width:"100%"},placeholder:t="Enter a numerical value",min:a,max:r,onChange:n,...i}=e;return(0,c.jsx)(U.Z,{onWheel:e=>e.currentTarget.blur(),step:s,style:l,placeholder:t,min:a,max:r,onChange:n,...i})};let V=async(e,s,l)=>{try{if(null===e||null===s)return;if(null!==l){let t=(await (0,y.So)(l,e,s,!0)).data.map(e=>e.id),a=[],r=[];return t.forEach(e=>{e.endsWith("/*")?a.push(e):r.push(e)}),[...a,...r]}}catch(e){console.error("Error fetching user models:",e)}},K=e=>{if(e.endsWith("/*")){let s=e.replace("/*","");return"All ".concat(s," models")}return e},B=(e,s)=>{let l=[],t=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));t.push(...r),l.push(e)}else t.push(e)}),[...l,...t].filter((e,s,l)=>l.indexOf(e)===s)};var H=l(20577),J=l(15424),W=l(75957);let G=(e,s)=>["metadata","config","enforced_params","aliases"].includes(e)||"json"===s.format,Y=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch(e){return!1}},$=(e,s,l)=>{let t={max_budget:"Enter maximum budget in USD (e.g., 100.50)",budget_duration:"Select a time period for budget reset",tpm_limit:"Enter maximum tokens per minute (whole number)",rpm_limit:"Enter maximum requests per minute (whole number)",duration:"Enter duration (e.g., 30s, 24h, 7d)",metadata:'Enter JSON object with key-value pairs\nExample: {"team": "research", "project": "nlp"}',config:'Enter configuration as JSON object\nExample: {"setting": "value"}',permissions:"Enter comma-separated permission strings",enforced_params:'Enter parameters as JSON object\nExample: {"param": "value"}',blocked:"Enter true/false or specific block conditions",aliases:'Enter aliases as JSON object\nExample: {"alias1": "value1", "alias2": "value2"}',models:"Select one or more model names",key_alias:"Enter a unique identifier for this key",tags:"Enter comma-separated tag strings"}[e]||({string:"Text input",number:"Numeric input",integer:"Whole number input",boolean:"True/False value"})[l]||"Text input";return G(e,s)?"".concat(t,"\nMust be valid JSON format"):s.enum?"Select from available options\nAllowed values: ".concat(s.enum.join(", ")):t};var X=e=>{let{schemaComponent:s,excludedFields:l=[],form:t,overrideLabels:a={},overrideTooltips:r={},customValidation:n={},defaultValues:i={}}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null);(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.lP)()).components.schemas[s];if(!e)throw Error('Schema component "'.concat(s,'" not found'));m(e);let a={};Object.keys(e.properties).filter(e=>!l.includes(e)&&void 0!==i[e]).forEach(e=>{a[e]=i[e]}),t.setFieldsValue(a)}catch(e){console.error("Schema fetch error:",e),h(e instanceof Error?e.message:"Failed to fetch schema")}})()},[s,t,l]);let x=e=>{if(e.type)return e.type;if(e.anyOf){let s=e.anyOf.map(e=>e.type);if(s.includes("number")||s.includes("integer"))return"number";s.includes("string")}return"string"},p=(e,s)=>{var l;let t;let d=x(s),m=null==o?void 0:null===(l=o.required)||void 0===l?void 0:l.includes(e),u=a[e]||s.title||e,h=r[e]||s.description,p=[];m&&p.push({required:!0,message:"".concat(u," is required")}),n[e]&&p.push({validator:n[e]}),G(e,s)&&p.push({validator:async(e,s)=>{if(s&&!Y(s))throw Error("Please enter valid JSON")}});let g=h?(0,c.jsxs)("span",{children:[u," ",(0,c.jsx)(W.Z,{title:h,children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}):u;return t=G(e,s)?(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter as JSON",className:"font-mono"}):s.enum?(0,c.jsx)(O.default,{children:s.enum.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"number"===d||"integer"===d?(0,c.jsx)(H.Z,{style:{width:"100%"},precision:"integer"===d?0:void 0}):"duration"===e?(0,c.jsx)(S.Z,{placeholder:"eg: 30s, 30h, 30d"}):(0,c.jsx)(S.Z,{placeholder:h||""}),(0,c.jsx)(L.Z.Item,{label:g,name:e,className:"mt-8",rules:p,initialValue:i[e],help:(0,c.jsx)("div",{className:"text-xs text-gray-500",children:$(e,s,d)}),children:t},e)};return u?(0,c.jsxs)("div",{className:"text-red-500",children:["Error: ",u]}):(null==o?void 0:o.properties)?(0,c.jsx)("div",{children:Object.entries(o.properties).filter(e=>{let[s]=e;return!l.includes(s)}).map(e=>{let[s,l]=e;return p(s,l)})}):null},Q=e=>{let{teams:s,value:l,onChange:t}=e;return(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:t,filterOption:(e,s)=>{var l,t,a;return!!s&&((null===(a=s.children)||void 0===a?void 0:null===(t=a[0])||void 0===t?void 0:null===(l=t.props)||void 0===l?void 0:l.children)||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==s?void 0:s.map(e=>(0,c.jsxs)(O.default.Option,{value:e.team_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})},ee=l(57365),es=l(93192);function el(e){let{isInvitationLinkModalVisible:s,setIsInvitationLinkModalVisible:l,baseUrl:t,invitationLinkData:a}=e,{Title:r,Paragraph:n}=es.default,i=()=>(null==a?void 0:a.has_user_setup_sso)?new URL("/ui",t).toString():new URL("/ui?invitation_id=".concat(null==a?void 0:a.id),t).toString();return(0,c.jsxs)(M.Z,{title:"Invitation Link",visible:s,width:800,footer:null,onOk:()=>{l(!1)},onCancel:()=>{l(!1)},children:[(0,c.jsx)(n,{children:"Copy and send the generated link to onboard this user to the proxy."}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"User ID"}),(0,c.jsx)(A.Z,{children:null==a?void 0:a.user_id})]}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{children:"Invitation Link"}),(0,c.jsx)(A.Z,{children:(0,c.jsx)(A.Z,{children:i()})})]}),(0,c.jsx)("div",{className:"flex justify-end mt-5",children:(0,c.jsx)(P.CopyToClipboard,{text:i(),onCopy:()=>D.ZP.success("Copied!"),children:(0,c.jsx)(k.Z,{variant:"primary",children:"Copy invitation link"})})})]})}var et=l(77388),ea=l(1709),er=l(73879),en=l(3632),ei=l(15452),eo=l.n(ei),ec=l(71157),ed=l(44643),em=e=>{let{accessToken:s,teams:l,possibleUIRoles:t,onUsersCreated:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.g)(s);g(e)}catch(e){console.error("Error fetching UI settings:",e)}})(),f(new URL("/",window.location.href).toString())},[s]);let _=async()=>{u(!0);let e=i.map(e=>({...e,status:"pending"}));o(e);let l=!1;for(let a=0;ae.trim())),e.models&&"string"==typeof e.models&&(e.models=e.models.split(",").map(e=>e.trim())),e.max_budget&&""!==e.max_budget.toString().trim()&&(e.max_budget=parseFloat(e.max_budget.toString()));let r=await (0,y.Ov)(s,null,e);if(console.log("Full response:",r),r&&(r.key||r.user_id)){l=!0,console.log("Success case triggered");let e=(null===(t=r.data)||void 0===t?void 0:t.user_id)||r.user_id;try{if(null==p?void 0:p.SSO_ENABLED){let e=new URL("/ui",j).toString();o(s=>s.map((s,l)=>l===a?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let l=await (0,y.XO)(s,e),t=new URL("/ui?invitation_id=".concat(l.id),j).toString();o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,invitation_link:t}:e))}}catch(e){console.error("Error creating invitation:",e),o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=(null==r?void 0:r.error)||"Failed to create user";console.log("Error message:",e),o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=(null==s?void 0:null===(n=s.response)||void 0===n?void 0:null===(r=n.data)||void 0===r?void 0:r.error)||(null==s?void 0:s.message)||String(s);o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}u(!1),l&&a&&a()};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>n(!0),children:"+ Bulk Invite Users"}),(0,c.jsx)(M.Z,{title:"Bulk Invite Users",visible:r,width:800,onCancel:()=>n(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,c.jsx)("div",{className:"flex flex-col",children:0===i.length?(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,c.jsxs)("div",{className:"ml-11 mb-6",children:[(0,c.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,c.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,c.jsx)("li",{children:"Download our CSV template"}),(0,c.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,c.jsx)("li",{children:"Save the file and upload it here"}),(0,c.jsx)("li",{children:"After creation, download the results file containing the API keys for each user"})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,c.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_email"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_role"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_view_only", "internal_user", "internal_user_view_only")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"teams"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"models"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=new Blob([eo().unparse([["user_email","user_role","teams","max_budget","budget_duration","models"],["user@example.com","internal_user","team-id-1,team-id-2","100","30d","gpt-3.5-turbo,gpt-4"]])],{type:"text/csv"}),s=window.URL.createObjectURL(e),l=document.createElement("a");l.href=s,l.download="bulk_users_template.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(s)},size:"lg",className:"w-full md:w-auto",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download CSV Template"]})]}),(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,c.jsx)("div",{className:"ml-11",children:(0,c.jsx)(et.Z,{beforeUpload:e=>(x(null),eo().parse(e,{complete:e=>{let s=e.data[0],l=["user_email","user_role"].filter(e=>!s.includes(e));if(l.length>0){x("Your CSV is missing these required columns: ".concat(l.join(", "))),o([]);return}try{let l=e.data.slice(1).map((e,l)=>{var t,a,r,n,i,o;let c={user_email:(null===(t=e[s.indexOf("user_email")])||void 0===t?void 0:t.trim())||"",user_role:(null===(a=e[s.indexOf("user_role")])||void 0===a?void 0:a.trim())||"",teams:null===(r=e[s.indexOf("teams")])||void 0===r?void 0:r.trim(),max_budget:null===(n=e[s.indexOf("max_budget")])||void 0===n?void 0:n.trim(),budget_duration:null===(i=e[s.indexOf("budget_duration")])||void 0===i?void 0:i.trim(),models:null===(o=e[s.indexOf("models")])||void 0===o?void 0:o.trim(),rowNumber:l+2,isValid:!0,error:""},d=[];c.user_email||d.push("Email is required"),c.user_role||d.push("Role is required"),c.user_email&&!c.user_email.includes("@")&&d.push("Invalid email format");let m=["proxy_admin","proxy_admin_view_only","internal_user","internal_user_view_only"];return c.user_role&&!m.includes(c.user_role)&&d.push("Invalid role. Must be one of: ".concat(m.join(", "))),c.max_budget&&isNaN(parseFloat(c.max_budget.toString()))&&d.push("Max budget must be a number"),d.length>0&&(c.isValid=!1,c.error=d.join(", ")),c}),t=l.filter(e=>e.isValid);o(l),0===t.length?x("No valid users found in the CSV. Please check the errors below."):t.length{x("Failed to parse CSV file: ".concat(e.message)),o([])},header:!1}),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,c.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,c.jsx)(en.Z,{className:"text-3xl text-gray-400 mb-2"}),(0,c.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,c.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,c.jsx)(k.Z,{size:"sm",children:"Browse files"})]})})})]}):(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:i.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),h&&(0,c.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,c.jsx)(A.Z,{className:"text-red-600 font-medium",children:h})}),(0,c.jsxs)("div",{className:"ml-11",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,c.jsx)("div",{className:"flex items-center",children:i.some(e=>"success"===e.status||"failed"===e.status)?(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[i.filter(e=>"success"===e.status).length," Successful"]}),i.some(e=>"failed"===e.status)&&(0,c.jsxs)(A.Z,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[i.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[i.filter(e=>e.isValid).length," of ",i.length," users valid"]})]})}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex space-x-3",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]})]}),i.some(e=>"success"===e.status)&&(0,c.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"mr-3 mt-1",children:(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-blue-500"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,c.jsxs)(A.Z,{className:"block text-sm text-blue-700 mt-1",children:[(0,c.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing API keys and invitation links. Users will need these API keys to make LLM requests through LiteLLM."]})]})]})}),(0,c.jsx)(ea.Z,{dataSource:i,columns:[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,s)=>s.isValid?s.status&&"pending"!==s.status?"success"===s.status?(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}),(0,c.jsx)("span",{className:"text-green-500",children:"Success"})]}),s.invitation_link&&(0,c.jsx)("div",{className:"mt-1",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:s.invitation_link}),(0,c.jsx)(P.CopyToClipboard,{text:s.invitation_link,onCopy:()=>D.ZP.success("Invitation link copied!"),children:(0,c.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Failed"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(s.error)})]}):(0,c.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:s.error})]})}],size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]}),i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Start New Bulk Import"}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=i.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([eo().unparse(e)],{type:"text/csv"}),l=window.URL.createObjectURL(s),t=document.createElement("a");t.href=l,t.download="bulk_users_results.csv",document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(l)},variant:"primary",className:"flex items-center",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download User Credentials"]})]})]})]})})})]})};let{Option:eu}=O.default;var eh=e=>{let{userID:s,accessToken:l,teams:t,possibleUIRoles:a,onUserCreated:r,isEmbedded:n=!1}=e,[i,o]=(0,d.useState)(null),[u]=L.Z.useForm(),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),N=(0,m.useRouter)(),[w,P]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.So)(l,s,"any"),t=[];for(let s=0;s{N&&P(new URL("/",window.location.href).toString())},[N]);let F=async e=>{var t,a,o;try{D.ZP.info("Making API Call"),n||x(!0),e.models&&0!==e.models.length||(e.models=["no-default-models"]),console.log("formValues in create user:",e);let a=await (0,y.Ov)(l,null,e);console.log("user create Response:",a),g(!0);let o=(null===(t=a.data)||void 0===t?void 0:t.user_id)||a.user_id;if(r&&n){r(o),u.resetFields();return}if(null==i?void 0:i.SSO_ENABLED){let e={id:crypto.randomUUID(),user_id:o,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:s,updated_at:new Date,updated_by:s,has_user_setup_sso:!0};Z(e),v(!0)}else(0,y.XO)(l,o).then(e=>{e.has_user_setup_sso=!1,Z(e),v(!0)});D.ZP.success("API user Created"),u.resetFields(),localStorage.removeItem("userData"+s)}catch(s){let e=(null===(o=s.response)||void 0===o?void 0:null===(a=o.data)||void 0===a?void 0:a.detail)||(null==s?void 0:s.message)||"Error creating the user";D.ZP.error(e),console.error("Error creating the user:",s)}};return n?(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]}):(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>x(!0),children:"+ Invite User"}),(0,c.jsx)(em,{accessToken:l,teams:t,possibleUIRoles:a}),(0,c.jsxs)(M.Z,{title:"Invite User",visible:h,width:800,footer:null,onOk:()=>{x(!1),u.resetFields()},onCancel:()=>{x(!1),g(!1),u.resetFields()},children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Create a User who can own keys"}),(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Global Proxy Role"," ",(0,c.jsx)(W.Z,{title:"This is the role that the user will globally on the proxy. This role is independent of any team/org specific roles.",children:(0,c.jsx)(J.Z,{})})]}),name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{children:"Personal Key Creation"})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(L.Z.Item,{className:"gap-2",label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Models user has access to, outside of team scope.",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),j.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]})]}),p&&(0,c.jsx)(el,{isInvitationLinkModalVisible:_,setIsInvitationLinkModalVisible:v,baseUrl:w,invitationLinkData:b})]})},ex=l(7310),ep=l.n(ex),eg=l(20347);let{Option:ej}=O.default,ef=e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set";var e_=e=>{let{value:s,onChange:l,className:t="",style:a={}}=e;return(0,c.jsxs)(O.default,{style:{width:"100%",...a},value:s||void 0,onChange:l,className:t,placeholder:"n/a",children:[(0,c.jsx)(ej,{value:"24h",children:"daily"}),(0,c.jsx)(ej,{value:"7d",children:"weekly"}),(0,c.jsx)(ej,{value:"30d",children:"monthly"})]})};let{Option:ey}=O.default,ev=e=>{let s=[];if(console.log("data:",JSON.stringify(e)),e)for(let l of e)l.metadata&&l.metadata.tags&&s.push(...l.metadata.tags);let l=Array.from(new Set(s)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",l),l},eb=async(e,s,l,t)=>{try{if(null===e||null===s)return[];if(null!==l){let a=(await (0,y.So)(l,e,s,!0,t)).data.map(e=>e.id);return console.log("available_model_names:",a),a}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},eZ=async(e,s,l,t)=>{try{if(null===e||null===s)return;if(null!==l){let a=(await (0,y.So)(l,e,s)).data.map(e=>e.id);console.log("available_model_names:",a),t(a)}}catch(e){console.error("Error fetching user models:",e)}};var eN=e=>{let{userID:s,team:l,teams:t,userRole:a,accessToken:r,data:n,setData:i}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)("you"),[U,V]=(0,d.useState)(ev(n)),[B,H]=(0,d.useState)([]),[G,Y]=(0,d.useState)(l),[$,ee]=(0,d.useState)(!1),[es,el]=(0,d.useState)(null),[et,ea]=(0,d.useState)({}),[er,en]=(0,d.useState)([]),[ei,eo]=(0,d.useState)(!1),ec=()=>{u(!1),o.resetFields()},ed=()=>{u(!1),x(null),Y(null),o.resetFields()};(0,d.useEffect)(()=>{s&&a&&r&&eZ(s,a,r,f)},[r,s,a]),(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.t3)(r)).guardrails.map(e=>e.guardrail_name);H(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[r]),(0,d.useEffect)(()=>{(async()=>{try{if(r){let e=sessionStorage.getItem("possibleUserRoles");if(e)ea(JSON.parse(e));else{let e=await (0,y.lg)(r);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),ea(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[r]);let em=async e=>{try{var l,t,a;let c=null!==(l=null==e?void 0:e.key_alias)&&void 0!==l?l:"",d=null!==(t=null==e?void 0:e.team_id)&&void 0!==t?t:null;if((null!==(a=null==n?void 0:n.filter(e=>e.team_id===d).map(e=>e.key_alias))&&void 0!==a?a:[]).includes(c))throw Error("Key alias ".concat(c," already exists for team with ID ").concat(d,", please provide another key alias"));if(D.ZP.info("Making API Call"),u(!0),"you"===b&&(e.user_id=s),"service_account"===b){let s={};try{s=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}s.service_account_id=e.key_alias,e.metadata=JSON.stringify(s)}let m=await (0,y.wX)(r,s,e);console.log("key create Response:",m),i(e=>e?[...e,m]:[m]),window.addNewKeyToList&&window.addNewKeyToList(m),x(m.key),g(m.soft_budget),D.ZP.success("API Key Created"),o.resetFields(),localStorage.removeItem("userData"+s)}catch(e){console.log("error in create key:",e),D.ZP.error("Error creating the key: ".concat(e))}};(0,d.useEffect)(()=>{if(s&&a&&r){var e;eb(s,a,r,null!==(e=null==G?void 0:G.team_id)&&void 0!==e?e:null).then(e=>{var s;v(Array.from(new Set([...null!==(s=null==G?void 0:G.models)&&void 0!==s?s:[],...e])))})}o.setFieldValue("models",[])},[G,r,s,a]);let eu=async e=>{if(!e){en([]);return}eo(!0);try{let s=new URLSearchParams;if(s.append("user_email",e),null==r)return;let l=(await (0,y.u5)(r,s)).map(e=>({label:"".concat(e.user_email," (").concat(e.user_id,")"),value:e.user_id,user:e}));en(l)}catch(e){console.error("Error fetching users:",e),D.ZP.error("Failed to search for users")}finally{eo(!1)}},ex=(0,d.useCallback)(ep()(e=>eu(e),300),[r]),ej=(e,s)=>{let l=s.user;o.setFieldsValue({user_id:l.user_id})};return(0,c.jsxs)("div",{children:[a&&eg.LQ.includes(a)&&(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>u(!0),children:"+ Create New Key"}),(0,c.jsx)(M.Z,{visible:m,width:1e3,footer:null,onOk:ec,onCancel:ed,children:(0,c.jsxs)(L.Z,{form:o,onFinish:em,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Ownership"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Owned By"," ",(0,c.jsx)(W.Z,{title:"Select who will own this API key",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,c.jsxs)(F.ZP.Group,{onChange:e=>Z(e.target.value),value:b,children:[(0,c.jsx)(F.ZP,{value:"you",children:"You"}),(0,c.jsx)(F.ZP,{value:"service_account",children:"Service Account"}),"Admin"===a&&(0,c.jsx)(F.ZP,{value:"another_user",children:"Another User"})]})}),"another_user"===b&&(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["User ID"," ",(0,c.jsx)(W.Z,{title:"The user who will own this key and be responsible for its usage",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===b,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{ex(e)},onSelect:(e,s)=>ej(e,s),options:er,loading:ei,allowClear:!0,style:{width:"100%"},notFoundContent:ei?"Searching...":"No users found"}),(0,c.jsx)(R.ZP,{onClick:()=>ee(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,c.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Team"," ",(0,c.jsx)(W.Z,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:l?l.team_id:null,className:"mt-4",children:(0,c.jsx)(Q,{teams:t,onChange:e=>{Y((null==t?void 0:t.find(s=>s.team_id===e))||null)}})})]}),(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Details"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["you"===b||"another_user"===b?"Key Name":"Service Account ID"," ",(0,c.jsx)(W.Z,{title:"you"===b||"another_user"===b?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:"Please input a ".concat("you"===b?"key name":"service account ID")}],help:"required",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",className:"mt-4",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},onChange:e=>{e.includes("all-team-models")&&o.setFieldsValue({models:["all-team-models"]})},children:[(0,c.jsx)(ey,{value:"all-team-models",children:"All Team Models"},"all-team-models"),_.map(e=>(0,c.jsx)(ey,{value:e,children:K(e)},e))]})})]}),(0,c.jsx)("div",{className:"mb-8",children:(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{className:"m-0",children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Max Budget (USD)"," ",(0,c.jsx)(W.Z,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:"Budget cannot exceed team max budget: $".concat((null==l?void 0:l.max_budget)!==null&&(null==l?void 0:l.max_budget)!==void 0?null==l?void 0:l.max_budget:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.max_budget&&s>l.max_budget)throw Error("Budget cannot exceed team max budget: $".concat(l.max_budget))}}],children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Reset Budget"," ",(0,c.jsx)(W.Z,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:"Team Reset Budget: ".concat((null==l?void 0:l.budget_duration)!==null&&(null==l?void 0:l.budget_duration)!==void 0?null==l?void 0:l.budget_duration:"None"),children:(0,c.jsx)(e_,{onChange:e=>o.setFieldValue("budget_duration",e)})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:"TPM cannot exceed team TPM limit: ".concat((null==l?void 0:l.tpm_limit)!==null&&(null==l?void 0:l.tpm_limit)!==void 0?null==l?void 0:l.tpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.tpm_limit&&s>l.tpm_limit)throw Error("TPM limit cannot exceed team TPM limit: ".concat(l.tpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:"RPM cannot exceed team RPM limit: ".concat((null==l?void 0:l.rpm_limit)!==null&&(null==l?void 0:l.rpm_limit)!==void 0?null==l?void 0:l.rpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.rpm_limit&&s>l.rpm_limit)throw Error("RPM limit cannot exceed team RPM limit: ".concat(l.rpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Expire Key"," ",(0,c.jsx)(W.Z,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days)",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"duration",className:"mt-4",children:(0,c.jsx)(S.Z,{placeholder:"e.g., 30d"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:B.map(e=>({value:e,label:e}))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Metadata"," ",(0,c.jsx)(W.Z,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Tags"," ",(0,c.jsx)(W.Z,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:U})}),(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("b",{children:"Advanced Settings"}),(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,c.jsx)("a",{href:y.H2?"".concat(y.H2,"/#/key%20management/generate_key_fn_key_generate_post"):"/#/key%20management/generate_key_fn_key_generate_post",target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:"documentation"})]}),children:(0,c.jsx)(J.Z,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(X,{schemaComponent:"GenerateKeyRequest",form:o,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Key"})})]})}),$&&(0,c.jsx)(M.Z,{title:"Create New User",visible:$,onCancel:()=>ee(!1),footer:null,width:800,children:(0,c.jsx)(eh,{userID:s,accessToken:r,teams:t,possibleUIRoles:et,onUserCreated:e=>{el(e),o.setFieldsValue({user_id:e}),ee(!1)},isEmbedded:!0})}),h&&(0,c.jsx)(M.Z,{visible:m,onOk:ec,onCancel:ed,footer:null,children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Save your Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please save this secret key somewhere safe and accessible. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:null!=h?(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:h})}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>{D.ZP.success("API Key copied to clipboard")},children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]}):(0,c.jsx)(A.Z,{children:"Key being created, this might take 30s"})})]})})]})},ew=l(7366),ek=e=>{let{selectedTeam:s,currentOrg:l,selectedKeyAlias:t,accessToken:a,currentPage:r=1}=e,[n,i]=(0,d.useState)({keys:[],total_count:0,current_page:1,total_pages:0}),[o,c]=(0,d.useState)(!0),[m,u]=(0,d.useState)(null),h=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};try{if(console.log("calling fetchKeys"),!a){console.log("accessToken",a);return}c(!0);let r=await (0,y.OD)(a,(null==l?void 0:l.organization_id)||null,(null==s?void 0:s.team_id)||"",t,e.page||1,50);console.log("data",r),i(r),u(null)}catch(e){u(e instanceof Error?e:Error("An error occurred"))}finally{c(!1)}};return(0,d.useEffect)(()=>{h(),console.log("selectedTeam",s,"currentOrg",l,"accessToken",a,"selectedKeyAlias",t)},[s,l,a,t]),{keys:n.keys,isLoading:o,error:m,pagination:{currentPage:n.current_page,totalPages:n.total_pages,totalCount:n.total_count},refresh:h,setKeys:e=>{i(s=>{let l="function"==typeof e?e(s.keys):e;return{...s,keys:l}})}}},eS=l(71594),eC=l(24525),eI=l(21626),eT=l(97214),eA=l(28241),eE=l(58834),eP=l(69552),eO=l(71876);function eL(e){let{data:s=[],columns:l,getRowCanExpand:t,renderSubComponent:a,isLoading:r=!1,expandedRequestId:n,onRowExpand:i}=e,o=(0,eS.b7)({data:s,columns:l,getRowCanExpand:t,getCoreRowModel:(0,eC.sC)(),getExpandedRowModel:(0,eC.rV)(),state:{expanded:n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{}},onExpandedChange:e=>{if(!i)return;let l=n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{},t="function"==typeof e?e(l):e;if(0===Object.keys(t).length){i(null);return}let a=Object.keys(t)[0],r=void 0!==a?s[parseInt(a)]:null;i(r?r.request_id:null)}});return(0,c.jsx)("div",{className:"rounded-lg custom-border",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:r?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading logs..."})})})}):o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))}),e.getIsExpanded()&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:e.getVisibleCells().length,children:a({row:e})})})]},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No logs found"})})})})})]})})}var eD=l(27281),eM=l(41649),eF=l(12514),eR=l(12485),eq=l(18135),eU=l(35242),ez=l(29706),eV=l(77991),eK=l(10900),eB=l(23628),eH=l(74998);function eJ(e){var s,l;let{keyData:t,onCancel:a,onSubmit:r,teams:n,accessToken:i,userID:o,userRole:m}=e,[u]=L.Z.useForm(),[h,x]=(0,d.useState)([]),p=null==n?void 0:n.find(e=>e.team_id===t.team_id),[g,j]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(o&&m&&i)try{if(null===t.team_id){let e=(await (0,y.So)(i,o,m)).data.map(e=>e.id);j(e)}else if(null==p?void 0:p.team_id){let e=await eb(o,m,i,p.team_id);j(Array.from(new Set([...p.models,...e])))}}catch(e){console.error("Error fetching models:",e)}})()},[o,m,i,p,t.team_id]);let f={...t,budget_duration:(l=t.budget_duration)&&({"24h":"daily","7d":"weekly","30d":"monthly"})[l]||null,metadata:t.metadata?JSON.stringify(t.metadata,null,2):"",guardrails:(null===(s=t.metadata)||void 0===s?void 0:s.guardrails)||[]};return(0,c.jsxs)(L.Z,{form:u,onFinish:r,initialValues:f,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Key Alias",name:"key_alias",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[g.length>0&&(0,c.jsx)(O.default.Option,{value:"all-team-models",children:"All Team Models"}),g.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"daily",children:"Daily"}),(0,c.jsx)(O.default.Option,{value:"weekly",children:"Weekly"}),(0,c.jsx)(O.default.Option,{value:"monthly",children:"Monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Guardrails",name:"guardrails",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsx)(L.Z.Item,{name:"token",hidden:!0,children:(0,c.jsx)(q.default,{})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(k.Z,{variant:"light",onClick:a,children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]})}function eW(e){let{selectedToken:s,visible:l,onClose:t,accessToken:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(!1);(0,d.useEffect)(()=>{l&&s&&r.setFieldsValue({key_alias:s.key_alias,max_budget:s.max_budget,tpm_limit:s.tpm_limit,rpm_limit:s.rpm_limit,duration:s.duration||""})},[l,s,r]),(0,d.useEffect)(()=>{l||(i(null),p(!1),r.resetFields())},[l,r]),(0,d.useEffect)(()=>{(null==o?void 0:o.duration)?h((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString()}catch(e){return null}})(o.duration)):h(null)},[null==o?void 0:o.duration]);let g=async()=>{if(s&&a){p(!0);try{let e=await r.validateFields(),l=await (0,y.s0)(a,s.token,e);i(l.key),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key"),p(!1)}}},j=()=>{i(null),p(!1),r.resetFields(),t()};return(0,c.jsx)(M.Z,{title:"Regenerate API Key",open:l,onCancel:j,footer:n?[(0,c.jsx)(k.Z,{onClick:j,children:"Close"},"close")]:[(0,c.jsx)(k.Z,{onClick:j,className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:g,disabled:x,children:x?"Regenerating...":"Regenerate"},"regenerate")],children:n?(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:(null==s?void 0:s.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:n})}),(0,c.jsx)(P.CopyToClipboard,{text:n,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]}):(0,c.jsxs)(L.Z,{form:r,layout:"vertical",onValuesChange:e=>{"duration"in e&&m(s=>({...s,duration:e.duration}))},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",(null==s?void 0:s.expires)?new Date(s.expires).toLocaleString():"Never"]}),u&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",u]})]})})}function eG(e){var s,l;let{keyId:t,onClose:a,keyData:r,accessToken:n,userID:i,userRole:o,teams:m,onKeyDataUpdate:u,onDelete:h}=e,[x,p]=(0,d.useState)(!1),[g]=L.Z.useForm(),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1);if(!r)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(A.Z,{children:"Key not found"})]});let b=async e=>{try{var s,l;if(!n)return;let t=e.token;if(e.key=t,e.metadata&&"string"==typeof e.metadata)try{let l=JSON.parse(e.metadata);e.metadata={...l,...(null===(s=e.guardrails)||void 0===s?void 0:s.length)>0?{guardrails:e.guardrails}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),D.ZP.error("Invalid metadata JSON");return}else e.metadata={...e.metadata||{},...(null===(l=e.guardrails)||void 0===l?void 0:l.length)>0?{guardrails:e.guardrails}:{}};e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,y.Nc)(n,e);u&&u(a),D.ZP.success("Key updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update key"),console.error("Error updating key:",e)}},Z=async()=>{try{if(!n)return;await (0,y.I1)(n,r.token),D.ZP.success("Key deleted successfully"),h&&h(),a()}catch(e){console.error("Error deleting the key:",e),D.ZP.error("Failed to delete key")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(E.Z,{children:r.key_alias||"API Key"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:r.token})]}),o&&eg.LQ.includes(o)&&(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{icon:eB.Z,variant:"secondary",onClick:()=>v(!0),className:"flex items-center",children:"Regenerate Key"}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>f(!0),className:"flex items-center",children:"Delete Key"})]})]}),(0,c.jsx)(eW,{selectedToken:r,visible:_,onClose:()=>v(!1),accessToken:n}),j&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:Z,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>f(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number(r.spend).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",null!==r.max_budget?"$".concat(r.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Key Settings"}),!x&&o&&eg.LQ.includes(o)&&(0,c.jsx)(k.Z,{variant:"light",onClick:()=>p(!0),children:"Edit Settings"})]}),x?(0,c.jsx)(eJ,{keyData:r,onCancel:()=>p(!1),onSubmit:b,teams:m,accessToken:n,userID:i,userRole:o}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.token})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key Alias"}),(0,c.jsx)(A.Z,{children:r.key_alias||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Secret Key"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.key_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)(A.Z,{children:r.team_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),(0,c.jsx)(A.Z,{children:r.organization_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:new Date(r.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Expires"}),(0,c.jsx)(A.Z,{children:r.expires?new Date(r.expires).toLocaleString():"Never"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Spend"}),(0,c.jsxs)(A.Z,{children:["$",Number(r.spend).toFixed(4)," USD"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsx)(A.Z,{children:null!==r.max_budget?"$".concat(r.max_budget," USD"):"Unlimited"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",null!==r.max_parallel_requests?r.max_parallel_requests:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model TPM Limits: ",(null===(s=r.metadata)||void 0===s?void 0:s.model_tpm_limit)?JSON.stringify(r.metadata.model_tpm_limit):"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model RPM Limits: ",(null===(l=r.metadata)||void 0===l?void 0:l.model_rpm_limit)?JSON.stringify(r.metadata.model_rpm_limit):"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(r.metadata,null,2)})]})]})]})})]})]})]})}var eY=l(87908),e$=l(82422),eX=l(2356),eQ=l(44633),e0=l(86462),e1=l(3837),e2=e=>{var s;let{options:l,onApplyFilters:t,onResetFilters:a,initialValues:r={},buttonLabel:n="Filter"}=e,[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)((null===(s=l[0])||void 0===s?void 0:s.name)||""),[h,x]=(0,d.useState)(r),[p,j]=(0,d.useState)(r),[f,_]=(0,d.useState)(!1),[y,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),S=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=e=>{let s=e.target;!S.current||S.current.contains(s)||s.closest(".ant-dropdown")||s.closest(".ant-select-dropdown")||o(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{l.length>0&&l[0].isSearchable&&l[0].searchFn&&C(l[0])},[]);let C=async e=>{if(e.isSearchable&&e.searchFn){Z(!0);try{let s=await e.searchFn("");v(s)}catch(e){console.error("Error loading initial options:",e),v([])}finally{Z(!1)}}};(0,d.useEffect)(()=>{i&&(null==L?void 0:L.isSearchable)&&(null==L?void 0:L.searchFn)&&C(L)},[i,m]);let I=e=>{u(e),_(!1);let s=l.find(s=>s.name===e);(null==s?void 0:s.isSearchable)&&(null==s?void 0:s.searchFn)?C(s):v([])},T=(0,d.useCallback)(ep()(async(e,s)=>{if(s.isSearchable&&s.searchFn){Z(!0);try{let l=await s.searchFn(e);v(l)}catch(e){console.error("Error searching:",e),v([])}finally{Z(!1)}}},300),[]),A=e=>{j(s=>({...s,[m]:e}))},E=()=>{let e={};l.forEach(s=>{e[s.name]=""}),j(e)},P=l.map(e=>({key:e.name,label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[m===e.name&&(0,c.jsx)(e$.Z,{className:"h-4 w-4 text-blue-600"}),e.label||e.name]})})),L=l.find(e=>e.name===m);return(0,c.jsxs)("div",{className:"relative",ref:S,children:[(0,c.jsx)(k.Z,{icon:eX.Z,onClick:()=>o(!i),variant:"secondary",size:"xs",className:"flex items-center pr-2",children:n}),i&&(0,c.jsx)(eF.Z,{className:"absolute left-0 mt-2 w-[500px] z-50 border border-gray-200 shadow-lg",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsx)(g.Z,{menu:{items:P,onClick:e=>{let{key:s}=e;return I(s)},style:{minWidth:"200px"}},onOpenChange:_,open:f,trigger:["click"],children:(0,c.jsxs)(R.ZP,{className:"min-w-40 text-left flex justify-between items-center",children:[(null==L?void 0:L.label)||m,f?(0,c.jsx)(eQ.Z,{className:"h-4 w-4"}):(0,c.jsx)(e0.Z,{className:"h-4 w-4"})]})}),(null==L?void 0:L.isSearchable)?(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search ".concat(L.label||m,"..."),value:p[m]||void 0,onChange:e=>A(e),onSearch:e=>{w(e),T(e,L)},onInputKeyDown:e=>{"Enter"===e.key&&N&&(A(N),e.preventDefault())},filterOption:!1,className:"flex-1 w-full max-w-full truncate min-w-100",loading:b,options:y,allowClear:!0,notFoundContent:b?(0,c.jsx)(eY.Z,{size:"small"}):(0,c.jsx)("div",{className:"p-2",children:N&&(0,c.jsxs)(R.ZP,{type:"link",className:"p-0 mt-1",onClick:()=>{A(N);let e=document.activeElement;e&&e.blur()},children:["Use “",N,"” as filter value"]})})}):(0,c.jsx)(q.default,{placeholder:"Enter value...",value:p[m]||"",onChange:e=>A(e.target.value),className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",suffix:p[m]?(0,c.jsx)(e1.Z,{className:"h-4 w-4 cursor-pointer text-gray-400 hover:text-gray-500",onClick:e=>{e.stopPropagation(),A("")}}):null})]}),(0,c.jsxs)("div",{className:"flex gap-2 justify-end",children:[(0,c.jsx)(R.ZP,{onClick:()=>{E(),a(),o(!1)},children:"Reset"}),(0,c.jsx)(R.ZP,{onClick:()=>{x(p),t(p),o(!1)},children:"Apply Filters"})]})]})})]})},e4=l(16593);let e5=async e=>{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.OD)(e,null,"",null,l,100),r=a.keys.map(e=>e.key_alias).filter(Boolean);s=[...s,...r],l{if(!e)return[];try{let l=[],t=1,a=!0;for(;a;){let r=await (0,y.It)(e,s||null,null);l=[...l,...r.teams],t{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.r6)(e);s=[...s,...a.organizations],l{if(!s){g([]);return}let e=[...s];o["Team ID"]&&(e=e.filter(e=>e.team_id===o["Team ID"])),o["Organization ID"]&&(e=e.filter(e=>e.organization_id===o["Organization ID"])),g(e)},[s,o]),(0,d.useEffect)(()=>{let e=async()=>{let e=await e3(a);e.length>0&&u(e);let s=await e6(a);s.length>0&&x(s)};a&&e()},[a]);let j=(0,e4.a)({queryKey:["allKeys"],queryFn:async()=>{if(!a)throw Error("Access token required");return await e5(a)},enabled:!!a}).data||[];return(0,d.useEffect)(()=>{l&&l.length>0&&u(e=>e.length{t&&t.length>0&&x(e=>e.length{if(c({"Team ID":e["Team ID"]||"","Organization ID":e["Organization ID"]||"","Key Alias":e["Key Alias"]||""}),e["Team ID"]){let s=null==m?void 0:m.find(s=>s.team_id===e["Team ID"]);s&&r(s)}if(e["Organization ID"]){let s=null==h?void 0:h.find(s=>s.organization_id===e["Organization ID"]);s&&n(s)}let s=e["Key Alias"];i(s&&j.find(e=>e===s)||null)},handleFilterReset:()=>{c({"Team ID":"","Organization ID":"","Key Alias":""}),r(null),n(null)}}}({keys:s,teams:i,organizations:j,accessToken:x,setSelectedTeam:m,setCurrentOrg:f,setSelectedKeyAlias:h});(0,d.useEffect)(()=>{if(x){let e=s.map(e=>e.user_id).filter(e=>null!==e);(async()=>{N((await (0,y.Of)(x,e,1,100)).users)})()}},[x,s]),(0,d.useEffect)(()=>{if(_){let e=()=>{_()};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}},[_]);let P=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return s.getCanExpand()?(0,c.jsx)("button",{onClick:s.getToggleExpandedHandler(),style:{cursor:"pointer"},children:s.getIsExpanded()?"▼":"▶"}):null}},{header:"Key ID",accessorKey:"token",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>b(e.getValue()),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>{let s=e.getValue();return(0,c.jsx)(W.Z,{title:s,children:s?s.length>20?"".concat(s.slice(0,20),"..."):s:"-"})}},{header:"Secret Key",accessorKey:"key_name",cell:e=>(0,c.jsx)("span",{className:"font-mono text-xs",children:e.getValue()})},{header:"Team Alias",accessorKey:"team_id",cell:e=>{let{row:s,getValue:l}=e,t=l(),a=null==I?void 0:I.find(e=>e.team_id===t);return(null==a?void 0:a.team_alias)||"Unknown"}},{header:"Team ID",accessorKey:"team_id",cell:e=>(0,c.jsx)(W.Z,{title:e.getValue(),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})},{header:"Organization ID",accessorKey:"organization_id",cell:e=>e.getValue()?e.renderValue():"-"},{header:"User Email",accessorKey:"user_id",cell:e=>{let s=e.getValue(),l=Z.find(e=>e.user_id===s);return(null==l?void 0:l.user_email)?l.user_email:"-"}},{header:"User ID",accessorKey:"user_id",cell:e=>{let s=e.getValue();return s?(0,c.jsx)(W.Z,{title:s,children:(0,c.jsxs)("span",{children:[s.slice(0,7),"..."]})}):"-"}},{header:"Created At",accessorKey:"created_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"-"}},{header:"Created By",accessorKey:"created_by",cell:e=>e.getValue()||"Unknown"},{header:"Expires",accessorKey:"expires",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"Never"}},{header:"Spend (USD)",accessorKey:"spend",cell:e=>Number(e.getValue()).toFixed(4)},{header:"Budget (USD)",accessorKey:"max_budget",cell:e=>null!==e.getValue()&&void 0!==e.getValue()?e.getValue():"Unlimited"},{header:"Budget Reset",accessorKey:"budget_reset_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleString():"Never"}},{header:"Models",accessorKey:"models",cell:e=>{let s=e.getValue();return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:s&&s.length>0?s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):"-"})}},{header:"Rate Limits",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{children:["TPM: ",null!==l.tpm_limit?l.tpm_limit:"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",null!==l.rpm_limit?l.rpm_limit:"Unlimited"]})]})}}];return(0,c.jsx)("div",{className:"w-full h-full overflow-hidden",children:v?(0,c.jsx)(eG,{keyId:v,onClose:()=>b(null),keyData:s.find(e=>e.token===v),onKeyDataUpdate:e=>{l(s=>s.map(s=>s.token===e.token?e8(s,e):s))},onDelete:()=>{l(e=>e.filter(e=>e.token!==v))},accessToken:x,userID:p,userRole:g,teams:I}):(0,c.jsxs)("div",{className:"border-b py-4 flex-1 overflow-hidden",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between w-full mb-2",children:[(0,c.jsx)(e2,{options:[{name:"Team ID",label:"Team ID",isSearchable:!0,searchFn:async e=>I&&0!==I.length?I.filter(s=>s.team_id.toLowerCase().includes(e.toLowerCase())||s.team_alias&&s.team_alias.toLowerCase().includes(e.toLowerCase())).map(e=>({label:"".concat(e.team_alias||e.team_id," (").concat(e.team_id,")"),value:e.team_id})):[]},{name:"Organization ID",label:"Organization ID",isSearchable:!0,searchFn:async e=>T&&0!==T.length?T.filter(s=>{var l,t;return null!==(t=null===(l=s.organization_id)||void 0===l?void 0:l.toLowerCase().includes(e.toLowerCase()))&&void 0!==t&&t}).filter(e=>null!==e.organization_id&&void 0!==e.organization_id).map(e=>({label:"".concat(e.organization_id||"Unknown"," (").concat(e.organization_id,")"),value:e.organization_id})):[]},{name:"Key Alias",label:"Key Alias",isSearchable:!0,searchFn:async e=>C.filter(s=>s.toLowerCase().includes(e.toLowerCase())).map(e=>({label:e,value:e}))}],onApplyFilters:A,initialValues:w,onResetFilters:E}),(0,c.jsxs)("div",{className:"flex items-center gap-4",children:[(0,c.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:["Showing ",t?"...":"".concat((a.currentPage-1)*n+1," - ").concat(Math.min(a.currentPage*n,a.totalCount))," of ",t?"...":a.totalCount," results"]}),(0,c.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",t?"...":a.currentPage," of ",t?"...":a.totalPages]}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage-1),disabled:t||1===a.currentPage,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage+1),disabled:t||a.currentPage===a.totalPages,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]}),(0,c.jsx)("div",{className:"h-[75vh] overflow-auto",children:(0,c.jsx)(eL,{columns:P.filter(e=>"expander"!==e.id),data:S,isLoading:t,getRowCanExpand:()=>!1,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{})})})]})})}console.log=function(){};var e9=e=>{let{userID:s,userRole:l,accessToken:t,selectedTeam:a,setSelectedTeam:r,data:n,setData:i,teams:o,premiumUser:m,currentOrg:u,organizations:h,setCurrentOrg:x,selectedKeyAlias:p,setSelectedKeyAlias:g}=e,[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),[C,I]=(0,d.useState)(null),[T,O]=(0,d.useState)(null),[F,R]=(0,d.useState)((null==a?void 0:a.team_id)||""),[q,U]=(0,d.useState)("");(0,d.useEffect)(()=>{R((null==a?void 0:a.team_id)||"")},[a]);let{keys:z,isLoading:K,error:B,pagination:J,refresh:W,setKeys:G}=ek({selectedTeam:a,currentOrg:u,selectedKeyAlias:p,accessToken:t});window.refreshKeysList=W,window.addNewKeyToList=e=>{G(s=>[e,...s])};let[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(null),[el,et]=(0,d.useState)([]),ea=new Set,[er,en]=(0,d.useState)(!1),[ei,eo]=(0,d.useState)(!1),[ec,ed]=(0,d.useState)(null),[em,eu]=(0,d.useState)(null),[eh]=L.Z.useForm(),[ex,ep]=(0,d.useState)(null),[eg,ej]=(0,d.useState)(ea),[ef,e_]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("in calculateNewExpiryTime for selectedToken",ee),(null==em?void 0:em.duration)?ep((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString("en-US",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!0})}catch(e){return null}})(em.duration)):ep(null),console.log("calculateNewExpiryTime:",ex)},[ee,null==em?void 0:em.duration]),(0,d.useEffect)(()=>{(async()=>{try{if(null===s||null===l||null===t)return;let e=await V(s,l,t);e&&et(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,s,l]),(0,d.useEffect)(()=>{if(o){let e=new Set;o.forEach((s,l)=>{let t=s.team_id;e.add(t)}),ej(e)}},[o]);let ey=async()=>{if(null!=b&&null!=n){try{await (0,y.I1)(t,b);let e=n.filter(e=>e.token!==b);i(e)}catch(e){console.error("Error deleting the key:",e)}v(!1),Z(null)}},ev=(e,s)=>{eu(l=>({...l,[e]:s}))},eb=async()=>{if(!m){D.ZP.error("Regenerate API Key is an Enterprise feature. Please upgrade to use this feature.");return}if(null!=ee)try{let e=await eh.validateFields(),s=await (0,y.s0)(t,ee.token,e);if(ed(s.key),n){let l=n.map(l=>l.token===(null==ee?void 0:ee.token)?{...l,key_name:s.key_name,...e}:l);i(l)}eo(!1),eh.resetFields(),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key")}};return(0,c.jsxs)("div",{children:[(0,c.jsx)(e7,{keys:z,setKeys:G,isLoading:K,pagination:J,onPageChange:e=>{W({page:e})},pageSize:100,teams:o,selectedTeam:a,setSelectedTeam:r,accessToken:t,userID:s,userRole:l,organizations:h,setCurrentOrg:x,refresh:W,selectedKeyAlias:p,setSelectedKeyAlias:g}),_&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ey,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{v(!1),Z(null)},children:"Cancel"})]})]})]})}),(0,c.jsx)(M.Z,{title:"Regenerate API Key",visible:ei,onCancel:()=>{eo(!1),eh.resetFields()},footer:[(0,c.jsx)(k.Z,{onClick:()=>{eo(!1),eh.resetFields()},className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:eb,disabled:!m,children:m?"Regenerate":"Upgrade to Regenerate"},"regenerate")],children:m?(0,c.jsxs)(L.Z,{form:eh,layout:"vertical",onValuesChange:(e,s)=>{"duration"in e&&ev("duration",e.duration)},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry:"," ",(null==ee?void 0:ee.expires)!=null?new Date(ee.expires).toLocaleString():"Never"]}),ex&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",ex]})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to use this feature"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat",target:"_blank",children:"Get Free Trial"})})]})}),ec&&(0,c.jsx)(M.Z,{visible:!!ec,onCancel:()=>ed(null),footer:[(0,c.jsx)(k.Z,{onClick:()=>ed(null),children:"Close"},"close")],children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:(null==ee?void 0:ee.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:ec})}),(0,c.jsx)(P.CopyToClipboard,{text:ec,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]})})]})},se=l(12011);console.log=function(){},console.log("isLocal:",!1);var ss=e=>{let{userID:s,userRole:l,teams:t,keys:a,setUserRole:r,userEmail:n,setUserEmail:i,setTeams:o,setKeys:h,premiumUser:x,organizations:p}=e,[g,j]=(0,d.useState)(null),[f,v]=(0,d.useState)(null),b=(0,m.useSearchParams)(),k=function(e){console.log("COOKIES",document.cookie);let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token"),S=b.get("invitation_id"),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)(null),[E,P]=(0,d.useState)([]),[O,L]=(0,d.useState)(null),[D,M]=(0,d.useState)(null),[F,R]=(0,d.useState)(null);if(window.addEventListener("beforeunload",function(){sessionStorage.clear()}),(0,d.useEffect)(()=>{if(k){let e=(0,u.o)(k);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),I(e.key),e.user_role){let s=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"app_user":return"App User";case"internal_user":return"Internal User";case"internal_user_viewer":return"Internal Viewer";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",s),r(s)}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e))}}if(s&&C&&l&&!a&&!g){let e=sessionStorage.getItem("userModels"+s);e?P(JSON.parse(e)):(console.log("currentOrg: ".concat(JSON.stringify(f))),(async()=>{try{let e=await (0,y.g)(C);L(e);let t=await (0,y.Br)(C,s,l,!1,null,null);j(t.user_info),console.log("userSpendData: ".concat(JSON.stringify(g))),(null==t?void 0:t.teams[0].keys)?h(t.keys.concat(t.teams.filter(e=>"Admin"===l||e.user_id===s).flatMap(e=>e.keys))):h(t.keys),sessionStorage.setItem("userData"+s,JSON.stringify(t.keys)),sessionStorage.setItem("userSpendData"+s,JSON.stringify(t.user_info));let a=(await (0,y.So)(C,s,l)).data.map(e=>e.id);console.log("available_model_names:",a),P(a),console.log("userModels:",E),sessionStorage.setItem("userModels"+s,JSON.stringify(a))}catch(e){console.error("There was an error fetching the data",e),e.message.includes("Invalid proxy server token passed")&&q()}})(),Z(C,s,l,f,o))}},[s,k,C,a,l]),(0,d.useEffect)(()=>{C&&(async()=>{try{let e=await (0,y.e2)(C,[C]);console.log("keyInfo: ",e)}catch(e){e.message.includes("Invalid proxy server token passed")&&q()}})()},[C]),(0,d.useEffect)(()=>{console.log("currentOrg: ".concat(JSON.stringify(f),", accessToken: ").concat(C,", userID: ").concat(s,", userRole: ").concat(l)),C&&(console.log("fetching teams"),Z(C,s,l,f,o))},[f]),(0,d.useEffect)(()=>{if(null!==a&&null!=D&&null!==D.team_id){let e=0;for(let s of(console.log("keys: ".concat(JSON.stringify(a))),a))D.hasOwnProperty("team_id")&&null!==s.team_id&&s.team_id===D.team_id&&(e+=s.spend);console.log("sum: ".concat(e)),A(e)}else if(null!==a){let e=0;for(let s of a)e+=s.spend;A(e)}},[D]),null!=S)return(0,c.jsx)(se.default,{});function q(){(0,_.b)();let e="/sso/key/generate";return console.log("Full URL:",e),window.location.href=e,null}if(null==k)return console.log("All cookies before redirect:",document.cookie),q(),null;try{let e=(0,u.o)(k);console.log("Decoded token:",e);let s=e.exp,l=Math.floor(Date.now()/1e3);if(s&&l>=s){console.log("Token expired, redirecting to login"),(0,_.b)();let e="/sso/key/generate";return console.log("Full URL for expired token:",e),window.location.href=e,null}}catch(s){console.error("Error decoding token:",s),(0,_.b)();let e="/sso/key/generate";return console.log("Full URL after token decode error:",e),window.location.href=e,null}if(null==C)return null;if(null==s)return(0,c.jsx)("h1",{children:"User ID is not set"});if(null==l&&r("App Owner"),l&&"Admin Viewer"==l){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to create keys"})]})}return console.log("inside user dashboard, selected team",D),console.log("All cookies after redirect:",document.cookie),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(N.Z,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,c.jsx)(eN,{userID:s,team:D,teams:t,userRole:l,accessToken:C,data:a,setData:h},D?D.team_id:null),(0,c.jsx)(e9,{userID:s,userRole:l,accessToken:C,selectedTeam:D||null,setSelectedTeam:M,selectedKeyAlias:F,setSelectedKeyAlias:R,data:a,setData:h,premiumUser:x,teams:t,currentOrg:f,setCurrentOrg:v,organizations:p})]})})})},sl=l(97765);(t=n||(n={})).OpenAI="OpenAI",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.Anthropic="Anthropic",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.Google_AI_Studio="Google AI Studio",t.Bedrock="Amazon Bedrock",t.Groq="Groq",t.MistralAI="Mistral AI",t.Deepseek="Deepseek",t.Cohere="Cohere",t.Databricks="Databricks",t.Ollama="Ollama",t.xAI="xAI",t.AssemblyAI="AssemblyAI",t.Cerebras="Cerebras",t.Sambanova="Sambanova",t.Perplexity="Perplexity",t.TogetherAI="TogetherAI",t.Openrouter="Openrouter",t.FireworksAI="Fireworks AI";let st={OpenAI:"openai",OpenAI_Text:"text-completion-openai",Azure:"azure",Azure_AI_Studio:"azure_ai",Anthropic:"anthropic",Google_AI_Studio:"gemini",Bedrock:"bedrock",Groq:"groq",MistralAI:"mistral",Cohere:"cohere_chat",OpenAI_Compatible:"openai",OpenAI_Text_Compatible:"text-completion-openai",Vertex_AI:"vertex_ai",Databricks:"databricks",xAI:"xai",Deepseek:"deepseek",Ollama:"ollama",AssemblyAI:"assemblyai",Cerebras:"cerebras",Sambanova:"sambanova",Perplexity:"perplexity",TogetherAI:"togetherai",Openrouter:"openrouter",FireworksAI:"fireworks_ai"},sa="/ui/assets/logos/",sr={Anthropic:"".concat(sa,"anthropic.svg"),AssemblyAI:"".concat(sa,"assemblyai_small.png"),Azure:"".concat(sa,"microsoft_azure.svg"),"Azure AI Foundry (Studio)":"".concat(sa,"microsoft_azure.svg"),"Amazon Bedrock":"".concat(sa,"bedrock.svg"),Cerebras:"".concat(sa,"cerebras.svg"),Cohere:"".concat(sa,"cohere.svg"),Databricks:"".concat(sa,"databricks.svg"),Deepseek:"".concat(sa,"deepseek.svg"),"Fireworks AI":"".concat(sa,"fireworks.svg"),Groq:"".concat(sa,"groq.svg"),"Google AI Studio":"".concat(sa,"google.svg"),"Mistral AI":"".concat(sa,"mistral.svg"),Ollama:"".concat(sa,"ollama.svg"),OpenAI:"".concat(sa,"openai_small.svg"),"OpenAI Text Completion":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Text Completion Models (Together AI, etc.)":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Endpoints (Together AI, etc.)":"".concat(sa,"openai_small.svg"),Openrouter:"".concat(sa,"openrouter.svg"),Perplexity:"".concat(sa,"perplexity-ai.svg"),Sambanova:"".concat(sa,"sambanova.svg"),TogetherAI:"".concat(sa,"togetherai.svg"),"Vertex AI (Anthropic, Gemini, etc.)":"".concat(sa,"google.svg"),xAI:"".concat(sa,"xai.svg")},sn=e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:sr[e],displayName:e}}let s=Object.keys(st).find(s=>st[s].toLowerCase()===e.toLowerCase());if(!s)return{logo:"",displayName:e};let l=n[s];return{logo:sr[l],displayName:l}},si=e=>"Vertex AI (Anthropic, Gemini, etc.)"===e?"gemini-pro":"Anthropic"==e||"Amazon Bedrock"==e?"claude-3-opus":"Google AI Studio"==e?"gemini-pro":"Azure AI Foundry (Studio)"==e?"azure_ai/command-r-plus":"Azure"==e?"azure/my-deployment":"gpt-3.5-turbo",so=(e,s)=>{console.log("Provider key: ".concat(e));let l=st[e];console.log("Provider mapped to: ".concat(l));let t=[];return e&&"object"==typeof s&&(Object.entries(s).forEach(e=>{let[s,a]=e;null!==a&&"object"==typeof a&&"litellm_provider"in a&&(a.litellm_provider===l||a.litellm_provider.includes(l))&&t.push(s)}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(s).forEach(e=>{let[s,l]=e;null!==l&&"object"==typeof l&&"litellm_provider"in l&&"cohere"===l.litellm_provider&&t.push(s)}))),t},sc=async(e,s,l)=>{try{console.log("handling submit for formValues:",e);let s=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let l=st[e.custom_llm_provider]+"/*";e.model_name=l,s.push({public_name:l,litellm_model:l}),e.model=l}let l=[];for(let t of s){let s={},a={},r=t.public_name;for(let[l,r]of(s.model=t.litellm_model,e.input_cost_per_token&&(e.input_cost_per_token=Number(e.input_cost_per_token)/1e6),e.output_cost_per_token&&(e.output_cost_per_token=Number(e.output_cost_per_token)/1e6),s.model=t.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==r&&"custom_pricing"!==l&&"pricing_model"!==l&&"cache_control"!==l){if("model_name"==l)s.model=r;else if("custom_llm_provider"==l){console.log("custom_llm_provider:",r);let e=st[r];s.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==l)continue;else if("base_model"===l)a[l]=r;else if("team_id"===l)a.team_id=r;else if("mode"==l)console.log("placing mode in modelInfo"),a.mode=r,delete s.mode;else if("custom_model_name"===l)s.model=r;else if("litellm_extra_params"==l){console.log("litellm_extra_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,t]of Object.entries(e))s[l]=t}}else if("model_info_params"==l){console.log("model_info_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[s,l]of Object.entries(e))a[s]=l}}else if("input_cost_per_token"===l||"output_cost_per_token"===l||"input_cost_per_second"===l){r&&(s[l]=Number(r));continue}else s[l]=r}l.push({litellmParamsObj:s,modelInfoObj:a,modelName:r})}return l}catch(e){D.ZP.error("Failed to create model: "+e,10)}},sd=async(e,s,l,t)=>{try{let a=await sc(e,s,l);if(!a||0===a.length)return;for(let e of a){let{litellmParamsObj:l,modelInfoObj:t,modelName:a}=e,r={model_name:a,litellm_params:l,model_info:t},n=await (0,y.kK)(s,r);console.log("response for model create call: ".concat(n.data))}t&&t(),l.resetFields()}catch(e){D.ZP.error("Failed to add model: "+e,10)}};var sm=l(53410),su=l(47451),sh=l(69410);let{Link:sx}=es.default,sp={[n.OpenAI]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Vertex_AI]:[{key:"vertex_project",label:"Vertex Project",placeholder:"adroit-cadet-1234..",required:!0},{key:"vertex_location",label:"Vertex Location",placeholder:"us-east-1",required:!0},{key:"vertex_credentials",label:"Vertex Credentials",required:!0,type:"upload"}],[n.AssemblyAI]:[{key:"api_base",label:"API Base",type:"select",required:!0,options:["https://api.assemblyai.com","https://api.eu.assemblyai.com"]},{key:"api_key",label:"AssemblyAI API Key",type:"password",required:!0}],[n.Azure]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_version",label:"API Version",placeholder:"2023-07-01-preview",tooltip:"By default litellm will use the latest version. If you want to use a different version, you can specify it here"},{key:"base_model",label:"Base Model",placeholder:"azure/gpt-3.5-turbo"},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.Azure_AI_Studio]:[{key:"api_base",label:"API Base",placeholder:"https://.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",tooltip:"Enter your full Target URI from Azure Foundry here. Example: https://litellm8397336933.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",required:!0},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.OpenAI_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Bedrock]:[{key:"aws_access_key_id",label:"AWS Access Key ID",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_secret_access_key",label:"AWS Secret Access Key",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_region_name",label:"AWS Region Name",placeholder:"us-east-1",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."}],[n.Ollama]:[],[n.Anthropic]:[{key:"api_key",label:"API Key",placeholder:"sk-",type:"password",required:!0}],[n.Google_AI_Studio]:[{key:"api_key",label:"API Key",placeholder:"aig-",type:"password",required:!0}],[n.Groq]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.MistralAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Deepseek]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cohere]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Databricks]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.xAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cerebras]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Sambanova]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Perplexity]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.TogetherAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Openrouter]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.FireworksAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}]};var sg=e=>{let{selectedProvider:s,uploadProps:l}=e,t=n[s],a=d.useMemo(()=>sp[t]||[],[t]);return(0,c.jsx)(c.Fragment,{children:a.map(e=>{var s;return(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:e.label,name:e.key,rules:e.required?[{required:!0,message:"Required"}]:void 0,tooltip:e.tooltip,className:"vertex_credentials"===e.key?"mb-0":void 0,children:"select"===e.type?(0,c.jsx)(O.default,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"upload"===e.type?(0,c.jsx)(et.Z,{...l,children:(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(en.Z,{}),children:"Click to Upload"})}):(0,c.jsx)(S.Z,{placeholder:e.placeholder,type:"password"===e.type?"password":"text"})}),"vertex_credentials"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Give litellm a gcp service account(.json file), so it can make the relevant calls"})})]}),"base_model"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,c.jsx)(sx,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key)})})};let{Title:sj,Link:sf}=es.default;var s_=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,onUpdateCredential:a,uploadProps:r,addOrEdit:i,existingCredential:o}=e,[m]=L.Z.useForm(),[u,h]=(0,d.useState)(n.OpenAI),[x,p]=(0,d.useState)(!1);return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(o))),(0,c.jsx)(M.Z,{title:"add"===i?"Add New Credential":"Edit Credential",visible:s,onCancel:()=>{l(),m.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:m,onFinish:e=>{"add"===i?t(e):a(e),m.resetFields()},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==o?void 0:o.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials",disabled:null!=o&&!!o.credential_name})}),(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,c.jsx)(O.default,{value:(null==o?void 0:o.credential_info.custom_llm_provider)||u,onChange:e=>{h(e)},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sg,{selectedProvider:u,uploadProps:r}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sf,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),m.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"add"===i?"Add Credential":"Update Credential"})]})]})]})})},sy=e=>{let{accessToken:s,uploadProps:l,credentialList:t,fetchCredentials:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)(null),[h]=L.Z.useForm();console.log("selectedCredential in credentials panel: ".concat(JSON.stringify(m)));let x=["credential_name","custom_llm_provider"],p=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.eZ)(s,e.credential_name,t);D.ZP.success("Credential updated successfully"),console.log("response: ".concat(JSON.stringify(r))),o(!1),a(s)},g=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.oC)(s,t);D.ZP.success("Credential added successfully"),console.log("response: ".concat(JSON.stringify(r))),n(!1),a(s)};(0,d.useEffect)(()=>{s&&a(s)},[s]);let j=e=>{let s={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"},l=s[e.toLowerCase()]||s.default;return(0,c.jsx)(eM.Z,{color:l,size:"xs",children:e})},f=async e=>{if(!s){console.error("No access token found");return}let l=await (0,y.gX)(s,e);console.log("response: ".concat(JSON.stringify(l))),D.ZP.success("Credential deleted successfully"),a(s)};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsxs)(A.Z,{children:["Configured credentials for different AI providers. Add and manage your API credentials."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/credentials",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]})}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Credential Name"}),(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Description"})]})}),(0,c.jsx)(eT.Z,{children:t&&0!==t.length?t.map((e,s)=>{var l,t;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.credential_name}),(0,c.jsx)(eA.Z,{children:j((null===(l=e.credential_info)||void 0===l?void 0:l.custom_llm_provider)||"-")}),(0,c.jsx)(eA.Z,{children:(null===(t=e.credential_info)||void 0===t?void 0:t.description)||"-"}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{icon:sm.Z,variant:"light",size:"sm",onClick:()=>{console.log("credential being set: ".concat(JSON.stringify(e))),u(e),o(!0)}}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"light",size:"sm",onClick:()=>f(e.credential_name)})]})]},s)}):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),className:"mt-4",children:"Add Credential"}),r&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:r,onCancel:()=>n(!1),uploadProps:l,addOrEdit:"add",onUpdateCredential:p,existingCredential:null}),i&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:i,existingCredential:m,onUpdateCredential:p,uploadProps:l,onCancel:()=>o(!1),addOrEdit:"edit"})]})};let sv=e=>{var s;return(null==e?void 0:null===(s=e.model_info)||void 0===s?void 0:s.team_public_model_name)?e.model_info.team_public_model_name:(null==e?void 0:e.model_name)||"-"};var sb=l(53003),sZ=l(47323),sN=l(75105),sw=l(40278),sk=l(14301),sS=l(59664),sC=e=>{let{modelMetrics:s,modelMetricsCategories:l,customTooltip:t,premiumUser:a}=e;return(0,c.jsx)(sS.Z,{title:"Time to First token (s)",className:"h-72",data:s,index:"date",showLegend:!1,categories:l,colors:["indigo","rose"],connectNulls:!0,customTooltip:t})},sI=e=>{let{teamData:s,canEditTeam:l,handleMemberDelete:t,setSelectedEditMember:a,setIsEditMemberModalVisible:r,setIsAddMemberModalVisible:n}=e;return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"User Email"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:s.team_info.members_with_roles.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_email})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.role})}),(0,c.jsx)(eA.Z,{children:l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{a(e),r(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(e)})]})})]},s))})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),children:"Add Member"})]})},sT=l(61994),sA=l(85180),sE=l(89245),sP=l(78355);let sO={"/key/generate":"Member can generate a virtual key for this team","/key/update":"Member can update a virtual key belonging to this team","/key/delete":"Member can delete a virtual key belonging to this team","/key/info":"Member can get info about a virtual key belonging to this team","/key/regenerate":"Member can regenerate a virtual key belonging to this team","/key/{key_id}/regenerate":"Member can regenerate a virtual key belonging to this team","/key/list":"Member can list virtual keys belonging to this team","/key/block":"Member can block a virtual key belonging to this team","/key/unblock":"Member can unblock a virtual key belonging to this team"},sL=e=>e.includes("/info")||e.includes("/list")?"GET":"POST",sD=e=>{let s=sL(e),l=sO[e];if(!l){for(let[s,t]of Object.entries(sO))if(e.includes(s)){l=t;break}}return l||(l="Access ".concat(e)),{method:s,endpoint:e,description:l,route:e}};var sM=e=>{let{teamId:s,accessToken:l,canEditTeam:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)(!0),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),g=async()=>{try{if(m(!0),!l)return;let e=await (0,y.aC)(l,s),t=e.all_available_permissions||[];r(t);let a=e.team_member_permissions||[];i(a),p(!1)}catch(e){D.ZP.error("Failed to load permissions"),console.error("Error fetching permissions:",e)}finally{m(!1)}};(0,d.useEffect)(()=>{g()},[s,l]);let j=(e,s)=>{i(s?[...n,e]:n.filter(s=>s!==e)),p(!0)},f=async()=>{try{if(!l)return;h(!0),await (0,y.TF)(l,s,n),D.ZP.success("Permissions updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update permissions"),console.error("Error updating permissions:",e)}finally{h(!1)}};if(o)return(0,c.jsx)("div",{className:"p-6 text-center",children:"Loading permissions..."});let _=a.length>0;return(0,c.jsxs)(eF.Z,{className:"bg-white shadow-md rounded-md p-6",children:[(0,c.jsxs)("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center border-b pb-4 mb-6",children:[(0,c.jsx)(E.Z,{className:"mb-2 sm:mb-0",children:"Member Permissions"}),t&&x&&(0,c.jsxs)("div",{className:"flex gap-3",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(sE.Z,{}),onClick:()=>{g()},children:"Reset"}),(0,c.jsxs)(k.Z,{onClick:f,loading:u,className:"flex items-center gap-2",children:[(0,c.jsx)(sP.Z,{})," Save Changes"]})]})]}),(0,c.jsx)(A.Z,{className:"mb-6 text-gray-600",children:"Control what team members can do when they are not team admins."}),_?(0,c.jsxs)(eI.Z,{className:"mt-4",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Method"}),(0,c.jsx)(eP.Z,{children:"Endpoint"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Access"})]})}),(0,c.jsx)(eT.Z,{children:a.map(e=>{let s=sD(e);return(0,c.jsxs)(eO.Z,{className:"hover:bg-gray-50 transition-colors",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"px-2 py-1 rounded text-xs font-medium ".concat("GET"===s.method?"bg-blue-100 text-blue-800":"bg-green-100 text-green-800"),children:s.method})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"font-mono text-sm text-gray-800",children:s.endpoint})}),(0,c.jsx)(eA.Z,{className:"text-gray-700",children:s.description}),(0,c.jsx)(eA.Z,{className:"text-right",children:(0,c.jsx)(sT.Z,{checked:n.includes(e),onChange:s=>j(e,s.target.checked),disabled:!t})})]},e)})})]}):(0,c.jsx)("div",{className:"py-12",children:(0,c.jsx)(sA.Z,{description:"No permissions available"})})]})},sF=e=>{var s,l,t;let{visible:a,onCancel:r,onSubmit:n,initialData:i,mode:o,config:m}=e,[u]=L.Z.useForm();console.log("Initial Data:",i),(0,d.useEffect)(()=>{if(a){if("edit"===o&&i)u.setFieldsValue({...i,role:i.role||m.defaultRole});else{var e;u.resetFields(),u.setFieldsValue({role:m.defaultRole||(null===(e=m.roleOptions[0])||void 0===e?void 0:e.value)})}}},[a,i,o,u,m.defaultRole,m.roleOptions]);let h=async e=>{try{let s=Object.entries(e).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:"string"==typeof t?t.trim():t}},{});n(s),u.resetFields(),D.ZP.success("Successfully ".concat("add"===o?"added":"updated"," member"))}catch(e){D.ZP.error("Failed to submit form"),console.error("Form submission error:",e)}},x=e=>{switch(e.type){case"input":return(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",onChange:e=>{e.target.value=e.target.value.trim()}});case"select":var s;return(0,c.jsx)(O.default,{children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))});default:return null}};return(0,c.jsx)(M.Z,{title:m.title||("add"===o?"Add Member":"Edit Member"),open:a,width:800,footer:null,onCancel:r,children:(0,c.jsxs)(L.Z,{form:u,onFinish:h,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[m.showEmail&&(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user@example.com",onChange:e=>{e.target.value=e.target.value.trim()}})}),m.showEmail&&m.showUserId&&(0,c.jsx)("div",{className:"text-center mb-4",children:(0,c.jsx)(A.Z,{children:"OR"})}),m.showUserId&&(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user_123",onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"Role"}),"edit"===o&&i&&(0,c.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(l=i.role,(null===(t=m.roleOptions.find(e=>e.value===l))||void 0===t?void 0:t.label)||l),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,c.jsx)(O.default,{children:"edit"===o&&i?[...m.roleOptions.filter(e=>e.value===i.role),...m.roleOptions.filter(e=>e.value!==i.role)].map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value)):m.roleOptions.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))})}),null===(s=m.additionalFields)||void 0===s?void 0:s.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:x(e)},e.name)),(0,c.jsxs)("div",{className:"text-right mt-6",children:[(0,c.jsx)(R.ZP,{onClick:r,className:"mr-2",children:"Cancel"}),(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"add"===o?"Add Member":"Save Changes"})]})]})})},sR=e=>{let{isVisible:s,onCancel:l,onSubmit:t,accessToken:a,title:r="Add Team Member",roles:n=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:i="user"}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)("user_email"),j=async(e,s)=>{if(!e){u([]);return}x(!0);try{let l=new URLSearchParams;if(l.append(s,e),null==a)return;let t=(await (0,y.u5)(a,l)).map(e=>({label:"user_email"===s?"".concat(e.user_email):"".concat(e.user_id),value:"user_email"===s?e.user_email:e.user_id,user:e}));u(t)}catch(e){console.error("Error fetching users:",e)}finally{x(!1)}},f=(0,d.useCallback)(ep()((e,s)=>j(e,s),300),[]),_=(e,s)=>{g(s),f(e,s)},v=(e,s)=>{let l=s.user;o.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:o.getFieldValue("role")})};return(0,c.jsx)(M.Z,{title:r,open:s,onCancel:()=>{o.resetFields(),u([]),l()},footer:null,width:800,children:(0,c.jsxs)(L.Z,{form:o,onFinish:t,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:i},children:[(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>_(e,"user_email"),onSelect:(e,s)=>v(e,s),options:"user_email"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>_(e,"user_id"),onSelect:(e,s)=>v(e,s),options:"user_id"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)(L.Z.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:i,children:n.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:(0,c.jsxs)(W.Z,{title:e.description,children:[(0,c.jsx)("span",{className:"font-medium",children:e.label}),(0,c.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,c.jsx)("div",{className:"text-right mt-4",children:(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"Add Member"})})]})})},sq=e=>{var s;let{teamId:l,onClose:t,accessToken:a,is_team_admin:r,is_proxy_admin:n,userModels:i,editTeam:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p,g]=(0,d.useState)(!1),[j]=L.Z.useForm(),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(null),[Z,N]=(0,d.useState)(!1);console.log("userModels in team info",i);let S=r||n,C=async()=>{try{if(x(!0),!a)return;let e=await (0,y.Xm)(a,l);u(e)}catch(e){D.ZP.error("Failed to load team information"),console.error("Error fetching team info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{C()},[l,a]);let I=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.cu)(a,l,s),D.ZP.success("Team member added successfully"),g(!1),j.resetFields(),C()}catch(e){D.ZP.error("Failed to add team member"),console.error("Error adding team member:",e)}},T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.sN)(a,l,s),D.ZP.success("Team member updated successfully"),_(!1),C()}catch(e){D.ZP.error("Failed to update team member"),console.error("Error updating team member:",e)}},P=async e=>{try{if(null==a)return;await (0,y.Lp)(a,l,e),D.ZP.success("Team member removed successfully"),C()}catch(e){D.ZP.error("Failed to remove team member"),console.error("Error removing team member:",e)}},M=async e=>{try{if(!a)return;let s={};try{s=e.metadata?JSON.parse(e.metadata):{}}catch(e){D.ZP.error("Invalid JSON in metadata field");return}let t={team_id:l,team_alias:e.team_alias,models:e.models,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration,metadata:{...s,guardrails:e.guardrails||[]}};await (0,y.Gh)(a,t),D.ZP.success("Team settings updated successfully"),N(!1),C()}catch(e){D.ZP.error("Failed to update team settings"),console.error("Error updating team:",e)}};if(h)return(0,c.jsx)("div",{className:"p-4",children:"Loading..."});if(!(null==m?void 0:m.team_info))return(0,c.jsx)("div",{className:"p-4",children:"Team not found"});let{team_info:F}=m;return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:F.team_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:F.team_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?3:0,children:[(0,c.jsx)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"},"overview"),...S?[(0,c.jsx)(eR.Z,{children:"Members"},"members"),(0,c.jsx)(eR.Z,{children:"Member Permissions"},"member-permissions"),(0,c.jsx)(eR.Z,{children:"Settings"},"settings")]:[]]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",F.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===F.max_budget?"Unlimited":"$".concat(F.max_budget)]}),F.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",F.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",F.rpm_limit||"Unlimited"]}),F.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",F.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sI,{teamData:m,canEditTeam:S,handleMemberDelete:P,setSelectedEditMember:b,setIsEditMemberModalVisible:_,setIsAddMemberModalVisible:g})}),S&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sM,{teamId:l,accessToken:a,canEditTeam:S})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Team Settings"}),S&&!Z&&(0,c.jsx)(k.Z,{onClick:()=>N(!0),children:"Edit Settings"})]}),Z?(0,c.jsxs)(L.Z,{form:j,onFinish:M,initialValues:{...F,team_alias:F.team_alias,models:F.models,tpm_limit:F.tpm_limit,rpm_limit:F.rpm_limit,max_budget:F.max_budget,budget_duration:F.budget_duration,guardrails:(null===(s=F.metadata)||void 0===s?void 0:s.guardrails)||[],metadata:F.metadata?JSON.stringify(F.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(q.default,{type:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map((e,s)=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},s))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>N(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team Name"}),(0,c.jsx)("div",{children:F.team_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"font-mono",children:F.team_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(F.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",F.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==F.max_budget?"$".concat(F.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",F.budget_duration||"Never"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Status"}),(0,c.jsx)(eM.Z,{color:F.blocked?"red":"green",children:F.blocked?"Blocked":"Active"})]})]})]})})]})]}),(0,c.jsx)(sF,{visible:f,onCancel:()=>_(!1),onSubmit:T,initialData:v,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Admin",value:"admin"},{label:"User",value:"user"}]}}),(0,c.jsx)(sR,{isVisible:p,onCancel:()=>g(!1),onSubmit:I,accessToken:a})]})},sU=l(45589);let{Title:sz,Link:sV}=es.default;var sK=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,existingCredential:a,setIsCredentialModalOpen:r}=e,[n]=L.Z.useForm();return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(a))),(0,c.jsx)(M.Z,{title:"Reuse Credentials",visible:s,onCancel:()=>{l(),n.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:n,onFinish:e=>{t(e),n.resetFields(),r(!1)},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==a?void 0:a.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries((null==a?void 0:a.credential_values)||{}).map(e=>{let[s,l]=e;return(0,c.jsx)(L.Z.Item,{label:s,name:s,initialValue:l,children:(0,c.jsx)(S.Z,{placeholder:"Enter ".concat(s),disabled:!0})},s)}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sV,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})},sB=l(63709),sH=l(45246),sJ=l(96473);let{Text:sW}=es.default;var sG=e=>{let{form:s,showCacheControl:l,onCacheControlChange:t}=e,a=e=>{let l=s.getFieldValue("litellm_extra_params");try{let t=l?JSON.parse(l):{};e.length>0?t.cache_control_injection_points=e:delete t.cache_control_injection_points,Object.keys(t).length>0?s.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):s.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Cache Control Injection Points",name:"cache_control",valuePropName:"checked",className:"mb-4",tooltip:"Tell litellm where to inject cache control checkpoints. You can specify either by role (to apply to all messages of that role) or by specific message index.",children:(0,c.jsx)(sB.Z,{onChange:t,className:"bg-gray-600"})}),l&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(sW,{className:"text-sm text-gray-500 block mb-4",children:"Providers like Anthropic, Bedrock API require users to specify where to inject cache control checkpoints, litellm can automatically add them for you as a cost saving feature."}),(0,c.jsx)(L.Z.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(e,l)=>{let{add:t,remove:r}=l;return(0,c.jsxs)(c.Fragment,{children:[e.map((l,t)=>(0,c.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,c.jsx)(L.Z.Item,{...l,label:"Type",name:[l.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,c.jsx)(O.default,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,c.jsx)(L.Z.Item,{...l,label:"Role",name:[l.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,c.jsx)(O.default,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),(0,c.jsx)(L.Z.Item,{...l,label:"Index",name:[l.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,c.jsx)(z,{type:"number",placeholder:"Optional",step:1,min:0,onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),e.length>1&&(0,c.jsx)(sH.Z,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{r(l.name),setTimeout(()=>{a(s.getFieldValue("cache_control_points"))},0)}})]},l.key)),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)("button",{type:"button",className:"flex items-center justify-center w-full border border-dashed border-gray-300 py-2 px-4 text-gray-600 hover:text-blue-600 hover:border-blue-300 transition-all rounded",onClick:()=>t(),children:[(0,c.jsx)(sJ.Z,{className:"mr-2"}),"Add Injection Point"]})})]})}})]})]})};function sY(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j,f,_,v,b,Z,N;let{modelId:C,onClose:I,modelData:T,accessToken:P,userID:O,userRole:F,editModel:q,setEditModalVisible:U,setSelectedModel:V,onModelUpdate:K}=e,[B]=L.Z.useForm(),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(!1),[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)(null),[en,ei]=(0,d.useState)(!1),eo="Admin"===F||T.model_info.created_by===O,ec=(null===(s=T.litellm_params)||void 0===s?void 0:s.litellm_credential_name)!=null&&(null===(l=T.litellm_params)||void 0===l?void 0:l.litellm_credential_name)!=void 0;console.log("usingExistingCredential, ",ec),console.log("modelData.litellm_params.litellm_credential_name, ",T.litellm_params.litellm_credential_name),(0,d.useEffect)(()=>{let e=async()=>{var e;if(!P)return;let s=await (0,y.ix)(P,C);console.log("modelInfoResponse, ",s);let l=s.data[0];J(l),(null==l?void 0:null===(e=l.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&ei(!0)};(async()=>{if(console.log("accessToken, ",P),!P||ec)return;let e=await (0,y.Qg)(P,null,C);console.log("existingCredentialResponse, ",e),er({credential_name:e.credential_name,credential_values:e.credential_values,credential_info:e.credential_info})})(),e()},[P,C]);let ed=async e=>{var s;if(console.log("values, ",e),!P)return;let l={credential_name:e.credential_name,model_id:C,credential_info:{custom_llm_provider:null===(s=H.litellm_params)||void 0===s?void 0:s.custom_llm_provider}};D.ZP.info("Storing credential.."),console.log("credentialResponse, ",await (0,y.oC)(P,l)),D.ZP.success("Credential stored successfully")},em=async e=>{try{var s;if(!P)return;es(!0);let l={...H.litellm_params,model:e.litellm_model_name,api_base:e.api_base,custom_llm_provider:e.custom_llm_provider,organization:e.organization,tpm:e.tpm,rpm:e.rpm,max_retries:e.max_retries,timeout:e.timeout,stream_timeout:e.stream_timeout,input_cost_per_token:e.input_cost/1e6,output_cost_per_token:e.output_cost/1e6};e.cache_control&&(null===(s=e.cache_control_injection_points)||void 0===s?void 0:s.length)>0?l.cache_control_injection_points=e.cache_control_injection_points:delete l.cache_control_injection_points;let t={model_name:e.model_name,litellm_params:l,model_info:{id:C}};await (0,y.um)(P,t);let a={...H,model_name:e.model_name,litellm_model_name:e.litellm_model_name,litellm_params:l};J(a),K&&K(a),D.ZP.success("Model settings updated successfully"),Q(!1),et(!1)}catch(e){console.error("Error updating model:",e),D.ZP.error("Failed to update model settings")}finally{es(!1)}};if(!T)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsx)(A.Z,{children:"Model not found"})]});let eu=async()=>{try{if(!P)return;await (0,y.Og)(P,C),D.ZP.success("Model deleted successfully"),K&&K({deleted:!0,model_info:{id:C}}),I()}catch(e){console.error("Error deleting the model:",e),D.ZP.error("Failed to delete model")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsxs)(E.Z,{children:["Public Model Name: ",sv(T)]}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:T.model_info.id})]}),(0,c.jsxs)("div",{className:"flex gap-2",children:["Admin"===F&&(0,c.jsx)(k.Z,{icon:sU.Z,variant:"secondary",onClick:()=>$(!0),className:"flex items-center",children:"Re-use Credentials"}),eo&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>G(!0),className:"flex items-center",children:"Delete Model"})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-6",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Raw JSON"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Provider"}),(0,c.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[T.provider&&(0,c.jsx)("img",{src:sn(T.provider).logo,alt:"".concat(T.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,l=s.parentElement;if(l){var t;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(t=T.provider)||void 0===t?void 0:t.charAt(0))||"-",l.replaceChild(e,s)}}}),(0,c.jsx)(E.Z,{children:T.provider||"Not Set"})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"LiteLLM Model"}),(0,c.jsx)("pre",{children:(0,c.jsx)(E.Z,{children:T.litellm_model_name||"Not Set"})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Pricing"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Input: $",T.input_cost,"/1M tokens"]}),(0,c.jsxs)(A.Z,{children:["Output: $",T.output_cost,"/1M tokens"]})]})]})]}),(0,c.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Created At ",T.model_info.created_at?new Date(T.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})}),"Created By ",T.model_info.created_by||"Not Set"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Model Settings"}),eo&&!el&&(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>et(!0),className:"flex items-center",children:"Edit Model"})]}),H?(0,c.jsx)(L.Z,{form:B,onFinish:em,initialValues:{model_name:H.model_name,litellm_model_name:H.litellm_model_name,api_base:H.litellm_params.api_base,custom_llm_provider:H.litellm_params.custom_llm_provider,organization:H.litellm_params.organization,tpm:H.litellm_params.tpm,rpm:H.litellm_params.rpm,max_retries:H.litellm_params.max_retries,timeout:H.litellm_params.timeout,stream_timeout:H.litellm_params.stream_timeout,input_cost:H.litellm_params.input_cost_per_token?1e6*H.litellm_params.input_cost_per_token:(null===(t=H.model_info)||void 0===t?void 0:t.input_cost_per_token)*1e6||null,output_cost:(null===(a=H.litellm_params)||void 0===a?void 0:a.output_cost_per_token)?1e6*H.litellm_params.output_cost_per_token:(null===(r=H.model_info)||void 0===r?void 0:r.output_cost_per_token)*1e6||null,cache_control:null!==(n=H.litellm_params)&&void 0!==n&&!!n.cache_control_injection_points,cache_control_injection_points:(null===(i=H.litellm_params)||void 0===i?void 0:i.cache_control_injection_points)||[]},layout:"vertical",onValuesChange:()=>Q(!0),children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"LiteLLM Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"litellm_model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter LiteLLM model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.litellm_model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"input_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter input cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(o=H.litellm_params)||void 0===o?void 0:o.input_cost_per_token)?((null===(m=H.litellm_params)||void 0===m?void 0:m.input_cost_per_token)*1e6).toFixed(4):(null==H?void 0:null===(u=H.model_info)||void 0===u?void 0:u.input_cost_per_token)?(1e6*H.model_info.input_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"output_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter output cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(h=H.litellm_params)||void 0===h?void 0:h.output_cost_per_token)?(1e6*H.litellm_params.output_cost_per_token).toFixed(4):(null==H?void 0:null===(x=H.model_info)||void 0===x?void 0:x.output_cost_per_token)?(1e6*H.model_info.output_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Base"}),el?(0,c.jsx)(L.Z.Item,{name:"api_base",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter API base"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(p=H.litellm_params)||void 0===p?void 0:p.api_base)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Custom LLM Provider"}),el?(0,c.jsx)(L.Z.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom LLM provider"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(g=H.litellm_params)||void 0===g?void 0:g.custom_llm_provider)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),el?(0,c.jsx)(L.Z.Item,{name:"organization",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter organization"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(j=H.litellm_params)||void 0===j?void 0:j.organization)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"TPM (Tokens per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"tpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter TPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(f=H.litellm_params)||void 0===f?void 0:f.tpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"RPM (Requests per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"rpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter RPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(_=H.litellm_params)||void 0===_?void 0:_.rpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Max Retries"}),el?(0,c.jsx)(L.Z.Item,{name:"max_retries",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter max retries"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(v=H.litellm_params)||void 0===v?void 0:v.max_retries)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(b=H.litellm_params)||void 0===b?void 0:b.timeout)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Stream Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"stream_timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter stream timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(Z=H.litellm_params)||void 0===Z?void 0:Z.stream_timeout)||"Not Set"})]}),el?(0,c.jsx)(sG,{form:B,showCacheControl:en,onCacheControlChange:e=>ei(e)}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Cache Control"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(N=H.litellm_params)||void 0===N?void 0:N.cache_control_injection_points)?(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{children:"Enabled"}),(0,c.jsx)("div",{className:"mt-2",children:H.litellm_params.cache_control_injection_points.map((e,s)=>(0,c.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,c.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,c.jsxs)("span",{children:[" Index: ",e.index]})]},s))})]}):"Disabled"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:T.model_info.team_id||"Not Set"})]})]}),el&&(0,c.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{B.resetFields(),Q(!1),et(!1)},children:"Cancel"}),(0,c.jsx)(k.Z,{variant:"primary",onClick:()=>B.submit(),loading:ee,children:"Save Changes"})]})]})}):(0,c.jsx)(A.Z,{children:"Loading..."})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(T,null,2)})})})]})]}),W&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Model"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this model?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(R.ZP,{onClick:eu,className:"ml-2",danger:!0,children:"Delete"}),(0,c.jsx)(R.ZP,{onClick:()=>G(!1),children:"Cancel"})]})]})]})}),Y&&!ec?(0,c.jsx)(sK,{isVisible:Y,onCancel:()=>$(!1),onAddCredential:ed,existingCredential:ea,setIsCredentialModalOpen:$}):(0,c.jsx)(M.Z,{open:Y,onCancel:()=>$(!1),title:"Using Existing Credential",children:(0,c.jsx)(A.Z,{children:T.litellm_params.litellm_credential_name})})]})}var s$=l(67960),sX=e=>{let{selectedProvider:s,providerModels:l,getPlaceholder:t}=e,a=L.Z.useFormInstance(),r=e=>{let s=e.target.value,l=(a.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:s,litellm_model:s}:e);a.setFieldsValue({model_mappings:l})};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)(L.Z.Item,{label:"LiteLLM Model Name(s)",tooltip:"Actual model name used for making litellm.completion() / litellm.embedding() call.",className:"mb-0",children:[(0,c.jsx)(L.Z.Item,{name:"model",rules:[{required:!0,message:"Please select at least one model."}],noStyle:!0,children:s===n.Azure||s===n.OpenAI_Compatible||s===n.Ollama?(0,c.jsx)(S.Z,{placeholder:t(s)}):l.length>0?(0,c.jsx)(O.default,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:e=>{let s=Array.isArray(e)?e:[e];if(s.includes("all-wildcard"))a.setFieldsValue({model_name:void 0,model_mappings:[]});else{let e=s.map(e=>({public_name:e,litellm_model:e}));a.setFieldsValue({model_mappings:e})}},optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:"All ".concat(s," Models (Wildcard)"),value:"all-wildcard"},...l.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,c.jsx)(S.Z,{placeholder:t(s)})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.model!==s.model,children:e=>{let{getFieldValue:s}=e,l=s("model")||[];return(Array.isArray(l)?l:[l]).includes("custom")&&(0,c.jsx)(L.Z.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom model name",onChange:r})})}})]}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Actual model name used for making litellm.completion() call. We loadbalance models with the same public name"})})]})]})},sQ=()=>{let e=L.Z.useFormInstance(),[s,l]=(0,d.useState)(0),t=L.Z.useWatch("model",e)||[],a=Array.isArray(t)?t:[t],r=L.Z.useWatch("custom_model_name",e),n=!a.includes("all-wildcard");if((0,d.useEffect)(()=>{if(r&&a.includes("custom")){let s=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:r,litellm_model:r}:e);e.setFieldValue("model_mappings",s),l(e=>e+1)}},[r,a,e]),(0,d.useEffect)(()=>{if(a.length>0&&!a.includes("all-wildcard")){let s=a.map(e=>"custom"===e&&r?{public_name:r,litellm_model:r}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",s),l(e=>e+1)}},[a,r,e]),!n)return null;let i=[{title:"Public Name",dataIndex:"public_name",key:"public_name",render:(s,l,t)=>(0,c.jsx)(S.Z,{value:s,onChange:s=>{let l=[...e.getFieldValue("model_mappings")];l[t].public_name=s.target.value,e.setFieldValue("model_mappings",l)}})},{title:"LiteLLM Model",dataIndex:"litellm_model",key:"litellm_model"}];return(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(L.Z.Item,{label:"Model Mappings",name:"model_mappings",tooltip:"Map public model names to LiteLLM model names for load balancing",labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",required:!0,children:(0,c.jsx)(ea.Z,{dataSource:e.getFieldValue("model_mappings"),columns:i,pagination:!1,size:"small"},s)})})},s0=l(90464);let{Link:s1}=es.default;var s2=e=>{let{showAdvancedSettings:s,setShowAdvancedSettings:l,teams:t}=e,[a]=L.Z.useForm(),[r,n]=d.useState(!1),[i,o]=d.useState("per_token"),[m,u]=d.useState(!1),h=(e,s)=>s&&(isNaN(Number(s))||0>Number(s))?Promise.reject("Please enter a valid positive number"):Promise.resolve(),x=(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject("Please enter valid JSON")}};return(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(C.Z,{className:"mt-2 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Advanced Settings"})}),(0,c.jsx)(I.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,c.jsx)(L.Z.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,c.jsx)(sB.Z,{onChange:e=>{n(e),e||a.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),r&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(L.Z.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:"per_token",onChange:e=>o(e),options:[{value:"per_token",label:"Per Million Tokens"},{value:"per_second",label:"Per Second"}]})}),"per_token"===i?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}):(0,c.jsx)(L.Z.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)(L.Z.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,c.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,c.jsx)(sB.Z,{onChange:e=>{let s=a.getFieldValue("litellm_extra_params");try{let l=s?JSON.parse(s):{};e?l.use_in_pass_through=!0:delete l.use_in_pass_through,Object.keys(l).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):a.setFieldValue("litellm_extra_params","")}catch(s){e?a.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):a.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,c.jsx)(sG,{form:a,showCacheControl:m,onCacheControlChange:e=>{if(u(e),!e){let e=a.getFieldValue("litellm_extra_params");try{let s=e?JSON.parse(e):{};delete s.cache_control_injection_points,Object.keys(s).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):a.setFieldValue("litellm_extra_params","")}catch(e){a.setFieldValue("litellm_extra_params","")}}}}),(0,c.jsx)(L.Z.Item,{label:"LiteLLM Params",name:"litellm_extra_params",tooltip:"Optional litellm params used for making a litellm.completion() call.",className:"mb-4 mt-4",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,c.jsxs)(su.Z,{className:"mb-4",children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,c.jsx)(L.Z.Item,{label:"Model Info",name:"model_info_params",tooltip:"Optional model info params. Returned when calling `/model/info` endpoint.",className:"mb-0",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})},s4=l(29),s5=l.n(s4),s3=l(23496),s6=l(35291),s8=l(23639);let{Text:s7}=es.default;var s9=e=>{let{formValues:s,accessToken:l,testMode:t,modelName:a="this model",onClose:r,onTestComplete:n}=e,[i,o]=d.useState(null),[m,u]=d.useState(null),[h,x]=d.useState(null),[p,g]=d.useState(!0),[j,f]=d.useState(!1),[_,v]=d.useState(!1),b=async()=>{g(!0),v(!1),o(null),u(null),x(null),f(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",s);let a=await sc(s,l,null);if(!a){console.log("No result from prepareModelAddRequest"),o("Failed to prepare model data. Please check your form inputs."),f(!1),g(!1);return}console.log("Result from prepareModelAddRequest:",a);let{litellmParamsObj:r,modelInfoObj:n,modelName:i}=a[0],c=await (0,y.Hx)(l,r,null==n?void 0:n.mode);if("success"===c.status)D.ZP.success("Connection test successful!"),o(null),f(!0);else{var e,t;let s=(null===(e=c.result)||void 0===e?void 0:e.error)||c.message||"Unknown error";o(s),u(r),x(null===(t=c.result)||void 0===t?void 0:t.raw_request_typed_dict),f(!1)}}catch(e){console.error("Test connection error:",e),o(e instanceof Error?e.message:String(e)),f(!1)}finally{g(!1),n&&n()}};d.useEffect(()=>{let e=setTimeout(()=>{b()},200);return()=>clearTimeout(e)},[]);let Z=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",N="string"==typeof i?Z(i):(null==i?void 0:i.message)?Z(i.message):"Unknown error",w=h?((e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")})(h.raw_request_api_base,h.raw_request_body,h.raw_request_headers||{}):"";return(0,c.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[p?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-776cdcbc0448e4ea",children:[(0,c.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-776cdcbc0448e4ea loading-spinner",children:(0,c.jsx)("div",{style:{border:"3px solid #f3f3f3",borderTop:"3px solid #1890ff",borderRadius:"50%",width:"30px",height:"30px",animation:"spin 1s linear infinite",margin:"0 auto"},className:"jsx-776cdcbc0448e4ea"})}),(0,c.jsxs)(s7,{style:{fontSize:"16px"},children:["Testing connection to ",a,"..."]}),(0,c.jsx)(s5(),{id:"776cdcbc0448e4ea",children:"@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);transform:rotate(0deg)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spin{0%{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}"})]}):j?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},children:[(0,c.jsx)("div",{style:{color:"#52c41a",fontSize:"32px",marginBottom:"16px"},children:(0,c.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,c.jsx)("path",{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"})})}),(0,c.jsxs)(s7,{type:"success",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," successful!"]})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,c.jsx)(s6.Z,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,c.jsxs)(s7,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," failed"]})]}),(0,c.jsxs)("div",{style:{backgroundColor:"#fff2f0",border:"1px solid #ffccc7",borderRadius:"8px",padding:"16px",marginBottom:"20px",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px"},children:"Error: "}),(0,c.jsx)(s7,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:N}),i&&(0,c.jsx)("div",{style:{marginTop:"12px"},children:(0,c.jsx)(R.ZP,{type:"link",onClick:()=>v(!_),style:{paddingLeft:0,height:"auto"},children:_?"Hide Details":"Show Details"})})]}),_&&(0,c.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"200px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:"string"==typeof i?i:JSON.stringify(i,null,2)})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:w||"No request data available"}),(0,c.jsx)(R.ZP,{style:{marginTop:"8px"},icon:(0,c.jsx)(s8.Z,{}),onClick:()=>{navigator.clipboard.writeText(w||""),D.ZP.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,c.jsx)(s3.Z,{style:{margin:"24px 0 16px"}}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,c.jsx)(R.ZP,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,c.jsx)(J.Z,{}),children:"View Documentation"})})]})};let le=[{value:"chat",label:"Chat - /chat/completions"},{value:"completion",label:"Completion - /completions"},{value:"embedding",label:"Embedding - /embeddings"},{value:"audio_speech",label:"Audio Speech - /audio/speech"},{value:"audio_transcription",label:"Audio Transcription - /audio/transcriptions"},{value:"image_generation",label:"Image Generation - /images/generations"},{value:"rerank",label:"Rerank - /rerank"},{value:"realtime",label:"Realtime - /realtime"}],{Title:ls,Link:ll}=es.default;var lt=e=>{let{form:s,handleOk:l,selectedProvider:t,setSelectedProvider:a,providerModels:r,setProviderModelsFn:i,getPlaceholder:o,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,credentials:p,accessToken:g,userRole:j}=e,[f,_]=(0,d.useState)("chat"),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),k=async()=>{Z(!0),w("test-".concat(Date.now())),v(!0)},S=eg.ZL.includes(j);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ls,{level:2,children:"Add new model"}),(0,c.jsx)(s$.Z,{children:(0,c.jsx)(L.Z,{form:s,onFinish:l,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"E.g. OpenAI, Azure OpenAI, Anthropic, Bedrock, etc.",labelCol:{span:10},labelAlign:"left",children:(0,c.jsx)(O.default,{showSearch:!0,value:t,onChange:e=>{a(e),i(e),s.setFieldsValue({model:[],model_name:void 0})},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sX,{selectedProvider:t,providerModels:r,getPlaceholder:o}),(0,c.jsx)(sQ,{}),(0,c.jsx)(L.Z.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,c.jsx)(O.default,{style:{width:"100%"},value:f,onChange:e=>_(e),options:le})}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-5 mt-1",children:[(0,c.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model ",(0,c.jsx)(ll,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,c.jsx)("div",{className:"mb-4",children:(0,c.jsx)(es.default.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,c.jsx)(L.Z.Item,{label:"Existing Credentials",name:"litellm_credential_name",children:(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{value:null,label:"None"},...p.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.litellm_credential_name!==s.litellm_credential_name||e.provider!==s.provider,children:e=>{let{getFieldValue:s}=e,l=s("litellm_credential_name");return(console.log("\uD83D\uDD11 Credential Name Changed:",l),l)?(0,c.jsx)("div",{className:"text-gray-500 text-sm text-center",children:"Using existing credentials - no additional provider fields needed"}):(0,c.jsx)(sg,{selectedProvider:t,uploadProps:m})}}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Team Settings"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{label:"Team",name:"team_id",className:"mb-4",tooltip:"Only keys for this team, will be able to call this model.",rules:[{required:!S,message:"Please select a team."}],children:(0,c.jsx)(Q,{teams:x})}),(0,c.jsx)(s2,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x}),(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(es.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{className:"space-x-2",children:[(0,c.jsx)(R.ZP,{onClick:k,loading:b,children:"Test Connect"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,c.jsx)(M.Z,{title:"Connection Test Results",open:y,onCancel:()=>{v(!1),Z(!1)},footer:[(0,c.jsx)(R.ZP,{onClick:()=>{v(!1),Z(!1)},children:"Close"},"close")],width:700,children:y&&(0,c.jsx)(s9,{formValues:s.getFieldsValue(),accessToken:g,testMode:f,modelName:s.getFieldValue("model_name")||s.getFieldValue("model"),onClose:()=>{v(!1),Z(!1)},onTestComplete:()=>Z(!1)},N)})]})},la=l(32986),lr=l(49084);function ln(e){let{data:s=[],columns:l,isLoading:t=!1}=e,[a,r]=d.useState([{id:"model_info.created_at",desc:!0}]),[n]=d.useState("onChange"),[i,o]=d.useState({}),[m,u]=d.useState({}),[h,x]=d.useState(!1),p=d.useRef(null);d.useEffect(()=>{let e=e=>{p.current&&!p.current.contains(e.target)&&x(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let g=(0,eS.b7)({data:s,columns:l,state:{sorting:a,columnSizing:i,columnVisibility:m},columnResizeMode:n,onSortingChange:r,onColumnSizingChange:o,onColumnVisibilityChange:u,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}}),j=e=>{if("string"==typeof e)return e;if("function"==typeof e){let s=e();if(s&&s.props&&s.props.children){let e=s.props.children;if("string"==typeof e)return e;if(e.props&&e.props.children)return e.props.children}}return""};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)("div",{className:"flex justify-end",children:(0,c.jsxs)("div",{className:"relative",ref:p,children:[(0,c.jsxs)("button",{onClick:()=>x(!h),className:"flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:[(0,c.jsx)(la.Z,{className:"h-4 w-4"}),"Columns"]}),h&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-56 bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50",children:(0,c.jsx)("div",{className:"py-1",children:g.getAllLeafColumns().map(e=>"actions"===e.id?null:(0,c.jsxs)("div",{className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer",onClick:()=>e.toggleVisibility(),children:[(0,c.jsx)("input",{type:"checkbox",checked:e.getIsVisible(),onChange:()=>e.toggleVisibility(),className:"h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,c.jsx)("span",{className:"ml-2",children:j(e.columnDef.header)})]},e.id))})})]})}),(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsx)("div",{className:"relative min-w-full",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1 w-full",children:[(0,c.jsx)(eE.Z,{children:g.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsxs)(eP.Z,{className:"py-1 h-8 relative ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getToggleSortingHandler(),children:[(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,c.jsx)("div",{onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:"absolute right-0 top-0 h-full w-2 cursor-col-resize select-none touch-none ".concat(e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200")})]},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading models..."})})})}):g.getRowModel().rows.length>0?g.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.column.id?120:e.column.getSize(),minWidth:"actions"===e.column.id?120:e.column.getSize(),maxWidth:"actions"===e.column.id?120:e.column.getSize(),position:"actions"===e.column.id?"sticky":"relative",right:"actions"===e.column.id?0:"auto"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No models found"})})})})})]})})})})]})}let li=(e,s,l,t,a,r,n,i,o)=>[{header:"Model ID",accessorKey:"model_info.id",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.model_info.id,children:(0,c.jsx)("div",{className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left w-full truncate whitespace-nowrap cursor-pointer",onClick:()=>t(l.model_info.id),children:l.model_info.id})})}},{header:"Public Model Name",accessorKey:"model_name",cell:e=>{let{row:s}=e,l=r(s.original)||"-";return(0,c.jsx)(W.Z,{title:l,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l})})}},{header:"Provider",accessorKey:"provider",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l.provider&&(0,c.jsx)("img",{src:sn(l.provider).logo,alt:"".concat(l.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,t=s.parentElement;if(t){var a;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(a=l.provider)||void 0===a?void 0:a.charAt(0))||"-",t.replaceChild(e,s)}}}),(0,c.jsx)("p",{className:"text-xs",children:l.provider||"-"})]})}},{header:"LiteLLM Model Name",accessorKey:"litellm_model_name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.litellm_model_name,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l.litellm_model_name||"-"})})}},{header:"Created At",accessorKey:"model_info.created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_at?new Date(l.model_info.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"model_info.updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.updated_at?new Date(l.model_info.updated_at).toLocaleDateString():"-"})}},{header:"Created By",accessorKey:"model_info.created_by",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_by||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Input Cost"})}),accessorKey:"input_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.input_cost||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Output Cost"})}),accessorKey:"output_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.output_cost||"-"})}},{header:"Team ID",accessorKey:"model_info.team_id",cell:e=>{let{row:s}=e,l=s.original;return l.model_info.team_id?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.model_info.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>a(l.model_info.team_id),children:[l.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:"Credentials",accessorKey:"litellm_credential_name",cell:e=>{let{row:s}=e,l=s.original;return l.litellm_params&&l.litellm_params.litellm_credential_name?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsxs)(W.Z,{title:l.litellm_params.litellm_credential_name,children:[l.litellm_params.litellm_credential_name.slice(0,7),"..."]})}):(0,c.jsx)("span",{className:"text-gray-400",children:"-"})}},{header:"Status",accessorKey:"model_info.db_model",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"\n inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium\n ".concat(l.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600","\n "),children:l.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:"",cell:l=>{var a;let{row:r}=l,n=r.original,i="Admin"===e||(null===(a=n.model_info)||void 0===a?void 0:a.created_by)===s;return(0,c.jsxs)("div",{className:"flex items-center justify-end gap-2 pr-4",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!0))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!1))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"})]})}}],{Title:lo,Link:lc}=es.default,ld={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"};var lm=e=>{let{accessToken:s,token:l,userRole:t,userID:a,modelData:r={data:[]},keys:i,setModelData:o,premiumUser:m,teams:u}=e,[h,x]=(0,d.useState)([]),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)([]);Object.values(n).filter(e=>isNaN(Number(e)));let[Z,N]=(0,d.useState)([]),[S,C]=(0,d.useState)(n.OpenAI),[I,T]=(0,d.useState)(""),[P,O]=(0,d.useState)(!1),[M,F]=(0,d.useState)(null),[R,q]=(0,d.useState)([]),[U,z]=(0,d.useState)([]),[V,K]=(0,d.useState)(null),[B,J]=(0,d.useState)([]),[W,G]=(0,d.useState)([]),[Y,$]=(0,d.useState)([]),[X,Q]=(0,d.useState)([]),[el,et]=(0,d.useState)([]),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)([]),[eo,ec]=(0,d.useState)([]),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[ex,ep]=(0,d.useState)(null),[ej,ef]=(0,d.useState)(0),[e_,ey]=(0,d.useState)({}),[ev,eb]=(0,d.useState)([]),[eZ,eN]=(0,d.useState)(!1),[ew,ek]=(0,d.useState)(null),[eS,eC]=(0,d.useState)(null),[eL,eM]=(0,d.useState)([]),[eK,eH]=(0,d.useState)([]),[eJ,eW]=(0,d.useState)(!1),[eG,eY]=(0,d.useState)(null),[e$,eQ]=(0,d.useState)(!1),[e0,e1]=(0,d.useState)(null),e2=async(e,l,r)=>{if(console.log("Updating model metrics for group:",e),!s||!a||!t||!l||!r)return;console.log("inside updateModelMetrics - startTime:",l,"endTime:",r),K(e);let n=null==ew?void 0:ew.token;void 0===n&&(n=null);let i=eS;void 0===i&&(i=null),l.setHours(0),l.setMinutes(0),l.setSeconds(0),r.setHours(23),r.setMinutes(59),r.setSeconds(59);try{let o=await (0,y.o6)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model metrics response:",o),G(o.data),$(o.all_api_bases);let c=await (0,y.Rg)(s,e,l.toISOString(),r.toISOString());Q(c.data),et(c.all_api_bases);let d=await (0,y.N8)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model exceptions response:",d),er(d.data),ei(d.exception_types);let m=await (0,y.fP)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);if(console.log("slowResponses:",m),em(m),e){let t=await (0,y.n$)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);ey(t);let a=await (0,y.v9)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);eb(a)}}catch(e){console.error("Failed to fetch model metrics",e)}},e4=async e=>{try{let s=await (0,y.N3)(e);console.log("credentials: ".concat(JSON.stringify(s))),eH(s.credentials)}catch(e){console.error("Error fetching credentials:",e)}};(0,d.useEffect)(()=>{e2(V,eu.from,eu.to)},[ew,eS]);let e5={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let s=new FileReader;s.onload=e=>{if(e.target){let s=e.target.result;p.setFieldsValue({vertex_credentials:s})}},s.readAsText(e)}return!1},onChange(e){"uploading"!==e.file.status&&console.log(e.file,e.fileList),"done"===e.file.status?D.ZP.success("".concat(e.file.name," file uploaded successfully")):"error"===e.file.status&&D.ZP.error("".concat(e.file.name," file upload failed."))}},e3=()=>{_(new Date().toLocaleString())},e6=async()=>{if(!s){console.error("Access token is missing");return}console.log("new modelGroupRetryPolicy:",ex);try{await (0,y.K_)(s,{router_settings:{model_group_retry_policy:ex}}),D.ZP.success("Retry settings saved successfully")}catch(e){console.error("Failed to save retry settings:",e),D.ZP.error("Failed to save retry settings")}};if((0,d.useEffect)(()=>{if(!s||!l||!t||!a)return;let e=async()=>{try{var e,l,r,n,i,c,d,m,u,h,x,p;let g=await (0,y.AZ)(s,a,t);console.log("Model data response:",g.data),o(g);let j=await (0,y.hy)(s);j&&N(j);let f=new Set;for(let e=0;e0&&(v=_[_.length-1],console.log("_initial_model_group:",v)),console.log("selectedModelGroup:",V);let b=await (0,y.o6)(s,a,t,v,null===(e=eu.from)||void 0===e?void 0:e.toISOString(),null===(l=eu.to)||void 0===l?void 0:l.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model metrics response:",b),G(b.data),$(b.all_api_bases);let Z=await (0,y.Rg)(s,v,null===(r=eu.from)||void 0===r?void 0:r.toISOString(),null===(n=eu.to)||void 0===n?void 0:n.toISOString());Q(Z.data),et(Z.all_api_bases);let w=await (0,y.N8)(s,a,t,v,null===(i=eu.from)||void 0===i?void 0:i.toISOString(),null===(c=eu.to)||void 0===c?void 0:c.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model exceptions response:",w),er(w.data),ei(w.exception_types);let k=await (0,y.fP)(s,a,t,v,null===(d=eu.from)||void 0===d?void 0:d.toISOString(),null===(m=eu.to)||void 0===m?void 0:m.toISOString(),null==ew?void 0:ew.token,eS),S=await (0,y.n$)(s,null===(u=eu.from)||void 0===u?void 0:u.toISOString().split("T")[0],null===(h=eu.to)||void 0===h?void 0:h.toISOString().split("T")[0],v);ey(S);let C=await (0,y.v9)(s,null===(x=eu.from)||void 0===x?void 0:x.toISOString().split("T")[0],null===(p=eu.to)||void 0===p?void 0:p.toISOString().split("T")[0],v);eb(C),console.log("dailyExceptions:",S),console.log("dailyExceptionsPerDeplyment:",C),console.log("slowResponses:",k),em(k);let I=await (0,y.j2)(s);eM(null==I?void 0:I.end_users);let T=(await (0,y.BL)(s,a,t)).router_settings;console.log("routerSettingsInfo:",T);let A=T.model_group_retry_policy,E=T.num_retries;console.log("model_group_retry_policy:",A),console.log("default_retries:",E),ep(A),ef(E)}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&t&&a&&e();let r=async()=>{let e=await (0,y.qm)(s);console.log("received model cost map data: ".concat(Object.keys(e))),j(e)};null==g&&r(),e3()},[s,l,t,a,g,f]),!r||!s||!l||!t||!a)return(0,c.jsx)("div",{children:"Loading..."});let e8=[],e7=[];for(let e=0;e(console.log("GET PROVIDER CALLED! - ".concat(g)),null!=g&&"object"==typeof g&&e in g)?g[e].litellm_provider:"openai";if(l){let e=l.split("/"),s=e[0];(n=t)||(n=1===e.length?u(l):s)}else n="-";a&&(i=null==a?void 0:a.input_cost_per_token,o=null==a?void 0:a.output_cost_per_token,c=null==a?void 0:a.max_tokens,d=null==a?void 0:a.max_input_tokens),(null==s?void 0:s.litellm_params)&&(m=Object.fromEntries(Object.entries(null==s?void 0:s.litellm_params).filter(e=>{let[s]=e;return"model"!==s&&"api_base"!==s}))),r.data[e].provider=n,r.data[e].input_cost=i,r.data[e].output_cost=o,r.data[e].litellm_model_name=l,e7.push(n),r.data[e].input_cost&&(r.data[e].input_cost=(1e6*Number(r.data[e].input_cost)).toFixed(2)),r.data[e].output_cost&&(r.data[e].output_cost=(1e6*Number(r.data[e].output_cost)).toFixed(2)),r.data[e].max_tokens=c,r.data[e].max_input_tokens=d,r.data[e].api_base=null==s?void 0:null===(ss=s.litellm_params)||void 0===ss?void 0:ss.api_base,r.data[e].cleanedLitellmParams=m,e8.push(s.model_name),console.log(r.data[e])}if(t&&"Admin Viewer"==t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to view all models"})]})}let sa=async()=>{try{D.ZP.info("Running health check..."),T("");let e=await (0,y.EY)(s);T(e)}catch(e){console.error("Error running health check:",e),T("Error running health check")}},sr=(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Select API Key Name"}),m?(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{ek(e)},children:e.key_alias},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>{eC(e)},children:e},s))]})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsxs)(ee.Z,{value:String(s),disabled:!0,onClick:()=>{ek(e)},children:["✨ ",e.key_alias," (Enterprise only Feature)"]},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsxs)(ee.Z,{value:e,disabled:!0,onClick:()=>{eC(e)},children:["✨ ",e," (Enterprise only Feature)"]},s))]})]})]}),sn=e=>{var s,l;let{payload:t,active:a}=e;if(!a||!t)return null;let r=null===(l=t[0])||void 0===l?void 0:null===(s=l.payload)||void 0===s?void 0:s.date,n=t.sort((e,s)=>s.value-e.value);if(n.length>5){let e=n.length-5;(n=n.slice(0,5)).push({dataKey:"".concat(e," other deployments"),value:t.slice(5).reduce((e,s)=>e+s.value,0),color:"gray"})}return(0,c.jsxs)("div",{className:"w-150 rounded-tremor-default border border-tremor-border bg-tremor-background p-2 text-tremor-default shadow-tremor-dropdown",children:[r&&(0,c.jsxs)("p",{className:"text-tremor-content-emphasis mb-2",children:["Date: ",r]}),n.map((e,s)=>{let l=parseFloat(e.value.toFixed(5)),t=0===l&&e.value>0?"<0.00001":l.toFixed(5);return(0,c.jsxs)("div",{className:"flex justify-between",children:[(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("div",{className:"w-2 h-2 mt-1 rounded-full bg-".concat(e.color,"-500")}),(0,c.jsx)("p",{className:"text-tremor-content",children:e.dataKey})]}),(0,c.jsx)("p",{className:"font-medium text-tremor-content-emphasis text-righ ml-2",children:t})]},s)})]})};console.log("selectedProvider: ".concat(S)),console.log("providerModels.length: ".concat(v.length));let sc=Object.keys(n).find(e=>n[e]===S);return(sc&&Z&&Z.find(e=>e.name===st[sc]),e0)?(0,c.jsx)("div",{className:"w-full h-full",children:(0,c.jsx)(sq,{teamId:e0,onClose:()=>e1(null),accessToken:s,is_team_admin:"Admin"===t,is_proxy_admin:"Proxy Admin"===t,userModels:e8,editTeam:!1,onUpdate:e3})}):(0,c.jsx)("div",{style:{width:"100%",height:"100%"},children:eG?(0,c.jsx)(sY,{modelId:eG,editModel:!0,onClose:()=>{eY(null),eQ(!1)},modelData:r.data.find(e=>e.model_info.id===eG),accessToken:s,userID:a,userRole:t,setEditModalVisible:O,setSelectedModel:F,onModelUpdate:e=>{o({...r,data:r.data.map(s=>s.model_info.id===e.model_info.id?e:s)}),e3()}}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[eg.ZL.includes(t)?(0,c.jsx)(eR.Z,{children:"All Models"}):(0,c.jsx)(eR.Z,{children:"Your Models"}),(0,c.jsx)(eR.Z,{children:"Add Model"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"LLM Credentials"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"/health Models"})}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Analytics"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Retry Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:e3})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(E.Z,{children:"Model Management"}),eg.ZL.includes(t)?(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add and manage models for the proxy"}):(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add models for teams you are an admin for."})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name:"}),(0,c.jsxs)(eD.Z,{className:"w-64",defaultValue:null!=V?V:"all",onValueChange:e=>K("all"===e?"all":e),value:null!=V?V:"all",children:[(0,c.jsx)(ee.Z,{value:"all",children:"All Models"}),R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))]})]})]}),(0,c.jsx)(ln,{columns:li(t,a,m,eY,e1,sv,e=>{F(e),O(!0)},e3,eQ),data:r.data.filter(e=>"all"===V||e.model_name===V||!V),isLoading:!1})]})}),(0,c.jsx)(ez.Z,{className:"h-full",children:(0,c.jsx)(lt,{form:p,handleOk:()=>{p.validateFields().then(e=>{sd(e,s,p,e3)}).catch(e=>{console.error("Validation failed:",e)})},selectedProvider:S,setSelectedProvider:C,providerModels:v,setProviderModelsFn:e=>{let s=so(e,g);b(s),console.log("providerModels: ".concat(s))},getPlaceholder:si,uploadProps:e5,showAdvancedSettings:eJ,setShowAdvancedSettings:eW,teams:u,credentials:eK,accessToken:s,userRole:t})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sy,{accessToken:s,uploadProps:e5,credentialList:eK,fetchCredentials:e4})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"`/health` will run a very small request through your models configured on litellm"}),(0,c.jsx)(k.Z,{onClick:sa,children:"Run `/health`"}),I&&(0,c.jsx)("pre",{children:JSON.stringify(I,null,2)})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:4,className:"mt-2 mb-2",children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:eu,className:"mr-2",onValueChange:e=>{eh(e),e2(V,e.from,e.to)}})]}),(0,c.jsxs)(sh.Z,{className:"ml-2",children:[(0,c.jsx)(A.Z,{children:"Select Model Group"}),(0,c.jsx)(eD.Z,{defaultValue:V||R[0],value:V||R[0],children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>e2(e,eu.from,eu.to),children:e},s))})]}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(sk.Z,{trigger:"click",content:sr,overlayStyle:{width:"20vw"},children:(0,c.jsx)(k.Z,{icon:eX.Z,size:"md",variant:"secondary",className:"mt-4 ml-2",style:{border:"none"},onClick:()=>eN(!0)})})})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"mr-2 max-h-[400px] min-h-[400px]",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Avg. Latency per Token"}),(0,c.jsx)(eR.Z,{value:"2",children:"Time to first token"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)("p",{className:"text-gray-500 italic",children:" (seconds/token)"}),(0,c.jsx)(A.Z,{className:"text-gray-500 italic mt-1 mb-1",children:"average Latency for successfull requests divided by the total tokens"}),W&&Y&&(0,c.jsx)(sN.Z,{title:"Model Latency",className:"h-72",data:W,showLegend:!1,index:"date",categories:Y,connectNulls:!0,customTooltip:sn})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sC,{modelMetrics:X,modelMetricsCategories:el,customTooltip:sn,premiumUser:m})})]})]})})}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"ml-2 max-h-[400px] min-h-[400px] overflow-y-auto",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Deployment"}),(0,c.jsx)(eP.Z,{children:"Success Responses"}),(0,c.jsxs)(eP.Z,{children:["Slow Responses ",(0,c.jsx)("p",{children:"Success Responses taking 600+s"})]})]})}),(0,c.jsx)(eT.Z,{children:ed.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.api_base}),(0,c.jsx)(eA.Z,{children:e.total_count}),(0,c.jsx)(eA.Z,{children:e.slow_count})]},s))})]})})})]}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Exceptions for ",V]}),(0,c.jsx)(sw.Z,{className:"h-60",data:ea,index:"model",categories:en,stack:!0,yAxisWidth:30})]})}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Up Rate Limit Errors (429) for ",V]}),(0,c.jsxs)(w.Z,{numItems:1,children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e_.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e_.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]}),(0,c.jsx)(sh.Z,{})]})]}),m?(0,c.jsx)(c.Fragment,{children:ev.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base?e.api_base:"Unknown API Base"}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors (429) ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]},s))}):(0,c.jsx)(c.Fragment,{children:ev&&ev.length>0&&ev.slice(0,1).map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"✨ Rate Limit Errors by Deployment"}),(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to see exceptions for all deployments"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]})]},s))})]})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name"}),(0,c.jsx)(eD.Z,{className:"mb-4 mt-2 ml-2 w-50",defaultValue:V||R[0],value:V||R[0],onValueChange:e=>K(e),children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))})]}),(0,c.jsxs)(E.Z,{children:["Retry Policy for ",V]}),(0,c.jsx)(A.Z,{className:"mb-6",children:"How many retries should be attempted based on the Exception"}),ld&&(0,c.jsx)("table",{children:(0,c.jsx)("tbody",{children:Object.entries(ld).map((e,s)=>{var l;let[t,a]=e,r=null==ex?void 0:null===(l=ex[V])||void 0===l?void 0:l[a];return null==r&&(r=ej),(0,c.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,c.jsx)("td",{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)("td",{children:(0,c.jsx)(H.Z,{className:"ml-5",value:r,min:0,step:1,onChange:e=>{ep(s=>{var l;let t=null!==(l=null==s?void 0:s[V])&&void 0!==l?l:{};return{...null!=s?s:{},[V]:{...t,[a]:e}}})}})})]},s)})})}),(0,c.jsx)(k.Z,{className:"mt-6 mr-8",onClick:e6,children:"Save"})]})]})]})})},lu=e=>{let{visible:s,possibleUIRoles:l,onCancel:t,user:a,onSubmit:r}=e,[n,i]=(0,d.useState)(a),[o]=L.Z.useForm();(0,d.useEffect)(()=>{o.resetFields()},[a]);let m=async()=>{o.resetFields(),t()},u=async e=>{r(e),o.resetFields(),t()};return a?(0,c.jsx)(M.Z,{visible:s,onCancel:m,footer:null,title:"Edit User "+a.user_id,width:1e3,children:(0,c.jsx)(L.Z,{form:o,onFinish:u,initialValues:a,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:l&&Object.entries(l).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Spend (USD)",name:"spend",tooltip:"(float) - Spend of all LLM calls completed by this user",help:"Across all keys (including keys with team_id).",children:(0,c.jsx)(H.Z,{min:0,step:.01})}),(0,c.jsx)(L.Z.Item,{label:"User Budget (USD)",name:"max_budget",tooltip:"(float) - Maximum budget of this user",help:"Maximum budget of this user.",children:(0,c.jsx)(z,{min:0,step:.01})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})}):null},lh=l(15731);let lx=(e,s,l)=>[{header:"User ID",accessorKey:"user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)(W.Z,{title:s.original.user_id,children:(0,c.jsx)("span",{className:"text-xs",children:s.original.user_id?"".concat(s.original.user_id.slice(0,7),"..."):"-"})})}},{header:"User Email",accessorKey:"user_email",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.user_email||"-"})}},{header:"Global Proxy Role",accessorKey:"user_role",cell:s=>{var l;let{row:t}=s;return(0,c.jsx)("span",{className:"text-xs",children:(null==e?void 0:null===(l=e[t.original.user_role])||void 0===l?void 0:l.ui_label)||"-"})}},{header:"User Spend ($ USD)",accessorKey:"spend",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.spend?s.original.spend.toFixed(2):"-"})}},{header:"User Max Budget ($ USD)",accessorKey:"max_budget",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.max_budget?s.original.max_budget:"Unlimited"})}},{header:()=>(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"SSO ID"}),(0,c.jsx)(W.Z,{title:"SSO ID is the ID of the user in the SSO provider. If the user is not using SSO, this will be null.",children:(0,c.jsx)(lh.Z,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.sso_user_id?s.original.sso_user_id:"-"})}},{header:"API Keys",accessorKey:"key_count",cell:e=>{let{row:s}=e;return(0,c.jsx)(w.Z,{numItems:2,children:s.original.key_count>0?(0,c.jsxs)(eM.Z,{size:"xs",color:"indigo",children:[s.original.key_count," Keys"]}):(0,c.jsx)(eM.Z,{size:"xs",color:"gray",children:"No Keys"})})}},{header:"Created At",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.created_at?new Date(s.original.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.updated_at?new Date(s.original.updated_at).toLocaleDateString():"-"})}},{id:"actions",header:"",cell:e=>{let{row:t}=e;return(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>s(t.original)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>l(t.original.user_id)})]})}}];function lp(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j;let{userId:f,onClose:_,accessToken:v,userRole:b,onDelete:Z}=e,[N,S]=(0,d.useState)(null),[C,I]=(0,d.useState)(!1),[T,P]=(0,d.useState)(!0);d.useEffect(()=>{console.log("userId: ".concat(f,", userRole: ").concat(b,", accessToken: ").concat(v)),(async()=>{try{if(!v)return;let e=await (0,y.Br)(v,f,b||"",!1,null,null,!0);S(e)}catch(e){console.error("Error fetching user data:",e),D.ZP.error("Failed to fetch user data")}finally{P(!1)}})()},[v,f,b]);let O=async()=>{try{if(!v)return;await (0,y.Eb)(v,[f]),D.ZP.success("User deleted successfully"),Z&&Z(),_()}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}};return T?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"Loading user data..."})]}):N?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(E.Z,{children:(null===(s=N.user_info)||void 0===s?void 0:s.user_email)||"User"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:N.user_id})]}),b&&eg.LQ.includes(b)&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>I(!0),className:"flex items-center",children:"Delete User"})]}),C&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:O,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>I(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Details"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number((null===(l=N.user_info)||void 0===l?void 0:l.spend)||0).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",(null===(t=N.user_info)||void 0===t?void 0:t.max_budget)!==null?"$".concat(N.user_info.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Teams"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(a=N.teams)||void 0===a?void 0:a.length)||0," teams"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"API Keys"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(r=N.keys)||void 0===r?void 0:r.length)||0," keys"]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"User ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:N.user_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Email"}),(0,c.jsx)(A.Z,{children:(null===(n=N.user_info)||void 0===n?void 0:n.user_email)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Role"}),(0,c.jsx)(A.Z,{children:(null===(i=N.user_info)||void 0===i?void 0:i.user_role)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:(null===(o=N.user_info)||void 0===o?void 0:o.created_at)?new Date(N.user_info.created_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:(null===(m=N.user_info)||void 0===m?void 0:m.updated_at)?new Date(N.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Teams"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(u=N.teams)||void 0===u?void 0:u.length)&&(null===(h=N.teams)||void 0===h?void 0:h.length)>0?null===(x=N.teams)||void 0===x?void 0:x.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e.team_alias||e.team_id},s)):(0,c.jsx)(A.Z,{children:"No teams"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Keys"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(p=N.keys)||void 0===p?void 0:p.length)&&(null===(g=N.keys)||void 0===g?void 0:g.length)>0?N.keys.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-green-100 rounded text-xs",children:e.key_alias||e.token},s)):(0,c.jsx)(A.Z,{children:"No API keys"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify((null===(j=N.user_info)||void 0===j?void 0:j.metadata)||{},null,2)})]})]})})})]})]})]}):(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"User not found"})]})}function lg(e){let{data:s=[],columns:l,isLoading:t=!1,onSortChange:a,currentSort:r,accessToken:n,userRole:i}=e,[o,m]=d.useState([{id:(null==r?void 0:r.sortBy)||"created_at",desc:(null==r?void 0:r.sortOrder)==="desc"}]),[u,h]=d.useState(null),x=(0,eS.b7)({data:s,columns:l,state:{sorting:o},onSortingChange:e=>{if(m(e),e.length>0){let s=e[0],l=s.id,t=s.desc?"desc":"asc";null==a||a(l,t)}},getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0}),p=e=>{h(e)};return(d.useEffect(()=>{r&&m([{id:r.sortBy,desc:"desc"===r.sortOrder}])},[r]),u)?(0,c.jsx)(lp,{userId:u,onClose:()=>{h(null)},accessToken:n,userRole:i}):(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:x.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading users..."})})})}):s.length>0?x.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:()=>{"user_id"===e.column.id&&p(e.getValue())},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No users found"})})})})})]})})})}var lj=l(67982),lf=e=>{var s;let{accessToken:l,possibleUIRoles:t,userID:a,userRole:r}=e,[n,i]=(0,d.useState)(!0),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)({}),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)([]),{Paragraph:v}=es.default,{Option:b}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){i(!1);return}try{let e=await (0,y.NL)(l);if(m(e),p(e.values||{}),l)try{let e=await (0,y.So)(l,a,r);if(e&&e.data){let s=e.data.map(e=>e.id);_(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),D.ZP.error("Failed to fetch SSO settings")}finally{i(!1)}})()},[l]);let Z=async()=>{if(l){j(!0);try{let e=await (0,y.nd)(l,x);m({...o,values:e.settings}),h(!1)}catch(e){console.error("Error updating SSO settings:",e),D.ZP.error("Failed to update settings")}finally{j(!1)}}},N=(e,s)=>{p(l=>({...l,[e]:s}))},w=(e,s,l)=>{var a;let r=s.type;return"user_role"===e&&t?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:Object.entries(t).filter(e=>{let[s]=e;return s.includes("internal_user")}).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(b,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{children:l}),(0,c.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:t})]})},s)})}):"budget_duration"===e?(0,c.jsx)(e_,{value:x[e]||null,onChange:s=>N(e,s),className:"mt-2"}):"boolean"===r?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!x[e],onChange:s=>N(e,s)})}):"array"===r&&(null===(a=s.items)||void 0===a?void 0:a.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:f.map(e=>(0,c.jsx)(b,{value:e,children:K(e)},e))}):"string"===r&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==x[e]?String(x[e]):"",onChange:s=>N(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},C=(e,s)=>{if(null==s)return(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"});if("user_role"===e&&t&&t[s]){let{ui_label:e,description:l}=t[s];return(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{className:"font-medium",children:e}),l&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:l})]})}return"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)})};return n?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):o?(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex justify-end items-center mb-4",children:!n&&o&&(u?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{h(!1),p(o.values||{})},disabled:g,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:Z,loading:g,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>h(!0),children:"Edit Settings"}))}),(null==o?void 0:null===(s=o.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(v,{className:"mb-4",children:o.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=o;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(v,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),u?(0,c.jsx)("div",{className:"mt-2",children:w(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:C(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No settings available or you do not have permission to view them."})})};console.log=function(){};var l_=e=>{let{accessToken:s,token:l,keys:t,userRole:a,userID:r,teams:n,setKeys:i}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(1),[g,j]=d.useState(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),[w,S]=(0,d.useState)(!1),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)({}),[E,P]=(0,d.useState)(""),[O,L]=(0,d.useState)("users"),[M,F]=(0,d.useState)({email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"}),[R,q]=(0,d.useState)(!1),[U,z]=(0,d.useState)(!1),[V,K]=(0,d.useState)("Email");(0,d.useRef)(null);let B=(0,d.useRef)(0);window.addEventListener("beforeunload",function(){sessionStorage.clear()});let H=(e,s)=>{let l={...M,[e]:s};F(l),console.log("called from handleFilterChange - newFilters:",JSON.stringify(l)),J(l)},J=(0,d.useCallback)(ep()(async e=>{if(!s||!l||!a||!r)return;let t=Date.now();B.current=t;try{let l=await (0,y.Of)(s,e.user_id?[e.user_id]:null,1,25,e.email||null,e.user_role||null,e.team||null,e.sso_user_id||null,e.sort_by,e.sort_order);t===B.current&&l&&(m(l),console.log("called from debouncedSearch filters:",JSON.stringify(e)),console.log("called from debouncedSearch data:",JSON.stringify(l)))}catch(e){console.error("Error searching users:",e)}},300),[s,l,a,r]);(0,d.useEffect)(()=>()=>{J.cancel()},[J]);let W=async()=>{if(C&&s)try{if(await (0,y.Eb)(s,[C]),D.ZP.success("User deleted successfully"),o){var e;let s=null===(e=o.users)||void 0===e?void 0:e.filter(e=>e.user_id!==C);m({...o,users:s||[]})}}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}S(!1),I(null)},G=async()=>{N(null),b(!1)},Y=async e=>{if(console.log("inside handleEditSubmit:",e),s&&l&&a&&r){try{await (0,y.pf)(s,e,null),D.ZP.success("User ".concat(e.user_id," updated successfully"))}catch(e){console.error("There was an error updating the user",e)}if(o){var t;let s=null===(t=o.users)||void 0===t?void 0:t.map(s=>s.user_id===e.user_id?e:s);m({...o,users:s||[]})}N(null),b(!1)}},$=async e=>{if(s&&l&&a&&r)try{let l=await (0,y.Of)(s,M.user_id?[M.user_id]:null,e,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(e),JSON.stringify(l)),m(l),p(e)}catch(e){console.error("Error changing page:",e)}};if((0,d.useEffect)(()=>{if(!s||!l||!a||!r)return;let e=async()=>{try{let e=sessionStorage.getItem("userList_".concat(x));if(e){let s=JSON.parse(e);m(s),console.log("called from useEffect")}else{let e=await (0,y.Of)(s,M.user_id?[M.user_id]:null,x,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(x),JSON.stringify(e)),m(e),console.log("called from useEffect 2")}let l=sessionStorage.getItem("possibleUserRoles");if(l)A(JSON.parse(l));else{let e=await (0,y.lg)(s);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),A(e)}}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&a&&r&&e()},[s,l,a,r]),!o||!s||!l||!a||!r)return(0,c.jsx)("div",{children:"Loading..."});let X=lx(T,e=>{N(e),b(!0)},e=>{I(e),S(!0)});return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Users"}),(0,c.jsx)("div",{className:"flex space-x-3",children:(0,c.jsx)(eh,{userID:r,accessToken:s,teams:n,possibleUIRoles:T})})]}),(0,c.jsxs)(eq.Z,{defaultIndex:0,onIndexChange:e=>L(0===e?"users":"settings"),children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Users"}),(0,c.jsx)(eR.Z,{children:"Default User Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by email...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.email,onChange:e=>H("email",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ".concat(R?"bg-gray-100":""),onClick:()=>q(!R),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filters",(M.user_id||M.user_role||M.team)&&(0,c.jsx)("span",{className:"w-2 h-2 rounded-full bg-blue-500"})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{F({email:"",user_id:"",user_role:"",team:"",sso_user_id:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"})},children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Reset Filters"]})]}),R&&(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Filter by User ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.user_id,onChange:e=>H("user_id",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})]}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.user_role,onValueChange:e=>H("user_role",e),placeholder:"Select Role",children:Object.entries(T).map(e=>{let[s,l]=e;return(0,c.jsx)(ee.Z,{value:s,children:l.ui_label},s)})})}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.team,onValueChange:e=>H("team",e),placeholder:"Select Team",children:null==n?void 0:n.map(e=>(0,c.jsx)(ee.Z,{value:e.team_id,children:e.team_alias||e.team_id},e.team_id))})}),(0,c.jsx)("div",{className:"relative w-64",children:(0,c.jsx)("input",{type:"text",placeholder:"Filter by SSO ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.sso_user_id,onChange:e=>H("sso_user_id",e.target.value)})})]}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",o&&o.users&&o.users.length>0?(o.page-1)*o.page_size+1:0," ","-"," ",o&&o.users?Math.min(o.page*o.page_size,o.total):0," ","of ",o?o.total:0," results"]}),(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>$(x-1),disabled:1===x,className:"px-3 py-1 text-sm border rounded-md ".concat(1===x?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),(0,c.jsx)("button",{onClick:()=>$(x+1),disabled:!o||x>=o.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(!o||x>=o.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})]})]})}),(0,c.jsx)(lg,{data:(null==o?void 0:o.users)||[],columns:X,isLoading:!o,accessToken:s,userRole:a,onSortChange:(e,s)=>{let l={...M,sort_by:e,sort_order:s};F(l),J(l)},currentSort:{sortBy:M.sort_by,sortOrder:M.sort_order}})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lf,{accessToken:s,possibleUIRoles:T,userID:r,userRole:a})})]})]}),(0,c.jsx)(lu,{visible:v,possibleUIRoles:T,onCancel:G,user:Z,onSubmit:Y}),w&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"}),(0,c.jsxs)("p",{className:"text-sm font-medium text-gray-900 mt-2",children:["User ID: ",C]})]})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:W,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{S(!1),I(null)},children:"Cancel"})]})]})]})})]})},ly=e=>{var s;let{accessToken:l,userID:t,userRole:a}=e,[r,n]=(0,d.useState)(!0),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)({}),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),{Paragraph:_}=es.default,{Option:v}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){n(!1);return}try{let e=await (0,y.EB)(l);if(o(e),x(e.values||{}),l)try{let e=await (0,y.So)(l,t,a);if(e&&e.data){let s=e.data.map(e=>e.id);f(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching team SSO settings:",e),D.ZP.error("Failed to fetch team settings")}finally{n(!1)}})()},[l]);let b=async()=>{if(l){g(!0);try{let e=await (0,y.r1)(l,h);o({...i,values:e.settings}),u(!1),D.ZP.success("Default team settings updated successfully")}catch(e){console.error("Error updating team settings:",e),D.ZP.error("Failed to update team settings")}finally{g(!1)}}},Z=(e,s)=>{x(l=>({...l,[e]:s}))},N=(e,s,l)=>{var t;let a=s.type;return"budget_duration"===e?(0,c.jsx)(e_,{value:h[e]||null,onChange:s=>Z(e,s),className:"mt-2"}):"boolean"===a?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!h[e],onChange:s=>Z(e,s)})}):"array"===a&&(null===(t=s.items)||void 0===t?void 0:t.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:j.map(e=>(0,c.jsx)(v,{value:e,children:K(e)},e))}):"string"===a&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:h[e]||"",onChange:s=>Z(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==h[e]?String(h[e]):"",onChange:s=>Z(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},w=(e,s)=>null==s?(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"}):"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)});return r?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):i?(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{className:"text-xl",children:"Default Team Settings"}),!r&&i&&(m?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{u(!1),x(i.values||{})},disabled:p,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:b,loading:p,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Settings"}))]}),(0,c.jsx)(A.Z,{children:"These settings will be applied by default when creating new teams."}),(null==i?void 0:null===(s=i.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(_,{className:"mb-4 mt-2",children:i.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=i;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(_,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),m?(0,c.jsx)("div",{className:"mt-2",children:N(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:w(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No team settings available or you do not have permission to view them."})})},lv=e=>{let{accessToken:s,userID:l}=e,[t,a]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(s&&l)try{let e=await (0,y.a6)(s);a(e)}catch(e){console.error("Error fetching available teams:",e)}})()},[s,l]);let r=async e=>{if(s&&l)try{await (0,y.cu)(s,e,{user_id:l,role:"user"}),D.ZP.success("Successfully joined team"),a(s=>s.filter(s=>s.team_id!==e))}catch(e){console.error("Error joining team:",e),D.ZP.error("Failed to join team")}};return(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{children:"Members"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsxs)(eT.Z,{children:[t.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.team_alias})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.description||"No description available"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[e.members_with_roles.length," members"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"flex flex-col",children:e.models&&0!==e.models.length?e.models.map((e,s)=>(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(e.slice(0,30),"..."):e})},s)):(0,c.jsx)(eM.Z,{size:"xs",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})})})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{size:"xs",variant:"secondary",onClick:()=>r(e.team_id),children:"Join Team"})})]},e.team_id)),0===t.length&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:5,className:"text-center",children:(0,c.jsx)(A.Z,{children:"No available teams to join"})})})]})]})})};console.log=function(){};let lb=(e,s)=>{let l=[];return e&&e.models.length>0?(console.log("organization.models: ".concat(e.models)),l=e.models):l=s,B(l,s)};var lZ=e=>{let{teams:s,searchParams:l,accessToken:t,setTeams:a,userID:r,userRole:n,organizations:i}=e,[o,m]=(0,d.useState)(""),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(null);(0,d.useEffect)(()=>{console.log("inside useeffect - ".concat(o)),t&&Z(t,r,n,u,a),ey()},[o]);let[g]=L.Z.useForm(),[j]=L.Z.useForm(),{Title:f,Paragraph:_}=es.default,[v,b]=(0,d.useState)(""),[E,P]=(0,d.useState)(!1),[F,U]=(0,d.useState)(null),[B,H]=(0,d.useState)(null),[G,Y]=(0,d.useState)(!1),[$,X]=(0,d.useState)(!1),[Q,ee]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)(!1),[eo,ec]=(0,d.useState)(null),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({}),[ex,ep]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("currentOrgForCreateTeam: ".concat(x));let e=lb(x,ea);console.log("models: ".concat(e)),em(e),g.setFieldValue("models",[])},[x,ea]),(0,d.useEffect)(()=>{(async()=>{try{if(null==t)return;let e=(await (0,y.t3)(t)).guardrails.map(e=>e.guardrail_name);ep(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[t]);let ej=async e=>{ec(e),ei(!0)},ef=async()=>{if(null!=eo&&null!=s&&null!=t){try{await (0,y.rs)(t,eo),Z(t,r,n,u,a)}catch(e){console.error("Error deleting the team:",e)}ei(!1),ec(null)}};(0,d.useEffect)(()=>{(async()=>{try{if(null===r||null===n||null===t)return;let e=await V(r,n,t);e&&er(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,r,n,s]);let e_=async e=>{try{if(console.log("formValues: ".concat(JSON.stringify(e))),null!=t){var l;let r=null==e?void 0:e.team_alias,n=null!==(l=null==s?void 0:s.map(e=>e.team_alias))&&void 0!==l?l:[],i=(null==e?void 0:e.organization_id)||(null==u?void 0:u.organization_id);if(""===i||"string"!=typeof i?e.organization_id=null:e.organization_id=i.trim(),n.includes(r))throw Error("Team alias ".concat(r," already exists, please pick another alias"));D.ZP.info("Creating Team");let o=await (0,y.hT)(t,e);null!==s?a([...s,o]):a([o]),console.log("response for team create call: ".concat(o)),D.ZP.success("Team created"),g.resetFields(),X(!1)}}catch(e){console.error("Error creating the team:",e),D.ZP.error("Error creating the team: "+e,20)}},ey=()=>{m(new Date().toLocaleString())};return(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:B?(0,c.jsx)(sq,{teamId:B,onUpdate:e=>{a(s=>null==s?s:s.map(s=>e.team_id===s.team_id?e8(s,e):s))},onClose:()=>{H(null),Y(!1)},accessToken:t,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let s=0;se.team_id===B)),is_proxy_admin:"Admin"==n,userModels:ea,editTeam:G}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Your Teams"}),(0,c.jsx)(eR.Z,{children:"Available Teams"}),(0,eg.tY)(n||"")&&(0,c.jsx)(eR.Z,{children:"Default Team Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[o&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",o]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:ey})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(A.Z,{children:["Click on “Team ID” to view team details ",(0,c.jsx)("b",{children:"and"})," manage team members."]}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Team ID"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Organization"}),(0,c.jsx)(eP.Z,{children:"Info"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.filter(e=>!u||e.organization_id===u.organization_id).sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{H(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.spend}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},children:Array.isArray(e.models)?(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)})},s))}):null}),(0,c.jsx)(eA.Z,{children:e.organization_id}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].keys&&eu[e.team_id].keys.length," ","Keys"]}),(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].members_with_roles&&eu[e.team_id].members_with_roles.length," ","Members"]})]}),(0,c.jsx)(eA.Z,{children:"Admin"==n?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{H(e.team_id),Y(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>ej(e.team_id),icon:eH.Z,size:"sm"})]}):null})]},e.team_id)):null})]}),en&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Team"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this team ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ef,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{ei(!1),ec(null)},children:"Cancel"})]})]})]})})]})}),"Admin"==n||"Org Admin"==n?(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>X(!0),children:"+ Create New Team"}),(0,c.jsx)(M.Z,{title:"Create Team",visible:$,width:800,footer:null,onOk:()=>{X(!1),g.resetFields()},onCancel:()=>{X(!1),g.resetFields()},children:(0,c.jsxs)(L.Z,{form:g,onFinish:e_,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Organization"," ",(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:u?u.organization_id:null,className:"mt-8",children:(0,c.jsx)(O.default,{showSearch:!0,allowClear:!0,placeholder:"Search or select an Organization",onChange:e=>{g.setFieldValue("organization_id",e),p((null==i?void 0:i.find(s=>s.organization_id===e))||null)},filterOption:(e,s)=>{var l;return!!s&&((null===(l=s.children)||void 0===l?void 0:l.toString())||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==i?void 0:i.map(e=>(0,c.jsxs)(O.default.Option,{value:e.organization_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"These are the models that your selected team has access to",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),ed.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Additional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,c.jsx)(S.Z,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:ex.map(e=>({value:e,label:e}))})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Team"})})]})})]}):null]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lv,{accessToken:t,userID:r})}),(0,eg.tY)(n||"")&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ly,{accessToken:t,userID:r||"",userRole:n||""})})]})]})})},lN=e=>{var s;let{organizationId:l,onClose:t,accessToken:a,is_org_admin:r,is_proxy_admin:n,userModels:i,editOrg:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),C=r||n,I=async()=>{try{if(x(!0),!a)return;let e=await (0,y.t$)(a,l);u(e)}catch(e){D.ZP.error("Failed to load organization information"),console.error("Error fetching organization info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{I()},[l,a]);let T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.vh)(a,l,s),D.ZP.success("Organization member added successfully"),_(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to add organization member"),console.error("Error adding organization member:",e)}},P=async e=>{try{if(!a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.LY)(a,l,s),D.ZP.success("Organization member updated successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to update organization member"),console.error("Error updating organization member:",e)}},M=async e=>{try{if(!a)return;await (0,y.Sb)(a,l,e.user_id),D.ZP.success("Organization member deleted successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to delete organization member"),console.error("Error deleting organization member:",e)}},F=async e=>{try{if(!a)return;let s={organization_id:l,organization_alias:e.organization_alias,models:e.models,litellm_budget_table:{tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration},metadata:e.metadata?JSON.parse(e.metadata):null};await (0,y.VA)(a,s),D.ZP.success("Organization settings updated successfully"),j(!1),I()}catch(e){D.ZP.error("Failed to update organization settings"),console.error("Error updating organization:",e)}};return h?(0,c.jsx)("div",{className:"p-4",children:"Loading..."}):m?(0,c.jsxs)("div",{className:"w-full h-screen p-4 bg-white",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:m.organization_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:m.organization_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?2:0,children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Members"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Organization Details"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Created: ",new Date(m.created_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Updated: ",new Date(m.updated_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Created By: ",m.created_by]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",m.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===m.litellm_budget_table.max_budget?"Unlimited":"$".concat(m.litellm_budget_table.max_budget)]}),m.litellm_budget_table.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",m.litellm_budget_table.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]}),m.litellm_budget_table.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",m.litellm_budget_table.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[75vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Created At"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:null===(s=m.members)||void 0===s?void 0:s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_role})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["$",e.spend.toFixed(6)]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:new Date(e.created_at).toLocaleString()})}),(0,c.jsx)(eA.Z,{children:C&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{N({role:e.user_role,user_email:e.user_email,user_id:e.user_id}),b(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{M(e)}})]})})]},s))})]})}),C&&(0,c.jsx)(k.Z,{onClick:()=>{_(!0)},children:"Add Member"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Organization Settings"}),C&&!g&&(0,c.jsx)(k.Z,{onClick:()=>j(!0),children:"Edit Settings"})]}),g?(0,c.jsxs)(L.Z,{form:p,onFinish:F,initialValues:{organization_alias:m.organization_alias,models:m.models,tpm_limit:m.litellm_budget_table.tpm_limit,rpm_limit:m.litellm_budget_table.rpm_limit,max_budget:m.litellm_budget_table.max_budget,budget_duration:m.litellm_budget_table.budget_duration,metadata:m.metadata?JSON.stringify(m.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>j(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization Name"}),(0,c.jsx)("div",{children:m.organization_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization ID"}),(0,c.jsx)("div",{className:"font-mono",children:m.organization_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(m.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==m.litellm_budget_table.max_budget?"$".concat(m.litellm_budget_table.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",m.litellm_budget_table.budget_duration||"Never"]})]})]})]})})]})]}),(0,c.jsx)(sR,{isVisible:f,onCancel:()=>_(!1),onSubmit:T,accessToken:a,title:"Add Organization Member",roles:[{label:"org_admin",value:"org_admin",description:"Can add and remove members, and change their roles."},{label:"internal_user",value:"internal_user",description:"Can view/create keys for themselves within organization."},{label:"internal_user_viewer",value:"internal_user_viewer",description:"Can only view their keys within organization."}],defaultRole:"internal_user"}),(0,c.jsx)(sF,{visible:v,onCancel:()=>b(!1),onSubmit:P,initialData:Z,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Org Admin",value:"org_admin"},{label:"Internal User",value:"internal_user"},{label:"Internal User Viewer",value:"internal_user_viewer"}]}})]}):(0,c.jsx)("div",{className:"p-4",children:"Organization not found"})};let lw=async(e,s)=>{s(await (0,y.r6)(e))};var lk=e=>{let{organizations:s,userRole:l,userModels:t,accessToken:a,lastRefreshed:r,handleRefreshClick:n,currentOrg:i,guardrailsList:o=[],setOrganizations:m,premiumUser:u}=e,[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(null),[b,Z]=(0,d.useState)(!1),[C]=L.Z.useForm();(0,d.useEffect)(()=>{0===s.length&&a&&lw(a,m)},[s,a]);let I=e=>{e&&(v(e),f(!0))},T=async()=>{if(_&&a)try{await (0,y.cq)(a,_),D.ZP.success("Organization deleted successfully"),f(!1),v(null),lw(a,m)}catch(e){console.error("Error deleting organization:",e)}},E=async e=>{try{if(!a)return;console.log("values in organizations new create call: ".concat(JSON.stringify(e))),await (0,y.H1)(a,e),Z(!1),C.resetFields(),lw(a,m)}catch(e){console.error("Error creating organization:",e)}};return u?h?(0,c.jsx)(lN,{organizationId:h,onClose:()=>{x(null),g(!1)},accessToken:a,is_org_admin:!0,is_proxy_admin:"Admin"===l,userModels:t,editOrg:p}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsx)("div",{className:"flex",children:(0,c.jsx)(eR.Z,{children:"Your Organizations"})}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[r&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",r]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:n})]})]}),(0,c.jsx)(eV.Z,{children:(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(A.Z,{children:"Click on “Organization ID” to view organization details."}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Organization ID"}),(0,c.jsx)(eP.Z,{children:"Organization Name"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"TPM / RPM Limits"}),(0,c.jsx)(eP.Z,{children:"Info"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>{var s,t,a,r,n,i,o,d,m;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.organization_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>x(e.organization_id),children:[null===(s=e.organization_id)||void 0===s?void 0:s.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{children:e.organization_alias}),(0,c.jsx)(eA.Z,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{children:e.spend}),(0,c.jsx)(eA.Z,{children:(null===(t=e.litellm_budget_table)||void 0===t?void 0:t.max_budget)!==null&&(null===(a=e.litellm_budget_table)||void 0===a?void 0:a.max_budget)!==void 0?null===(r=e.litellm_budget_table)||void 0===r?void 0:r.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{children:Array.isArray(e.models)&&(0,c.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)},s))})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["TPM: ",(null===(n=e.litellm_budget_table)||void 0===n?void 0:n.tpm_limit)?null===(i=e.litellm_budget_table)||void 0===i?void 0:i.tpm_limit:"Unlimited",(0,c.jsx)("br",{}),"RPM: ",(null===(o=e.litellm_budget_table)||void 0===o?void 0:o.rpm_limit)?null===(d=e.litellm_budget_table)||void 0===d?void 0:d.rpm_limit:"Unlimited"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[(null===(m=e.members)||void 0===m?void 0:m.length)||0," Members"]})}),(0,c.jsx)(eA.Z,{children:"Admin"===l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{x(e.organization_id),g(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>I(e.organization_id),icon:eH.Z,size:"sm"})]})})]},e.organization_id)}):null})]})})}),("Admin"===l||"Org Admin"===l)&&(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>Z(!0),children:"+ Create New Organization"}),(0,c.jsx)(M.Z,{title:"Create Organization",visible:b,width:800,footer:null,onCancel:()=>{Z(!1),C.resetFields()},children:(0,c.jsxs)(L.Z,{form:C,onFinish:E,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),t&&t.length>0&&t.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Organization"})})]})})]})]})]})}),j?(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Organization"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this organization?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:T,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{f(!1),v(null)},children:"Cancel"})]})]})]})}):(0,c.jsx)(c.Fragment,{})]}):(0,c.jsx)("div",{children:(0,c.jsxs)(A.Z,{children:["This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key ",(0,c.jsx)("a",{href:"https://litellm.ai/pricing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})},lS=l(94789);let lC={google:"https://artificialanalysis.ai/img/logos/google_small.svg",microsoft:"https://upload.wikimedia.org/wikipedia/commons/a/a8/Microsoft_Azure_Logo.svg",okta:"https://www.okta.com/sites/default/files/Okta_Logo_BrightBlue_Medium.png",generic:""},lI={google:{envVarMap:{google_client_id:"GOOGLE_CLIENT_ID",google_client_secret:"GOOGLE_CLIENT_SECRET"},fields:[{label:"GOOGLE CLIENT ID",name:"google_client_id"},{label:"GOOGLE CLIENT SECRET",name:"google_client_secret"}]},microsoft:{envVarMap:{microsoft_client_id:"MICROSOFT_CLIENT_ID",microsoft_client_secret:"MICROSOFT_CLIENT_SECRET",microsoft_tenant:"MICROSOFT_TENANT"},fields:[{label:"MICROSOFT CLIENT ID",name:"microsoft_client_id"},{label:"MICROSOFT CLIENT SECRET",name:"microsoft_client_secret"},{label:"MICROSOFT TENANT",name:"microsoft_tenant"}]},okta:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint",placeholder:"https://your-okta-domain/authorize"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint",placeholder:"https://your-okta-domain/token"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint",placeholder:"https://your-okta-domain/userinfo"}]},generic:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint"}]}};var lT=e=>{let{isAddSSOModalVisible:s,isInstructionsModalVisible:l,handleAddSSOOk:t,handleAddSSOCancel:a,handleShowInstructions:r,handleInstructionsOk:n,handleInstructionsCancel:i,form:o}=e,d=e=>{let s=lI[e];return s?s.fields.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,rules:[{required:!0,message:"Please enter the ".concat(e.label.toLowerCase())}],children:e.name.includes("client")?(0,c.jsx)(q.default.Password,{}):(0,c.jsx)(S.Z,{placeholder:e.placeholder})},e.name)):null};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(M.Z,{title:"Add SSO",visible:s,width:800,footer:null,onOk:t,onCancel:a,children:(0,c.jsxs)(L.Z,{form:o,onFinish:r,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,c.jsx)(O.default,{children:Object.entries(lC).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[l&&(0,c.jsx)("img",{src:l,alt:s,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,c.jsxs)("span",{children:[s.charAt(0).toUpperCase()+s.slice(1)," SSO"]})]})},s)})})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("sso_provider");return l?d(l):null}}),(0,c.jsx)(L.Z.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"PROXY BASE URL",name:"proxy_base_url",rules:[{required:!0,message:"Please enter the proxy base url"}],children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})}),(0,c.jsxs)(M.Z,{title:"SSO Setup Instructions",visible:l,width:800,footer:null,onOk:n,onCancel:i,children:[(0,c.jsx)("p",{children:"Follow these steps to complete the SSO setup:"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"1. DO NOT Exit this TAB"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"2. Open a new tab, visit your proxy base url"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"3. Confirm your SSO is configured correctly and you can login on the new Tab"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"4. If Step 3 is successful, you can close this tab"}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{onClick:n,children:"Done"})})]})]})},lA=l(62272),lE=l(92403),lP=l(29271),lO=l(34419),lL=e=>{let{accessToken:s,userID:l,proxySettings:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)("");(0,d.useEffect)(()=>{let e="";u(t&&t.PROXY_BASE_URL&&void 0!==t.PROXY_BASE_URL?t.PROXY_BASE_URL:window.location.origin)},[t]);let h="".concat(m,"/scim/v2"),x=async e=>{if(!s||!l){D.ZP.error("You need to be logged in to create a SCIM token");return}try{n(!0);let t={key_alias:e.key_alias||"SCIM Access Token",team_id:null,models:[],allowed_routes:["/scim/*"]},a=await (0,y.wX)(s,l,t);o(a),D.ZP.success("SCIM token created successfully")}catch(e){console.error("Error creating SCIM token:",e),D.ZP.error("Failed to create SCIM token")}finally{n(!1)}};return(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex items-center mb-4",children:(0,c.jsx)(E.Z,{children:"SCIM Configuration"})}),(0,c.jsx)(A.Z,{className:"text-gray-600",children:"System for Cross-domain Identity Management (SCIM) allows you to automatically provision and manage users and groups in LiteLLM."}),(0,c.jsx)(lj.Z,{}),(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"1"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lA.Z,{className:"h-5 w-5 mr-2"}),"SCIM Tenant URL"]})]}),(0,c.jsx)(A.Z,{className:"text-gray-600 mb-3",children:"Use this URL in your identity provider SCIM integration settings."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:h,disabled:!0,className:"flex-grow"}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>D.ZP.success("URL copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"ml-2 flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"2"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-5 w-5 mr-2"}),"Authentication Token"]})]}),(0,c.jsx)(lS.Z,{title:"Using SCIM",color:"blue",className:"mb-4",children:"You need a SCIM token to authenticate with the SCIM API. Create one below and use it in your SCIM provider configuration."}),i?(0,c.jsxs)(eF.Z,{className:"border border-yellow-300 bg-yellow-50",children:[(0,c.jsxs)("div",{className:"flex items-center mb-2 text-yellow-800",children:[(0,c.jsx)(lP.Z,{className:"h-5 w-5 mr-2"}),(0,c.jsx)(E.Z,{className:"text-lg text-yellow-800",children:"Your SCIM Token"})]}),(0,c.jsx)(A.Z,{className:"text-yellow-800 mb-4 font-medium",children:"Make sure to copy this token now. You will not be able to see it again."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:i.token,className:"flex-grow mr-2 bg-white",type:"password",disabled:!0}),(0,c.jsx)(P.CopyToClipboard,{text:i.token,onCopy:()=>D.ZP.success("Token copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]}),(0,c.jsxs)(k.Z,{className:"mt-4 flex items-center",variant:"secondary",onClick:()=>o(null),children:[(0,c.jsx)(lO.Z,{className:"h-4 w-4 mr-1"}),"Create Another Token"]})]}):(0,c.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,c.jsxs)(L.Z,{form:a,onFinish:x,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Token Name",rules:[{required:!0,message:"Please enter a name for your token"}],children:(0,c.jsx)(S.Z,{placeholder:"SCIM Access Token"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)(k.Z,{variant:"primary",type:"submit",loading:r,className:"flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-4 w-4 mr-1"}),"Create SCIM Token"]})})]})})]})]})]})})};let lD=()=>{let[e,s]=(0,d.useState)("http://localhost:4000");return(0,d.useEffect)(()=>{{let{protocol:e,host:l}=window.location;s("".concat(e,"//").concat(l))}},[]),e};var lM=e=>{let{searchParams:s,accessToken:l,showSSOBanner:t,premiumUser:a,proxySettings:r}=e,[n]=L.Z.useForm(),[i]=L.Z.useForm(),{Title:o,Paragraph:u}=es.default,[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)(null),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(!1),[S,C]=(0,d.useState)(!1),[I,T]=(0,d.useState)(!1),[A,E]=(0,d.useState)(!1),[P,O]=(0,d.useState)(!1),[F,U]=(0,d.useState)(!1),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)([]),[H,J]=(0,d.useState)(null);(0,m.useRouter)();let[W,G]=(0,d.useState)(null);console.log=function(){};let Y=lD(),$="All IP Addresses Allowed",X=Y;X+="/fallback/login";let Q=async()=>{try{if(!0!==a){D.ZP.error("This feature is only available for premium users. Please upgrade your account.");return}if(l){let e=await (0,y.PT)(l);B(e&&e.length>0?e:[$])}else B([$])}catch(e){console.error("Error fetching allowed IPs:",e),D.ZP.error("Failed to fetch allowed IPs ".concat(e)),B([$])}finally{!0===a&&O(!0)}},ee=async e=>{try{if(l){await (0,y.eH)(l,e.ip);let s=await (0,y.PT)(l);B(s),D.ZP.success("IP address added successfully")}}catch(e){console.error("Error adding IP:",e),D.ZP.error("Failed to add IP address ".concat(e))}finally{U(!1)}},el=async e=>{J(e),V(!0)},et=async()=>{if(H&&l)try{await (0,y.$I)(l,H);let e=await (0,y.PT)(l);B(e.length>0?e:[$]),D.ZP.success("IP address deleted successfully")}catch(e){console.error("Error deleting IP:",e),D.ZP.error("Failed to delete IP address ".concat(e))}finally{V(!1),J(null)}};(0,d.useEffect)(()=>{(async()=>{if(null!=l){let e=[],s=await (0,y.Xd)(l,"proxy_admin_viewer");console.log("proxy admin viewer response: ",s);let t=s.users;console.log("proxy viewers response: ".concat(t)),t.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy viewers: ".concat(t));let a=(await (0,y.Xd)(l,"proxy_admin")).users;a.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy admins: ".concat(a)),console.log("combinedList: ".concat(e)),g(e),G(await (0,y.lg)(l))}})()},[l]);let ea=async e=>{try{if(null!=l&&null!=p){var s;D.ZP.info("Making API Call"),e.user_email,e.user_id;let t=await (0,y.pf)(l,e,"proxy_admin"),a=(null===(s=t.data)||void 0===s?void 0:s.user_id)||t.user_id;(0,y.XO)(l,a).then(e=>{f(e),v(!0)}),console.log("response for team create call: ".concat(t));let r=p.findIndex(e=>(console.log("user.user_id=".concat(e.user_id,"; response.user_id=").concat(a)),e.user_id===t.user_id));console.log("foundIndex: ".concat(r)),-1==r&&(console.log("updates admin with new user"),p.push(t),g(p)),n.resetFields(),w(!1)}}catch(e){console.error("Error creating the key:",e)}},er=async e=>{if(null==l)return;let s=lI[e.sso_provider],t={PROXY_BASE_URL:e.proxy_base_url};s&&Object.entries(s.envVarMap).forEach(s=>{let[l,a]=s;e[l]&&(t[a]=e[l])}),(0,y.K_)(l,{environment_variables:t})};return console.log("admins: ".concat(null==p?void 0:p.length)),(0,c.jsxs)("div",{className:"w-full m-2 mt-2 p-8",children:[(0,c.jsx)(o,{level:4,children:"Admin Access "}),(0,c.jsx)(u,{children:"Go to 'Internal Users' page to add other admins."}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Security Settings"}),(0,c.jsx)(eR.Z,{children:"SCIM"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(o,{level:4,children:" ✨ Security Settings"}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem"},children:[(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:()=>!0===a?T(!0):D.ZP.error("Only premium users can add SSO"),children:"Add SSO"})}),(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:Q,children:"Allowed IPs"})})]})]}),(0,c.jsxs)("div",{className:"flex justify-start mb-4",children:[(0,c.jsx)(lT,{isAddSSOModalVisible:I,isInstructionsModalVisible:A,handleAddSSOOk:()=>{T(!1),n.resetFields()},handleAddSSOCancel:()=>{T(!1),n.resetFields()},handleShowInstructions:e=>{ea(e),er(e),T(!1),E(!0)},handleInstructionsOk:()=>{E(!1)},handleInstructionsCancel:()=>{E(!1)},form:n}),(0,c.jsx)(M.Z,{title:"Manage Allowed IP Addresses",width:800,visible:P,onCancel:()=>O(!1),footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>U(!0),children:"Add IP Address"},"add"),(0,c.jsx)(k.Z,{onClick:()=>O(!1),children:"Close"},"close")],children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"IP Address"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:K.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e}),(0,c.jsx)(eA.Z,{className:"text-right",children:e!==$&&(0,c.jsx)(k.Z,{onClick:()=>el(e),color:"red",size:"xs",children:"Delete"})})]},s))})]})}),(0,c.jsx)(M.Z,{title:"Add Allowed IP Address",visible:F,onCancel:()=>U(!1),footer:null,children:(0,c.jsxs)(L.Z,{onFinish:ee,children:[(0,c.jsx)(L.Z.Item,{name:"ip",rules:[{required:!0,message:"Please enter an IP address"}],children:(0,c.jsx)(q.default,{placeholder:"Enter IP address"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add IP Address"})})]})}),(0,c.jsx)(M.Z,{title:"Confirm Delete",visible:z,onCancel:()=>V(!1),onOk:et,footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>et(),children:"Yes"},"delete"),(0,c.jsx)(k.Z,{onClick:()=>V(!1),children:"Close"},"close")],children:(0,c.jsxs)("p",{children:["Are you sure you want to delete the IP address: ",H,"?"]})})]}),(0,c.jsxs)(lS.Z,{title:"Login without SSO",color:"teal",children:["If you need to login without sso, you can access"," ",(0,c.jsxs)("a",{href:X,target:"_blank",children:[(0,c.jsx)("b",{children:X})," "]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lL,{accessToken:l,userID:p&&p.length>0?p[0].user_id:null,proxySettings:r})})]})]})]})},lF=l(92858),lR=e=>{let{alertingSettings:s,handleInputChange:l,handleResetField:t,handleSubmit:a,premiumUser:r}=e,[n]=L.Z.useForm();return(0,c.jsxs)(L.Z,{form:n,onFinish:()=>{console.log("INSIDE ONFINISH");let e=n.getFieldsValue(),s=Object.entries(e).every(e=>{let[s,l]=e;return"boolean"!=typeof l&&(""===l||null==l)});console.log("formData: ".concat(JSON.stringify(e),", isEmpty: ").concat(s)),s?console.log("Some form fields are empty."):a(e)},labelAlign:"left",children:[s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{align:"center",children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),e.premium_field?r?(0,c.jsx)(L.Z.Item,{name:e.field_name,children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s)}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>l(e.field_name,s)}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}):(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})})}):(0,c.jsx)(L.Z.Item,{name:e.field_name,className:"mb-0",valuePropName:"Boolean"===e.field_type?"checked":"value",children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s),className:"p-0"}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>{l(e.field_name,s),n.setFieldsValue({[e.field_name]:s})}}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>t(e.field_name,s),children:"Reset"})})]},s)),(0,c.jsx)("div",{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Update Settings"})})]})},lq=e=>{let{accessToken:s,premiumUser:l}=e,[t,a]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(0,y.RQ)(s).then(e=>{a(e)})},[s]),(0,c.jsx)(lR,{alertingSettings:t,handleInputChange:(e,s)=>{let l=t.map(l=>l.field_name===e?{...l,field_value:s}:l);console.log("updatedSettings: ".concat(JSON.stringify(l))),a(l)},handleResetField:(e,l)=>{if(s)try{let s=t.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:s.field_default_value}:s);a(s)}catch(e){console.log("ERROR OCCURRED!")}},handleSubmit:e=>{if(!s||(console.log("formValues: ".concat(e)),null==e||void 0==e))return;let l={};t.forEach(e=>{l[e.field_name]=e.field_value});let a={...e,...l};console.log("mergedFormValues: ".concat(JSON.stringify(a)));let{slack_alerting:r,...n}=a;console.log("slack_alerting: ".concat(r,", alertingArgs: ").concat(JSON.stringify(n)));try{(0,y.jA)(s,"alerting_args",n),"boolean"==typeof r&&(!0==r?(0,y.jA)(s,"alerting",["slack"]):(0,y.jA)(s,"alerting",[])),D.ZP.success("Wait 10s for proxy to update.")}catch(e){}},premiumUser:l})},lU=l(86582);let{Title:lz,Paragraph:lV}=es.default;console.log=function(){};var lK=e=>{let{accessToken:s,userRole:l,userID:t,premiumUser:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h]=L.Z.useForm(),[x,p]=(0,d.useState)(null),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)({}),[Z,N]=(0,d.useState)([]),[C,I]=(0,d.useState)(!1),[T,E]=(0,d.useState)([]),[P,F]=(0,d.useState)(null),[q,U]=(0,d.useState)([]),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)(null),H=e=>{Z.includes(e)?N(Z.filter(s=>s!==e)):N([...Z,e])},J={llm_exceptions:"LLM Exceptions",llm_too_slow:"LLM Responses Too Slow",llm_requests_hanging:"LLM Requests Hanging",budget_alerts:"Budget Alerts (API Keys, Users)",db_exceptions:"Database Exceptions (Read/Write)",daily_reports:"Weekly/Monthly Spend Reports",outage_alerts:"Outage Alerts",region_outage_alerts:"Region Outage Alerts"};(0,d.useEffect)(()=>{s&&l&&t&&(0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e),n(e.callbacks),E(e.available_callbacks);let s=e.alerts;if(console.log("alerts_data",s),s&&s.length>0){let e=s[0];console.log("_alert_info",e);let l=e.variables.SLACK_WEBHOOK_URL;console.log("catch_all_webhook",l),N(e.active_alerts),_(l),b(e.alerts_to_webhook)}o(s)})},[s,l,t]);let W=e=>Z&&Z.includes(e),G=()=>{if(!s)return;let e={};i.filter(e=>"email"===e.name).forEach(s=>{var l;Object.entries(null!==(l=s.variables)&&void 0!==l?l:{}).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));a&&a.value&&(e[l]=null==a?void 0:a.value)})}),console.log("updatedVariables",e);try{(0,y.K_)(s,{general_settings:{alerting:["email"]},environment_variables:e})}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Email settings updated successfully")},Y=async e=>{if(!s)return;let l={};Object.entries(e).forEach(e=>{let[s,t]=e;"callback"!==s&&(l[s]=t)});try{await (0,y.K_)(s,{environment_variables:l}),D.ZP.success("Callback added successfully"),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},$=async e=>{if(!s)return;let l=null==e?void 0:e.callback,t={};Object.entries(e).forEach(e=>{let[s,l]=e;"callback"!==s&&(t[s]=l)});try{await (0,y.K_)(s,{environment_variables:t,litellm_settings:{success_callback:[l]}}),D.ZP.success("Callback ".concat(l," added successfully")),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},X=e=>{console.log("inside handleSelectedCallbackChange",e),p(e.litellm_callback_name),console.log("all callbacks",T),e&&e.litellm_callback_params?(U(e.litellm_callback_params),console.log("selectedCallbackParams",q)):U([])};return s?(console.log("callbacks: ".concat(r)),(0,c.jsxs)("div",{className:"w-full mx-4",children:[(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Logging Callbacks"}),(0,c.jsx)(eR.Z,{value:"2",children:"Alerting Types"}),(0,c.jsx)(eR.Z,{value:"3",children:"Alerting Settings"}),(0,c.jsx)(eR.Z,{value:"4",children:"Email Alerts"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Active Logging Callbacks"}),(0,c.jsx)(w.Z,{numItems:2,children:(0,c.jsx)(eF.Z,{className:"max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eP.Z,{children:"Callback Name"})})}),(0,c.jsx)(eT.Z,{children:r.map((e,l)=>(0,c.jsxs)(eO.Z,{className:"flex justify-between",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.name})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"flex justify-between",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{B(e),V(!0)}}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,e.name),className:"ml-2",variant:"secondary",children:"Test Callback"})]})})]},l))})]})})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>I(!0),children:"Add Callback"})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(A.Z,{className:"my-2",children:["Alerts are only supported for Slack Webhook URLs. Get your webhook urls from"," ",(0,c.jsx)("a",{href:"https://api.slack.com/messaging/webhooks",target:"_blank",style:{color:"blue"},children:"here"})]}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{children:"Slack Webhook URL"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(J).map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:"region_outage_alerts"==l?a?(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)}):(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})}):(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:l,type:"password",defaultValue:v&&v[l]?v[l]:f})})]},s)})})]}),(0,c.jsx)(k.Z,{size:"xs",className:"mt-2",onClick:()=>{if(!s)return;let e={};Object.entries(J).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));console.log("key",l),console.log("webhookInput",a);let r=(null==a?void 0:a.value)||"";console.log("newWebhookValue",r),e[l]=r}),console.log("updatedAlertToWebhooks",e);let l={general_settings:{alert_to_webhook_url:e,alert_types:Z}};console.log("payload",l);try{(0,y.K_)(s,l)}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Alerts updated successfully")},children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"slack"),className:"mx-2",children:"Test Alerts"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lq,{accessToken:s,premiumUser:a})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Email Settings"}),(0,c.jsxs)(A.Z,{children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: email alerts"})," ",(0,c.jsx)("br",{})]}),(0,c.jsx)("div",{className:"flex w-full",children:i.filter(e=>"email"===e.name).map((e,s)=>{var l;return(0,c.jsx)(eA.Z,{children:(0,c.jsx)("ul",{children:(0,c.jsx)(w.Z,{numItems:2,children:Object.entries(null!==(l=e.variables)&&void 0!==l?l:{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("li",{className:"mx-2 my-2",children:[!0!=a&&("EMAIL_LOGO_URL"===s||"EMAIL_SUPPORT_CONTACT"===s)?(0,c.jsxs)("div",{children:[(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:(0,c.jsxs)(A.Z,{className:"mt-2",children:[" ","✨ ",s]})}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",disabled:!0,style:{width:"400px"}})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-2",children:s}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",style:{width:"400px"}})]}),(0,c.jsxs)("p",{style:{fontSize:"small",fontStyle:"italic"},children:["SMTP_HOST"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP host address, e.g. `smtp.resend.com`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PORT"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP port number, e.g. `587`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_USERNAME"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP username, e.g. `username`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PASSWORD"===s&&(0,c.jsx)("span",{style:{color:"red"},children:" Required * "}),"SMTP_SENDER_EMAIL"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the sender email address, e.g. `sender@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"TEST_EMAIL_ADDRESS"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Email Address to send `Test Email Alert` to. example: `info@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"EMAIL_LOGO_URL"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the Logo that appears in the email, pass a url to your logo"}),"EMAIL_SUPPORT_CONTACT"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the support email address that appears in the email. Default is support@berri.ai"})]})]},s)})})})},s)})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>G(),children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"email"),className:"mx-2",children:"Test Email Alerts"})]})})]})]})}),(0,c.jsxs)(M.Z,{title:"Add Logging Callback",visible:C,width:800,onCancel:()=>I(!1),footer:null,children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/logging",className:"mb-8 mt-4",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: Logging"}),(0,c.jsx)(L.Z,{form:h,onFinish:$,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(lU.Z,{label:"Callback",name:"callback",rules:[{required:!0,message:"Please select a callback"}],children:(0,c.jsx)(O.default,{onChange:e=>{let s=T[e];s&&(console.log(s.ui_callback_name),X(s))},children:T&&Object.values(T).map(e=>(0,c.jsx)(ee.Z,{value:e.litellm_callback_name,children:e.ui_callback_name},e.litellm_callback_name))})}),q&&q.map(e=>(0,c.jsx)(lU.Z,{label:e,name:e,rules:[{required:!0,message:"Please enter the value for "+e}],children:(0,c.jsx)(S.Z,{type:"password"})},e)),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]}),(0,c.jsx)(M.Z,{visible:z,width:800,title:"Edit ".concat(null==K?void 0:K.name," Settings"),onCancel:()=>V(!1),footer:null,children:(0,c.jsxs)(L.Z,{form:h,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(c.Fragment,{children:K&&K.variables&&Object.entries(K.variables).map(e=>{let[s,l]=e;return(0,c.jsx)(lU.Z,{label:s,name:s,children:(0,c.jsx)(S.Z,{type:"password",defaultValue:l})},s)})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]})):null},lB=l(92414),lH=l(46030);let{Option:lJ}=O.default;var lW=e=>{let{models:s,accessToken:l,routerSettings:t,setRouterSettings:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>i(!0),children:"+ Add Fallbacks"}),(0,c.jsx)(M.Z,{title:"Add Fallbacks",visible:n,width:800,footer:null,onOk:()=>{i(!1),r.resetFields()},onCancel:()=>{i(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:e=>{console.log(e);let{model_name:s,models:n}=e,o=[...t.fallbacks||[],{[s]:n}],c={...t,fallbacks:o};console.log(c);try{(0,y.K_)(l,{router_settings:c}),a(c)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully"),i(!1),r.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Public Model Name",name:"model_name",rules:[{required:!0,message:"Set the model to fallback for"}],help:"required",children:(0,c.jsx)(eD.Z,{defaultValue:o,children:s&&s.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>m(e),children:e},s))})}),(0,c.jsx)(L.Z.Item,{label:"Fallback Models",name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",children:(0,c.jsx)(lB.Z,{value:s,children:s&&s.filter(e=>e!=o).map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Fallbacks"})})]})})]})},lG=l(26433);async function lY(e,s){console.log=function(){},console.log("isLocal:",!1);let l=window.location.origin,t=new lG.ZP.OpenAI({apiKey:s,baseURL:l,dangerouslyAllowBrowser:!0});try{let s=await t.chat.completions.create({model:e,messages:[{role:"user",content:"Hi, this is a test message"}],mock_testing_fallbacks:!0});D.ZP.success((0,c.jsxs)("span",{children:["Test model=",(0,c.jsx)("strong",{children:e}),", received model=",(0,c.jsx)("strong",{children:s.model}),". See"," ",(0,c.jsx)("a",{href:"#",onClick:()=>window.open("https://docs.litellm.ai/docs/proxy/reliability","_blank"),style:{textDecoration:"underline",color:"blue"},children:"curl"})]}))}catch(e){D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20)}}let l$={ttl:3600,lowest_latency_buffer:0},lX=e=>{let{selectedStrategy:s,strategyArgs:l,paramExplanation:t}=e;return(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{className:"text-sm font-medium text-tremor-content-strong dark:text-dark-tremor-content-strong",children:"Routing Strategy Specific Args"}),(0,c.jsx)(I.Z,{children:"latency-based-routing"==s?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(l).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:t[s]})]}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]})}):(0,c.jsx)(A.Z,{children:"No specific settings"})})]})};var lQ=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)({}),[i,o]=(0,d.useState)({}),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(null),Z={routing_strategy_args:"(dict) Arguments to pass to the routing strategy",routing_strategy:"(string) Routing strategy to use",allowed_fails:"(int) Number of times a deployment can fail before being added to cooldown",cooldown_time:"(int) time in seconds to cooldown a deployment after failure",num_retries:"(int) Number of retries for failed requests. Defaults to 0.",timeout:"(float) Timeout for requests. Defaults to None.",retry_after:"(int) Minimum time to wait before retrying a failed request",ttl:"(int) Sliding window to look back over when calculating the average latency of a deployment. Default - 1 hour (in seconds).",lowest_latency_buffer:"(float) Shuffle between deployments within this % of the lowest latency. Default - 0 (i.e. always pick lowest latency)."};(0,d.useEffect)(()=>{s&&l&&t&&((0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e);let s=e.router_settings;"model_group_retry_policy"in s&&delete s.model_group_retry_policy,n(s)}),(0,y.YU)(s).then(e=>{u(e)}))},[s,l,t]);let C=async e=>{if(!s)return;console.log("received key: ".concat(e)),console.log("routerSettings['fallbacks']: ".concat(r.fallbacks));let l=r.fallbacks.map(s=>(e in s&&delete s[e],s)).filter(e=>Object.keys(e).length>0),t={...r,fallbacks:l};try{await (0,y.K_)(s,{router_settings:t}),n(t),D.ZP.success("Router settings updated successfully")}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}},I=(e,s)=>{u(m.map(l=>l.field_name===e?{...l,field_value:s}:l))},T=(e,l)=>{if(!s)return;let t=m[l].field_value;if(null!=t&&void 0!=t)try{(0,y.jA)(s,e,t);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:!0}:s);u(l)}catch(e){}},P=(e,l)=>{if(s)try{(0,y.ao)(s,e);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:null}:s);u(l)}catch(e){}},O=e=>{if(!s)return;console.log("router_settings",e);let l=Object.fromEntries(Object.entries(e).map(e=>{let[s,l]=e;if("routing_strategy_args"!==s&&"routing_strategy"!==s){var t;return[s,(null===(t=document.querySelector('input[name="'.concat(s,'"]')))||void 0===t?void 0:t.value)||l]}if("routing_strategy"==s)return[s,f];if("routing_strategy_args"==s&&"latency-based-routing"==f){let e={},s=document.querySelector('input[name="lowest_latency_buffer"]'),l=document.querySelector('input[name="ttl"]');return(null==s?void 0:s.value)&&(e.lowest_latency_buffer=Number(s.value)),(null==l?void 0:l.value)&&(e.ttl=Number(l.value)),console.log("setRoutingStrategyArgs: ".concat(e)),["routing_strategy_args",e]}return null}).filter(e=>null!=e));console.log("updatedVariables",l);try{(0,y.K_)(s,{router_settings:l})}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully")};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Loadbalancing"}),(0,c.jsx)(eR.Z,{value:"2",children:"Fallbacks"}),(0,c.jsx)(eR.Z,{value:"3",children:"General"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:[(0,c.jsx)(E.Z,{children:"Router Settings"}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(r).filter(e=>{let[s,l]=e;return"fallbacks"!=s&&"context_window_fallbacks"!=s&&"routing_strategy_args"!=s}).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:Z[s]})]}),(0,c.jsx)(eA.Z,{children:"routing_strategy"==s?(0,c.jsxs)(eD.Z,{defaultValue:l,className:"w-full max-w-md",onValueChange:_,children:[(0,c.jsx)(ee.Z,{value:"usage-based-routing",children:"usage-based-routing"}),(0,c.jsx)(ee.Z,{value:"latency-based-routing",children:"latency-based-routing"}),(0,c.jsx)(ee.Z,{value:"simple-shuffle",children:"simple-shuffle"})]}):(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]}),(0,c.jsx)(lX,{selectedStrategy:f,strategyArgs:r&&r.routing_strategy_args&&Object.keys(r.routing_strategy_args).length>0?r.routing_strategy_args:l$,paramExplanation:Z})]}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>O(r),children:"Save Changes"})})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Model Name"}),(0,c.jsx)(eP.Z,{children:"Fallbacks"})]})}),(0,c.jsx)(eT.Z,{children:r.fallbacks&&r.fallbacks.map((e,l)=>Object.entries(e).map(e=>{let[t,a]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:t}),(0,c.jsx)(eA.Z,{children:Array.isArray(a)?a.join(", "):a}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{onClick:()=>lY(t,s),children:"Test Fallback"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>C(t)})})]},l.toString()+t)}))})]}),(0,c.jsx)(lW,{models:(null==a?void 0:a.data)?a.data.map(e=>e.model_name):[],accessToken:s,routerSettings:r,setRouterSettings:n})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"}),(0,c.jsx)(eP.Z,{children:"Status"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:m.filter(e=>"TypedDictionary"!==e.field_type).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),(0,c.jsx)(eA.Z,{children:"Integer"==e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>I(e.field_name,s)}):null}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{onClick:()=>T(e.field_name,s),children:"Update"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>P(e.field_name,s),children:"Reset"})]})]},s))})]})})})]})]})}):null},l0=l(93142),l1=e=>{let{value:s={},onChange:l}=e,[t,a]=(0,d.useState)(Object.entries(s)),r=e=>{let s=t.filter((s,l)=>l!==e);a(s),null==l||l(Object.fromEntries(s))},n=(e,s,r)=>{let n=[...t];n[e]=[s,r],a(n),null==l||l(Object.fromEntries(n))};return(0,c.jsxs)("div",{children:[t.map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(l0.Z,{style:{display:"flex",marginBottom:8},align:"start",children:[(0,c.jsx)(S.Z,{placeholder:"Header Name",value:l,onChange:e=>n(s,e.target.value,t)}),(0,c.jsx)(S.Z,{placeholder:"Header Value",value:t,onChange:e=>n(s,l,e.target.value)}),(0,c.jsx)(sH.Z,{onClick:()=>r(s)})]},s)}),(0,c.jsx)(R.ZP,{type:"dashed",onClick:()=>{a([...t,["",""]])},icon:(0,c.jsx)(sJ.Z,{}),children:"Add Header"})]})};let{Option:l2}=O.default;var l4=e=>{let{accessToken:s,setPassThroughItems:l,passThroughItems:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>n(!0),children:"+ Add Pass-Through Endpoint"}),(0,c.jsx)(M.Z,{title:"Add Pass-Through Endpoint",visible:r,width:800,footer:null,onOk:()=>{n(!1),a.resetFields()},onCancel:()=>{n(!1),a.resetFields()},children:(0,c.jsxs)(L.Z,{form:a,onFinish:e=>{console.log(e);let r=[...t,{headers:e.headers,path:e.path,target:e.target}];try{(0,y.Vt)(s,e),l(r)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("Pass through endpoint successfully added"),n(!1),a.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Path",name:"path",rules:[{required:!0,message:"The route to be added to the LiteLLM Proxy Server."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Target",name:"target",rules:[{required:!0,message:"The URL to which requests for this path should be forwarded."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Headers",name:"headers",rules:[{required:!0,message:"Key-value pairs of headers to be forwarded with the request. You can set any key value pair here and it will be forwarded to your target endpoint"}],help:"required",children:(0,c.jsx)(l1,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Pass-Through Endpoint"})})]})})]})},l5=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&l&&t&&(0,y.mp)(s).then(e=>{n(e.endpoints)})},[s,l,t]);let i=(e,l)=>{if(s)try{(0,y.EG)(s,e);let l=r.filter(s=>s.path!==e);n(l),D.ZP.success("Endpoint deleted successfully.")}catch(e){}};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsx)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Path"}),(0,c.jsx)(eP.Z,{children:"Target"}),(0,c.jsx)(eP.Z,{children:"Headers"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:r.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.path})}),(0,c.jsx)(eA.Z,{children:e.target}),(0,c.jsx)(eA.Z,{children:JSON.stringify(e.headers)}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>i(e.path,s),children:"Reset"})})]},s))})]}),(0,c.jsx)(l4,{accessToken:s,setPassThroughItems:n,passThroughItems:r})]})})}):null},l3=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a}=e,[r]=L.Z.useForm(),n=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call");let s=await (0,y.Zr)(l,e);console.log("key create Response:",s),a(e=>e?[...e,s]:[s]),D.ZP.success("API Key Created"),r.resetFields()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Create Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),r.resetFields()},onCancel:()=>{t(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:n,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Budget"})})]})})},l6=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a,existingBudget:r,handleUpdateCall:n}=e;console.log("existingBudget",r);let[i]=L.Z.useForm();(0,d.useEffect)(()=>{i.setFieldsValue(r)},[r,i]);let o=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call"),t(!0);let s=await (0,y.qI)(l,e);a(e=>e?[...e,s]:[s]),D.ZP.success("Budget Updated"),i.resetFields(),n()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Edit Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),i.resetFields()},onCancel:()=>{t(!1),i.resetFields()},children:(0,c.jsxs)(L.Z,{form:i,onFinish:o,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:r,children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})},l8=l(17906),l7=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&(0,y.O3)(s).then(e=>{m(e)})},[s]);let u=async(e,l)=>{console.log("budget_id",e),null!=s&&(i(o.find(s=>s.budget_id===e)||null),r(!0))},h=async(e,l)=>{if(null==s)return;D.ZP.info("Request made"),await (0,y.NV)(s,e);let t=[...o];t.splice(l,1),m(t),D.ZP.success("Budget Deleted.")},x=async()=>{null!=s&&(0,y.O3)(s).then(e=>{m(e)})};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)(k.Z,{size:"sm",variant:"primary",className:"mb-2",onClick:()=>t(!0),children:"+ Create Budget"}),(0,c.jsx)(l3,{accessToken:s,isModalVisible:l,setIsModalVisible:t,setBudgetList:m}),n&&(0,c.jsx)(l6,{accessToken:s,isModalVisible:a,setIsModalVisible:r,setBudgetList:m,existingBudget:n,handleUpdateCall:x}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Create a budget to assign to customers."}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Budget ID"}),(0,c.jsx)(eP.Z,{children:"Max Budget"}),(0,c.jsx)(eP.Z,{children:"TPM"}),(0,c.jsx)(eP.Z,{children:"RPM"})]})}),(0,c.jsx)(eT.Z,{children:o.slice().sort((e,s)=>new Date(s.updated_at).getTime()-new Date(e.updated_at).getTime()).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.budget_id}),(0,c.jsx)(eA.Z,{children:e.max_budget?e.max_budget:"n/a"}),(0,c.jsx)(eA.Z,{children:e.tpm_limit?e.tpm_limit:"n/a"}),(0,c.jsx)(eA.Z,{children:e.rpm_limit?e.rpm_limit:"n/a"}),(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>u(e.budget_id,s)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>h(e.budget_id,s)})]},s))})]})]}),(0,c.jsxs)("div",{className:"mt-5",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"How to use budget id"}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Assign Budget to Customer"}),(0,c.jsx)(eR.Z,{children:"Test it (Curl)"}),(0,c.jsx)(eR.Z,{children:"Test it (OpenAI SDK)"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:"\ncurl -X POST --location '/end_user/new' \n-H 'Authorization: Bearer ' \n-H 'Content-Type: application/json' \n-d '{\"user_id\": \"my-customer-id', \"budget_id\": \"\"}' # \uD83D\uDC48 KEY CHANGE\n\n "})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:'\ncurl -X POST --location \'/chat/completions\' \n-H \'Authorization: Bearer \' \n-H \'Content-Type: application/json\' \n-d \'{\n "model": "gpt-3.5-turbo\', \n "messages":[{"role": "user", "content": "Hey, how\'s it going?"}],\n "user": "my-customer-id"\n}\' # \uD83D\uDC48 KEY CHANGE\n\n '})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'from openai import OpenAI\nclient = OpenAI(\n base_url="",\n api_key=""\n)\n\ncompletion = client.chat.completions.create(\n model="gpt-3.5-turbo",\n messages=[\n {"role": "system", "content": "You are a helpful assistant."},\n {"role": "user", "content": "Hello!"}\n ],\n user="my-customer-id"\n)\n\nprint(completion.choices[0].message)'})})]})]})]})]})},l9=l(77398),te=l.n(l9);async function ts(e){try{let s=await fetch("http://ip-api.com/json/".concat(e)),l=await s.json();console.log("ip lookup data",l);let t=l.countryCode?l.countryCode.toUpperCase().split("").map(e=>String.fromCodePoint(e.charCodeAt(0)+127397)).join(""):"";return l.country?"".concat(t," ").concat(l.country):"Unknown"}catch(e){return console.error("Error looking up IP:",e),"Unknown"}}let tl=e=>{let{ipAddress:s}=e,[l,t]=d.useState("-");return d.useEffect(()=>{if(!s)return;let e=!0;return ts(s).then(s=>{e&&t(s)}).catch(()=>{e&&t("-")}),()=>{e=!1}},[s]),(0,c.jsx)("span",{children:l})},tt=e=>{try{return new Date(e).toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0}).replace(",","")}catch(e){return"Error converting time"}},ta=e=>{let{utcTime:s}=e;return(0,c.jsx)("span",{style:{fontFamily:"monospace",width:"180px",display:"inline-block"},children:tt(s)})},tr=(e,s)=>{var l,t;return(null===(t=e.metadata)||void 0===t?void 0:null===(l=t.mcp_tool_call_metadata)||void 0===l?void 0:l.mcp_server_logo_url)?e.metadata.mcp_tool_call_metadata.mcp_server_logo_url:s?sn(s).logo:""},tn=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return(0,c.jsx)(()=>{let[e,l]=d.useState(s.getIsExpanded()),t=d.useCallback(()=>{l(e=>!e),s.getToggleExpandedHandler()()},[s]);return s.getCanExpand()?(0,c.jsx)("button",{onClick:t,style:{cursor:"pointer"},"aria-label":e?"Collapse row":"Expand row",className:"w-6 h-6 flex items-center justify-center focus:outline-none",children:(0,c.jsx)("svg",{className:"w-4 h-4 transform transition-transform duration-75 ".concat(e?"rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}):(0,c.jsx)("span",{className:"w-6 h-6 flex items-center justify-center",children:"●"})},{})}},{header:"Time",accessorKey:"startTime",cell:e=>(0,c.jsx)(ta,{utcTime:e.getValue()})},{header:"Status",accessorKey:"metadata.status",cell:e=>{let s="failure"!==(e.getValue()||"Success").toLowerCase();return(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat(s?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:s?"Success":"Failure"})}},{header:"Request ID",accessorKey:"request_id",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||""),children:(0,c.jsx)("span",{className:"font-mono text-xs max-w-[15ch] truncate block",children:String(e.getValue()||"")})})},{header:"Cost",accessorKey:"spend",cell:e=>(0,c.jsxs)("span",{children:["$",Number(e.getValue()||0).toFixed(6)]})},{header:"Country",accessorKey:"requester_ip_address",cell:e=>(0,c.jsx)(tl,{ipAddress:e.getValue()})},{header:"Team Name",accessorKey:"metadata.user_api_key_team_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Key Hash",accessorKey:"metadata.user_api_key",cell:e=>{let s=String(e.getValue()||"-"),l=e.row.original.onKeyHashClick;return(0,c.jsx)(W.Z,{title:s,children:(0,c.jsx)("span",{className:"font-mono max-w-[15ch] truncate block cursor-pointer hover:text-blue-600",onClick:()=>null==l?void 0:l(s),children:s})})}},{header:"Key Name",accessorKey:"metadata.user_api_key_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Model",accessorKey:"model",cell:e=>{let s=e.row.original,l=s.custom_llm_provider,t=String(e.getValue()||"");return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l&&(0,c.jsx)("img",{src:tr(s,l),alt:"",className:"w-4 h-4",onError:e=>{e.target.style.display="none"}}),(0,c.jsx)(W.Z,{title:t,children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:t})})]})}},{header:"Tokens",accessorKey:"total_tokens",cell:e=>{let s=e.row.original;return(0,c.jsxs)("span",{className:"text-sm",children:[String(s.total_tokens||"0"),(0,c.jsxs)("span",{className:"text-gray-400 text-xs ml-1",children:["(",String(s.prompt_tokens||"0"),"+",String(s.completion_tokens||"0"),")"]})]})}},{header:"Internal User",accessorKey:"user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"End User",accessorKey:"end_user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Tags",accessorKey:"request_tags",cell:e=>{let s=e.getValue();if(!s||0===Object.keys(s).length)return"-";let l=Object.entries(s),t=l[0],a=l.slice(1);return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:(0,c.jsx)(W.Z,{title:(0,c.jsx)("div",{className:"flex flex-col gap-1",children:l.map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{children:[s,": ",String(l)]},s)})}),children:(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[t[0],": ",String(t[1]),a.length>0&&" +".concat(a.length)]})})})}}],ti=async(e,s,l,t)=>{console.log("prefetchLogDetails called with",e.length,"logs");let a=e.map(e=>{if(e.request_id)return console.log("Prefetching details for request_id:",e.request_id),t.prefetchQuery({queryKey:["logDetails",e.request_id,s],queryFn:async()=>{console.log("Fetching details for",e.request_id);let t=await (0,y.qk)(l,e.request_id,s);return console.log("Received details for",e.request_id,":",t?"success":"failed"),t},staleTime:6e5,gcTime:6e5})});try{let e=await Promise.all(a);return console.log("All prefetch promises completed:",e.length),e}catch(e){throw console.error("Error in prefetchLogDetails:",e),e}},to=e=>{var s;let{errorInfo:l}=e,[t,a]=d.useState({}),[r,n]=d.useState(!1),i=e=>{a(s=>({...s,[e]:!s[e]}))},o=l.traceback&&(s=l.traceback)?Array.from(s.matchAll(/File "([^"]+)", line (\d+)/g)).map(e=>{let l=e[1],t=e[2],a=l.split("/").pop()||l,r=e.index||0,n=s.indexOf('File "',r+1),i=n>-1?s.substring(r,n).trim():s.substring(r).trim(),o=i.split("\n"),c="";return o.length>1&&(c=o[o.length-1].trim()),{filePath:l,fileName:a,lineNumber:t,code:c,inFunction:i.includes(" in ")?i.split(" in ")[1].split("\n")[0]:""}}):[];return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsxs)("h3",{className:"text-lg font-medium flex items-center text-red-600",children:[(0,c.jsx)("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),"Error Details"]})}),(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"bg-red-50 rounded-md p-4 mb-4",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Type:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_class||"Unknown Error"})]}),(0,c.jsxs)("div",{className:"flex mt-2",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Message:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_message||"Unknown error occurred"})]})]}),l.traceback&&(0,c.jsxs)("div",{className:"mt-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-2",children:[(0,c.jsx)("h4",{className:"font-medium",children:"Traceback"}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsx)("button",{onClick:()=>{let e=!r;if(n(e),o.length>0){let s={};o.forEach((l,t)=>{s[t]=e}),a(s)}},className:"text-gray-500 hover:text-gray-700 flex items-center text-sm",children:r?"Collapse All":"Expand All"}),(0,c.jsxs)("button",{onClick:()=>navigator.clipboard.writeText(l.traceback||""),className:"text-gray-500 hover:text-gray-700 flex items-center",title:"Copy traceback",children:[(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,c.jsx)("span",{className:"ml-1",children:"Copy"})]})]})]}),(0,c.jsx)("div",{className:"bg-white rounded-md border border-gray-200 overflow-hidden shadow-sm",children:o.map((e,s)=>(0,c.jsxs)("div",{className:"border-b border-gray-200 last:border-b-0",children:[(0,c.jsxs)("div",{className:"px-4 py-2 flex items-center justify-between cursor-pointer hover:bg-gray-50",onClick:()=>i(s),children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-gray-400 mr-2 w-12 text-right",children:e.lineNumber}),(0,c.jsx)("span",{className:"text-gray-600 font-medium",children:e.fileName}),(0,c.jsx)("span",{className:"text-gray-500 mx-1",children:"in"}),(0,c.jsx)("span",{className:"text-indigo-600 font-medium",children:e.inFunction||e.fileName})]}),(0,c.jsx)("svg",{className:"w-5 h-5 text-gray-500 transition-transform ".concat(t[s]?"transform rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),(t[s]||!1)&&e.code&&(0,c.jsx)("div",{className:"px-12 py-2 font-mono text-sm text-gray-800 bg-gray-50 overflow-x-auto border-t border-gray-100",children:e.code})]},s))})]})]})]})},tc=e=>{let{show:s}=e;return s?(0,c.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start",children:[(0,c.jsx)("div",{className:"text-blue-500 mr-3 flex-shrink-0 mt-0.5",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,c.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,c.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}),(0,c.jsxs)("div",{children:[(0,c.jsx)("h4",{className:"text-sm font-medium text-blue-800",children:"Request/Response Data Not Available"}),(0,c.jsxs)("p",{className:"text-sm text-blue-700 mt-1",children:["To view request and response details, enable prompt storage in your LiteLLM configuration by adding the following to your ",(0,c.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded",children:"proxy_config.yaml"})," file:"]}),(0,c.jsx)("pre",{className:"mt-2 bg-white p-3 rounded border border-blue-200 text-xs font-mono overflow-auto",children:"general_settings:\n store_model_in_db: true\n store_prompts_in_spend_logs: true"}),(0,c.jsx)("p",{className:"text-xs text-blue-700 mt-2",children:"Note: This will only affect new requests after the configuration change."})]})]}):null};function td(e){var s,l,t,a;let{accessToken:r,token:n,userRole:i,userID:o,allTeams:m}=e,[u,h]=(0,d.useState)(""),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(1),[b]=(0,d.useState)(50),Z=(0,d.useRef)(null),N=(0,d.useRef)(null),w=(0,d.useRef)(null),[k,S]=(0,d.useState)(te()().subtract(24,"hours").format("YYYY-MM-DDTHH:mm")),[C,I]=(0,d.useState)(te()().format("YYYY-MM-DDTHH:mm")),[T,A]=(0,d.useState)(!1),[E,P]=(0,d.useState)(!1),[O,L]=(0,d.useState)(""),[D,M]=(0,d.useState)(""),[F,R]=(0,d.useState)(""),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(null),[K,B]=(0,d.useState)(null),[H,J]=(0,d.useState)("Team ID"),[W,G]=(0,d.useState)(i&&eg.lo.includes(i)),[Y,$]=(0,d.useState)(null),X=(0,x.NL)();(0,d.useEffect)(()=>{(async()=>{if(K&&r){let e=await (0,y.t0)(r,K);console.log("keyData",e),V({...e.info,token:K,api_key:K})}})()},[K,r]),(0,d.useEffect)(()=>{function e(e){Z.current&&!Z.current.contains(e.target)&&f(!1),N.current&&!N.current.contains(e.target)&&g(!1),w.current&&!w.current.contains(e.target)&&P(!1)}return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{i&&eg.lo.includes(i)&&G(!0)},[i]);let Q=(0,e4.a)({queryKey:["logs","table",_,b,k,C,F,q,W?o:null],queryFn:async()=>{if(!r||!n||!i||!o)return console.log("Missing required auth parameters"),{data:[],total:0,page:1,page_size:b,total_pages:0};let e=te()(k).utc().format("YYYY-MM-DD HH:mm:ss"),s=T?te()(C).utc().format("YYYY-MM-DD HH:mm:ss"):te()().utc().format("YYYY-MM-DD HH:mm:ss"),l=await (0,y.h3)(r,q||void 0,F||void 0,void 0,e,s,_,b,W?o:void 0);return await ti(l.data,e,r,X),l.data=l.data.map(s=>{let l=X.getQueryData(["logDetails",s.request_id,e]);return(null==l?void 0:l.messages)&&(null==l?void 0:l.response)&&(s.messages=l.messages,s.response=l.response),s}),l},enabled:!!r&&!!n&&!!i&&!!o,refetchInterval:5e3,refetchIntervalInBackground:!0});if((0,d.useEffect)(()=>{var e;(null===(e=Q.data)||void 0===e?void 0:e.data)&&Y&&!Q.data.data.some(e=>e.request_id===Y)&&$(null)},[null===(s=Q.data)||void 0===s?void 0:s.data,Y]),!r||!n||!i||!o)return console.log("got None values for one of accessToken, token, userRole, userID"),null;let ee=(null===(t=Q.data)||void 0===t?void 0:null===(l=t.data)||void 0===l?void 0:l.filter(e=>!u||e.request_id.includes(u)||e.model.includes(u)||e.user&&e.user.includes(u)).map(e=>({...e,onKeyHashClick:e=>B(e)})))||[],es=()=>{if(T)return"".concat(te()(k).format("MMM D, h:mm A")," - ").concat(te()(C).format("MMM D, h:mm A"));let e=te()(),s=te()(k),l=e.diff(s,"minutes");if(l<=15)return"Last 15 Minutes";if(l<=60)return"Last Hour";let t=e.diff(s,"hours");return t<=4?"Last 4 Hours":t<=24?"Last 24 Hours":t<=168?"Last 7 Days":"".concat(s.format("MMM D")," - ").concat(e.format("MMM D"))};return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Request Logs"})}),z&&K&&z.api_key===K?(0,c.jsx)(eG,{keyId:K,keyData:z,accessToken:r,userID:o,userRole:i,teams:m,onClose:()=>B(null)}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between space-y-4 md:space-y-0",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by Request ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:u,onChange:e=>h(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"relative",ref:N,children:[(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>g(!p),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filter"]}),p&&(0,c.jsx)("div",{className:"absolute left-0 mt-2 w-[500px] bg-white rounded-lg shadow-lg border p-4 z-50",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsxs)("div",{className:"relative",children:[(0,c.jsxs)("button",{onClick:()=>f(!j),className:"px-3 py-1.5 border rounded-md bg-white text-sm min-w-[160px] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-left flex justify-between items-center",children:[H,(0,c.jsx)("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),j&&(0,c.jsx)("div",{className:"absolute left-0 mt-1 w-[160px] bg-white border rounded-md shadow-lg z-50",children:["Team ID","Key Hash"].map(e=>(0,c.jsxs)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2 ".concat(H===e?"bg-blue-50 text-blue-600":""),onClick:()=>{J(e),f(!1),"Team ID"===e?M(""):L("")},children:[H===e&&(0,c.jsx)("svg",{className:"h-4 w-4 text-blue-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e]},e))})]}),(0,c.jsx)("input",{type:"text",placeholder:"Enter value...",className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:"Team ID"===H?O:D,onChange:e=>{"Team ID"===H?L(e.target.value):M(e.target.value)}}),(0,c.jsx)("button",{className:"p-1 hover:bg-gray-100 rounded-md",onClick:()=>{L(""),M("")},children:(0,c.jsx)("span",{className:"text-gray-500",children:"\xd7"})})]}),(0,c.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm border rounded-md hover:bg-gray-50",onClick:()=>{L(""),M(""),g(!1)},children:"Cancel"}),(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{R(O),U(D),v(1),g(!1)},children:"Apply Filters"})]})]})})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsxs)("div",{className:"relative",ref:w,children:[(0,c.jsxs)("button",{onClick:()=>P(!E),className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"})}),es()]}),E&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border p-2 z-50",children:(0,c.jsxs)("div",{className:"space-y-1",children:[[{label:"Last 15 Minutes",value:15,unit:"minutes"},{label:"Last Hour",value:1,unit:"hours"},{label:"Last 4 Hours",value:4,unit:"hours"},{label:"Last 24 Hours",value:24,unit:"hours"},{label:"Last 7 Days",value:7,unit:"days"}].map(e=>(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(es()===e.label?"bg-blue-50 text-blue-600":""),onClick:()=>{I(te()().format("YYYY-MM-DDTHH:mm")),S(te()().subtract(e.value,e.unit).format("YYYY-MM-DDTHH:mm")),P(!1),A(!1)},children:e.label},e.label)),(0,c.jsx)("div",{className:"border-t my-2"}),(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(T?"bg-blue-50 text-blue-600":""),onClick:()=>A(!T),children:"Custom Range"})]})})]}),(0,c.jsxs)("button",{onClick:()=>{Q.refetch()},className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",title:"Refresh data",children:[(0,c.jsx)("svg",{className:"w-4 h-4 ".concat(Q.isFetching?"animate-spin":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),(0,c.jsx)("span",{children:"Refresh"})]})]}),T&&(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:k,onChange:e=>{S(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})}),(0,c.jsx)("span",{className:"text-gray-500",children:"to"}),(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:C,onChange:e=>{I(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})})]})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",Q.isLoading?"...":Q.data?(_-1)*b+1:0," ","-"," ",Q.isLoading?"...":Q.data?Math.min(_*b,Q.data.total):0," ","of"," ",Q.isLoading?"...":Q.data?Q.data.total:0," ","results"]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",Q.isLoading?"...":_," of"," ",Q.isLoading?"...":Q.data?Q.data.total_pages:1]}),(0,c.jsx)("button",{onClick:()=>v(e=>Math.max(1,e-1)),disabled:Q.isLoading||1===_,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>v(e=>{var s;return Math.min((null===(s=Q.data)||void 0===s?void 0:s.total_pages)||1,e+1)}),disabled:Q.isLoading||_===((null===(a=Q.data)||void 0===a?void 0:a.total_pages)||1),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})}),(0,c.jsx)(eL,{columns:tn,data:ee,renderSubComponent:tm,getRowCanExpand:()=>!0,onRowExpand:e=>{$(e)},expandedRequestId:Y})]})})]})}function tm(e){var s,l,t,a,r,n;let{row:i}=e,o=e=>{let s={...e};return"proxy_server_request"in s&&delete s.proxy_server_request,s},d=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},m=()=>{var e;return(null===(e=i.original.metadata)||void 0===e?void 0:e.proxy_server_request)?d(i.original.metadata.proxy_server_request):d(i.original.messages)},u=(null===(s=i.original.metadata)||void 0===s?void 0:s.status)==="failure",h=u?null===(l=i.original.metadata)||void 0===l?void 0:l.error_information:null,x=i.original.messages&&(Array.isArray(i.original.messages)?i.original.messages.length>0:Object.keys(i.original.messages).length>0),p=i.original.response&&Object.keys(d(i.original.response)).length>0,g=()=>u&&h?{error:{message:h.error_message||"An error occurred",type:h.error_class||"error",code:h.error_code||"unknown",param:null}}:d(i.original.response);return(0,c.jsxs)("div",{className:"p-6 bg-gray-50 space-y-6",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Details"})}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4 p-4",children:[(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Request ID:"}),(0,c.jsx)("span",{className:"font-mono text-sm",children:i.original.request_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model:"}),(0,c.jsx)("span",{children:i.original.model})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model ID:"}),(0,c.jsx)("span",{children:i.original.model_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Provider:"}),(0,c.jsx)("span",{children:i.original.custom_llm_provider||"-"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"API Base:"}),(0,c.jsx)(W.Z,{title:i.original.api_base||"-",children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:i.original.api_base||"-"})})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Start Time:"}),(0,c.jsx)("span",{children:i.original.startTime})]})]}),(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Tokens:"}),(0,c.jsxs)("span",{children:[i.original.total_tokens," (",i.original.prompt_tokens,"+",i.original.completion_tokens,")"]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cost:"}),(0,c.jsxs)("span",{children:["$",Number(i.original.spend||0).toFixed(6)]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cache Hit:"}),(0,c.jsx)("span",{children:i.original.cache_hit})]}),(null==i?void 0:null===(t=i.original)||void 0===t?void 0:t.requester_ip_address)&&(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"IP Address:"}),(0,c.jsx)("span",{children:null==i?void 0:null===(a=i.original)||void 0===a?void 0:a.requester_ip_address})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Status:"}),(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat("failure"!==((null===(r=i.original.metadata)||void 0===r?void 0:r.status)||"Success").toLowerCase()?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:"failure"!==((null===(n=i.original.metadata)||void 0===n?void 0:n.status)||"Success").toLowerCase()?"Success":"Failure"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"End Time:"}),(0,c.jsx)("span",{children:i.original.endTime})]})]})]})]}),(0,c.jsx)(tc,{show:!x&&!p}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request"}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(m(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy request",disabled:!x,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(m(),null,2)})})]}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsxs)("h3",{className:"text-lg font-medium",children:["Response",u&&(0,c.jsxs)("span",{className:"ml-2 text-sm text-red-600",children:["• HTTP code ",(null==h?void 0:h.error_code)||400]})]}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(g(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy response",disabled:!p,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96 bg-gray-50",children:p?(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(g(),null,2)}):(0,c.jsx)("div",{className:"text-gray-500 text-sm italic text-center py-4",children:"Response data not available"})})]})]}),u&&h&&(0,c.jsx)(to,{errorInfo:h}),i.original.request_tags&&Object.keys(i.original.request_tags).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"flex justify-between items-center p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Tags"})}),(0,c.jsx)("div",{className:"p-4",children:(0,c.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(i.original.request_tags).map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[s,": ",String(l)]},s)})})})]}),i.original.metadata&&Object.keys(i.original.metadata).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Metadata"}),(0,c.jsx)("button",{onClick:()=>{let e=o(i.original.metadata);navigator.clipboard.writeText(JSON.stringify(e,null,2))},className:"p-1 hover:bg-gray-200 rounded",title:"Copy metadata",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-64",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(o(i.original.metadata),null,2)})})]})]})}var tu=l(92699),th=l(14042);console.log=function(){};var tx=e=>{let{userID:s,userRole:l,accessToken:t,userSpend:a,userMaxBudget:r,selectedTeam:n}=e;console.log("userSpend: ".concat(a));let[i,o]=(0,d.useState)(null!==a?a:0),[m,u]=(0,d.useState)(n?n.max_budget:null);(0,d.useEffect)(()=>{if(n){if("Default Team"===n.team_alias)u(r);else{let e=!1;if(n.team_memberships)for(let l of n.team_memberships)l.user_id===s&&"max_budget"in l.litellm_budget_table&&null!==l.litellm_budget_table.max_budget&&(u(l.litellm_budget_table.max_budget),e=!0);e||u(n.max_budget)}}},[n,r]);let[h,x]=(0,d.useState)([]);(0,d.useEffect)(()=>{let e=async()=>{if(!t||!s||!l)return};(async()=>{try{if(null===s||null===l)return;if(null!==t){let e=(await (0,y.So)(t,s,l)).data.map(e=>e.id);console.log("available_model_names:",e),x(e)}}catch(e){console.error("Error fetching user models:",e)}})(),e()},[l,t,s]),(0,d.useEffect)(()=>{null!==a&&o(a)},[a]);let p=[];n&&n.models&&(p=n.models),p&&p.includes("all-proxy-models")?(console.log("user models:",h),p=h):p&&p.includes("all-team-models")?p=n.models:p&&0===p.length&&(p=h);let g=void 0!==i?i.toFixed(4):null;return console.log("spend in view user spend: ".concat(i)),(0,c.jsx)("div",{className:"flex items-center",children:(0,c.jsxs)("div",{className:"flex justify-between gap-x-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Total Spend"}),(0,c.jsxs)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:["$",g]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Max Budget"}),(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:null!==m?"$".concat(m," limit"):"No limit"})]})]})})};let tp=e=>{let{key:s,info:l}=e;return{token:s,...l}};var tg=e=>{let{topKeys:s,accessToken:l,userID:t,userRole:a,teams:r}=e,[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(void 0),[x,p]=(0,d.useState)("table"),g=async e=>{if(l)try{let s=await (0,y.t0)(l,e.api_key),t=tp(s);h(t),m(e.api_key),i(!0)}catch(e){console.error("Error fetching key info:",e)}},j=()=>{i(!1),m(null),h(void 0)};return d.useEffect(()=>{let e=e=>{"Escape"===e.key&&n&&j()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[n]),(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{className:"mb-4 flex justify-end items-center",children:(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>p("table"),className:"px-3 py-1 text-sm rounded-md ".concat("table"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Table View"}),(0,c.jsx)("button",{onClick:()=>p("chart"),className:"px-3 py-1 text-sm rounded-md ".concat("chart"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Chart View"})]})}),"chart"===x?(0,c.jsx)("div",{className:"relative",children:(0,c.jsx)(sw.Z,{className:"mt-4 h-40 cursor-pointer hover:opacity-90",data:s,index:"key_alias",categories:["spend"],colors:["cyan"],yAxisWidth:80,tickGap:5,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>e?"$".concat(e.toFixed(2)):"No Key Alias",onValueChange:e=>g(e),showTooltip:!0,customTooltip:e=>{var s,l,t;let a=null===(l=e.payload)||void 0===l?void 0:null===(s=l[0])||void 0===s?void 0:s.payload;return(0,c.jsx)("div",{className:"p-3 bg-black/90 shadow-lg rounded-lg text-white",children:(0,c.jsxs)("div",{className:"space-y-1.5",children:[(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Key: "}),(0,c.jsxs)("span",{className:"font-mono text-gray-100",children:[null==a?void 0:null===(t=a.api_key)||void 0===t?void 0:t.slice(0,10),"..."]})]}),(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Spend: "}),(0,c.jsxs)("span",{className:"text-white font-medium",children:["$",null==a?void 0:a.spend.toFixed(2)]})]})]})})}})}):(0,c.jsx)("div",{className:"border rounded-lg overflow-hidden",children:(0,c.jsx)(eL,{columns:[{header:"Key ID",accessorKey:"api_key",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>g(e.row.original),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>e.getValue()||"-"},{header:"Spend (USD)",accessorKey:"spend",cell:e=>"$".concat(Number(e.getValue()).toFixed(2))}],data:s,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{}),getRowCanExpand:()=>!1,isLoading:!1})}),n&&o&&u&&(console.log("Rendering modal with:",{isModalOpen:n,selectedKey:o,keyData:u}),(0,c.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e=>{e.target===e.currentTarget&&j()},children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-xl relative w-11/12 max-w-6xl max-h-[90vh] overflow-y-auto min-h-[750px]",children:[(0,c.jsx)("button",{onClick:j,className:"absolute top-4 right-4 text-gray-500 hover:text-gray-700 focus:outline-none","aria-label":"Close",children:(0,c.jsx)("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})}),(0,c.jsx)("div",{className:"p-6 h-full",children:(0,c.jsx)(eG,{keyId:o,onClose:j,keyData:u,accessToken:l,userID:t,userRole:a,teams:r})})]})}))]})},tj=l(44851);let tf=e=>{var s,l;let{modelName:t,metrics:a}=e;return(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:a.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:a.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:a.total_tokens.toLocaleString()}),(0,c.jsxs)(A.Z,{children:[Math.round(a.total_tokens/a.total_successful_requests)," avg per successful request"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",a.total_spend.toFixed(2)]}),(0,c.jsxs)(A.Z,{children:["$",(a.total_spend/a.total_successful_requests).toFixed(3)," per successful request"]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Requests per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.api_requests"],colors:["blue"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.spend"],colors:["green"],valueFormatter:e=>"$".concat(e.toFixed(2))})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Success vs Failed Requests"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Prompt Caching Metrics"}),(0,c.jsxs)("div",{className:"mb-2",children:[(0,c.jsxs)(A.Z,{children:["Cache Read: ",(null===(s=a.total_cache_read_input_tokens)||void 0===s?void 0:s.toLocaleString())||0," tokens"]}),(0,c.jsxs)(A.Z,{children:["Cache Creation: ",(null===(l=a.total_cache_creation_input_tokens)||void 0===l?void 0:l.toLocaleString())||0," tokens"]})]}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.cache_read_input_tokens","metrics.cache_creation_input_tokens"],colors:["cyan","purple"],valueFormatter:e=>e.toLocaleString()})]})]})]})},t_=e=>{let{modelMetrics:s}=e,l=Object.keys(s).sort((e,l)=>""===e?1:""===l?-1:s[l].total_spend-s[e].total_spend),t={total_requests:0,total_successful_requests:0,total_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:{}};Object.values(s).forEach(e=>{t.total_requests+=e.total_requests,t.total_successful_requests+=e.total_successful_requests,t.total_tokens+=e.total_tokens,t.total_spend+=e.total_spend,t.total_cache_read_input_tokens+=e.total_cache_read_input_tokens||0,t.total_cache_creation_input_tokens+=e.total_cache_creation_input_tokens||0,e.daily_data.forEach(e=>{t.daily_data[e.date]||(t.daily_data[e.date]={prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,spend:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),t.daily_data[e.date].prompt_tokens+=e.metrics.prompt_tokens,t.daily_data[e.date].completion_tokens+=e.metrics.completion_tokens,t.daily_data[e.date].total_tokens+=e.metrics.total_tokens,t.daily_data[e.date].api_requests+=e.metrics.api_requests,t.daily_data[e.date].spend+=e.metrics.spend,t.daily_data[e.date].successful_requests+=e.metrics.successful_requests,t.daily_data[e.date].failed_requests+=e.metrics.failed_requests,t.daily_data[e.date].cache_read_input_tokens+=e.metrics.cache_read_input_tokens||0,t.daily_data[e.date].cache_creation_input_tokens+=e.metrics.cache_creation_input_tokens||0})});let a=Object.entries(t.daily_data).map(e=>{let[s,l]=e;return{date:s,metrics:l}}).sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime());return(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{className:"border rounded-lg p-4",children:[(0,c.jsx)(E.Z,{children:"Overall Usage"}),(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4 mb-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:t.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:t.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:t.total_tokens.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",t.total_spend.toFixed(2)]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]})]})]}),(0,c.jsx)(tj.Z,{defaultActiveKey:l[0],children:l.map(e=>(0,c.jsx)(tj.Z.Panel,{header:(0,c.jsxs)("div",{className:"flex justify-between items-center w-full",children:[(0,c.jsx)(E.Z,{children:s[e].label||"Unknown Item"}),(0,c.jsxs)("div",{className:"flex space-x-4 text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["$",s[e].total_spend.toFixed(2)]}),(0,c.jsxs)("span",{children:[s[e].total_requests.toLocaleString()," requests"]})]})]}),children:(0,c.jsx)(tf,{modelName:e||"Unknown Model",metrics:s[e]})},e))})]})},ty=(e,s)=>{let l=e.metadata.key_alias||"key-hash-".concat(s),t=e.metadata.team_id;return t?"".concat(l," (team_id: ").concat(t,")"):l},tv=(e,s)=>{let l={};return e.results.forEach(e=>{Object.entries(e.breakdown[s]||{}).forEach(t=>{let[a,r]=t;l[a]||(l[a]={label:"api_keys"===s?ty(r,a):a,total_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0,prompt_tokens:0,completion_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:[]}),l[a].total_requests+=r.metrics.api_requests,l[a].prompt_tokens+=r.metrics.prompt_tokens,l[a].completion_tokens+=r.metrics.completion_tokens,l[a].total_tokens+=r.metrics.total_tokens,l[a].total_spend+=r.metrics.spend,l[a].total_successful_requests+=r.metrics.successful_requests,l[a].total_failed_requests+=r.metrics.failed_requests,l[a].total_cache_read_input_tokens+=r.metrics.cache_read_input_tokens||0,l[a].total_cache_creation_input_tokens+=r.metrics.cache_creation_input_tokens||0,l[a].daily_data.push({date:e.date,metrics:{prompt_tokens:r.metrics.prompt_tokens,completion_tokens:r.metrics.completion_tokens,total_tokens:r.metrics.total_tokens,api_requests:r.metrics.api_requests,spend:r.metrics.spend,successful_requests:r.metrics.successful_requests,failed_requests:r.metrics.failed_requests,cache_read_input_tokens:r.metrics.cache_read_input_tokens||0,cache_creation_input_tokens:r.metrics.cache_creation_input_tokens||0}})})}),Object.values(l).forEach(e=>{e.daily_data.sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime())}),l};var tb=e=>{let{accessToken:s,entityType:l,entityId:t,userID:a,userRole:r,entityList:n}=e,[i,o]=(0,d.useState)({results:[],metadata:{total_spend:0,total_api_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0}}),m=tv(i,"models"),u=tv(i,"api_keys"),[h,x]=(0,d.useState)([]),[p,g]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),j=async()=>{if(!s||!p.from||!p.to)return;let e=p.from,t=p.to;if("tag"===l)o(await (0,y.Z9)(s,e,t,1,h.length>0?h:null));else if("team"===l)o(await (0,y.ol)(s,e,t,1,h.length>0?h:null));else throw Error("Invalid entity type")};(0,d.useEffect)(()=>{j()},[s,p,t,h]);let f=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={provider:l,spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend,e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens}catch(e){console.log("Error processing provider ".concat(l,": ").concat(e))}})}),Object.values(e).filter(e=>e.spend>0).sort((e,s)=>s.spend-e.spend)},_=e=>0===h.length?e:e.filter(e=>h.includes(e.metadata.id)),v=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.entities||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{alias:t.metadata.team_alias||l,id:l}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.total_tokens+=t.metrics.total_tokens})}),_(Object.values(e).sort((e,s)=>s.metrics.spend-e.metrics.spend))};return(0,c.jsxs)("div",{style:{width:"100%"},children:[(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:p,onValueChange:g})]}),n&&n.length>0&&(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(A.Z,{children:["Filter by ","tag"===l?"Tags":"Teams"]}),(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},placeholder:"Select ".concat("tag"===l?"tags":"teams"," to filter..."),value:h,onChange:x,options:(()=>{if(n)return n})(),className:"mt-2",allowClear:!0})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["tag"===l?"Tag":"Team"," Spend Overview"]}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Spend"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",i.metadata.total_spend.toFixed(2)]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_api_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:i.metadata.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:i.metadata.total_failed_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_tokens.toLocaleString()})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...i.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:t}=e;if(!t||!(null==s?void 0:s[0]))return null;let a=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:a.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Total Spend: $",a.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",a.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",a.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",a.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Tokens: ",a.metrics.total_tokens]}),(0,c.jsxs)("div",{className:"mt-2 border-t pt-2",children:[(0,c.jsxs)("p",{className:"font-semibold",children:["Spend by ","tag"===l?"Tag":"Team",":"]}),Object.entries(a.breakdown.entities||{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[l.metadata.team_alias||s,": $",l.metrics.spend.toFixed(2)]},s)})]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-col space-y-2",children:[(0,c.jsxs)(E.Z,{children:["Spend Per ","tag"===l?"Tag":"Team"]}),(0,c.jsxs)("div",{className:"flex items-center text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["Get Started Tracking cost per ",l," "]}),(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tags",className:"text-blue-500 hover:text-blue-700 ml-1",children:"here"})]})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sw.Z,{className:"mt-4 h-52",data:v(),index:"metadata.alias",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(4)),layout:"vertical",showLegend:!1,yAxisWidth:100})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"tag"===l?"Tag":"Team"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:v().filter(e=>e.metrics.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.metadata.alias}),(0,c.jsxs)(eA.Z,{children:["$",e.metrics.spend.toFixed(4)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.metrics.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.metrics.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.metrics.total_tokens.toLocaleString()})]},e.metadata.id))})]})})]})]})})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:s,userID:a,userRole:r,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend}catch(e){console.log("Error adding spend for ".concat(l,": ").concat(e,", got metrics: ").concat(JSON.stringify(t)))}e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,...l}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsx)(E.Z,{children:"Provider Usage"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:f(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan","blue","indigo","violet","purple"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:f().map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:m})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:u})})]})]})]})},tZ=e=>{var s,l,t,a,r,n,i,o,m,u;let{accessToken:h,userRole:x,userID:p,teams:g}=e,[j,f]=(0,d.useState)({results:[],metadata:{}}),[_,v]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),[b,Z]=(0,d.useState)([]),k=async()=>{h&&Z(Object.values(await (0,y.UM)(h)).map(e=>({label:e.name,value:e.name})))};(0,d.useEffect)(()=>{k()},[h]);let S=(null===(s=j.metadata)||void 0===s?void 0:s.total_spend)||0,C=()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{provider:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}})},I=async()=>{if(!h||!_.from||!_.to)return;let e=_.from,s=_.to;try{let l=await (0,y.xX)(h,e,s);if(l.metadata.total_pages>10)throw Error("Too many pages of data (>10). Please select a smaller date range.");if(1===l.metadata.total_pages){f(l);return}let t=[...l.results];for(let a=2;a<=l.metadata.total_pages;a++){let l=await (0,y.xX)(h,e,s,a);t.push(...l.results)}f({results:t,metadata:l.metadata})}catch(e){throw console.error("Error fetching user spend data:",e),e}};(0,d.useEffect)(()=>{I()},[h,_]);let T=tv(j,"models"),P=tv(j,"api_keys");return(0,c.jsxs)("div",{style:{width:"100%"},className:"p-8",children:[(0,c.jsxs)(A.Z,{className:"text-sm text-gray-500 mb-4",children:["This is the new usage dashboard. ",(0,c.jsx)("br",{})," You may see empty data, as these use ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/blob/6de348125208dd4be81ff0e5813753df2fbe9735/schema.prisma#L320",className:"text-blue-500 hover:text-blue-700 ml-1",children:"new aggregate tables"})," to allow UI to work at 1M+ spend logs. To access the old dashboard, go to Experimental ",">"," Old Usage."]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Global Usage"}):(0,c.jsx)(eR.Z,{children:"Your Usage"}),(0,c.jsx)(eR.Z,{children:"Team Usage"}),eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Tag Usage"}):(0,c.jsx)(c.Fragment,{})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:_,onValueChange:e=>{v(e)}})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:p,userRole:x,accessToken:h,userSpend:S,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Usage Metrics"}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(t=j.metadata)||void 0===t?void 0:null===(l=t.total_api_requests)||void 0===l?void 0:l.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:(null===(r=j.metadata)||void 0===r?void 0:null===(a=r.total_successful_requests)||void 0===a?void 0:a.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:(null===(i=j.metadata)||void 0===i?void 0:null===(n=i.total_failed_requests)||void 0===n?void 0:n.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(m=j.metadata)||void 0===m?void 0:null===(o=m.total_tokens)||void 0===o?void 0:o.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Average Cost per Request"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",((S||0)/((null===(u=j.metadata)||void 0===u?void 0:u.total_api_requests)||1)).toFixed(4)]})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...j.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Requests: ",t.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",t.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",t.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.metrics.total_tokens]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:h,userID:p,userRole:x,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Top Models"})}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.key}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",t.requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-green-600",children:["Successful: ",t.successful_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-red-600",children:["Failed: ",t.failed_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.tokens.toLocaleString()]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Spend by Provider"})}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:C(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:C().filter(e=>e.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend<1e-5?"less than 0.00001":e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:T})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:P})})]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"team",userID:p,userRole:x,entityList:(null==g?void 0:g.map(e=>({label:e.team_alias,value:e.team_id})))||null})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"tag",userID:p,userRole:x,entityList:b})})]})]})]})},tN=e=>{let{proxySettings:s}=e,l="";return s&&s.PROXY_BASE_URL&&void 0!==s.PROXY_BASE_URL&&(l=s.PROXY_BASE_URL),(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(w.Z,{className:"gap-2 p-8 h-[80vh] w-full mt-2",children:(0,c.jsxs)("div",{className:"mb-5",children:[(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:"OpenAI Compatible Proxy: API Reference"}),(0,c.jsx)(A.Z,{className:"mt-2 mb-2",children:"LiteLLM is OpenAI Compatible. This means your API Key works with the OpenAI SDK. Just replace the base_url to point to your litellm proxy. Example Below "}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"OpenAI Python SDK"}),(0,c.jsx)(eR.Z,{children:"LlamaIndex"}),(0,c.jsx)(eR.Z,{children:"Langchain Py"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport openai\nclient = openai.OpenAI(\n api_key="your_api_key",\n base_url="'.concat(l,'" # LiteLLM Proxy is OpenAI compatible, Read More: https://docs.litellm.ai/docs/proxy/user_keys\n)\n\nresponse = client.chat.completions.create(\n model="gpt-3.5-turbo", # model to send to the proxy\n messages = [\n {\n "role": "user",\n "content": "this is a test request, write a short poem"\n }\n ]\n)\n\nprint(response)\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport os, dotenv\n\nfrom llama_index.llms import AzureOpenAI\nfrom llama_index.embeddings import AzureOpenAIEmbedding\nfrom llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext\n\nllm = AzureOpenAI(\n engine="azure-gpt-3.5", # model_name on litellm proxy\n temperature=0.0,\n azure_endpoint="'.concat(l,'", # litellm proxy endpoint\n api_key="sk-1234", # litellm proxy API Key\n api_version="2023-07-01-preview",\n)\n\nembed_model = AzureOpenAIEmbedding(\n deployment_name="azure-embedding-model",\n azure_endpoint="').concat(l,'",\n api_key="sk-1234",\n api_version="2023-07-01-preview",\n)\n\n\ndocuments = SimpleDirectoryReader("llama_index_data").load_data()\nservice_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context)\n\nquery_engine = index.as_query_engine()\nresponse = query_engine.query("What did the author do growing up?")\nprint(response)\n\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n)\nfrom langchain.schema import HumanMessage, SystemMessage\n\nchat = ChatOpenAI(\n openai_api_base="'.concat(l,'",\n model = "gpt-3.5-turbo",\n temperature=0.1\n)\n\nmessages = [\n SystemMessage(\n content="You are a helpful assistant that im using to make a test request to."\n ),\n HumanMessage(\n content="test from litellm. tell me why it\'s amazing in 1 sentence"\n ),\n]\nresponse = chat(messages)\n\nprint(response)\n\n ')})})]})]})]})})})},tw=l(243);async function tk(e,s,l,t,a,r,n,i,o){console.log=function(){},console.log("isLocal:",!1);let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t;let a=Date.now(),c=!1;for await(let _ of(await d.chat.completions.create({model:l,stream:!0,stream_options:{include_usage:!0},messages:e},{signal:r}))){var m,u,h,x,p,g,j,f;console.log("Stream chunk:",_);let e=null===(m=_.choices[0])||void 0===m?void 0:m.delta;if(console.log("Delta content:",null===(h=_.choices[0])||void 0===h?void 0:null===(u=h.delta)||void 0===u?void 0:u.content),console.log("Delta reasoning content:",null==e?void 0:e.reasoning_content),!c&&((null===(p=_.choices[0])||void 0===p?void 0:null===(x=p.delta)||void 0===x?void 0:x.content)||e&&e.reasoning_content)&&(c=!0,t=Date.now()-a,console.log("First token received! Time:",t,"ms"),i?(console.log("Calling onTimingData with:",t),i(t)):console.log("onTimingData callback is not defined!")),null===(j=_.choices[0])||void 0===j?void 0:null===(g=j.delta)||void 0===g?void 0:g.content){let e=_.choices[0].delta.content;s(e,_.model)}if(e&&e.reasoning_content){let s=e.reasoning_content;n&&n(s)}if(_.usage&&o){console.log("Usage data found:",_.usage);let e={completionTokens:_.usage.completion_tokens,promptTokens:_.usage.prompt_tokens,totalTokens:_.usage.total_tokens};(null===(f=_.usage.completion_tokens_details)||void 0===f?void 0:f.reasoning_tokens)&&(e.reasoningTokens=_.usage.completion_tokens_details.reasoning_tokens),o(e)}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Chat completion request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}async function tS(e,s,l,t,a,r){console.log=function(){},console.log("isLocal:",!1);let n=window.location.origin,i=new lG.ZP.OpenAI({apiKey:t,baseURL:n,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=await i.images.generate({model:l,prompt:e},{signal:r});if(console.log(t.data),t.data&&t.data[0]){if(t.data[0].url)s(t.data[0].url,l);else if(t.data[0].b64_json){let e=t.data[0].b64_json;s("data:image/png;base64,".concat(e),l)}else throw Error("No image data found in response")}else throw Error("Invalid response format")}catch(e){throw(null==r?void 0:r.aborted)?console.log("Image generation request was cancelled"):D.ZP.error("Error occurred while generating image. Please try again. Error: ".concat(e),20),e}}async function tC(e,s,l,t){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],r=arguments.length>5?arguments[5]:void 0,n=arguments.length>6?arguments[6]:void 0,i=arguments.length>7?arguments[7]:void 0,o=arguments.length>8?arguments[8]:void 0;if(!t)throw Error("API key is required");console.log=function(){};let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=Date.now(),a=!1,c=e.map(e=>({role:e.role,content:e.content,type:"message"}));for await(let e of(await d.responses.create({model:l,input:c,stream:!0},{signal:r})))if(console.log("Response event:",e),"object"==typeof e&&null!==e){if("response.role.delta"===e.type)continue;if("response.output_text.delta"===e.type&&"string"==typeof e.delta){let r=e.delta;if(console.log("Text delta",r),r.trim().length>0&&(s("assistant",r,l),!a)){a=!0;let e=Date.now()-t;console.log("First token received! Time:",e,"ms"),i&&i(e)}}if("response.reasoning.delta"===e.type&&"delta"in e){let s=e.delta;"string"==typeof s&&n&&n(s)}if("response.completed"===e.type&&"response"in e){let s=e.response.usage;if(console.log("Usage data:",s),s&&o){var m;console.log("Usage data:",s);let e={completionTokens:s.output_tokens,promptTokens:s.input_tokens,totalTokens:s.total_tokens};(null===(m=s.completion_tokens_details)||void 0===m?void 0:m.reasoning_tokens)&&(e.reasoningTokens=s.completion_tokens_details.reasoning_tokens),o(e)}}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Responses API request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}let tI=async e=>{try{let s=await (0,y.kn)(e);if(console.log("model_info:",s),(null==s?void 0:s.data.length)>0){let e=s.data.map(e=>({model_group:e.model_group,mode:null==e?void 0:e.mode}));return e.sort((e,s)=>e.model_group.localeCompare(s.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};(a=i||(i={})).IMAGE_GENERATION="image_generation",a.CHAT="chat",a.RESPONSES="responses",(r=o||(o={})).IMAGE="image",r.CHAT="chat",r.RESPONSES="responses";let tT={image_generation:"image",chat:"chat",responses:"responses"},tA=e=>{if(console.log("getEndpointType:",e),Object.values(i).includes(e)){let s=tT[e];return console.log("endpointType:",s),s}return"chat"};var tE=l(94263),tP=e=>{let{endpointType:s,onEndpointChange:l,className:t}=e,a=[{value:o.CHAT,label:"/v1/chat/completions"},{value:o.RESPONSES,label:"/v1/responses"},{value:o.IMAGE,label:"/v1/images/generations"}];return(0,c.jsxs)("div",{className:t,children:[(0,c.jsx)(A.Z,{children:"Endpoint Type:"}),(0,c.jsx)(O.default,{value:s,style:{width:"100%"},onChange:l,options:a,className:"rounded-md"})]})},tO=e=>{let{onChange:s,value:l,className:t,accessToken:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)(!1);return(0,d.useEffect)(()=>{(async()=>{if(a)try{let e=await (0,y.UM)(a);console.log("List tags response:",e),n(Object.values(e))}catch(e){console.error("Error fetching tags:",e)}})()},[]),(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select tags",onChange:s,value:l,loading:i,className:t,options:r.map(e=>({label:e.name,value:e.name,title:e.description||e.name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})};let tL=(e,s)=>{let l=s.find(s=>s.model_group===e);return(null==l?void 0:l.mode)?tA(l.mode):o.CHAT};var tD=l(83322),tM=l(70464),tF=l(77565),tR=e=>{let{reasoningContent:s}=e,[l,t]=(0,d.useState)(!0);return s?(0,c.jsxs)("div",{className:"reasoning-content mt-1 mb-2",children:[(0,c.jsxs)(R.ZP,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>t(!l),icon:(0,c.jsx)(tD.Z,{}),children:[l?"Hide reasoning":"Show reasoning",l?(0,c.jsx)(tM.Z,{className:"ml-1"}):(0,c.jsx)(tF.Z,{className:"ml-1"})]}),l&&(0,c.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700",children:(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),...r,children:a})}},children:s})})]}):null},tq=l(5540),tU=l(71282),tz=l(11741),tV=l(16601),tK=e=>{let{timeToFirstToken:s,usage:l}=e;return s||l?(0,c.jsxs)("div",{className:"response-metrics mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500 flex flex-wrap gap-3",children:[void 0!==s&&(0,c.jsx)(W.Z,{title:"Time to first token",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tq.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:[(s/1e3).toFixed(2),"s"]})]})}),(null==l?void 0:l.promptTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Prompt tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tU.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["In: ",l.promptTokens]})]})}),(null==l?void 0:l.completionTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Completion tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tz.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Out: ",l.completionTokens]})]})}),(null==l?void 0:l.reasoningTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Reasoning tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tD.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Reasoning: ",l.reasoningTokens]})]})}),(null==l?void 0:l.totalTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Total tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tV.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Total: ",l.totalTokens]})]})})]}):null},tB=l(61935),tH=l(69993),tJ=l(12660),tW=l(71891),tG=l(26430),tY=l(26349),t$=l(23907);let{TextArea:tX}=q.default;var tQ=e=>{let{accessToken:s,token:l,userRole:t,userID:a,disabledPersonalKeyCreation:r}=e,[n,i]=(0,d.useState)(r?"custom":"session"),[m,u]=(0,d.useState)(""),[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)([]),[f,_]=(0,d.useState)(void 0),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)([]),N=(0,d.useRef)(null),[w,C]=(0,d.useState)(o.CHAT),[I,T]=(0,d.useState)(!1),E=(0,d.useRef)(null),[P,L]=(0,d.useState)([]),M=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e="session"===n?s:m;if(!e||!l||!t||!a){console.log("userApiKey or token or userRole or userID is missing = ",e,l,t,a);return}(async()=>{try{if(!e){console.log("userApiKey is missing");return}let s=await tI(e);if(console.log("Fetched models:",s),s.length>0&&(Z(s),_(s[0].model_group),s[0].mode)){let e=tL(s[0].model_group,s);C(e)}}catch(e){console.error("Error fetching model info:",e)}})()},[s,a,t,n,m]),(0,d.useEffect)(()=>{M.current&&setTimeout(()=>{var e;null===(e=M.current)||void 0===e||e.scrollIntoView({behavior:"smooth",block:"end"})},100)},[p]);let F=(e,s,l)=>{console.log("updateTextUI called with:",e,s,l),g(t=>{let a=t[t.length-1];if(!a||a.role!==e||a.isImage)return[...t,{role:e,content:s,model:l}];{var r;let e={...a,content:a.content+s,model:null!==(r=a.model)&&void 0!==r?r:l};return[...t.slice(0,-1),e]}})},R=e=>{g(s=>{let l=s[s.length-1];return l&&"assistant"===l.role&&!l.isImage?[...s.slice(0,s.length-1),{...l,reasoningContent:(l.reasoningContent||"")+e}]:s.length>0&&"user"===s[s.length-1].role?[...s,{role:"assistant",content:"",reasoningContent:e}]:s})},q=e=>{console.log("updateTimingData called with:",e),g(s=>{let l=s[s.length-1];if(console.log("Current last message:",l),l&&"assistant"===l.role){console.log("Updating assistant message with timeToFirstToken:",e);let t=[...s.slice(0,s.length-1),{...l,timeToFirstToken:e}];return console.log("Updated chat history:",t),t}return l&&"user"===l.role?(console.log("Creating new assistant message with timeToFirstToken:",e),[...s,{role:"assistant",content:"",timeToFirstToken:e}]):(console.log("No appropriate message found to update timing"),s)})},U=e=>{console.log("Received usage data:",e),g(s=>{let l=s[s.length-1];if(l&&"assistant"===l.role){console.log("Updating message with usage data:",e);let t={...l,usage:e};return console.log("Updated message:",t),[...s.slice(0,s.length-1),t]}return s})},z=(e,s)=>{g(l=>[...l,{role:"assistant",content:e,model:s,isImage:!0}])},V=async()=>{if(""===h.trim()||!l||!t||!a)return;let e="session"===n?s:m;if(!e){D.ZP.error("Please provide an API key or select Current UI Session");return}E.current=new AbortController;let r=E.current.signal,i={role:"user",content:h};g([...p,i]),T(!0);try{if(f){if(w===o.CHAT){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tk(s,(e,s)=>F("assistant",e,s),f,e,P,r,R,q,U)}else if(w===o.IMAGE)await tS(h,(e,s)=>z(e,s),f,e,P,r);else if(w===o.RESPONSES){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tC(s,(e,s,l)=>F(e,s,l),f,e,P,r,R,q,U)}}}catch(e){r.aborted?console.log("Request was cancelled"):(console.error("Error fetching response",e),F("assistant","Error fetching response"))}finally{T(!1),E.current=null}x("")};if(t&&"Admin Viewer"===t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to test models"})]})}let K=(0,c.jsx)(tB.Z,{style:{fontSize:24},spin:!0});return(0,c.jsx)("div",{className:"w-full h-screen p-4 bg-white",children:(0,c.jsx)(eF.Z,{className:"w-full rounded-xl shadow-md overflow-hidden",children:(0,c.jsxs)("div",{className:"flex h-[80vh] w-full",children:[(0,c.jsx)("div",{className:"w-1/4 p-4 border-r border-gray-200 bg-gray-50",children:(0,c.jsx)("div",{className:"mb-6",children:(0,c.jsxs)("div",{className:"space-y-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(lE.Z,{className:"mr-2"})," API Key Source"]}),(0,c.jsx)(O.default,{disabled:r,defaultValue:"session",style:{width:"100%"},onChange:e=>i(e),options:[{value:"session",label:"Current UI Session"},{value:"custom",label:"Virtual Key"}],className:"rounded-md"}),"custom"===n&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom API key",type:"password",onValueChange:u,value:m,icon:lE.Z})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tH.Z,{className:"mr-2"})," Select Model"]}),(0,c.jsx)(O.default,{placeholder:"Select a Model",onChange:e=>{console.log("selected ".concat(e)),_(e),"custom"!==e&&C(tL(e,b)),v("custom"===e)},options:[...b.map(e=>({value:e.model_group,label:e.model_group})),{value:"custom",label:"Enter custom model"}],style:{width:"100%"},showSearch:!0,className:"rounded-md"}),y&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{_(e)},500)}})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tJ.Z,{className:"mr-2"})," Endpoint Type"]}),(0,c.jsx)(tP,{endpointType:w,onEndpointChange:e=>{C(e)},className:"mb-4"})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tW.Z,{className:"mr-2"})," Tags"]}),(0,c.jsx)(tO,{value:P,onChange:L,className:"mb-4",accessToken:s||""})]}),(0,c.jsx)(k.Z,{onClick:()=>{g([]),D.ZP.success("Chat history cleared.")},className:"w-full bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300 mt-4",icon:tG.Z,children:"Clear Chat"})]})})}),(0,c.jsxs)("div",{className:"w-3/4 flex flex-col bg-white",children:[(0,c.jsxs)("div",{className:"flex-1 overflow-auto p-4 pb-0",children:[0===p.length&&(0,c.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[(0,c.jsx)(tH.Z,{style:{fontSize:"48px",marginBottom:"16px"}}),(0,c.jsx)(A.Z,{children:"Start a conversation or generate an image"})]}),p.map((e,s)=>(0,c.jsx)("div",{className:"mb-4 ".concat("user"===e.role?"text-right":"text-left"),children:(0,c.jsxs)("div",{className:"inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4",style:{backgroundColor:"user"===e.role?"#f0f8ff":"#ffffff",border:"user"===e.role?"1px solid #e6f0fa":"1px solid #f0f0f0",textAlign:"left"},children:[(0,c.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full mr-1",style:{backgroundColor:"user"===e.role?"#e6f0fa":"#f5f5f5"},children:"user"===e.role?(0,c.jsx)(j.Z,{style:{fontSize:"12px",color:"#2563eb"}}):(0,c.jsx)(tH.Z,{style:{fontSize:"12px",color:"#4b5563"}})}),(0,c.jsx)("strong",{className:"text-sm capitalize",children:e.role}),"assistant"===e.role&&e.model&&(0,c.jsx)("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-normal",children:e.model})]}),e.reasoningContent&&(0,c.jsx)(tR,{reasoningContent:e.reasoningContent}),(0,c.jsxs)("div",{className:"whitespace-pre-wrap break-words max-w-full message-content",style:{wordWrap:"break-word",overflowWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},children:[e.isImage?(0,c.jsx)("img",{src:e.content,alt:"Generated image",className:"max-w-full rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"500px"}}):(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",wrapLines:!0,wrapLongLines:!0,...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),style:{wordBreak:"break-word"},...r,children:a})},pre:e=>{let{node:s,...l}=e;return(0,c.jsx)("pre",{style:{overflowX:"auto",maxWidth:"100%"},...l})}},children:e.content}),"assistant"===e.role&&(e.timeToFirstToken||e.usage)&&(0,c.jsx)(tK,{timeToFirstToken:e.timeToFirstToken,usage:e.usage})]})]})},s)),I&&(0,c.jsx)("div",{className:"flex justify-center items-center my-4",children:(0,c.jsx)(eY.Z,{indicator:K})}),(0,c.jsx)("div",{ref:M,style:{height:"1px"}})]}),(0,c.jsx)("div",{className:"p-4 border-t border-gray-200 bg-white",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tX,{value:h,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),V())},placeholder:w===o.CHAT||w===o.RESPONSES?"Type your message... (Shift+Enter for new line)":"Describe the image you want to generate...",disabled:I,className:"flex-1",autoSize:{minRows:1,maxRows:6},style:{resize:"none",paddingRight:"10px",paddingLeft:"10px"}}),I?(0,c.jsx)(k.Z,{onClick:()=>{E.current&&(E.current.abort(),E.current=null,T(!1),D.ZP.info("Request cancelled"))},className:"ml-2 bg-red-50 hover:bg-red-100 text-red-600 border-red-200",icon:tY.Z,children:"Cancel"}):(0,c.jsx)(k.Z,{onClick:V,className:"ml-2 text-white",icon:w===o.CHAT?t$.Z:tH.Z,children:w===o.CHAT?"Send":"Generate"})]})})]})]})})})},t0=l(19226),t1=l(45937),t2=l(28595),t4=l(68208),t5=l(9775),t3=l(41361),t6=l(37527),t8=l(88009),t7=l(48231),t9=l(41169),ae=l(44625),as=l(57400),al=l(58630),at=l(55322);let{Sider:aa}=t0.default;var ar=e=>{let{setPage:s,userRole:l,defaultSelectedKey:t}=e,a=[{key:"1",page:"api-keys",label:"Virtual Keys",icon:(0,c.jsx)(lE.Z,{})},{key:"3",page:"llm-playground",label:"Test Key",icon:(0,c.jsx)(t2.Z,{}),roles:eg.LQ},{key:"2",page:"models",label:"Models",icon:(0,c.jsx)(t4.Z,{}),roles:eg.LQ},{key:"12",page:"new_usage",label:"Usage",icon:(0,c.jsx)(t5.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"6",page:"teams",label:"Teams",icon:(0,c.jsx)(t3.Z,{})},{key:"17",page:"organizations",label:"Organizations",icon:(0,c.jsx)(t6.Z,{}),roles:eg.ZL},{key:"5",page:"users",label:"Internal Users",icon:(0,c.jsx)(j.Z,{}),roles:eg.ZL},{key:"14",page:"api_ref",label:"API Reference",icon:(0,c.jsx)(tJ.Z,{})},{key:"16",page:"model-hub",label:"Model Hub",icon:(0,c.jsx)(t8.Z,{})},{key:"15",page:"logs",label:"Logs",icon:(0,c.jsx)(t7.Z,{})},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,c.jsx)(t9.Z,{}),children:[{key:"9",page:"caching",label:"Caching",icon:(0,c.jsx)(ae.Z,{}),roles:eg.ZL},{key:"10",page:"budgets",label:"Budgets",icon:(0,c.jsx)(t6.Z,{}),roles:eg.ZL},{key:"11",page:"guardrails",label:"Guardrails",icon:(0,c.jsx)(as.Z,{}),roles:eg.ZL},{key:"4",page:"usage",label:"Old Usage",icon:(0,c.jsx)(t5.Z,{})},{key:"20",page:"transform-request",label:"API Playground",icon:(0,c.jsx)(tJ.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"18",page:"mcp-tools",label:"MCP Tools",icon:(0,c.jsx)(al.Z,{}),roles:eg.ZL},{key:"19",page:"tag-management",label:"Tag Management",icon:(0,c.jsx)(tW.Z,{}),roles:eg.ZL}]},{key:"settings",page:"settings",label:"Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL,children:[{key:"11",page:"general-settings",label:"Router Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"12",page:"pass-through-settings",label:"Pass-Through",icon:(0,c.jsx)(tJ.Z,{}),roles:eg.ZL},{key:"8",page:"settings",label:"Logging & Alerts",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"13",page:"admin-panel",label:"Admin Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL}]}],r=(e=>{let s=a.find(s=>s.page===e);if(s)return s.key;for(let s of a)if(s.children){let l=s.children.find(s=>s.page===e);if(l)return l.key}return"1"})(t),n=a.filter(e=>!!(!e.roles||e.roles.includes(l))&&(e.children&&(e.children=e.children.filter(e=>!e.roles||e.roles.includes(l))),!0));return(0,c.jsx)(t0.default,{style:{minHeight:"100vh"},children:(0,c.jsx)(aa,{theme:"light",width:220,children:(0,c.jsx)(t1.Z,{mode:"inline",selectedKeys:[r],style:{borderRight:0,backgroundColor:"transparent",fontSize:"14px"},items:n.map(e=>{var l;return{key:e.key,icon:e.icon,label:e.label,children:null===(l=e.children)||void 0===l?void 0:l.map(e=>({key:e.key,icon:e.icon,label:e.label,onClick:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}})),onClick:e.children?void 0:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}}})})})})},an=l(96889);console.log("process.env.NODE_ENV","production"),console.log=function(){};let ai=e=>null!==e&&("Admin"===e||"Admin Viewer"===e);var ao=e=>{let{accessToken:s,token:l,userRole:t,userID:a,keys:r,premiumUser:n}=e,i=new Date,[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)([]),[v,b]=(0,d.useState)([]),[Z,S]=(0,d.useState)([]),[C,I]=(0,d.useState)([]),[T,P]=(0,d.useState)([]),[O,L]=(0,d.useState)([]),[D,M]=(0,d.useState)({}),[F,R]=(0,d.useState)([]),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(["all-tags"]),[K,B]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(0),Y=new Date(i.getFullYear(),i.getMonth(),1),$=new Date(i.getFullYear(),i.getMonth()+1,0),X=er(Y),Q=er($);function es(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}console.log("keys in usage",r),console.log("premium user in usage",n);let el=async()=>{if(s)try{let e=await (0,y.g)(s);return console.log("usage tab: proxy_settings",e),e}catch(e){console.error("Error fetching proxy settings:",e)}};(0,d.useEffect)(()=>{ea(K.from,K.to)},[K,z]);let et=async(e,l,t)=>{if(!e||!l||!s)return;l.setHours(23,59,59,999),e.setHours(0,0,0,0),console.log("uiSelectedKey",t);let a=await (0,y.b1)(s,t,e.toISOString(),l.toISOString());console.log("End user data updated successfully",a),j(a)},ea=async(e,l)=>{if(!e||!l||!s)return;let t=await el();null!=t&&t.DISABLE_EXPENSIVE_DB_QUERIES||(l.setHours(23,59,59,999),e.setHours(0,0,0,0),b((await (0,y.J$)(s,e.toISOString(),l.toISOString(),0===z.length?void 0:z)).spend_per_tag),console.log("Tag spend data updated successfully"))};function er(e){let s=e.getFullYear(),l=e.getMonth()+1,t=e.getDate();return"".concat(s,"-").concat(l<10?"0"+l:l,"-").concat(t<10?"0"+t:t)}console.log("Start date is ".concat(X)),console.log("End date is ".concat(Q));let en=async(e,s,l)=>{try{let l=await e();s(l)}catch(e){console.error(l,e)}},ei=(e,s,l,t)=>{let a=[],r=new Date(s),n=e=>{if(e.includes("-"))return e;{let[s,l]=e.split(" ");return new Date(new Date().getFullYear(),new Date("".concat(s," 01 2024")).getMonth(),parseInt(l)).toISOString().split("T")[0]}},i=new Map(e.map(e=>{let s=n(e.date);return[s,{...e,date:s}]}));for(;r<=l;){let e=r.toISOString().split("T")[0];if(i.has(e))a.push(i.get(e));else{let s={date:e,api_requests:0,total_tokens:0};t.forEach(e=>{s[e]||(s[e]=0)}),a.push(s)}r.setDate(r.getDate()+1)}return a},eo=async()=>{if(s)try{let e=await (0,y.FC)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e,t,a,[]),n=Number(r.reduce((e,s)=>e+(s.spend||0),0).toFixed(2));G(n),m(r)}catch(e){console.error("Error fetching overall spend:",e)}},ec=()=>en(()=>s&&l?(0,y.OU)(s,l,X,Q):Promise.reject("No access token or token"),L,"Error fetching provider spend"),ed=async()=>{s&&await en(async()=>(await (0,y.tN)(s)).map(e=>({key:e.api_key.substring(0,10),api_key:e.api_key,key_alias:e.key_alias,spend:Number(e.total_spend.toFixed(2))})),h,"Error fetching top keys")},em=async()=>{s&&await en(async()=>(await (0,y.Au)(s)).map(e=>({key:e.model,spend:Number(e.total_spend.toFixed(2))})),p,"Error fetching top models")},eu=async()=>{s&&await en(async()=>{let e=await (0,y.mR)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0);return _(ei(e.daily_spend,t,a,e.teams)),I(e.teams),e.total_spend_per_team.map(e=>({name:e.team_id||"",value:Number(e.total_spend||0).toFixed(2)}))},P,"Error fetching team spend")},eh=()=>{s&&en(async()=>(await (0,y.X)(s)).tag_names,S,"Error fetching tag names")},ex=()=>{s&&en(()=>{var e,l;return(0,y.J$)(s,null===(e=K.from)||void 0===e?void 0:e.toISOString(),null===(l=K.to)||void 0===l?void 0:l.toISOString(),void 0)},e=>b(e.spend_per_tag),"Error fetching top tags")},ep=()=>{s&&en(()=>(0,y.b1)(s,null,void 0,void 0),j,"Error fetching top end users")},eg=async()=>{if(s)try{let e=await (0,y.wd)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e.daily_data||[],t,a,["api_requests","total_tokens"]);M({...e,daily_data:r})}catch(e){console.error("Error fetching global activity:",e)}},ej=async()=>{if(s)try{let e=await (0,y.xA)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=e.map(e=>({...e,daily_data:ei(e.daily_data||[],t,a,["api_requests","total_tokens"])}));R(r)}catch(e){console.error("Error fetching global activity per model:",e)}};return((0,d.useEffect)(()=>{(async()=>{if(s&&l&&t&&a){let e=await el();e&&(J(e),null!=e&&e.DISABLE_EXPENSIVE_DB_QUERIES)||(console.log("fetching data - valiue of proxySettings",H),eo(),ec(),ed(),em(),eg(),ej(),ai(t)&&(eu(),eh(),ex(),ep()))}})()},[s,l,t,a,X,Q]),null==H?void 0:H.DISABLE_EXPENSIVE_DB_QUERIES)?(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Database Query Limit Reached"}),(0,c.jsxs)(A.Z,{className:"mt-4",children:["SpendLogs in DB has ",H.NUM_SPEND_LOGS_ROWS," rows.",(0,c.jsx)("br",{}),"Please follow our guide to view usage when SpendLogs has more than 1M rows."]}),(0,c.jsx)(k.Z,{className:"mt-4",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/spending_monitoring",target:"_blank",children:"View Usage Guide"})})]})}):(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mt-2",children:[(0,c.jsx)(eR.Z,{children:"All Up"}),ai(t)?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(eR.Z,{children:"Team Based Usage"}),(0,c.jsx)(eR.Z,{children:"Customer Usage"}),(0,c.jsx)(eR.Z,{children:"Tag Based Usage"})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsx)("div",{})})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[100vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:a,userRole:t,accessToken:s,userSpend:W,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Monthly Spend"}),(0,c.jsx)(sw.Z,{data:o,index:"date",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$ ".concat(e.toFixed(2)),yAxisWidth:100,tickGap:5})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:u,accessToken:s,userID:a,userRole:t,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:x,index:"key",categories:["spend"],colors:["cyan"],yAxisWidth:200,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>"$".concat(e.toFixed(2))})]})}),(0,c.jsx)(N.Z,{numColSpan:1}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Spend by Provider"}),(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",variant:"pie",data:O,index:"provider",category:"spend",colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2))})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"})]})}),(0,c.jsx)(eT.Z,{children:O.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsx)(eA.Z,{children:1e-5>parseFloat(e.spend.toFixed(2))?"less than 0.00":e.spend.toFixed(2)})]},e.provider))})]})})]})})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"All Up"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(D.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["api_requests"],onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(D.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["total_tokens"],onValueChange:e=>console.log(e)})]})]})]}),(0,c.jsx)(c.Fragment,{children:F.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.model}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(e.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["api_requests"],valueFormatter:es,onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(e.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["total_tokens"],valueFormatter:es,onValueChange:e=>console.log(e)})]})]})]},s))})]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Total Spend Per Team"}),(0,c.jsx)(an.Z,{data:T})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend Per Team"}),(0,c.jsx)(sw.Z,{className:"h-72",data:f,showLegend:!0,index:"date",categories:C,yAxisWidth:80,stack:!0})]})]}),(0,c.jsx)(N.Z,{numColSpan:2})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:["Customers of your LLM API calls. Tracked when a `user` param is passed in your LLM calls ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/users",target:"_blank",children:"docs here"})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:K,onValueChange:e=>{B(e),et(e.from,e.to,null)}})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Key"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{et(K.from,K.to,null)},children:"All Keys"},"all-keys"),null==r?void 0:r.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{et(K.from,K.to,e.token)},children:e.key_alias},s):null)]})]})]}),(0,c.jsx)(eF.Z,{className:"mt-4",children:(0,c.jsxs)(eI.Z,{className:"max-h-[70vh] min-h-[500px]",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Customer"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Total Events"})]})}),(0,c.jsx)(eT.Z,{children:null==g?void 0:g.map((e,s)=>{var l;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.end_user}),(0,c.jsx)(eA.Z,{children:null===(l=e.total_spend)||void 0===l?void 0:l.toFixed(4)}),(0,c.jsx)(eA.Z,{children:e.total_count})]},s)})})]})})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sb.Z,{className:"mb-4",enableSelect:!0,value:K,onValueChange:e=>{B(e),ea(e.from,e.to)}})}),(0,c.jsx)(N.Z,{children:n?(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsx)(lH.Z,{value:String(e),children:e},e))]})}):(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsxs)(ee.Z,{value:String(e),disabled:!0,children:["✨ ",e," (Enterprise only Feature)"]},e))]})})})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full mb-4",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend Per Tag"}),(0,c.jsxs)(A.Z,{children:["Get Started Tracking cost per tag ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/cost_tracking",target:"_blank",children:"here"})]}),(0,c.jsx)(sw.Z,{className:"h-72",data:v,index:"name",categories:["spend"],colors:["cyan"]})]})}),(0,c.jsx)(N.Z,{numColSpan:2})]})]})]})]})})},ac=l(51853);let ad=e=>{let{responseTimeMs:s}=e;return null==s?null:(0,c.jsxs)("div",{className:"flex items-center space-x-1 text-xs text-gray-500 font-mono",children:[(0,c.jsx)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{d:"M12 6V12L16 14M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,c.jsxs)("span",{children:[s.toFixed(0),"ms"]})]})},am=e=>{let s=e;if("string"==typeof s)try{s=JSON.parse(s)}catch(e){}return s},au=e=>{let{label:s,value:l}=e,[t,a]=d.useState(!1),[r,n]=d.useState(!1),i=(null==l?void 0:l.toString())||"N/A",o=i.length>50?i.substring(0,50)+"...":i;return(0,c.jsx)("tr",{className:"hover:bg-gray-50",children:(0,c.jsx)("td",{className:"px-4 py-2 align-top",colSpan:2,children:(0,c.jsxs)("div",{className:"flex items-center justify-between group",children:[(0,c.jsxs)("div",{className:"flex items-center flex-1",children:[(0,c.jsx)("button",{onClick:()=>a(!t),className:"text-gray-400 hover:text-gray-600 mr-2",children:t?"▼":"▶"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("div",{className:"text-sm text-gray-600",children:s}),(0,c.jsx)("pre",{className:"mt-1 text-sm font-mono text-gray-800 whitespace-pre-wrap",children:t?i:o})]})]}),(0,c.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(i),n(!0),setTimeout(()=>n(!1),2e3)},className:"opacity-0 group-hover:opacity-100 text-gray-400 hover:text-gray-600",children:(0,c.jsx)(ac.Z,{className:"h-4 w-4"})})]})})})},ah=e=>{var s,l,t,a,r,n,i,o,d,m,u,h,x,p;let{response:g}=e,j=null,f={},_={};try{if(null==g?void 0:g.error)try{let e="string"==typeof g.error.message?JSON.parse(g.error.message):g.error.message;j={message:(null==e?void 0:e.message)||"Unknown error",traceback:(null==e?void 0:e.traceback)||"No traceback available",litellm_params:(null==e?void 0:e.litellm_cache_params)||{},health_check_cache_params:(null==e?void 0:e.health_check_cache_params)||{}},f=am(j.litellm_params)||{},_=am(j.health_check_cache_params)||{}}catch(e){console.warn("Error parsing error details:",e),j={message:String(g.error.message||"Unknown error"),traceback:"Error parsing details",litellm_params:{},health_check_cache_params:{}}}else f=am(null==g?void 0:g.litellm_cache_params)||{},_=am(null==g?void 0:g.health_check_cache_params)||{}}catch(e){console.warn("Error in response parsing:",e),f={},_={}}let y={redis_host:(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host)||(null==_?void 0:null===(i=_.connection_kwargs)||void 0===i?void 0:i.host)||(null==_?void 0:_.host)||"N/A",redis_port:(null==_?void 0:null===(m=_.redis_client)||void 0===m?void 0:null===(d=m.connection_pool)||void 0===d?void 0:null===(o=d.connection_kwargs)||void 0===o?void 0:o.port)||(null==_?void 0:null===(x=_.redis_async_client)||void 0===x?void 0:null===(h=x.connection_pool)||void 0===h?void 0:null===(u=h.connection_kwargs)||void 0===u?void 0:u.port)||(null==_?void 0:null===(p=_.connection_kwargs)||void 0===p?void 0:p.port)||(null==_?void 0:_.port)||"N/A",redis_version:(null==_?void 0:_.redis_version)||"N/A",startup_nodes:(()=>{try{var e,s,l,t,a,r,n,i,o,c,d,m,u;if(null==_?void 0:null===(e=_.redis_kwargs)||void 0===e?void 0:e.startup_nodes)return JSON.stringify(_.redis_kwargs.startup_nodes);let h=(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host),x=(null==_?void 0:null===(c=_.redis_client)||void 0===c?void 0:null===(o=c.connection_pool)||void 0===o?void 0:null===(i=o.connection_kwargs)||void 0===i?void 0:i.port)||(null==_?void 0:null===(u=_.redis_async_client)||void 0===u?void 0:null===(m=u.connection_pool)||void 0===m?void 0:null===(d=m.connection_kwargs)||void 0===d?void 0:d.port);return h&&x?JSON.stringify([{host:h,port:x}]):"N/A"}catch(e){return"N/A"}})(),namespace:(null==_?void 0:_.namespace)||"N/A"};return(0,c.jsx)("div",{className:"bg-white rounded-lg shadow",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"border-b border-gray-200 px-4",children:[(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Summary"}),(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Raw Response"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-6",children:[(null==g?void 0:g.status)==="healthy"?(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}):(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsxs)(A.Z,{className:"text-sm font-medium ".concat((null==g?void 0:g.status)==="healthy"?"text-green-500":"text-red-500"),children:["Cache Status: ",(null==g?void 0:g.status)||"unhealthy"]})]}),(0,c.jsx)("table",{className:"w-full border-collapse",children:(0,c.jsxs)("tbody",{children:[j&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold text-red-600",children:"Error Details"})}),(0,c.jsx)(au,{label:"Error Message",value:j.message}),(0,c.jsx)(au,{label:"Traceback",value:j.traceback})]}),(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Cache Details"})}),(0,c.jsx)(au,{label:"Cache Configuration",value:String(null==f?void 0:f.type)}),(0,c.jsx)(au,{label:"Ping Response",value:String(g.ping_response)}),(0,c.jsx)(au,{label:"Set Cache Response",value:g.set_cache_response||"N/A"}),(0,c.jsx)(au,{label:"litellm_settings.cache_params",value:JSON.stringify(f,null,2)}),(null==f?void 0:f.type)==="redis"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Redis Details"})}),(0,c.jsx)(au,{label:"Redis Host",value:y.redis_host||"N/A"}),(0,c.jsx)(au,{label:"Redis Port",value:y.redis_port||"N/A"}),(0,c.jsx)(au,{label:"Redis Version",value:y.redis_version||"N/A"}),(0,c.jsx)(au,{label:"Startup Nodes",value:y.startup_nodes||"N/A"}),(0,c.jsx)(au,{label:"Namespace",value:y.namespace||"N/A"})]})]})})]})}),(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsx)("div",{className:"bg-gray-50 rounded-md p-4 font-mono text-sm",children:(0,c.jsx)("pre",{className:"whitespace-pre-wrap break-words overflow-auto max-h-[500px]",children:(()=>{try{let e={...g,litellm_cache_params:f,health_check_cache_params:_},s=JSON.parse(JSON.stringify(e,(e,s)=>{if("string"==typeof s)try{return JSON.parse(s)}catch(e){}return s}));return JSON.stringify(s,null,2)}catch(e){return"Error formatting JSON: "+e.message}})()})})})]})]})})},ax=e=>{let{accessToken:s,healthCheckResponse:l,runCachingHealthCheck:t,responseTimeMs:a}=e,[r,n]=d.useState(null),[i,o]=d.useState(!1),m=async()=>{o(!0);let e=performance.now();await t(),n(performance.now()-e),o(!1)};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsx)(k.Z,{onClick:m,disabled:i,className:"bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white text-sm px-4 py-2 rounded-md",children:i?"Running Health Check...":"Run Health Check"}),(0,c.jsx)(ad,{responseTimeMs:r})]}),l&&(0,c.jsx)(ah,{response:l})]})},ap=e=>{if(e)return e.toISOString().split("T")[0]};function ag(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}var aj=e=>{let{accessToken:s,token:l,userRole:t,userID:a,premiumUser:r}=e,[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)("0"),[f,_]=(0,d.useState)("0"),[v,b]=(0,d.useState)("0"),[Z,k]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[S,C]=(0,d.useState)(""),[I,T]=(0,d.useState)("");(0,d.useEffect)(()=>{s&&Z&&((async()=>{p(await (0,y.zg)(s,ap(Z.from),ap(Z.to)))})(),C(new Date().toLocaleString()))},[s]);let E=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.api_key)&&void 0!==s?s:""}))),P=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.model)&&void 0!==s?s:""})));Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.call_type)&&void 0!==s?s:""})));let O=async(e,l)=>{e&&l&&s&&(l.setHours(23,59,59,999),e.setHours(0,0,0,0),p(await (0,y.zg)(s,ap(e),ap(l))))};(0,d.useEffect)(()=>{console.log("DATA IN CACHE DASHBOARD",x);let e=x;o.length>0&&(e=e.filter(e=>o.includes(e.api_key))),u.length>0&&(e=e.filter(e=>u.includes(e.model))),console.log("before processed data in cache dashboard",e);let s=0,l=0,t=0,a=e.reduce((e,a)=>{console.log("Processing item:",a),a.call_type||(console.log("Item has no call_type:",a),a.call_type="Unknown"),s+=(a.total_rows||0)-(a.cache_hit_true_rows||0),l+=a.cache_hit_true_rows||0,t+=a.cached_completion_tokens||0;let r=e.find(e=>e.name===a.call_type);return r?(r["LLM API requests"]+=(a.total_rows||0)-(a.cache_hit_true_rows||0),r["Cache hit"]+=a.cache_hit_true_rows||0,r["Cached Completion Tokens"]+=a.cached_completion_tokens||0,r["Generated Completion Tokens"]+=a.generated_completion_tokens||0):e.push({name:a.call_type,"LLM API requests":(a.total_rows||0)-(a.cache_hit_true_rows||0),"Cache hit":a.cache_hit_true_rows||0,"Cached Completion Tokens":a.cached_completion_tokens||0,"Generated Completion Tokens":a.generated_completion_tokens||0}),e},[]);j(ag(l)),_(ag(t));let r=l+s;r>0?b((l/r*100).toFixed(2)):b("0"),i(a),console.log("PROCESSED DATA IN CACHE DASHBOARD",a)},[o,u,Z,x]);let L=async()=>{try{D.ZP.info("Running cache health check..."),T("");let e=await (0,y.Tj)(null!==s?s:"");console.log("CACHING HEALTH CHECK RESPONSE",e),T(e)}catch(s){let e;if(console.error("Error running health check:",s),s&&s.message)try{let l=JSON.parse(s.message);l.error&&(l=l.error),e=l}catch(l){e={message:s.message}}else e={message:"Unknown error occurred"};T({error:e})}};return(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-full w-full mt-2 mb-8",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Cache Analytics"}),(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"Cache Health"})})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[S&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",S]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:()=>{C(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(w.Z,{numItems:3,className:"gap-4 mt-4",children:[(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select API Keys",value:o,onValueChange:m,children:E.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select Models",value:u,onValueChange:h,children:P.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(sb.Z,{enableSelect:!0,value:Z,onValueChange:e=>{k(e),O(e.from,e.to)},selectPlaceholder:"Select date range"})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hit Ratio"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsxs)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:[v,"%"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hits"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:g})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cached Tokens"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:f})})]})]}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cache Hits vs API Requests"}),(0,c.jsx)(sw.Z,{title:"Cache Hits vs API Requests",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["LLM API requests","Cache hit"],colors:["sky","teal"],yAxisWidth:48}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cached Completion Tokens vs Generated Completion Tokens"}),(0,c.jsx)(sw.Z,{className:"mt-6",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["Generated Completion Tokens","Cached Completion Tokens"],colors:["sky","teal"],yAxisWidth:48})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ax,{accessToken:s,healthCheckResponse:I,runCachingHealthCheck:L})})]})]})},af=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(async()=>{try{let e=await (0,y.t3)(s);console.log("guardrails: ".concat(JSON.stringify(e))),t(e.guardrails)}catch(e){console.error("Error fetching guardrails:",e)}})()},[s]),(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsxs)(A.Z,{className:"mb-4",children:["Configured guardrails and their current status. Setup guardrails in config.yaml."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Guardrail Name"}),(0,c.jsx)(eP.Z,{children:"Mode"}),(0,c.jsx)(eP.Z,{children:"Status"})]})}),(0,c.jsx)(eT.Z,{children:l&&0!==l.length?null==l?void 0:l.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.guardrail_name}),(0,c.jsx)(eA.Z,{children:e.litellm_params.mode}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"inline-flex rounded-full px-2 py-1 text-xs font-medium\n ".concat(e.litellm_params.default_on?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"),children:e.litellm_params.default_on?"Always On":"Per Request"})})]},s)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:3,className:"mt-4 text-gray-500 text-center py-4",children:"No guardrails configured"})})})]})})]})},a_=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)('{\n "model": "openai/gpt-4o",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n },\n {\n "role": "user",\n "content": "Explain quantum computing in simple terms"\n }\n ],\n "temperature": 0.7,\n "max_tokens": 500,\n "stream": true\n}'),[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(!1),o=(e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")},m=async()=>{i(!0);try{let e;try{e=JSON.parse(l)}catch(e){D.ZP.error("Invalid JSON in request body"),i(!1);return}let t={call_type:"completion",request_body:e};if(!s){D.ZP.error("No access token found"),i(!1);return}let a=await (0,y.Yo)(s,t);if(a.raw_request_api_base&&a.raw_request_body){let e=o(a.raw_request_api_base,a.raw_request_body,a.raw_request_headers||{});r(e),D.ZP.success("Request transformed successfully")}else{let e="string"==typeof a?a:JSON.stringify(a);r(e),D.ZP.info("Transformed request received in unexpected format")}}catch(e){console.error("Error transforming request:",e),D.ZP.error("Failed to transform request")}finally{i(!1)}};return(0,c.jsxs)("div",{className:"w-full m-2",style:{overflow:"hidden"},children:[(0,c.jsx)(E.Z,{children:"Playground"}),(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"See how LiteLLM transforms your request for the specified provider."}),(0,c.jsxs)("div",{style:{display:"flex",gap:"16px",width:"100%",minWidth:0,overflow:"hidden"},className:"mt-4",children:[(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"600px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Original Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"The request you would send to LiteLLM /chat/completions endpoint."})]}),(0,c.jsx)("textarea",{style:{flex:"1 1 auto",width:"100%",minHeight:"240px",padding:"16px",border:"1px solid #e8e8e8",borderRadius:"6px",fontFamily:"monospace",fontSize:"14px",resize:"none",marginBottom:"24px",overflow:"auto"},value:l,onChange:e=>t(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),m())},placeholder:"Press Cmd/Ctrl + Enter to transform"}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"auto"},children:(0,c.jsxs)(R.ZP,{type:"primary",style:{backgroundColor:"#000",display:"flex",alignItems:"center",gap:"8px"},onClick:m,loading:n,children:[(0,c.jsx)("span",{children:"Transform"}),(0,c.jsx)("span",{children:"→"})]})})]}),(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"800px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Transformed Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"How LiteLLM transforms your request for the specified provider."}),(0,c.jsx)("br",{}),(0,c.jsx)("p",{style:{color:"#666",margin:0},className:"text-xs",children:"Note: Sensitive headers are not shown."})]}),(0,c.jsxs)("div",{style:{position:"relative",backgroundColor:"#f5f5f5",borderRadius:"6px",flex:"1 1 auto",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,c.jsx)("pre",{style:{padding:"16px",fontFamily:"monospace",fontSize:"14px",margin:0,overflow:"auto",flex:"1 1 auto"},children:a||'curl -X POST \\\n https://api.openai.com/v1/chat/completions \\\n -H \'Authorization: Bearer sk-xxx\' \\\n -H \'Content-Type: application/json\' \\\n -d \'{\n "model": "gpt-4",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n }\n ],\n "temperature": 0.7\n }\''}),(0,c.jsx)(R.ZP,{type:"text",icon:(0,c.jsx)(s8.Z,{}),style:{position:"absolute",right:"8px",top:"8px"},size:"small",onClick:()=>{navigator.clipboard.writeText(a||""),D.ZP.success("Copied to clipboard")}})]})]})]}),(0,c.jsx)("div",{className:"mt-4 text-right w-full",children:(0,c.jsxs)("p",{className:"text-sm text-gray-500",children:["Found an error? File an issue ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/issues",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})]})},ay=l(21770);let av=[{accessorKey:"mcp_info.server_name",header:"Provider",cell:e=>{let{row:s}=e,l=s.original.mcp_info.server_name,t=s.original.mcp_info.logo_url;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[t&&(0,c.jsx)("img",{src:t,alt:"".concat(l," logo"),className:"h-5 w-5 object-contain"}),(0,c.jsx)("span",{className:"font-medium",children:l})]})}},{accessorKey:"name",header:"Tool Name",cell:e=>{let{row:s}=e,l=s.getValue("name");return(0,c.jsx)("div",{children:(0,c.jsx)("span",{className:"font-mono text-sm",children:l})})}},{accessorKey:"description",header:"Description",cell:e=>{let{row:s}=e,l=s.getValue("description");return(0,c.jsx)("div",{className:"max-w-md",children:(0,c.jsx)("span",{className:"text-sm text-gray-700",children:l})})}},{id:"actions",header:"Actions",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"flex items-center space-x-2",children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{"function"==typeof s.original.onToolSelect&&s.original.onToolSelect(l)},children:"Test Tool"})})}}];function ab(e){let{tool:s,onSubmit:l,isLoading:t,result:a,error:r,onClose:n}=e,[i,o]=d.useState({}),m=d.useMemo(()=>"string"==typeof s.inputSchema?{type:"object",properties:{input:{type:"string",description:"Input for this tool"}},required:["input"]}:s.inputSchema,[s.inputSchema]),u=(e,s)=>{o(l=>({...l,[e]:s}))};return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-lg border p-6 max-w-4xl w-full",children:[(0,c.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("h2",{className:"text-xl font-bold",children:["Test Tool: ",(0,c.jsx)("span",{className:"font-mono",children:s.name})]}),(0,c.jsx)("p",{className:"text-gray-600",children:s.description}),(0,c.jsxs)("p",{className:"text-sm text-gray-500 mt-1",children:["Provider: ",s.mcp_info.server_name]})]}),(0,c.jsx)("button",{onClick:n,className:"p-1 rounded-full hover:bg-gray-200",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,c.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Input Parameters"}),(0,c.jsxs)("form",{onSubmit:e=>{e.preventDefault(),l(i)},children:["string"==typeof s.inputSchema?(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:"This tool uses a dynamic input schema."}),(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Input ",(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),(0,c.jsx)("input",{type:"text",value:i.input||"",onChange:e=>u("input",e.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"})]})]}):Object.entries(m.properties).map(e=>{var s,l,t;let[a,r]=e;return(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[a," ",(null===(s=m.required)||void 0===s?void 0:s.includes(a))&&(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),r.description&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:r.description}),"string"===r.type&&(0,c.jsx)("input",{type:"text",value:i[a]||"",onChange:e=>u(a,e.target.value),required:null===(l=m.required)||void 0===l?void 0:l.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"number"===r.type&&(0,c.jsx)("input",{type:"number",value:i[a]||"",onChange:e=>u(a,parseFloat(e.target.value)),required:null===(t=m.required)||void 0===t?void 0:t.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"boolean"===r.type&&(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("input",{type:"checkbox",checked:i[a]||!1,onChange:e=>u(a,e.target.checked),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),(0,c.jsx)("span",{className:"ml-2 text-sm text-gray-600",children:"Enable"})]})]},a)}),(0,c.jsx)("div",{className:"mt-6",children:(0,c.jsx)(k.Z,{type:"submit",disabled:t,className:"w-full px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white",children:t?"Calling...":"Call Tool"})})]})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg overflow-auto max-h-[500px]",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Result"}),t&&(0,c.jsx)("div",{className:"flex justify-center items-center py-8",children:(0,c.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-700"})}),r&&(0,c.jsxs)("div",{className:"bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-md",children:[(0,c.jsx)("p",{className:"font-medium",children:"Error"}),(0,c.jsx)("pre",{className:"mt-2 text-xs overflow-auto whitespace-pre-wrap",children:r.message})]}),a&&!t&&!r&&(0,c.jsxs)("div",{children:[a.map((e,s)=>(0,c.jsxs)("div",{className:"mb-4",children:["text"===e.type&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.text})}),"image"===e.type&&e.url&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("img",{src:e.url,alt:"Tool result",className:"max-w-full h-auto rounded"})}),"embedded_resource"===e.type&&(0,c.jsxs)("div",{className:"bg-white border p-3 rounded-md",children:[(0,c.jsx)("p",{className:"text-sm font-medium",children:"Embedded Resource"}),(0,c.jsxs)("p",{className:"text-xs text-gray-500",children:["Type: ",e.resource_type]}),e.url&&(0,c.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline",children:"View Resource"})]})]},s)),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)("details",{className:"text-xs",children:[(0,c.jsx)("summary",{className:"cursor-pointer text-gray-500 hover:text-gray-700",children:"Raw JSON Response"}),(0,c.jsx)("pre",{className:"mt-2 bg-gray-100 p-2 rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(a,null,2)})]})})]}),!a&&!t&&!r&&(0,c.jsx)("div",{className:"text-center py-8 text-gray-500",children:(0,c.jsx)("p",{children:"The result will appear here after you call the tool."})})]})]})]})}function aZ(e){let{columns:s,data:l,isLoading:t}=e;return(0,c.jsx)(eL,{columns:s,data:l,isLoading:t,renderSubComponent:()=>(0,c.jsx)("div",{}),getRowCanExpand:()=>!1})}function aN(e){let{accessToken:s,userRole:l,userID:t}=e,[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),{data:x,isLoading:p}=(0,e4.a)({queryKey:["mcpTools"],queryFn:()=>{if(!s)throw Error("Access Token required");return(0,y.lU)(s)},enabled:!!s}),{mutate:g,isPending:j}=(0,ay.D)({mutationFn:e=>{if(!s)throw Error("Access Token required");return(0,y.tB)(s,e.tool.name,e.arguments)},onSuccess:e=>{m(e),h(null)},onError:e=>{h(e),m(null)}}),f=d.useMemo(()=>x?x.map(e=>({...e,onToolSelect:e=>{i(e),m(null),h(null)}})):[],[x]),_=d.useMemo(()=>f.filter(e=>{let s=a.toLowerCase();return e.name.toLowerCase().includes(s)||e.description.toLowerCase().includes(s)||e.mcp_info.server_name.toLowerCase().includes(s)}),[f,a]);return s&&l&&t?(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"MCP Tools"})}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search tools...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:a,onChange:e=>r(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"text-sm text-gray-500",children:[_.length," tool",1!==_.length?"s":""," available"]})]})}),(0,c.jsx)(aZ,{columns:av,data:_,isLoading:p})]}),n&&(0,c.jsx)("div",{className:"fixed inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center z-50 p-4",children:(0,c.jsx)(ab,{tool:n,onSubmit:e=>{n&&g({tool:n,arguments:e})},isLoading:j,result:o,error:u,onClose:()=>i(null)})})]}):(0,c.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Missing required authentication parameters."})}var aw=e=>{let{tagId:s,onClose:l,accessToken:t,is_admin:a,editTag:r}=e,[n]=L.Z.useForm(),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(r),[h,x]=(0,d.useState)([]),p=async()=>{if(t)try{let e=(await (0,y.mC)(t,[s]))[s];e&&(o(e),r&&n.setFieldsValue({name:e.name,description:e.description,models:e.models}))}catch(e){console.error("Error fetching tag details:",e),D.ZP.error("Error fetching tag details: "+e)}};(0,d.useEffect)(()=>{p()},[s,t]),(0,d.useEffect)(()=>{t&&eZ("dummy-user","Admin",t,x)},[t]);let g=async e=>{if(t)try{await (0,y.n9)(t,{name:e.name,description:e.description,models:e.models}),D.ZP.success("Tag updated successfully"),u(!1),p()}catch(e){console.error("Error updating tag:",e),D.ZP.error("Error updating tag: "+e)}};return i?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{onClick:l,className:"mb-4",children:"← Back to Tags"}),(0,c.jsxs)(E.Z,{children:["Tag Name: ",i.name]}),(0,c.jsx)(A.Z,{className:"text-gray-500",children:i.description||"No description"})]}),a&&!m&&(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Tag"})]}),m?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(L.Z,{form:n,onFinish:g,layout:"vertical",initialValues:i,children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(q.default,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed LLMs"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process this type of data",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:h.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))})}),(0,c.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,c.jsx)(k.Z,{onClick:()=>u(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]})}):(0,c.jsx)("div",{className:"space-y-6",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Tag Details"}),(0,c.jsxs)("div",{className:"space-y-4 mt-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Name"}),(0,c.jsx)(A.Z,{children:i.name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Description"}),(0,c.jsx)(A.Z,{children:i.description||"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Allowed LLMs"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-2",children:0===i.models.length?(0,c.jsx)(eM.Z,{color:"red",children:"All Models"}):i.models.map(e=>{var s;return(0,c.jsx)(eM.Z,{color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(null===(s=i.model_info)||void 0===s?void 0:s[e])||e})},e)})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:i.created_at?new Date(i.created_at).toLocaleString():"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:i.updated_at?new Date(i.updated_at).toLocaleString():"-"})]})]})]})})]}):(0,c.jsx)("div",{children:"Loading..."})},ak=e=>{let{data:s,onEdit:l,onDelete:t,onSelectTag:a}=e,[r,n]=d.useState([{id:"created_at",desc:!0}]),i=[{header:"Tag Name",accessorKey:"name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.name,children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5",onClick:()=>a(l.name),children:l.name})})})}},{header:"Description",accessorKey:"description",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.description,children:(0,c.jsx)("span",{className:"text-xs",children:l.description||"-"})})}},{header:"Allowed LLMs",accessorKey:"models",cell:e=>{var s,l;let{row:t}=e,a=t.original;return(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:(null==a?void 0:null===(s=a.models)||void 0===s?void 0:s.length)===0?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Models"}):null==a?void 0:null===(l=a.models)||void 0===l?void 0:l.map(e=>{var s;return(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(0,c.jsx)(A.Z,{children:(null===(s=a.model_info)||void 0===s?void 0:s[e])||e})})},e)})})}},{header:"Created",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:new Date(l.created_at).toLocaleDateString()})}},{id:"actions",header:"",cell:e=>{let{row:s}=e,a=s.original;return(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>l(a),className:"cursor-pointer"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(a.name),className:"cursor-pointer"})]})}}],o=(0,eS.b7)({data:s,columns:i,state:{sorting:r},onSortingChange:n,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0});return(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:i.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No tags found"})})})})})]})})})},aS=e=>{let{accessToken:s,userID:l,userRole:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v]=L.Z.useForm(),[b,Z]=(0,d.useState)([]),C=async()=>{if(s)try{let e=await (0,y.UM)(s);console.log("List tags response:",e),r(Object.values(e))}catch(e){console.error("Error fetching tags:",e),D.ZP.error("Error fetching tags: "+e)}},I=async e=>{if(s)try{await (0,y.mY)(s,{name:e.tag_name,description:e.description,models:e.allowed_llms}),D.ZP.success("Tag created successfully"),i(!1),v.resetFields(),C()}catch(e){console.error("Error creating tag:",e),D.ZP.error("Error creating tag: "+e)}},T=async e=>{j(e),p(!0)},E=async()=>{if(s&&g){try{await (0,y.fE)(s,g),D.ZP.success("Tag deleted successfully"),C()}catch(e){console.error("Error deleting tag:",e),D.ZP.error("Error deleting tag: "+e)}p(!1),j(null)}};return(0,d.useEffect)(()=>{l&&t&&s&&(async()=>{try{let e=await (0,y.AZ)(s,l,t);e&&e.data&&Z(e.data)}catch(e){console.error("Error fetching models:",e),D.ZP.error("Error fetching models: "+e)}})()},[s,l,t]),(0,d.useEffect)(()=>{C()},[s]),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:o?(0,c.jsx)(aw,{tagId:o,onClose:()=>{m(null),h(!1)},accessToken:s,is_admin:"Admin"===t,editTag:u}):(0,c.jsxs)("div",{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)("div",{className:"flex justify-between mt-2 w-full items-center mb-4",children:[(0,c.jsx)("h1",{children:"Tag Management"}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center cursor-pointer",onClick:()=>{C(),_(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(A.Z,{className:"mb-4",children:["Click on a tag name to view and edit its details.",(0,c.jsxs)("p",{children:["You can use tags to restrict the usage of certain LLMs based on tags passed in the request. Read more about tag routing ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tag_routing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})]}),(0,c.jsx)(k.Z,{className:"mb-4",onClick:()=>i(!0),children:"+ Create New Tag"}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(ak,{data:a,onEdit:e=>{m(e.name),h(!0)},onDelete:T,onSelectTag:m})})}),(0,c.jsx)(M.Z,{title:"Create New Tag",visible:n,width:800,footer:null,onCancel:()=>{i(!1),v.resetFields()},children:(0,c.jsxs)(L.Z,{form:v,onFinish:I,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"tag_name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed Models"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process requests from this tag",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_llms",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:b.map(e=>(0,c.jsx)(O.default.Option,{value:e.model_info.id,children:(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{children:e.model_name}),(0,c.jsxs)("span",{className:"text-gray-400 ml-2",children:["(",e.model_info.id,")"]})]})},e.model_info.id))})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Tag"})})]})}),x&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Tag"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this tag?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:E,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{p(!1),j(null)},children:"Cancel"})]})]})]})})]})})},aC=l(49096),aI=l(53335);let{cva:aT,cx:aA,compose:aE}=(0,aC.ZD)({hooks:{onComplete:e=>(0,aI.m6)(e)}});function aP(e){var s,l;let{className:t="",...a}=e,r=(0,d.useId)();return s=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),s=e.find(e=>{var s;return(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))===r}),l=e.find(e=>{var s;return e.effect instanceof KeyframeEffect&&(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))!==r});s&&l&&(s.currentTime=l.currentTime)},l=[r],(0,d.useLayoutEffect)(s,l),(0,c.jsxs)("svg",{"data-spinner-id":r,className:aA("pointer-events-none size-12 animate-spin text-current",t),fill:"none",viewBox:"0 0 24 24",...a,children:[(0,c.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,c.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}let aO=new h.S;function aL(){return(0,c.jsxs)("div",{className:aA("h-screen","flex items-center justify-center gap-4"),children:[(0,c.jsx)("div",{className:"text-lg font-medium py-2 pr-4 border-r border-r-gray-200",children:"\uD83D\uDE85 LiteLLM"}),(0,c.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,c.jsx)(aP,{className:"size-4"}),(0,c.jsx)("span",{className:"text-gray-600 text-sm",children:"Loading..."})]})]})}function aD(){let[e,s]=(0,d.useState)(""),[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,h]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[N,w]=(0,d.useState)({PROXY_BASE_URL:"",PROXY_LOGOUT_URL:""}),[k,S]=(0,d.useState)(!0),C=(0,m.useSearchParams)(),[I,T]=(0,d.useState)({data:[]}),[A,E]=(0,d.useState)(null),[P,O]=(0,d.useState)(!0),[L,D]=(0,d.useState)(null),M=C.get("invitation_id"),[F,R]=(0,d.useState)(()=>C.get("page")||"api-keys"),[q,U]=(0,d.useState)(null),z=!1===P&&null===A&&null===M;return((0,d.useEffect)(()=>{E(function(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token")),O(!1)},[]),(0,d.useEffect)(()=>{z&&(window.location.href=(y.H2||"")+"/sso/key/generate")},[A,P]),(0,d.useEffect)(()=>{if(!A)return;let e=(0,u.o)(A);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),U(e.key),r(e.disabled_non_admin_personal_key_creation),e.user_role){let l=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e.toLowerCase())),console.log("Received user role length: ".concat(e.toLowerCase().length)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"org_admin":return"Org Admin";case"internal_user":return"Internal User";case"internal_viewer":return"Internal Viewer";case"app_user":return"App User";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",l),s(l),"Admin Viewer"==l&&R("usage")}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e)),e.login_method?S("username_password"==e.login_method):console.log("User Email is not set ".concat(e)),e.premium_user&&t(e.premium_user),e.auth_header_name&&(0,y.K8)(e.auth_header_name),e.user_id&&D(e.user_id)}},[A]),(0,d.useEffect)(()=>{q&&L&&e&&eZ(L,e,q,v),q&&L&&e&&Z(q,L,e,null,h),q&&lw(q,f)},[q,L,e]),P)?(0,c.jsx)(aL,{}):(0,c.jsx)(d.Suspense,{fallback:(0,c.jsx)(aL,{}),children:(0,c.jsx)(x.aH,{client:aO,children:M?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):(0,c.jsxs)("div",{className:"flex flex-col min-h-screen",children:[(0,c.jsx)(b,{userID:L,userRole:e,premiumUser:l,userEmail:n,setProxySettings:w,proxySettings:N,accessToken:q}),(0,c.jsxs)("div",{className:"flex flex-1 overflow-auto",children:[(0,c.jsx)("div",{className:"mt-8",children:(0,c.jsx)(ar,{setPage:e=>{let s=new URLSearchParams(C);s.set("page",e),window.history.pushState(null,"","?".concat(s.toString())),R(e)},userRole:e,defaultSelectedKey:F})}),"api-keys"==F?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):"models"==F?(0,c.jsx)(lm,{userID:L,userRole:e,token:A,keys:p,accessToken:q,modelData:I,setModelData:T,premiumUser:l,teams:o}):"llm-playground"==F?(0,c.jsx)(tQ,{userID:L,userRole:e,token:A,accessToken:q,disabledPersonalKeyCreation:a}):"users"==F?(0,c.jsx)(l_,{userID:L,userRole:e,token:A,keys:p,teams:o,accessToken:q,setKeys:g}):"teams"==F?(0,c.jsx)(lZ,{teams:o,setTeams:h,searchParams:C,accessToken:q,userID:L,userRole:e,organizations:j}):"organizations"==F?(0,c.jsx)(lk,{organizations:j,setOrganizations:f,userModels:_,accessToken:q,userRole:e,premiumUser:l}):"admin-panel"==F?(0,c.jsx)(lM,{setTeams:h,searchParams:C,accessToken:q,showSSOBanner:k,premiumUser:l,proxySettings:N}):"api_ref"==F?(0,c.jsx)(tN,{proxySettings:N}):"settings"==F?(0,c.jsx)(lK,{userID:L,userRole:e,accessToken:q,premiumUser:l}):"budgets"==F?(0,c.jsx)(l7,{accessToken:q}):"guardrails"==F?(0,c.jsx)(af,{accessToken:q}):"transform-request"==F?(0,c.jsx)(a_,{accessToken:q}):"general-settings"==F?(0,c.jsx)(lQ,{userID:L,userRole:e,accessToken:q,modelData:I}):"model-hub"==F?(0,c.jsx)(tu.Z,{accessToken:q,publicPage:!1,premiumUser:l}):"caching"==F?(0,c.jsx)(aj,{userID:L,userRole:e,token:A,accessToken:q,premiumUser:l}):"pass-through-settings"==F?(0,c.jsx)(l5,{userID:L,userRole:e,accessToken:q,modelData:I}):"logs"==F?(0,c.jsx)(td,{userID:L,userRole:e,token:A,accessToken:q,allTeams:null!=o?o:[]}):"mcp-tools"==F?(0,c.jsx)(aN,{accessToken:q,userRole:e,userID:L}):"tag-management"==F?(0,c.jsx)(aS,{accessToken:q,userRole:e,userID:L}):"new_usage"==F?(0,c.jsx)(tZ,{userID:L,userRole:e,accessToken:q,teams:null!=o?o:[]}):(0,c.jsx)(ao,{userID:L,userRole:e,token:A,accessToken:q,keys:p,premiumUser:l})]})]})})})}},3914:function(e,s,l){"use strict";function t(){let e=window.location.hostname,s=["Lax","Strict","None"];["/","/ui"].forEach(l=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,";"),s.forEach(s=>{let t="None"===s?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; SameSite=").concat(s,";").concat(t),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,"; SameSite=").concat(s,";").concat(t)})}),console.log("After clearing cookies:",document.cookie)}function a(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}l.d(s,{b:function(){return t},e:function(){return a}})}},function(e){e.O(0,[665,990,42,261,899,466,250,699,971,117,744],function(){return e(e.s=36362)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/app/page-36914b80c40b5032.js b/ui/litellm-dashboard/out/_next/static/chunks/app/page-36914b80c40b5032.js deleted file mode 100644 index eca8f272d7..0000000000 --- a/ui/litellm-dashboard/out/_next/static/chunks/app/page-36914b80c40b5032.js +++ /dev/null @@ -1 +0,0 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[931],{60497:function(e,s,l){Promise.resolve().then(l.bind(l,76737))},12011:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return y}});var t=l(57437),a=l(2265),r=l(99376),n=l(20831),i=l(94789),o=l(12514),c=l(49804),d=l(67101),m=l(84264),u=l(49566),h=l(96761),x=l(84566),p=l(19250),g=l(14474),j=l(13634),f=l(73002),_=l(3914);function y(){let[e]=j.Z.useForm(),s=(0,r.useSearchParams)();(0,_.e)("token");let l=s.get("invitation_id"),[y,v]=(0,a.useState)(null),[b,Z]=(0,a.useState)(""),[N,w]=(0,a.useState)(""),[k,S]=(0,a.useState)(null),[C,I]=(0,a.useState)(""),[T,A]=(0,a.useState)("");return(0,a.useEffect)(()=>{l&&(0,p.W_)(l).then(e=>{let s=e.login_url;console.log("login_url:",s),I(s);let l=e.token,t=(0,g.o)(l);A(l),console.log("decoded:",t),v(t.key),console.log("decoded user email:",t.user_email),w(t.user_email),S(t.user_id)})},[l]),(0,t.jsx)("div",{className:"mx-auto w-full max-w-md mt-10",children:(0,t.jsxs)(o.Z,{children:[(0,t.jsx)(h.Z,{className:"text-sm mb-5 text-center",children:"\uD83D\uDE85 LiteLLM"}),(0,t.jsx)(h.Z,{className:"text-xl",children:"Sign up"}),(0,t.jsx)(m.Z,{children:"Claim your user account to login to Admin UI."}),(0,t.jsx)(i.Z,{className:"mt-4",title:"SSO",icon:x.GH$,color:"sky",children:(0,t.jsxs)(d.Z,{numItems:2,className:"flex justify-between items-center",children:[(0,t.jsx)(c.Z,{children:"SSO is under the Enterprise Tier."}),(0,t.jsx)(c.Z,{children:(0,t.jsx)(n.Z,{variant:"primary",className:"mb-2",children:(0,t.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})})})]})}),(0,t.jsxs)(j.Z,{className:"mt-10 mb-5 mx-auto",layout:"vertical",onFinish:e=>{console.log("in handle submit. accessToken:",y,"token:",T,"formValues:",e),y&&T&&(e.user_email=N,k&&l&&(0,p.m_)(y,l,k,e.password).then(e=>{let s="/ui/";s+="?login=success",document.cookie="token="+T,console.log("redirecting to:",s),window.location.href=s}))},children:[(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)(j.Z.Item,{label:"Email Address",name:"user_email",children:(0,t.jsx)(u.Z,{type:"email",disabled:!0,value:N,defaultValue:N,className:"max-w-md"})}),(0,t.jsx)(j.Z.Item,{label:"Password",name:"password",rules:[{required:!0,message:"password required to sign up"}],help:"Create a password for your account",children:(0,t.jsx)(u.Z,{placeholder:"",type:"password",className:"max-w-md"})})]}),(0,t.jsx)("div",{className:"mt-10",children:(0,t.jsx)(f.ZP,{htmlType:"submit",children:"Sign Up"})})]})]})})}},76737:function(e,s,l){"use strict";l.r(s),l.d(s,{default:function(){return aD}});var t,a,r,n,i,o,c=l(57437),d=l(2265),m=l(99376),u=l(14474),h=l(21623),x=l(29827),p=l(27648),g=l(80795),j=l(15883),f=l(40428),_=l(3914),y=l(19250);let v=async e=>{if(!e)return null;try{return await (0,y.g)(e)}catch(e){return console.error("Error fetching proxy settings:",e),null}};var b=e=>{let{userID:s,userEmail:l,userRole:t,premiumUser:a,proxySettings:r,setProxySettings:n,accessToken:i}=e,[o,m]=(0,d.useState)("");(0,d.useEffect)(()=>{(async()=>{if(i){let e=await v(i);console.log("response from fetchProxySettings",e),e&&n(e)}})()},[i]),(0,d.useEffect)(()=>{m((null==r?void 0:r.PROXY_LOGOUT_URL)||"")},[r]);let u=[{key:"1",label:(0,c.jsxs)("div",{className:"py-1",children:[(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Role: ",t]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Email: ",l||"Unknown"]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[(0,c.jsx)(j.Z,{})," ",s]}),(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:["Premium User: ",String(a)]})]})},{key:"2",label:(0,c.jsxs)("p",{className:"text-sm hover:text-gray-900",onClick:()=>{(0,_.b)(),window.location.href=o},children:[(0,c.jsx)(f.Z,{})," Logout"]})}];return(0,c.jsx)("nav",{className:"bg-white border-b border-gray-200 sticky top-0 z-10",children:(0,c.jsx)("div",{className:"w-full",children:(0,c.jsxs)("div",{className:"flex items-center h-12 px-4",children:[(0,c.jsx)("div",{className:"flex items-center flex-shrink-0",children:(0,c.jsx)(p.default,{href:"/",className:"flex items-center",children:(0,c.jsx)("img",{src:"/get_image",alt:"LiteLLM Brand",className:"h-8 w-auto"})})}),(0,c.jsxs)("div",{className:"flex items-center space-x-5 ml-auto",children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/",target:"_blank",rel:"noopener noreferrer",className:"text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:"Docs"}),(0,c.jsx)(g.Z,{menu:{items:u,style:{padding:"4px",marginTop:"4px"}},children:(0,c.jsxs)("button",{className:"inline-flex items-center text-[13px] text-gray-600 hover:text-gray-900 transition-colors",children:["User",(0,c.jsx)("svg",{className:"ml-1 w-4 h-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M19 9l-7 7-7-7"})})]})})]})]})})})};let Z=async(e,s,l,t,a)=>{let r;r="Admin"!=l&&"Admin Viewer"!=l?await (0,y.It)(e,(null==t?void 0:t.organization_id)||null,s):await (0,y.It)(e,(null==t?void 0:t.organization_id)||null),console.log("givenTeams: ".concat(r)),a(r)};var N=l(49804),w=l(67101),k=l(20831),S=l(49566),C=l(87452),I=l(88829),T=l(72208),A=l(84264),E=l(96761),P=l(29233),O=l(52787),L=l(13634),D=l(41021),M=l(51369),F=l(29967),R=l(73002),q=l(56632),U=l(30150),z=e=>{let{step:s=.01,style:l={width:"100%"},placeholder:t="Enter a numerical value",min:a,max:r,onChange:n,...i}=e;return(0,c.jsx)(U.Z,{onWheel:e=>e.currentTarget.blur(),step:s,style:l,placeholder:t,min:a,max:r,onChange:n,...i})};let V=async(e,s,l)=>{try{if(null===e||null===s)return;if(null!==l){let t=(await (0,y.So)(l,e,s,!0)).data.map(e=>e.id),a=[],r=[];return t.forEach(e=>{e.endsWith("/*")?a.push(e):r.push(e)}),[...a,...r]}}catch(e){console.error("Error fetching user models:",e)}},K=e=>{if(e.endsWith("/*")){let s=e.replace("/*","");return"All ".concat(s," models")}return e},B=(e,s)=>{let l=[],t=[];return console.log("teamModels",e),console.log("allModels",s),e.forEach(e=>{if(e.endsWith("/*")){let a=e.replace("/*",""),r=s.filter(e=>e.startsWith(a+"/"));t.push(...r),l.push(e)}else t.push(e)}),[...l,...t].filter((e,s,l)=>l.indexOf(e)===s)};var H=l(20577),J=l(15424),W=l(75957);let G=(e,s)=>["metadata","config","enforced_params","aliases"].includes(e)||"json"===s.format,Y=e=>{if(!e)return!0;try{return JSON.parse(e),!0}catch(e){return!1}},$=(e,s,l)=>{let t={max_budget:"Enter maximum budget in USD (e.g., 100.50)",budget_duration:"Select a time period for budget reset",tpm_limit:"Enter maximum tokens per minute (whole number)",rpm_limit:"Enter maximum requests per minute (whole number)",duration:"Enter duration (e.g., 30s, 24h, 7d)",metadata:'Enter JSON object with key-value pairs\nExample: {"team": "research", "project": "nlp"}',config:'Enter configuration as JSON object\nExample: {"setting": "value"}',permissions:"Enter comma-separated permission strings",enforced_params:'Enter parameters as JSON object\nExample: {"param": "value"}',blocked:"Enter true/false or specific block conditions",aliases:'Enter aliases as JSON object\nExample: {"alias1": "value1", "alias2": "value2"}',models:"Select one or more model names",key_alias:"Enter a unique identifier for this key",tags:"Enter comma-separated tag strings"}[e]||({string:"Text input",number:"Numeric input",integer:"Whole number input",boolean:"True/False value"})[l]||"Text input";return G(e,s)?"".concat(t,"\nMust be valid JSON format"):s.enum?"Select from available options\nAllowed values: ".concat(s.enum.join(", ")):t};var X=e=>{let{schemaComponent:s,excludedFields:l=[],form:t,overrideLabels:a={},overrideTooltips:r={},customValidation:n={},defaultValues:i={}}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null);(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.lP)()).components.schemas[s];if(!e)throw Error('Schema component "'.concat(s,'" not found'));m(e);let a={};Object.keys(e.properties).filter(e=>!l.includes(e)&&void 0!==i[e]).forEach(e=>{a[e]=i[e]}),t.setFieldsValue(a)}catch(e){console.error("Schema fetch error:",e),h(e instanceof Error?e.message:"Failed to fetch schema")}})()},[s,t,l]);let x=e=>{if(e.type)return e.type;if(e.anyOf){let s=e.anyOf.map(e=>e.type);if(s.includes("number")||s.includes("integer"))return"number";s.includes("string")}return"string"},p=(e,s)=>{var l;let t;let d=x(s),m=null==o?void 0:null===(l=o.required)||void 0===l?void 0:l.includes(e),u=a[e]||s.title||e,h=r[e]||s.description,p=[];m&&p.push({required:!0,message:"".concat(u," is required")}),n[e]&&p.push({validator:n[e]}),G(e,s)&&p.push({validator:async(e,s)=>{if(s&&!Y(s))throw Error("Please enter valid JSON")}});let g=h?(0,c.jsxs)("span",{children:[u," ",(0,c.jsx)(W.Z,{title:h,children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}):u;return t=G(e,s)?(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter as JSON",className:"font-mono"}):s.enum?(0,c.jsx)(O.default,{children:s.enum.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"number"===d||"integer"===d?(0,c.jsx)(H.Z,{style:{width:"100%"},precision:"integer"===d?0:void 0}):"duration"===e?(0,c.jsx)(S.Z,{placeholder:"eg: 30s, 30h, 30d"}):(0,c.jsx)(S.Z,{placeholder:h||""}),(0,c.jsx)(L.Z.Item,{label:g,name:e,className:"mt-8",rules:p,initialValue:i[e],help:(0,c.jsx)("div",{className:"text-xs text-gray-500",children:$(e,s,d)}),children:t},e)};return u?(0,c.jsxs)("div",{className:"text-red-500",children:["Error: ",u]}):(null==o?void 0:o.properties)?(0,c.jsx)("div",{children:Object.entries(o.properties).filter(e=>{let[s]=e;return!l.includes(s)}).map(e=>{let[s,l]=e;return p(s,l)})}):null},Q=e=>{let{teams:s,value:l,onChange:t}=e;return(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search or select a team",value:l,onChange:t,filterOption:(e,s)=>{var l,t,a;return!!s&&((null===(a=s.children)||void 0===a?void 0:null===(t=a[0])||void 0===t?void 0:null===(l=t.props)||void 0===l?void 0:l.children)||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==s?void 0:s.map(e=>(0,c.jsxs)(O.default.Option,{value:e.team_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.team_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.team_id,")"]})]},e.team_id))})},ee=l(57365),es=l(93192);function el(e){let{isInvitationLinkModalVisible:s,setIsInvitationLinkModalVisible:l,baseUrl:t,invitationLinkData:a}=e,{Title:r,Paragraph:n}=es.default,i=()=>(null==a?void 0:a.has_user_setup_sso)?new URL("/ui",t).toString():new URL("/ui?invitation_id=".concat(null==a?void 0:a.id),t).toString();return(0,c.jsxs)(M.Z,{title:"Invitation Link",visible:s,width:800,footer:null,onOk:()=>{l(!1)},onCancel:()=>{l(!1)},children:[(0,c.jsx)(n,{children:"Copy and send the generated link to onboard this user to the proxy."}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"User ID"}),(0,c.jsx)(A.Z,{children:null==a?void 0:a.user_id})]}),(0,c.jsxs)("div",{className:"flex justify-between pt-5 pb-2",children:[(0,c.jsx)(A.Z,{children:"Invitation Link"}),(0,c.jsx)(A.Z,{children:(0,c.jsx)(A.Z,{children:i()})})]}),(0,c.jsx)("div",{className:"flex justify-end mt-5",children:(0,c.jsx)(P.CopyToClipboard,{text:i(),onCopy:()=>D.ZP.success("Copied!"),children:(0,c.jsx)(k.Z,{variant:"primary",children:"Copy invitation link"})})})]})}var et=l(77388),ea=l(1709),er=l(73879),en=l(3632),ei=l(15452),eo=l.n(ei),ec=l(71157),ed=l(44643),em=e=>{let{accessToken:s,teams:l,possibleUIRoles:t,onUsersCreated:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.g)(s);g(e)}catch(e){console.error("Error fetching UI settings:",e)}})(),f(new URL("/",window.location.href).toString())},[s]);let _=async()=>{u(!0);let e=i.map(e=>({...e,status:"pending"}));o(e);let l=!1;for(let a=0;ae.trim())),e.models&&"string"==typeof e.models&&(e.models=e.models.split(",").map(e=>e.trim())),e.max_budget&&""!==e.max_budget.toString().trim()&&(e.max_budget=parseFloat(e.max_budget.toString()));let r=await (0,y.Ov)(s,null,e);if(console.log("Full response:",r),r&&(r.key||r.user_id)){l=!0,console.log("Success case triggered");let e=(null===(t=r.data)||void 0===t?void 0:t.user_id)||r.user_id;try{if(null==p?void 0:p.SSO_ENABLED){let e=new URL("/ui",j).toString();o(s=>s.map((s,l)=>l===a?{...s,status:"success",key:r.key||r.user_id,invitation_link:e}:s))}else{let l=await (0,y.XO)(s,e),t=new URL("/ui?invitation_id=".concat(l.id),j).toString();o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,invitation_link:t}:e))}}catch(e){console.error("Error creating invitation:",e),o(e=>e.map((e,s)=>s===a?{...e,status:"success",key:r.key||r.user_id,error:"User created but failed to generate invitation link"}:e))}}else{console.log("Error case triggered");let e=(null==r?void 0:r.error)||"Failed to create user";console.log("Error message:",e),o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}catch(s){console.error("Caught error:",s);let e=(null==s?void 0:null===(n=s.response)||void 0===n?void 0:null===(r=n.data)||void 0===r?void 0:r.error)||(null==s?void 0:s.message)||String(s);o(s=>s.map((s,l)=>l===a?{...s,status:"failed",error:e}:s))}}u(!1),l&&a&&a()};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>n(!0),children:"+ Bulk Invite Users"}),(0,c.jsx)(M.Z,{title:"Bulk Invite Users",visible:r,width:800,onCancel:()=>n(!1),bodyStyle:{maxHeight:"70vh",overflow:"auto"},footer:null,children:(0,c.jsx)("div",{className:"flex flex-col",children:0===i.length?(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"1"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Download and fill the template"})]}),(0,c.jsxs)("div",{className:"ml-11 mb-6",children:[(0,c.jsx)("p",{className:"mb-4",children:"Add multiple users at once by following these steps:"}),(0,c.jsxs)("ol",{className:"list-decimal list-inside space-y-2 ml-2 mb-4",children:[(0,c.jsx)("li",{children:"Download our CSV template"}),(0,c.jsx)("li",{children:"Add your users' information to the spreadsheet"}),(0,c.jsx)("li",{children:"Save the file and upload it here"}),(0,c.jsx)("li",{children:"After creation, download the results file containing the API keys for each user"})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-md border border-gray-200 mb-4",children:[(0,c.jsx)("h4",{className:"font-medium mb-2",children:"Template Column Names"}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_email"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:"User's email address (required)"})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-red-500 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"user_role"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'User\'s role (one of: "proxy_admin", "proxy_admin_view_only", "internal_user", "internal_user_view_only")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"teams"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated team IDs (e.g., "team-1,team-2")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"max_budget"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Maximum budget as a number (e.g., "100")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"budget_duration"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Budget reset period (e.g., "30d", "1mo")'})]})]}),(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"w-3 h-3 rounded-full bg-gray-300 mt-1.5 mr-2 flex-shrink-0"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"font-medium",children:"models"}),(0,c.jsx)("p",{className:"text-sm text-gray-600",children:'Comma-separated allowed models (e.g., "gpt-3.5-turbo,gpt-4")'})]})]})]})]}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=new Blob([eo().unparse([["user_email","user_role","teams","max_budget","budget_duration","models"],["user@example.com","internal_user","team-id-1,team-id-2","100","30d","gpt-3.5-turbo,gpt-4"]])],{type:"text/csv"}),s=window.URL.createObjectURL(e),l=document.createElement("a");l.href=s,l.download="bulk_users_template.csv",document.body.appendChild(l),l.click(),document.body.removeChild(l),window.URL.revokeObjectURL(s)},size:"lg",className:"w-full md:w-auto",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download CSV Template"]})]}),(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"2"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Upload your completed CSV"})]}),(0,c.jsx)("div",{className:"ml-11",children:(0,c.jsx)(et.Z,{beforeUpload:e=>(x(null),eo().parse(e,{complete:e=>{let s=e.data[0],l=["user_email","user_role"].filter(e=>!s.includes(e));if(l.length>0){x("Your CSV is missing these required columns: ".concat(l.join(", "))),o([]);return}try{let l=e.data.slice(1).map((e,l)=>{var t,a,r,n,i,o;let c={user_email:(null===(t=e[s.indexOf("user_email")])||void 0===t?void 0:t.trim())||"",user_role:(null===(a=e[s.indexOf("user_role")])||void 0===a?void 0:a.trim())||"",teams:null===(r=e[s.indexOf("teams")])||void 0===r?void 0:r.trim(),max_budget:null===(n=e[s.indexOf("max_budget")])||void 0===n?void 0:n.trim(),budget_duration:null===(i=e[s.indexOf("budget_duration")])||void 0===i?void 0:i.trim(),models:null===(o=e[s.indexOf("models")])||void 0===o?void 0:o.trim(),rowNumber:l+2,isValid:!0,error:""},d=[];c.user_email||d.push("Email is required"),c.user_role||d.push("Role is required"),c.user_email&&!c.user_email.includes("@")&&d.push("Invalid email format");let m=["proxy_admin","proxy_admin_view_only","internal_user","internal_user_view_only"];return c.user_role&&!m.includes(c.user_role)&&d.push("Invalid role. Must be one of: ".concat(m.join(", "))),c.max_budget&&isNaN(parseFloat(c.max_budget.toString()))&&d.push("Max budget must be a number"),d.length>0&&(c.isValid=!1,c.error=d.join(", ")),c}),t=l.filter(e=>e.isValid);o(l),0===t.length?x("No valid users found in the CSV. Please check the errors below."):t.length{x("Failed to parse CSV file: ".concat(e.message)),o([])},header:!1}),!1),accept:".csv",maxCount:1,showUploadList:!1,children:(0,c.jsxs)("div",{className:"border-2 border-dashed border-gray-300 rounded-lg p-8 text-center hover:border-blue-500 transition-colors cursor-pointer",children:[(0,c.jsx)(en.Z,{className:"text-3xl text-gray-400 mb-2"}),(0,c.jsx)("p",{className:"mb-1",children:"Drag and drop your CSV file here"}),(0,c.jsx)("p",{className:"text-sm text-gray-500 mb-3",children:"or"}),(0,c.jsx)(k.Z,{size:"sm",children:"Browse files"})]})})})]}):(0,c.jsxs)("div",{className:"mb-6",children:[(0,c.jsxs)("div",{className:"flex items-center mb-4",children:[(0,c.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 text-white flex items-center justify-center mr-3",children:"3"}),(0,c.jsx)("h3",{className:"text-lg font-medium",children:i.some(e=>"success"===e.status||"failed"===e.status)?"User Creation Results":"Review and create users"})]}),h&&(0,c.jsx)("div",{className:"ml-11 mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:(0,c.jsx)(A.Z,{className:"text-red-600 font-medium",children:h})}),(0,c.jsxs)("div",{className:"ml-11",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-3",children:[(0,c.jsx)("div",{className:"flex items-center",children:i.some(e=>"success"===e.status||"failed"===e.status)?(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"Creation Summary"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-green-100 text-green-800 px-2 py-1 rounded mr-2",children:[i.filter(e=>"success"===e.status).length," Successful"]}),i.some(e=>"failed"===e.status)&&(0,c.jsxs)(A.Z,{className:"text-sm bg-red-100 text-red-800 px-2 py-1 rounded",children:[i.filter(e=>"failed"===e.status).length," Failed"]})]}):(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{className:"text-lg font-medium mr-3",children:"User Preview"}),(0,c.jsxs)(A.Z,{className:"text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded",children:[i.filter(e=>e.isValid).length," of ",i.length," users valid"]})]})}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex space-x-3",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]})]}),i.some(e=>"success"===e.status)&&(0,c.jsx)("div",{className:"mb-4 p-4 bg-blue-50 border border-blue-200 rounded-md",children:(0,c.jsxs)("div",{className:"flex items-start",children:[(0,c.jsx)("div",{className:"mr-3 mt-1",children:(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-blue-500"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium text-blue-800",children:"User creation complete"}),(0,c.jsxs)(A.Z,{className:"block text-sm text-blue-700 mt-1",children:[(0,c.jsx)("span",{className:"font-medium",children:"Next step:"})," Download the credentials file containing API keys and invitation links. Users will need these API keys to make LLM requests through LiteLLM."]})]})]})}),(0,c.jsx)(ea.Z,{dataSource:i,columns:[{title:"Row",dataIndex:"rowNumber",key:"rowNumber",width:80},{title:"Email",dataIndex:"user_email",key:"user_email"},{title:"Role",dataIndex:"user_role",key:"user_role"},{title:"Teams",dataIndex:"teams",key:"teams"},{title:"Budget",dataIndex:"max_budget",key:"max_budget"},{title:"Status",key:"status",render:(e,s)=>s.isValid?s.status&&"pending"!==s.status?"success"===s.status?(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}),(0,c.jsx)("span",{className:"text-green-500",children:"Success"})]}),s.invitation_link&&(0,c.jsx)("div",{className:"mt-1",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-xs text-gray-500 truncate max-w-[150px]",children:s.invitation_link}),(0,c.jsx)(P.CopyToClipboard,{text:s.invitation_link,onCopy:()=>D.ZP.success("Invitation link copied!"),children:(0,c.jsx)("button",{className:"ml-1 text-blue-500 text-xs hover:text-blue-700",children:"Copy"})})]})})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Failed"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:JSON.stringify(s.error)})]}):(0,c.jsx)("span",{className:"text-gray-500",children:"Pending"}):(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsx)("span",{className:"text-red-500",children:"Invalid"})]}),s.error&&(0,c.jsx)("span",{className:"text-sm text-red-500 ml-7",children:s.error})]})}],size:"small",pagination:{pageSize:5},scroll:{y:300},rowClassName:e=>e.isValid?"":"bg-red-50"}),!i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Back"}),(0,c.jsx)(k.Z,{onClick:_,disabled:0===i.filter(e=>e.isValid).length||m,children:m?"Creating...":"Create ".concat(i.filter(e=>e.isValid).length," Users")})]}),i.some(e=>"success"===e.status||"failed"===e.status)&&(0,c.jsxs)("div",{className:"flex justify-end mt-4",children:[(0,c.jsx)(k.Z,{onClick:()=>{o([]),x(null)},variant:"secondary",className:"mr-3",children:"Start New Bulk Import"}),(0,c.jsxs)(k.Z,{onClick:()=>{let e=i.map(e=>({user_email:e.user_email,user_role:e.user_role,status:e.status,key:e.key||"",invitation_link:e.invitation_link||"",error:e.error||""})),s=new Blob([eo().unparse(e)],{type:"text/csv"}),l=window.URL.createObjectURL(s),t=document.createElement("a");t.href=l,t.download="bulk_users_results.csv",document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(l)},variant:"primary",className:"flex items-center",children:[(0,c.jsx)(er.Z,{className:"mr-2"})," Download User Credentials"]})]})]})]})})})]})};let{Option:eu}=O.default;var eh=e=>{let{userID:s,accessToken:l,teams:t,possibleUIRoles:a,onUserCreated:r,isEmbedded:n=!1}=e,[i,o]=(0,d.useState)(null),[u]=L.Z.useForm(),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),N=(0,m.useRouter)(),[w,P]=(0,d.useState)("http://localhost:4000");(0,d.useEffect)(()=>{(async()=>{try{let e=await (0,y.So)(l,s,"any"),t=[];for(let s=0;s{N&&P(new URL("/",window.location.href).toString())},[N]);let F=async e=>{var t,a,o;try{D.ZP.info("Making API Call"),n||x(!0),e.models&&0!==e.models.length||(e.models=["no-default-models"]),console.log("formValues in create user:",e);let a=await (0,y.Ov)(l,null,e);console.log("user create Response:",a),g(!0);let o=(null===(t=a.data)||void 0===t?void 0:t.user_id)||a.user_id;if(r&&n){r(o),u.resetFields();return}if(null==i?void 0:i.SSO_ENABLED){let e={id:crypto.randomUUID(),user_id:o,is_accepted:!1,accepted_at:null,expires_at:new Date(Date.now()+6048e5),created_at:new Date,created_by:s,updated_at:new Date,updated_by:s,has_user_setup_sso:!0};Z(e),v(!0)}else(0,y.XO)(l,o).then(e=>{e.has_user_setup_sso=!1,Z(e),v(!0)});D.ZP.success("API user Created"),u.resetFields(),localStorage.removeItem("userData"+s)}catch(s){let e=(null===(o=s.response)||void 0===o?void 0:null===(a=o.data)||void 0===a?void 0:a.detail)||(null==s?void 0:s.message)||"Error creating the user";D.ZP.error(e),console.error("Error creating the user:",s)}};return n?(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]}):(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{className:"mx-auto mb-0",onClick:()=>x(!0),children:"+ Invite User"}),(0,c.jsx)(em,{accessToken:l,teams:t,possibleUIRoles:a}),(0,c.jsxs)(M.Z,{title:"Invite User",visible:h,width:800,footer:null,onOk:()=>{x(!1),u.resetFields()},onCancel:()=>{x(!1),g(!1),u.resetFields()},children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Create a User who can own keys"}),(0,c.jsxs)(L.Z,{form:u,onFinish:F,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"User Email",name:"user_email",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Global Proxy Role"," ",(0,c.jsx)(W.Z,{title:"This is the role that the user will globally on the proxy. This role is independent of any team/org specific roles.",children:(0,c.jsx)(J.Z,{})})]}),name:"user_role",children:(0,c.jsx)(O.default,{children:a&&Object.entries(a).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Team ID",className:"gap-2",name:"team_id",help:"If selected, user will be added as a 'user' role to the team.",children:(0,c.jsx)(O.default,{placeholder:"Select Team ID",style:{width:"100%"},children:t?t.map(e=>(0,c.jsx)(eu,{value:e.team_id,children:e.team_alias},e.team_id)):(0,c.jsx)(eu,{value:null,children:"Default Team"},"default")})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{children:"Personal Key Creation"})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(L.Z.Item,{className:"gap-2",label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Models user has access to, outside of team scope.",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",help:"Models user has access to, outside of team scope.",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),j.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create User"})})]})]}),p&&(0,c.jsx)(el,{isInvitationLinkModalVisible:_,setIsInvitationLinkModalVisible:v,baseUrl:w,invitationLinkData:b})]})},ex=l(7310),ep=l.n(ex),eg=l(20347);let{Option:ej}=O.default,ef=e=>e?({"24h":"daily","7d":"weekly","30d":"monthly"})[e]||e:"Not set";var e_=e=>{let{value:s,onChange:l,className:t="",style:a={}}=e;return(0,c.jsxs)(O.default,{style:{width:"100%",...a},value:s||void 0,onChange:l,className:t,placeholder:"n/a",children:[(0,c.jsx)(ej,{value:"24h",children:"daily"}),(0,c.jsx)(ej,{value:"7d",children:"weekly"}),(0,c.jsx)(ej,{value:"30d",children:"monthly"})]})};let{Option:ey}=O.default,ev=e=>{let s=[];if(console.log("data:",JSON.stringify(e)),e)for(let l of e)l.metadata&&l.metadata.tags&&s.push(...l.metadata.tags);let l=Array.from(new Set(s)).map(e=>({value:e,label:e}));return console.log("uniqueTags:",l),l},eb=async(e,s,l,t)=>{try{if(null===e||null===s)return[];if(null!==l){let a=(await (0,y.So)(l,e,s,!0,t)).data.map(e=>e.id);return console.log("available_model_names:",a),a}return[]}catch(e){return console.error("Error fetching user models:",e),[]}},eZ=async(e,s,l,t)=>{try{if(null===e||null===s)return;if(null!==l){let a=(await (0,y.So)(l,e,s)).data.map(e=>e.id);console.log("available_model_names:",a),t(a)}}catch(e){console.error("Error fetching user models:",e)}};var eN=e=>{let{userID:s,team:l,teams:t,userRole:a,accessToken:r,data:n,setData:i}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)("you"),[U,V]=(0,d.useState)(ev(n)),[B,H]=(0,d.useState)([]),[G,Y]=(0,d.useState)(l),[$,ee]=(0,d.useState)(!1),[es,el]=(0,d.useState)(null),[et,ea]=(0,d.useState)({}),[er,en]=(0,d.useState)([]),[ei,eo]=(0,d.useState)(!1),ec=()=>{u(!1),o.resetFields()},ed=()=>{u(!1),x(null),Y(null),o.resetFields()};(0,d.useEffect)(()=>{s&&a&&r&&eZ(s,a,r,f)},[r,s,a]),(0,d.useEffect)(()=>{(async()=>{try{let e=(await (0,y.t3)(r)).guardrails.map(e=>e.guardrail_name);H(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[r]),(0,d.useEffect)(()=>{(async()=>{try{if(r){let e=sessionStorage.getItem("possibleUserRoles");if(e)ea(JSON.parse(e));else{let e=await (0,y.lg)(r);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),ea(e)}}}catch(e){console.error("Error fetching possible user roles:",e)}})()},[r]);let em=async e=>{try{var l,t,a;let c=null!==(l=null==e?void 0:e.key_alias)&&void 0!==l?l:"",d=null!==(t=null==e?void 0:e.team_id)&&void 0!==t?t:null;if((null!==(a=null==n?void 0:n.filter(e=>e.team_id===d).map(e=>e.key_alias))&&void 0!==a?a:[]).includes(c))throw Error("Key alias ".concat(c," already exists for team with ID ").concat(d,", please provide another key alias"));if(D.ZP.info("Making API Call"),u(!0),"you"===b&&(e.user_id=s),"service_account"===b){let s={};try{s=JSON.parse(e.metadata||"{}")}catch(e){console.error("Error parsing metadata:",e)}s.service_account_id=e.key_alias,e.metadata=JSON.stringify(s)}let m=await (0,y.wX)(r,s,e);console.log("key create Response:",m),i(e=>e?[...e,m]:[m]),window.addNewKeyToList&&window.addNewKeyToList(m),x(m.key),g(m.soft_budget),D.ZP.success("API Key Created"),o.resetFields(),localStorage.removeItem("userData"+s)}catch(e){console.log("error in create key:",e),D.ZP.error("Error creating the key: ".concat(e))}};(0,d.useEffect)(()=>{if(s&&a&&r){var e;eb(s,a,r,null!==(e=null==G?void 0:G.team_id)&&void 0!==e?e:null).then(e=>{var s;v(Array.from(new Set([...null!==(s=null==G?void 0:G.models)&&void 0!==s?s:[],...e])))})}o.setFieldValue("models",[])},[G,r,s,a]);let eu=async e=>{if(!e){en([]);return}eo(!0);try{let s=new URLSearchParams;if(s.append("user_email",e),null==r)return;let l=(await (0,y.u5)(r,s)).map(e=>({label:"".concat(e.user_email," (").concat(e.user_id,")"),value:e.user_id,user:e}));en(l)}catch(e){console.error("Error fetching users:",e),D.ZP.error("Failed to search for users")}finally{eo(!1)}},ex=(0,d.useCallback)(ep()(e=>eu(e),300),[r]),ej=(e,s)=>{let l=s.user;o.setFieldsValue({user_id:l.user_id})};return(0,c.jsxs)("div",{children:[a&&eg.LQ.includes(a)&&(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>u(!0),children:"+ Create New Key"}),(0,c.jsx)(M.Z,{visible:m,width:1e3,footer:null,onOk:ec,onCancel:ed,children:(0,c.jsxs)(L.Z,{form:o,onFinish:em,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Ownership"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Owned By"," ",(0,c.jsx)(W.Z,{title:"Select who will own this API key",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),className:"mb-4",children:(0,c.jsxs)(F.ZP.Group,{onChange:e=>Z(e.target.value),value:b,children:[(0,c.jsx)(F.ZP,{value:"you",children:"You"}),(0,c.jsx)(F.ZP,{value:"service_account",children:"Service Account"}),"Admin"===a&&(0,c.jsx)(F.ZP,{value:"another_user",children:"Another User"})]})}),"another_user"===b&&(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["User ID"," ",(0,c.jsx)(W.Z,{title:"The user who will own this key and be responsible for its usage",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"user_id",className:"mt-4",rules:[{required:"another_user"===b,message:"Please input the user ID of the user you are assigning the key to"}],children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",marginBottom:"8px"},children:[(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Type email to search for users",filterOption:!1,onSearch:e=>{ex(e)},onSelect:(e,s)=>ej(e,s),options:er,loading:ei,allowClear:!0,style:{width:"100%"},notFoundContent:ei?"Searching...":"No users found"}),(0,c.jsx)(R.ZP,{onClick:()=>ee(!0),style:{marginLeft:"8px"},children:"Create User"})]}),(0,c.jsx)("div",{className:"text-xs text-gray-500",children:"Search by email to find users"})]})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Team"," ",(0,c.jsx)(W.Z,{title:"The team this key belongs to, which determines available models and budget limits",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"team_id",initialValue:l?l.team_id:null,className:"mt-4",children:(0,c.jsx)(Q,{teams:t,onChange:e=>{Y((null==t?void 0:t.find(s=>s.team_id===e))||null)}})})]}),(0,c.jsxs)("div",{className:"mb-8",children:[(0,c.jsx)(E.Z,{className:"mb-4",children:"Key Details"}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["you"===b||"another_user"===b?"Key Name":"Service Account ID"," ",(0,c.jsx)(W.Z,{title:"you"===b||"another_user"===b?"A descriptive name to identify this key":"Unique identifier for this service account",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"key_alias",rules:[{required:!0,message:"Please input a ".concat("you"===b?"key name":"service account ID")}],help:"required",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"Select which models this key can access. Choose 'All Team Models' to grant access to all models available to the team",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",className:"mt-4",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},onChange:e=>{e.includes("all-team-models")&&o.setFieldsValue({models:["all-team-models"]})},children:[(0,c.jsx)(ey,{value:"all-team-models",children:"All Team Models"},"all-team-models"),_.map(e=>(0,c.jsx)(ey,{value:e,children:K(e)},e))]})})]}),(0,c.jsx)("div",{className:"mb-8",children:(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)(E.Z,{className:"m-0",children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Max Budget (USD)"," ",(0,c.jsx)(W.Z,{title:"Maximum amount in USD this key can spend. When reached, the key will be blocked from making further requests",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"max_budget",help:"Budget cannot exceed team max budget: $".concat((null==l?void 0:l.max_budget)!==null&&(null==l?void 0:l.max_budget)!==void 0?null==l?void 0:l.max_budget:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.max_budget&&s>l.max_budget)throw Error("Budget cannot exceed team max budget: $".concat(l.max_budget))}}],children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Reset Budget"," ",(0,c.jsx)(W.Z,{title:"How often the budget should reset. For example, setting 'daily' will reset the budget every 24 hours",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"budget_duration",help:"Team Reset Budget: ".concat((null==l?void 0:l.budget_duration)!==null&&(null==l?void 0:l.budget_duration)!==void 0?null==l?void 0:l.budget_duration:"None"),children:(0,c.jsx)(e_,{onChange:e=>o.setFieldValue("budget_duration",e)})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Tokens per minute Limit (TPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of tokens this key can process per minute. Helps control usage and costs",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tpm_limit",help:"TPM cannot exceed team TPM limit: ".concat((null==l?void 0:l.tpm_limit)!==null&&(null==l?void 0:l.tpm_limit)!==void 0?null==l?void 0:l.tpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.tpm_limit&&s>l.tpm_limit)throw Error("TPM limit cannot exceed team TPM limit: ".concat(l.tpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{className:"mt-4",label:(0,c.jsxs)("span",{children:["Requests per minute Limit (RPM)"," ",(0,c.jsx)(W.Z,{title:"Maximum number of API requests this key can make per minute. Helps prevent abuse and manage load",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"rpm_limit",help:"RPM cannot exceed team RPM limit: ".concat((null==l?void 0:l.rpm_limit)!==null&&(null==l?void 0:l.rpm_limit)!==void 0?null==l?void 0:l.rpm_limit:"unlimited"),rules:[{validator:async(e,s)=>{if(s&&l&&null!==l.rpm_limit&&s>l.rpm_limit)throw Error("RPM limit cannot exceed team RPM limit: ".concat(l.rpm_limit))}}],children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Expire Key"," ",(0,c.jsx)(W.Z,{title:"Set when this key should expire. Format: 30s (seconds), 30m (minutes), 30h (hours), 30d (days)",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"duration",className:"mt-4",children:(0,c.jsx)(S.Z,{placeholder:"e.g., 30d"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Apply safety guardrails to this key to filter content or enforce policies",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-4",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:B.map(e=>({value:e,label:e}))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Metadata"," ",(0,c.jsx)(W.Z,{title:"JSON object with additional information about this key. Used for tracking or custom logic",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"metadata",className:"mt-4",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:"Enter metadata as JSON"})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Tags"," ",(0,c.jsx)(W.Z,{title:"Tags for tracking spend and/or doing tag-based routing. Used for analytics and filtering",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"tags",className:"mt-4",help:"Tags for tracking spend and/or doing tag-based routing.",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Enter tags",tokenSeparators:[","],options:U})}),(0,c.jsxs)(C.Z,{className:"mt-4 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("b",{children:"Advanced Settings"}),(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Learn more about advanced settings in our"," ",(0,c.jsx)("a",{href:y.H2?"".concat(y.H2,"/#/key%20management/generate_key_fn_key_generate_post"):"/#/key%20management/generate_key_fn_key_generate_post",target:"_blank",rel:"noopener noreferrer",className:"text-blue-400 hover:text-blue-300",children:"documentation"})]}),children:(0,c.jsx)(J.Z,{className:"text-gray-400 hover:text-gray-300 cursor-help"})})]})}),(0,c.jsx)(I.Z,{children:(0,c.jsx)(X,{schemaComponent:"GenerateKeyRequest",form:o,excludedFields:["key_alias","team_id","models","duration","metadata","tags","guardrails","max_budget","budget_duration","tpm_limit","rpm_limit"]})})]})]})]})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Key"})})]})}),$&&(0,c.jsx)(M.Z,{title:"Create New User",visible:$,onCancel:()=>ee(!1),footer:null,width:800,children:(0,c.jsx)(eh,{userID:s,accessToken:r,teams:t,possibleUIRoles:et,onUserCreated:e=>{el(e),o.setFieldsValue({user_id:e}),ee(!1)},isEmbedded:!0})}),h&&(0,c.jsx)(M.Z,{visible:m,onOk:ec,onCancel:ed,footer:null,children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Save your Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please save this secret key somewhere safe and accessible. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:null!=h?(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:h})}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>{D.ZP.success("API Key copied to clipboard")},children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]}):(0,c.jsx)(A.Z,{children:"Key being created, this might take 30s"})})]})})]})},ew=l(7366),ek=e=>{let{selectedTeam:s,currentOrg:l,selectedKeyAlias:t,accessToken:a,currentPage:r=1}=e,[n,i]=(0,d.useState)({keys:[],total_count:0,current_page:1,total_pages:0}),[o,c]=(0,d.useState)(!0),[m,u]=(0,d.useState)(null),h=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};try{if(console.log("calling fetchKeys"),!a){console.log("accessToken",a);return}c(!0);let r=await (0,y.OD)(a,(null==l?void 0:l.organization_id)||null,(null==s?void 0:s.team_id)||"",t,e.page||1,50);console.log("data",r),i(r),u(null)}catch(e){u(e instanceof Error?e:Error("An error occurred"))}finally{c(!1)}};return(0,d.useEffect)(()=>{h(),console.log("selectedTeam",s,"currentOrg",l,"accessToken",a,"selectedKeyAlias",t)},[s,l,a,t]),{keys:n.keys,isLoading:o,error:m,pagination:{currentPage:n.current_page,totalPages:n.total_pages,totalCount:n.total_count},refresh:h,setKeys:e=>{i(s=>{let l="function"==typeof e?e(s.keys):e;return{...s,keys:l}})}}},eS=l(71594),eC=l(24525),eI=l(21626),eT=l(97214),eA=l(28241),eE=l(58834),eP=l(69552),eO=l(71876);function eL(e){let{data:s=[],columns:l,getRowCanExpand:t,renderSubComponent:a,isLoading:r=!1,expandedRequestId:n,onRowExpand:i}=e,o=(0,eS.b7)({data:s,columns:l,getRowCanExpand:t,getCoreRowModel:(0,eC.sC)(),getExpandedRowModel:(0,eC.rV)(),state:{expanded:n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{}},onExpandedChange:e=>{if(!i)return;let l=n?s.reduce((e,s,l)=>(s.request_id===n&&(e[l]=!0),e),{}):{},t="function"==typeof e?e(l):e;if(0===Object.keys(t).length){i(null);return}let a=Object.keys(t)[0],r=void 0!==a?s[parseInt(a)]:null;i(r?r.request_id:null)}});return(0,c.jsx)("div",{className:"rounded-lg custom-border",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:r?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading logs..."})})})}):o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap",children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))}),e.getIsExpanded()&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:e.getVisibleCells().length,children:a({row:e})})})]},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No logs found"})})})})})]})})}var eD=l(27281),eM=l(41649),eF=l(12514),eR=l(12485),eq=l(18135),eU=l(35242),ez=l(29706),eV=l(77991),eK=l(10900),eB=l(23628),eH=l(74998);function eJ(e){var s,l;let{keyData:t,onCancel:a,onSubmit:r,teams:n,accessToken:i,userID:o,userRole:m}=e,[u]=L.Z.useForm(),[h,x]=(0,d.useState)([]),p=null==n?void 0:n.find(e=>e.team_id===t.team_id),[g,j]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(o&&m&&i)try{if(null===t.team_id){let e=(await (0,y.So)(i,o,m)).data.map(e=>e.id);j(e)}else if(null==p?void 0:p.team_id){let e=await eb(o,m,i,p.team_id);j(Array.from(new Set([...p.models,...e])))}}catch(e){console.error("Error fetching models:",e)}})()},[o,m,i,p,t.team_id]);let f={...t,budget_duration:(l=t.budget_duration)&&({"24h":"daily","7d":"weekly","30d":"monthly"})[l]||null,metadata:t.metadata?JSON.stringify(t.metadata,null,2):"",guardrails:(null===(s=t.metadata)||void 0===s?void 0:s.guardrails)||[]};return(0,c.jsxs)(L.Z,{form:u,onFinish:r,initialValues:f,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Key Alias",name:"key_alias",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[g.length>0&&(0,c.jsx)(O.default.Option,{value:"all-team-models",children:"All Team Models"}),g.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,style:{width:"100%"},placeholder:"Enter a numerical value"})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"daily",children:"Daily"}),(0,c.jsx)(O.default.Option,{value:"weekly",children:"Weekly"}),(0,c.jsx)(O.default.Option,{value:"monthly",children:"Monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"TPM Limit",name:"tpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"RPM Limit",name:"rpm_limit",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Max Parallel Requests",name:"max_parallel_requests",children:(0,c.jsx)(z,{min:0})}),(0,c.jsx)(L.Z.Item,{label:"Model TPM Limit",name:"model_tpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Model RPM Limit",name:"model_rpm_limit",children:(0,c.jsx)(q.default.TextArea,{rows:4,placeholder:'{"gpt-4": 100, "claude-v1": 200}'})}),(0,c.jsx)(L.Z.Item,{label:"Guardrails",name:"guardrails",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsx)(L.Z.Item,{name:"token",hidden:!0,children:(0,c.jsx)(q.default,{})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(k.Z,{variant:"light",onClick:a,children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]})}function eW(e){let{selectedToken:s,visible:l,onClose:t,accessToken:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(!1);(0,d.useEffect)(()=>{l&&s&&r.setFieldsValue({key_alias:s.key_alias,max_budget:s.max_budget,tpm_limit:s.tpm_limit,rpm_limit:s.rpm_limit,duration:s.duration||""})},[l,s,r]),(0,d.useEffect)(()=>{l||(i(null),p(!1),r.resetFields())},[l,r]),(0,d.useEffect)(()=>{(null==o?void 0:o.duration)?h((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString()}catch(e){return null}})(o.duration)):h(null)},[null==o?void 0:o.duration]);let g=async()=>{if(s&&a){p(!0);try{let e=await r.validateFields(),l=await (0,y.s0)(a,s.token,e);i(l.key),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key"),p(!1)}}},j=()=>{i(null),p(!1),r.resetFields(),t()};return(0,c.jsx)(M.Z,{title:"Regenerate API Key",open:l,onCancel:j,footer:n?[(0,c.jsx)(k.Z,{onClick:j,children:"Close"},"close")]:[(0,c.jsx)(k.Z,{onClick:j,className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:g,disabled:x,children:x?"Regenerating...":"Regenerate"},"regenerate")],children:n?(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:(null==s?void 0:s.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{className:"bg-gray-100 p-2 rounded mb-2",children:(0,c.jsx)("pre",{className:"break-words whitespace-normal",children:n})}),(0,c.jsx)(P.CopyToClipboard,{text:n,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]}):(0,c.jsxs)(L.Z,{form:r,layout:"vertical",onValuesChange:e=>{"duration"in e&&m(s=>({...s,duration:e.duration}))},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry: ",(null==s?void 0:s.expires)?new Date(s.expires).toLocaleString():"Never"]}),u&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",u]})]})})}function eG(e){var s,l;let{keyId:t,onClose:a,keyData:r,accessToken:n,userID:i,userRole:o,teams:m,onKeyDataUpdate:u,onDelete:h}=e,[x,p]=(0,d.useState)(!1),[g]=L.Z.useForm(),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1);if(!r)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(A.Z,{children:"Key not found"})]});let b=async e=>{try{var s,l;if(!n)return;let t=e.token;if(e.key=t,e.metadata&&"string"==typeof e.metadata)try{let l=JSON.parse(e.metadata);e.metadata={...l,...(null===(s=e.guardrails)||void 0===s?void 0:s.length)>0?{guardrails:e.guardrails}:{}}}catch(e){console.error("Error parsing metadata JSON:",e),D.ZP.error("Invalid metadata JSON");return}else e.metadata={...e.metadata||{},...(null===(l=e.guardrails)||void 0===l?void 0:l.length)>0?{guardrails:e.guardrails}:{}};e.budget_duration&&(e.budget_duration=({daily:"24h",weekly:"7d",monthly:"30d"})[e.budget_duration]);let a=await (0,y.Nc)(n,e);u&&u(a),D.ZP.success("Key updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update key"),console.error("Error updating key:",e)}},Z=async()=>{try{if(!n)return;await (0,y.I1)(n,r.token),D.ZP.success("Key deleted successfully"),h&&h(),a()}catch(e){console.error("Error deleting the key:",e),D.ZP.error("Failed to delete key")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:a,className:"mb-4",children:"Back to Keys"}),(0,c.jsx)(E.Z,{children:r.key_alias||"API Key"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:r.token})]}),o&&eg.LQ.includes(o)&&(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{icon:eB.Z,variant:"secondary",onClick:()=>v(!0),className:"flex items-center",children:"Regenerate Key"}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>f(!0),className:"flex items-center",children:"Delete Key"})]})]}),(0,c.jsx)(eW,{selectedToken:r,visible:_,onClose:()=>v(!1),accessToken:n}),j&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:Z,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>f(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number(r.spend).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",null!==r.max_budget?"$".concat(r.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Key Settings"}),!x&&o&&eg.LQ.includes(o)&&(0,c.jsx)(k.Z,{variant:"light",onClick:()=>p(!0),children:"Edit Settings"})]}),x?(0,c.jsx)(eJ,{keyData:r,onCancel:()=>p(!1),onSubmit:b,teams:m,accessToken:n,userID:i,userRole:o}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.token})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Key Alias"}),(0,c.jsx)(A.Z,{children:r.key_alias||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Secret Key"}),(0,c.jsx)(A.Z,{className:"font-mono",children:r.key_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)(A.Z,{children:r.team_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),(0,c.jsx)(A.Z,{children:r.organization_id||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:new Date(r.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Expires"}),(0,c.jsx)(A.Z,{children:r.expires?new Date(r.expires).toLocaleString():"Never"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Spend"}),(0,c.jsxs)(A.Z,{children:["$",Number(r.spend).toFixed(4)," USD"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsx)(A.Z,{children:null!==r.max_budget?"$".concat(r.max_budget," USD"):"Unlimited"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:r.models&&r.models.length>0?r.models.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):(0,c.jsx)(A.Z,{children:"No models specified"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)(A.Z,{children:["TPM: ",null!==r.tpm_limit?r.tpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",null!==r.rpm_limit?r.rpm_limit:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",null!==r.max_parallel_requests?r.max_parallel_requests:"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model TPM Limits: ",(null===(s=r.metadata)||void 0===s?void 0:s.model_tpm_limit)?JSON.stringify(r.metadata.model_tpm_limit):"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["Model RPM Limits: ",(null===(l=r.metadata)||void 0===l?void 0:l.model_rpm_limit)?JSON.stringify(r.metadata.model_rpm_limit):"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(r.metadata,null,2)})]})]})]})})]})]})]})}var eY=l(87908),e$=l(82422),eX=l(2356),eQ=l(44633),e0=l(86462),e1=l(3837),e2=e=>{var s;let{options:l,onApplyFilters:t,onResetFilters:a,initialValues:r={},buttonLabel:n="Filter"}=e,[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)((null===(s=l[0])||void 0===s?void 0:s.name)||""),[h,x]=(0,d.useState)(r),[p,j]=(0,d.useState)(r),[f,_]=(0,d.useState)(!1),[y,v]=(0,d.useState)([]),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),S=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=e=>{let s=e.target;!S.current||S.current.contains(s)||s.closest(".ant-dropdown")||s.closest(".ant-select-dropdown")||o(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{l.length>0&&l[0].isSearchable&&l[0].searchFn&&C(l[0])},[]);let C=async e=>{if(e.isSearchable&&e.searchFn){Z(!0);try{let s=await e.searchFn("");v(s)}catch(e){console.error("Error loading initial options:",e),v([])}finally{Z(!1)}}};(0,d.useEffect)(()=>{i&&(null==L?void 0:L.isSearchable)&&(null==L?void 0:L.searchFn)&&C(L)},[i,m]);let I=e=>{u(e),_(!1);let s=l.find(s=>s.name===e);(null==s?void 0:s.isSearchable)&&(null==s?void 0:s.searchFn)?C(s):v([])},T=(0,d.useCallback)(ep()(async(e,s)=>{if(s.isSearchable&&s.searchFn){Z(!0);try{let l=await s.searchFn(e);v(l)}catch(e){console.error("Error searching:",e),v([])}finally{Z(!1)}}},300),[]),A=e=>{j(s=>({...s,[m]:e}))},E=()=>{let e={};l.forEach(s=>{e[s.name]=""}),j(e)},P=l.map(e=>({key:e.name,label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[m===e.name&&(0,c.jsx)(e$.Z,{className:"h-4 w-4 text-blue-600"}),e.label||e.name]})})),L=l.find(e=>e.name===m);return(0,c.jsxs)("div",{className:"relative",ref:S,children:[(0,c.jsx)(k.Z,{icon:eX.Z,onClick:()=>o(!i),variant:"secondary",size:"xs",className:"flex items-center pr-2",children:n}),i&&(0,c.jsx)(eF.Z,{className:"absolute left-0 mt-2 w-[500px] z-50 border border-gray-200 shadow-lg",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsx)(g.Z,{menu:{items:P,onClick:e=>{let{key:s}=e;return I(s)},style:{minWidth:"200px"}},onOpenChange:_,open:f,trigger:["click"],children:(0,c.jsxs)(R.ZP,{className:"min-w-40 text-left flex justify-between items-center",children:[(null==L?void 0:L.label)||m,f?(0,c.jsx)(eQ.Z,{className:"h-4 w-4"}):(0,c.jsx)(e0.Z,{className:"h-4 w-4"})]})}),(null==L?void 0:L.isSearchable)?(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Search ".concat(L.label||m,"..."),value:p[m]||void 0,onChange:e=>A(e),onSearch:e=>{w(e),T(e,L)},onInputKeyDown:e=>{"Enter"===e.key&&N&&(A(N),e.preventDefault())},filterOption:!1,className:"flex-1 w-full max-w-full truncate min-w-100",loading:b,options:y,allowClear:!0,notFoundContent:b?(0,c.jsx)(eY.Z,{size:"small"}):(0,c.jsx)("div",{className:"p-2",children:N&&(0,c.jsxs)(R.ZP,{type:"link",className:"p-0 mt-1",onClick:()=>{A(N);let e=document.activeElement;e&&e.blur()},children:["Use “",N,"” as filter value"]})})}):(0,c.jsx)(q.default,{placeholder:"Enter value...",value:p[m]||"",onChange:e=>A(e.target.value),className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",suffix:p[m]?(0,c.jsx)(e1.Z,{className:"h-4 w-4 cursor-pointer text-gray-400 hover:text-gray-500",onClick:e=>{e.stopPropagation(),A("")}}):null})]}),(0,c.jsxs)("div",{className:"flex gap-2 justify-end",children:[(0,c.jsx)(R.ZP,{onClick:()=>{E(),a(),o(!1)},children:"Reset"}),(0,c.jsx)(R.ZP,{onClick:()=>{x(p),t(p),o(!1)},children:"Apply Filters"})]})]})})]})},e4=l(16593);let e5=async e=>{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.OD)(e,null,"",null,l,100),r=a.keys.map(e=>e.key_alias).filter(Boolean);s=[...s,...r],l{if(!e)return[];try{let l=[],t=1,a=!0;for(;a;){let r=await (0,y.It)(e,s||null,null);l=[...l,...r.teams],t{if(!e)return[];try{let s=[],l=1,t=!0;for(;t;){let a=await (0,y.r6)(e);s=[...s,...a.organizations],l{if(!s){g([]);return}let e=[...s];o["Team ID"]&&(e=e.filter(e=>e.team_id===o["Team ID"])),o["Organization ID"]&&(e=e.filter(e=>e.organization_id===o["Organization ID"])),g(e)},[s,o]),(0,d.useEffect)(()=>{let e=async()=>{let e=await e6(a);e.length>0&&u(e);let s=await e3(a);s.length>0&&x(s)};a&&e()},[a]);let j=(0,e4.a)({queryKey:["allKeys"],queryFn:async()=>{if(!a)throw Error("Access token required");return await e5(a)},enabled:!!a}).data||[];return(0,d.useEffect)(()=>{l&&l.length>0&&u(e=>e.length{t&&t.length>0&&x(e=>e.length{if(c({"Team ID":e["Team ID"]||"","Organization ID":e["Organization ID"]||"","Key Alias":e["Key Alias"]||""}),e["Team ID"]){let s=null==m?void 0:m.find(s=>s.team_id===e["Team ID"]);s&&r(s)}if(e["Organization ID"]){let s=null==h?void 0:h.find(s=>s.organization_id===e["Organization ID"]);s&&n(s)}let s=e["Key Alias"];i(s&&j.find(e=>e===s)||null)},handleFilterReset:()=>{c({"Team ID":"","Organization ID":"","Key Alias":""}),r(null),n(null)}}}({keys:s,teams:i,organizations:j,accessToken:x,setSelectedTeam:m,setCurrentOrg:f,setSelectedKeyAlias:h});(0,d.useEffect)(()=>{if(x){let e=s.map(e=>e.user_id).filter(e=>null!==e);(async()=>{N((await (0,y.Of)(x,e,1,100)).users)})()}},[x,s]),(0,d.useEffect)(()=>{if(_){let e=()=>{_()};return window.addEventListener("storage",e),()=>{window.removeEventListener("storage",e)}}},[_]);let P=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return s.getCanExpand()?(0,c.jsx)("button",{onClick:s.getToggleExpandedHandler(),style:{cursor:"pointer"},children:s.getIsExpanded()?"▼":"▶"}):null}},{header:"Key ID",accessorKey:"token",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>b(e.getValue()),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>{let s=e.getValue();return(0,c.jsx)(W.Z,{title:s,children:s?s.length>20?"".concat(s.slice(0,20),"..."):s:"-"})}},{header:"Secret Key",accessorKey:"key_name",cell:e=>(0,c.jsx)("span",{className:"font-mono text-xs",children:e.getValue()})},{header:"Team Alias",accessorKey:"team_id",cell:e=>{let{row:s,getValue:l}=e,t=l(),a=null==I?void 0:I.find(e=>e.team_id===t);return(null==a?void 0:a.team_alias)||"Unknown"}},{header:"Team ID",accessorKey:"team_id",cell:e=>(0,c.jsx)(W.Z,{title:e.getValue(),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})},{header:"Organization ID",accessorKey:"organization_id",cell:e=>e.getValue()?e.renderValue():"-"},{header:"User Email",accessorKey:"user_id",cell:e=>{let s=e.getValue(),l=Z.find(e=>e.user_id===s);return(null==l?void 0:l.user_email)?l.user_email:"-"}},{header:"User ID",accessorKey:"user_id",cell:e=>{let s=e.getValue();return s?(0,c.jsx)(W.Z,{title:s,children:(0,c.jsxs)("span",{children:[s.slice(0,7),"..."]})}):"-"}},{header:"Created At",accessorKey:"created_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"-"}},{header:"Created By",accessorKey:"created_by",cell:e=>e.getValue()||"Unknown"},{header:"Expires",accessorKey:"expires",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleDateString():"Never"}},{header:"Spend (USD)",accessorKey:"spend",cell:e=>Number(e.getValue()).toFixed(4)},{header:"Budget (USD)",accessorKey:"max_budget",cell:e=>null!==e.getValue()&&void 0!==e.getValue()?e.getValue():"Unlimited"},{header:"Budget Reset",accessorKey:"budget_reset_at",cell:e=>{let s=e.getValue();return s?new Date(s).toLocaleString():"Never"}},{header:"Models",accessorKey:"models",cell:e=>{let s=e.getValue();return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:s&&s.length>0?s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e},s)):"-"})}},{header:"Rate Limits",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{children:["TPM: ",null!==l.tpm_limit?l.tpm_limit:"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",null!==l.rpm_limit?l.rpm_limit:"Unlimited"]})]})}}];return(0,c.jsx)("div",{className:"w-full h-full overflow-hidden",children:v?(0,c.jsx)(eG,{keyId:v,onClose:()=>b(null),keyData:s.find(e=>e.token===v),onKeyDataUpdate:e=>{l(s=>s.map(s=>s.token===e.token?e8(s,e):s))},onDelete:()=>{l(e=>e.filter(e=>e.token!==v))},accessToken:x,userID:p,userRole:g,teams:I}):(0,c.jsxs)("div",{className:"border-b py-4 flex-1 overflow-hidden",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between w-full mb-2",children:[(0,c.jsx)(e2,{options:[{name:"Team ID",label:"Team ID",isSearchable:!0,searchFn:async e=>I&&0!==I.length?I.filter(s=>s.team_id.toLowerCase().includes(e.toLowerCase())||s.team_alias&&s.team_alias.toLowerCase().includes(e.toLowerCase())).map(e=>({label:"".concat(e.team_alias||e.team_id," (").concat(e.team_id,")"),value:e.team_id})):[]},{name:"Organization ID",label:"Organization ID",isSearchable:!0,searchFn:async e=>T&&0!==T.length?T.filter(s=>{var l,t;return null!==(t=null===(l=s.organization_id)||void 0===l?void 0:l.toLowerCase().includes(e.toLowerCase()))&&void 0!==t&&t}).filter(e=>null!==e.organization_id&&void 0!==e.organization_id).map(e=>({label:"".concat(e.organization_id||"Unknown"," (").concat(e.organization_id,")"),value:e.organization_id})):[]},{name:"Key Alias",label:"Key Alias",isSearchable:!0,searchFn:async e=>C.filter(s=>s.toLowerCase().includes(e.toLowerCase())).map(e=>({label:e,value:e}))}],onApplyFilters:A,initialValues:w,onResetFilters:E}),(0,c.jsxs)("div",{className:"flex items-center gap-4",children:[(0,c.jsxs)("span",{className:"inline-flex text-sm text-gray-700",children:["Showing ",t?"...":"".concat((a.currentPage-1)*n+1," - ").concat(Math.min(a.currentPage*n,a.totalCount))," of ",t?"...":a.totalCount," results"]}),(0,c.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",t?"...":a.currentPage," of ",t?"...":a.totalPages]}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage-1),disabled:t||1===a.currentPage,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>r(a.currentPage+1),disabled:t||a.currentPage===a.totalPages,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]}),(0,c.jsx)("div",{className:"h-[75vh] overflow-auto",children:(0,c.jsx)(eL,{columns:P.filter(e=>"expander"!==e.id),data:S,isLoading:t,getRowCanExpand:()=>!1,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{})})})]})})}console.log=function(){};var e9=e=>{let{userID:s,userRole:l,accessToken:t,selectedTeam:a,setSelectedTeam:r,data:n,setData:i,teams:o,premiumUser:m,currentOrg:u,organizations:h,setCurrentOrg:x,selectedKeyAlias:p,setSelectedKeyAlias:g}=e,[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(null),[C,I]=(0,d.useState)(null),[T,O]=(0,d.useState)(null),[F,R]=(0,d.useState)((null==a?void 0:a.team_id)||""),[q,U]=(0,d.useState)("");(0,d.useEffect)(()=>{R((null==a?void 0:a.team_id)||"")},[a]);let{keys:z,isLoading:K,error:B,pagination:J,refresh:W,setKeys:G}=ek({selectedTeam:a,currentOrg:u,selectedKeyAlias:p,accessToken:t});window.refreshKeysList=W,window.addNewKeyToList=e=>{G(s=>[e,...s])};let[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(null),[el,et]=(0,d.useState)([]),ea=new Set,[er,en]=(0,d.useState)(!1),[ei,eo]=(0,d.useState)(!1),[ec,ed]=(0,d.useState)(null),[em,eu]=(0,d.useState)(null),[eh]=L.Z.useForm(),[ex,ep]=(0,d.useState)(null),[eg,ej]=(0,d.useState)(ea),[ef,e_]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("in calculateNewExpiryTime for selectedToken",ee),(null==em?void 0:em.duration)?ep((e=>{if(!e)return null;try{let s;let l=new Date;if(e.endsWith("s"))s=(0,ew.Z)(l,{seconds:parseInt(e)});else if(e.endsWith("h"))s=(0,ew.Z)(l,{hours:parseInt(e)});else if(e.endsWith("d"))s=(0,ew.Z)(l,{days:parseInt(e)});else throw Error("Invalid duration format");return s.toLocaleString("en-US",{year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric",hour12:!0})}catch(e){return null}})(em.duration)):ep(null),console.log("calculateNewExpiryTime:",ex)},[ee,null==em?void 0:em.duration]),(0,d.useEffect)(()=>{(async()=>{try{if(null===s||null===l||null===t)return;let e=await V(s,l,t);e&&et(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,s,l]),(0,d.useEffect)(()=>{if(o){let e=new Set;o.forEach((s,l)=>{let t=s.team_id;e.add(t)}),ej(e)}},[o]);let ey=async()=>{if(null!=b&&null!=n){try{await (0,y.I1)(t,b);let e=n.filter(e=>e.token!==b);i(e)}catch(e){console.error("Error deleting the key:",e)}v(!1),Z(null)}},ev=(e,s)=>{eu(l=>({...l,[e]:s}))},eb=async()=>{if(!m){D.ZP.error("Regenerate API Key is an Enterprise feature. Please upgrade to use this feature.");return}if(null!=ee)try{let e=await eh.validateFields(),s=await (0,y.s0)(t,ee.token,e);if(ed(s.key),n){let l=n.map(l=>l.token===(null==ee?void 0:ee.token)?{...l,key_name:s.key_name,...e}:l);i(l)}eo(!1),eh.resetFields(),D.ZP.success("API Key regenerated successfully")}catch(e){console.error("Error regenerating key:",e),D.ZP.error("Failed to regenerate API Key")}};return(0,c.jsxs)("div",{children:[(0,c.jsx)(e7,{keys:z,setKeys:G,isLoading:K,pagination:J,onPageChange:e=>{W({page:e})},pageSize:100,teams:o,selectedTeam:a,setSelectedTeam:r,accessToken:t,userID:s,userRole:l,organizations:h,setCurrentOrg:x,refresh:W,selectedKeyAlias:p,setSelectedKeyAlias:g}),_&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Key"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this key ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ey,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{v(!1),Z(null)},children:"Cancel"})]})]})]})}),(0,c.jsx)(M.Z,{title:"Regenerate API Key",visible:ei,onCancel:()=>{eo(!1),eh.resetFields()},footer:[(0,c.jsx)(k.Z,{onClick:()=>{eo(!1),eh.resetFields()},className:"mr-2",children:"Cancel"},"cancel"),(0,c.jsx)(k.Z,{onClick:eb,disabled:!m,children:m?"Regenerate":"Upgrade to Regenerate"},"regenerate")],children:m?(0,c.jsxs)(L.Z,{form:eh,layout:"vertical",onValuesChange:(e,s)=>{"duration"in e&&ev("duration",e.duration)},children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Key Alias",children:(0,c.jsx)(S.Z,{disabled:!0})}),(0,c.jsx)(L.Z.Item,{name:"max_budget",label:"Max Budget (USD)",children:(0,c.jsx)(H.Z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"tpm_limit",label:"TPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"rpm_limit",label:"RPM Limit",children:(0,c.jsx)(H.Z,{style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{name:"duration",label:"Expire Key (eg: 30s, 30h, 30d)",className:"mt-8",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsxs)("div",{className:"mt-2 text-sm text-gray-500",children:["Current expiry:"," ",(null==ee?void 0:ee.expires)!=null?new Date(ee.expires).toLocaleString():"Never"]}),ex&&(0,c.jsxs)("div",{className:"mt-2 text-sm text-green-600",children:["New expiry: ",ex]})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to use this feature"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://calendly.com/d/4mp-gd3-k5k/litellm-1-1-onboarding-chat",target:"_blank",children:"Get Free Trial"})})]})}),ec&&(0,c.jsx)(M.Z,{visible:!!ec,onCancel:()=>ed(null),footer:[(0,c.jsx)(k.Z,{onClick:()=>ed(null),children:"Close"},"close")],children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full",children:[(0,c.jsx)(E.Z,{children:"Regenerated Key"}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)("p",{children:["Please replace your old key with the new key generated. For security reasons, ",(0,c.jsx)("b",{children:"you will not be able to view it again"})," ","through your LiteLLM account. If you lose this secret key, you will need to generate a new one."]})}),(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(A.Z,{className:"mt-3",children:"Key Alias:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:(null==ee?void 0:ee.key_alias)||"No alias set"})}),(0,c.jsx)(A.Z,{className:"mt-3",children:"New API Key:"}),(0,c.jsx)("div",{style:{background:"#f8f8f8",padding:"10px",borderRadius:"5px",marginBottom:"10px"},children:(0,c.jsx)("pre",{style:{wordWrap:"break-word",whiteSpace:"normal"},children:ec})}),(0,c.jsx)(P.CopyToClipboard,{text:ec,onCopy:()=>D.ZP.success("API Key copied to clipboard"),children:(0,c.jsx)(k.Z,{className:"mt-3",children:"Copy API Key"})})]})]})})]})},se=l(12011);console.log=function(){},console.log("isLocal:",!1);var ss=e=>{let{userID:s,userRole:l,teams:t,keys:a,setUserRole:r,userEmail:n,setUserEmail:i,setTeams:o,setKeys:h,premiumUser:x,organizations:p}=e,[g,j]=(0,d.useState)(null),[f,v]=(0,d.useState)(null),b=(0,m.useSearchParams)(),k=function(e){console.log("COOKIES",document.cookie);let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token"),S=b.get("invitation_id"),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)(null),[E,P]=(0,d.useState)([]),[O,L]=(0,d.useState)(null),[D,M]=(0,d.useState)(null),[F,R]=(0,d.useState)(null);if(window.addEventListener("beforeunload",function(){sessionStorage.clear()}),(0,d.useEffect)(()=>{if(k){let e=(0,u.o)(k);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),I(e.key),e.user_role){let s=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"app_user":return"App User";case"internal_user":return"Internal User";case"internal_user_viewer":return"Internal Viewer";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",s),r(s)}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e))}}if(s&&C&&l&&!a&&!g){let e=sessionStorage.getItem("userModels"+s);e?P(JSON.parse(e)):(console.log("currentOrg: ".concat(JSON.stringify(f))),(async()=>{try{let e=await (0,y.g)(C);L(e);let t=await (0,y.Br)(C,s,l,!1,null,null);j(t.user_info),console.log("userSpendData: ".concat(JSON.stringify(g))),(null==t?void 0:t.teams[0].keys)?h(t.keys.concat(t.teams.filter(e=>"Admin"===l||e.user_id===s).flatMap(e=>e.keys))):h(t.keys),sessionStorage.setItem("userData"+s,JSON.stringify(t.keys)),sessionStorage.setItem("userSpendData"+s,JSON.stringify(t.user_info));let a=(await (0,y.So)(C,s,l)).data.map(e=>e.id);console.log("available_model_names:",a),P(a),console.log("userModels:",E),sessionStorage.setItem("userModels"+s,JSON.stringify(a))}catch(e){console.error("There was an error fetching the data",e)}})(),Z(C,s,l,f,o))}},[s,k,C,a,l]),(0,d.useEffect)(()=>{console.log("currentOrg: ".concat(JSON.stringify(f),", accessToken: ").concat(C,", userID: ").concat(s,", userRole: ").concat(l)),C&&(console.log("fetching teams"),Z(C,s,l,f,o))},[f]),(0,d.useEffect)(()=>{if(null!==a&&null!=D&&null!==D.team_id){let e=0;for(let s of(console.log("keys: ".concat(JSON.stringify(a))),a))D.hasOwnProperty("team_id")&&null!==s.team_id&&s.team_id===D.team_id&&(e+=s.spend);console.log("sum: ".concat(e)),A(e)}else if(null!==a){let e=0;for(let s of a)e+=s.spend;A(e)}},[D]),null!=S)return(0,c.jsx)(se.default,{});if(null==k){console.log("All cookies before redirect:",document.cookie),(0,_.b)();let e="/sso/key/generate";return console.log("Full URL:",e),window.location.href=e,null}if(null==C)return null;if(null==s)return(0,c.jsx)("h1",{children:"User ID is not set"});if(null==l&&r("App Owner"),l&&"Admin Viewer"==l){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to create keys"})]})}return console.log("inside user dashboard, selected team",D),console.log("All cookies after redirect:",document.cookie),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(N.Z,{numColSpan:1,className:"flex flex-col gap-2",children:[(0,c.jsx)(eN,{userID:s,team:D,teams:t,userRole:l,accessToken:C,data:a,setData:h},D?D.team_id:null),(0,c.jsx)(e9,{userID:s,userRole:l,accessToken:C,selectedTeam:D||null,setSelectedTeam:M,selectedKeyAlias:F,setSelectedKeyAlias:R,data:a,setData:h,premiumUser:x,teams:t,currentOrg:f,setCurrentOrg:v,organizations:p})]})})})},sl=l(97765);(t=n||(n={})).OpenAI="OpenAI",t.OpenAI_Compatible="OpenAI-Compatible Endpoints (Together AI, etc.)",t.OpenAI_Text="OpenAI Text Completion",t.OpenAI_Text_Compatible="OpenAI-Compatible Text Completion Models (Together AI, etc.)",t.Azure="Azure",t.Azure_AI_Studio="Azure AI Foundry (Studio)",t.Anthropic="Anthropic",t.Vertex_AI="Vertex AI (Anthropic, Gemini, etc.)",t.Google_AI_Studio="Google AI Studio",t.Bedrock="Amazon Bedrock",t.Groq="Groq",t.MistralAI="Mistral AI",t.Deepseek="Deepseek",t.Cohere="Cohere",t.Databricks="Databricks",t.Ollama="Ollama",t.xAI="xAI",t.AssemblyAI="AssemblyAI",t.Cerebras="Cerebras",t.Sambanova="Sambanova",t.Perplexity="Perplexity",t.TogetherAI="TogetherAI",t.Openrouter="Openrouter",t.FireworksAI="Fireworks AI";let st={OpenAI:"openai",OpenAI_Text:"text-completion-openai",Azure:"azure",Azure_AI_Studio:"azure_ai",Anthropic:"anthropic",Google_AI_Studio:"gemini",Bedrock:"bedrock",Groq:"groq",MistralAI:"mistral",Cohere:"cohere_chat",OpenAI_Compatible:"openai",OpenAI_Text_Compatible:"text-completion-openai",Vertex_AI:"vertex_ai",Databricks:"databricks",xAI:"xai",Deepseek:"deepseek",Ollama:"ollama",AssemblyAI:"assemblyai",Cerebras:"cerebras",Sambanova:"sambanova",Perplexity:"perplexity",TogetherAI:"togetherai",Openrouter:"openrouter",FireworksAI:"fireworks_ai"},sa="/ui/assets/logos/",sr={Anthropic:"".concat(sa,"anthropic.svg"),AssemblyAI:"".concat(sa,"assemblyai_small.png"),Azure:"".concat(sa,"microsoft_azure.svg"),"Azure AI Foundry (Studio)":"".concat(sa,"microsoft_azure.svg"),"Amazon Bedrock":"".concat(sa,"bedrock.svg"),Cerebras:"".concat(sa,"cerebras.svg"),Cohere:"".concat(sa,"cohere.svg"),Databricks:"".concat(sa,"databricks.svg"),Deepseek:"".concat(sa,"deepseek.svg"),"Fireworks AI":"".concat(sa,"fireworks.svg"),Groq:"".concat(sa,"groq.svg"),"Google AI Studio":"".concat(sa,"google.svg"),"Mistral AI":"".concat(sa,"mistral.svg"),Ollama:"".concat(sa,"ollama.svg"),OpenAI:"".concat(sa,"openai_small.svg"),"OpenAI Text Completion":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Text Completion Models (Together AI, etc.)":"".concat(sa,"openai_small.svg"),"OpenAI-Compatible Endpoints (Together AI, etc.)":"".concat(sa,"openai_small.svg"),Openrouter:"".concat(sa,"openrouter.svg"),Perplexity:"".concat(sa,"perplexity-ai.svg"),Sambanova:"".concat(sa,"sambanova.svg"),TogetherAI:"".concat(sa,"togetherai.svg"),"Vertex AI (Anthropic, Gemini, etc.)":"".concat(sa,"google.svg"),xAI:"".concat(sa,"xai.svg")},sn=e=>{if(!e)return{logo:"",displayName:"-"};if("gemini"===e.toLowerCase()){let e="Google AI Studio";return{logo:sr[e],displayName:e}}let s=Object.keys(st).find(s=>st[s].toLowerCase()===e.toLowerCase());if(!s)return{logo:"",displayName:e};let l=n[s];return{logo:sr[l],displayName:l}},si=e=>"Vertex AI (Anthropic, Gemini, etc.)"===e?"gemini-pro":"Anthropic"==e||"Amazon Bedrock"==e?"claude-3-opus":"Google AI Studio"==e?"gemini-pro":"Azure AI Foundry (Studio)"==e?"azure_ai/command-r-plus":"Azure"==e?"azure/my-deployment":"gpt-3.5-turbo",so=(e,s)=>{console.log("Provider key: ".concat(e));let l=st[e];console.log("Provider mapped to: ".concat(l));let t=[];return e&&"object"==typeof s&&(Object.entries(s).forEach(e=>{let[s,a]=e;null!==a&&"object"==typeof a&&"litellm_provider"in a&&(a.litellm_provider===l||a.litellm_provider.includes(l))&&t.push(s)}),"Cohere"==e&&(console.log("Adding cohere chat models"),Object.entries(s).forEach(e=>{let[s,l]=e;null!==l&&"object"==typeof l&&"litellm_provider"in l&&"cohere"===l.litellm_provider&&t.push(s)}))),t},sc=async(e,s,l)=>{try{console.log("handling submit for formValues:",e);let s=e.model_mappings||[];if("model_mappings"in e&&delete e.model_mappings,e.model&&e.model.includes("all-wildcard")){let l=st[e.custom_llm_provider]+"/*";e.model_name=l,s.push({public_name:l,litellm_model:l}),e.model=l}let l=[];for(let t of s){let s={},a={},r=t.public_name;for(let[l,r]of(s.model=t.litellm_model,e.input_cost_per_token&&(e.input_cost_per_token=Number(e.input_cost_per_token)/1e6),e.output_cost_per_token&&(e.output_cost_per_token=Number(e.output_cost_per_token)/1e6),s.model=t.litellm_model,console.log("formValues add deployment:",e),Object.entries(e)))if(""!==r&&"custom_pricing"!==l&&"pricing_model"!==l&&"cache_control"!==l){if("model_name"==l)s.model=r;else if("custom_llm_provider"==l){console.log("custom_llm_provider:",r);let e=st[r];s.custom_llm_provider=e,console.log("custom_llm_provider mappingResult:",e)}else if("model"==l)continue;else if("base_model"===l)a[l]=r;else if("team_id"===l)a.team_id=r;else if("mode"==l)console.log("placing mode in modelInfo"),a.mode=r,delete s.mode;else if("custom_model_name"===l)s.model=r;else if("litellm_extra_params"==l){console.log("litellm_extra_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[l,t]of Object.entries(e))s[l]=t}}else if("model_info_params"==l){console.log("model_info_params:",r);let e={};if(r&&void 0!=r){try{e=JSON.parse(r)}catch(e){throw D.ZP.error("Failed to parse LiteLLM Extra Params: "+e,10),Error("Failed to parse litellm_extra_params: "+e)}for(let[s,l]of Object.entries(e))a[s]=l}}else if("input_cost_per_token"===l||"output_cost_per_token"===l||"input_cost_per_second"===l){r&&(s[l]=Number(r));continue}else s[l]=r}l.push({litellmParamsObj:s,modelInfoObj:a,modelName:r})}return l}catch(e){D.ZP.error("Failed to create model: "+e,10)}},sd=async(e,s,l,t)=>{try{let a=await sc(e,s,l);if(!a||0===a.length)return;for(let e of a){let{litellmParamsObj:l,modelInfoObj:t,modelName:a}=e,r={model_name:a,litellm_params:l,model_info:t},n=await (0,y.kK)(s,r);console.log("response for model create call: ".concat(n.data))}t&&t(),l.resetFields()}catch(e){D.ZP.error("Failed to add model: "+e,10)}};var sm=l(53410),su=l(47451),sh=l(69410);let{Link:sx}=es.default,sp={[n.OpenAI]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text]:[{key:"api_base",label:"API Base",type:"select",options:["https://api.openai.com/v1","https://eu.api.openai.com"],defaultValue:"https://api.openai.com/v1"},{key:"organization",label:"OpenAI Organization ID",placeholder:"[OPTIONAL] my-unique-org"},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Vertex_AI]:[{key:"vertex_project",label:"Vertex Project",placeholder:"adroit-cadet-1234..",required:!0},{key:"vertex_location",label:"Vertex Location",placeholder:"us-east-1",required:!0},{key:"vertex_credentials",label:"Vertex Credentials",required:!0,type:"upload"}],[n.AssemblyAI]:[{key:"api_base",label:"API Base",type:"select",required:!0,options:["https://api.assemblyai.com","https://api.eu.assemblyai.com"]},{key:"api_key",label:"AssemblyAI API Key",type:"password",required:!0}],[n.Azure]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_version",label:"API Version",placeholder:"2023-07-01-preview",tooltip:"By default litellm will use the latest version. If you want to use a different version, you can specify it here"},{key:"base_model",label:"Base Model",placeholder:"azure/gpt-3.5-turbo"},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.Azure_AI_Studio]:[{key:"api_base",label:"API Base",placeholder:"https://.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",tooltip:"Enter your full Target URI from Azure Foundry here. Example: https://litellm8397336933.openai.azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-10-21",required:!0},{key:"api_key",label:"Azure API Key",type:"password",required:!0}],[n.OpenAI_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.OpenAI_Text_Compatible]:[{key:"api_base",label:"API Base",placeholder:"https://...",required:!0},{key:"api_key",label:"OpenAI API Key",type:"password",required:!0}],[n.Bedrock]:[{key:"aws_access_key_id",label:"AWS Access Key ID",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_secret_access_key",label:"AWS Secret Access Key",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."},{key:"aws_region_name",label:"AWS Region Name",placeholder:"us-east-1",required:!0,tooltip:"You can provide the raw key or the environment variable (e.g. `os.environ/MY_SECRET_KEY`)."}],[n.Ollama]:[],[n.Anthropic]:[{key:"api_key",label:"API Key",placeholder:"sk-",type:"password",required:!0}],[n.Google_AI_Studio]:[{key:"api_key",label:"API Key",placeholder:"aig-",type:"password",required:!0}],[n.Groq]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.MistralAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Deepseek]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cohere]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Databricks]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.xAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Cerebras]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Sambanova]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Perplexity]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.TogetherAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.Openrouter]:[{key:"api_key",label:"API Key",type:"password",required:!0}],[n.FireworksAI]:[{key:"api_key",label:"API Key",type:"password",required:!0}]};var sg=e=>{let{selectedProvider:s,uploadProps:l}=e,t=n[s],a=d.useMemo(()=>sp[t]||[],[t]);return(0,c.jsx)(c.Fragment,{children:a.map(e=>{var s;return(0,c.jsxs)(d.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:e.label,name:e.key,rules:e.required?[{required:!0,message:"Required"}]:void 0,tooltip:e.tooltip,className:"vertex_credentials"===e.key?"mb-0":void 0,children:"select"===e.type?(0,c.jsx)(O.default,{placeholder:e.placeholder,defaultValue:e.defaultValue,children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:e},e))}):"upload"===e.type?(0,c.jsx)(et.Z,{...l,children:(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(en.Z,{}),children:"Click to Upload"})}):(0,c.jsx)(S.Z,{placeholder:e.placeholder,type:"password"===e.type?"password":"text"})}),"vertex_credentials"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Give litellm a gcp service account(.json file), so it can make the relevant calls"})})]}),"base_model"===e.key&&(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-2",children:["The actual model your azure deployment uses. Used for accurate cost tracking. Select name from"," ",(0,c.jsx)(sx,{href:"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json",target:"_blank",children:"here"})]})})]})]},e.key)})})};let{Title:sj,Link:sf}=es.default;var s_=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,onUpdateCredential:a,uploadProps:r,addOrEdit:i,existingCredential:o}=e,[m]=L.Z.useForm(),[u,h]=(0,d.useState)(n.OpenAI),[x,p]=(0,d.useState)(!1);return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(o))),(0,c.jsx)(M.Z,{title:"add"===i?"Add New Credential":"Edit Credential",visible:s,onCancel:()=>{l(),m.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:m,onFinish:e=>{"add"===i?t(e):a(e),m.resetFields()},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==o?void 0:o.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials",disabled:null!=o&&!!o.credential_name})}),(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"Helper to auto-populate provider specific fields",children:(0,c.jsx)(O.default,{value:(null==o?void 0:o.credential_info.custom_llm_provider)||u,onChange:e=>{h(e)},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sg,{selectedProvider:u,uploadProps:r}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sf,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),m.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"add"===i?"Add Credential":"Update Credential"})]})]})]})})},sy=e=>{let{accessToken:s,uploadProps:l,credentialList:t,fetchCredentials:a}=e,[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(!1),[m,u]=(0,d.useState)(null),[h]=L.Z.useForm();console.log("selectedCredential in credentials panel: ".concat(JSON.stringify(m)));let x=["credential_name","custom_llm_provider"],p=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.eZ)(s,e.credential_name,t);D.ZP.success("Credential updated successfully"),console.log("response: ".concat(JSON.stringify(r))),o(!1),a(s)},g=async e=>{if(!s){console.error("No access token found");return}let l=Object.entries(e).filter(e=>{let[s]=e;return!x.includes(s)}).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:t}},{}),t={credential_name:e.credential_name,credential_values:l,credential_info:{custom_llm_provider:e.custom_llm_provider}},r=await (0,y.oC)(s,t);D.ZP.success("Credential added successfully"),console.log("response: ".concat(JSON.stringify(r))),n(!1),a(s)};(0,d.useEffect)(()=>{s&&a(s)},[s]);let j=e=>{let s={openai:"blue",azure:"indigo",anthropic:"purple",default:"gray"},l=s[e.toLowerCase()]||s.default;return(0,c.jsx)(eM.Z,{color:l,size:"xs",children:e})},f=async e=>{if(!s){console.error("No access token found");return}let l=await (0,y.gX)(s,e);console.log("response: ".concat(JSON.stringify(l))),D.ZP.success("Credential deleted successfully"),a(s)};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsxs)(A.Z,{children:["Configured credentials for different AI providers. Add and manage your API credentials."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/credentials",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]})}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Credential Name"}),(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Description"})]})}),(0,c.jsx)(eT.Z,{children:t&&0!==t.length?t.map((e,s)=>{var l,t;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.credential_name}),(0,c.jsx)(eA.Z,{children:j((null===(l=e.credential_info)||void 0===l?void 0:l.custom_llm_provider)||"-")}),(0,c.jsx)(eA.Z,{children:(null===(t=e.credential_info)||void 0===t?void 0:t.description)||"-"}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{icon:sm.Z,variant:"light",size:"sm",onClick:()=>{console.log("credential being set: ".concat(JSON.stringify(e))),u(e),o(!0)}}),(0,c.jsx)(k.Z,{icon:eH.Z,variant:"light",size:"sm",onClick:()=>f(e.credential_name)})]})]},s)}):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:4,className:"text-center py-4 text-gray-500",children:"No credentials configured"})})})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),className:"mt-4",children:"Add Credential"}),r&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:r,onCancel:()=>n(!1),uploadProps:l,addOrEdit:"add",onUpdateCredential:p,existingCredential:null}),i&&(0,c.jsx)(s_,{onAddCredential:g,isVisible:i,existingCredential:m,onUpdateCredential:p,uploadProps:l,onCancel:()=>o(!1),addOrEdit:"edit"})]})};let sv=e=>{var s;return(null==e?void 0:null===(s=e.model_info)||void 0===s?void 0:s.team_public_model_name)?e.model_info.team_public_model_name:(null==e?void 0:e.model_name)||"-"};var sb=l(53003),sZ=l(47323),sN=l(75105),sw=l(40278),sk=l(14301),sS=l(59664),sC=e=>{let{modelMetrics:s,modelMetricsCategories:l,customTooltip:t,premiumUser:a}=e;return(0,c.jsx)(sS.Z,{title:"Time to First token (s)",className:"h-72",data:s,index:"date",showLegend:!1,categories:l,colors:["indigo","rose"],connectNulls:!0,customTooltip:t})},sI=e=>{let{teamData:s,canEditTeam:l,handleMemberDelete:t,setSelectedEditMember:a,setIsEditMemberModalVisible:r,setIsAddMemberModalVisible:n}=e;return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"User Email"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:s.team_info.members_with_roles.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_email})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.role})}),(0,c.jsx)(eA.Z,{children:l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{a(e),r(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(e)})]})})]},s))})]})}),(0,c.jsx)(k.Z,{onClick:()=>n(!0),children:"Add Member"})]})},sT=l(61994),sA=l(85180),sE=l(89245),sP=l(78355);let sO={"/key/generate":"Member can generate a virtual key for this team","/key/update":"Member can update a virtual key belonging to this team","/key/delete":"Member can delete a virtual key belonging to this team","/key/info":"Member can get info about a virtual key belonging to this team","/key/regenerate":"Member can regenerate a virtual key belonging to this team","/key/{key_id}/regenerate":"Member can regenerate a virtual key belonging to this team","/key/list":"Member can list virtual keys belonging to this team","/key/block":"Member can block a virtual key belonging to this team","/key/unblock":"Member can unblock a virtual key belonging to this team"},sL=e=>e.includes("/info")||e.includes("/list")?"GET":"POST",sD=e=>{let s=sL(e),l=sO[e];if(!l){for(let[s,t]of Object.entries(sO))if(e.includes(s)){l=t;break}}return l||(l="Access ".concat(e)),{method:s,endpoint:e,description:l,route:e}};var sM=e=>{let{teamId:s,accessToken:l,canEditTeam:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)(!0),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),g=async()=>{try{if(m(!0),!l)return;let e=await (0,y.aC)(l,s),t=e.all_available_permissions||[];r(t);let a=e.team_member_permissions||[];i(a),p(!1)}catch(e){D.ZP.error("Failed to load permissions"),console.error("Error fetching permissions:",e)}finally{m(!1)}};(0,d.useEffect)(()=>{g()},[s,l]);let j=(e,s)=>{i(s?[...n,e]:n.filter(s=>s!==e)),p(!0)},f=async()=>{try{if(!l)return;h(!0),await (0,y.TF)(l,s,n),D.ZP.success("Permissions updated successfully"),p(!1)}catch(e){D.ZP.error("Failed to update permissions"),console.error("Error updating permissions:",e)}finally{h(!1)}};if(o)return(0,c.jsx)("div",{className:"p-6 text-center",children:"Loading permissions..."});let _=a.length>0;return(0,c.jsxs)(eF.Z,{className:"bg-white shadow-md rounded-md p-6",children:[(0,c.jsxs)("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center border-b pb-4 mb-6",children:[(0,c.jsx)(E.Z,{className:"mb-2 sm:mb-0",children:"Member Permissions"}),t&&x&&(0,c.jsxs)("div",{className:"flex gap-3",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(sE.Z,{}),onClick:()=>{g()},children:"Reset"}),(0,c.jsxs)(k.Z,{onClick:f,loading:u,className:"flex items-center gap-2",children:[(0,c.jsx)(sP.Z,{})," Save Changes"]})]})]}),(0,c.jsx)(A.Z,{className:"mb-6 text-gray-600",children:"Control what team members can do when they are not team admins."}),_?(0,c.jsxs)(eI.Z,{className:"mt-4",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Method"}),(0,c.jsx)(eP.Z,{children:"Endpoint"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Access"})]})}),(0,c.jsx)(eT.Z,{children:a.map(e=>{let s=sD(e);return(0,c.jsxs)(eO.Z,{className:"hover:bg-gray-50 transition-colors",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"px-2 py-1 rounded text-xs font-medium ".concat("GET"===s.method?"bg-blue-100 text-blue-800":"bg-green-100 text-green-800"),children:s.method})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("span",{className:"font-mono text-sm text-gray-800",children:s.endpoint})}),(0,c.jsx)(eA.Z,{className:"text-gray-700",children:s.description}),(0,c.jsx)(eA.Z,{className:"text-right",children:(0,c.jsx)(sT.Z,{checked:n.includes(e),onChange:s=>j(e,s.target.checked),disabled:!t})})]},e)})})]}):(0,c.jsx)("div",{className:"py-12",children:(0,c.jsx)(sA.Z,{description:"No permissions available"})})]})},sF=e=>{var s,l,t;let{visible:a,onCancel:r,onSubmit:n,initialData:i,mode:o,config:m}=e,[u]=L.Z.useForm();console.log("Initial Data:",i),(0,d.useEffect)(()=>{if(a){if("edit"===o&&i)u.setFieldsValue({...i,role:i.role||m.defaultRole});else{var e;u.resetFields(),u.setFieldsValue({role:m.defaultRole||(null===(e=m.roleOptions[0])||void 0===e?void 0:e.value)})}}},[a,i,o,u,m.defaultRole,m.roleOptions]);let h=async e=>{try{let s=Object.entries(e).reduce((e,s)=>{let[l,t]=s;return{...e,[l]:"string"==typeof t?t.trim():t}},{});n(s),u.resetFields(),D.ZP.success("Successfully ".concat("add"===o?"added":"updated"," member"))}catch(e){D.ZP.error("Failed to submit form"),console.error("Form submission error:",e)}},x=e=>{switch(e.type){case"input":return(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",onChange:e=>{e.target.value=e.target.value.trim()}});case"select":var s;return(0,c.jsx)(O.default,{children:null===(s=e.options)||void 0===s?void 0:s.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))});default:return null}};return(0,c.jsx)(M.Z,{title:m.title||("add"===o?"Add Member":"Edit Member"),open:a,width:800,footer:null,onCancel:r,children:(0,c.jsxs)(L.Z,{form:u,onFinish:h,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[m.showEmail&&(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",rules:[{type:"email",message:"Please enter a valid email!"}],children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user@example.com",onChange:e=>{e.target.value=e.target.value.trim()}})}),m.showEmail&&m.showUserId&&(0,c.jsx)("div",{className:"text-center mb-4",children:(0,c.jsx)(A.Z,{children:"OR"})}),m.showUserId&&(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(q.default,{className:"px-3 py-2 border rounded-md w-full",placeholder:"user_123",onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"Role"}),"edit"===o&&i&&(0,c.jsxs)("span",{className:"text-gray-500 text-sm",children:["(Current: ",(l=i.role,(null===(t=m.roleOptions.find(e=>e.value===l))||void 0===t?void 0:t.label)||l),")"]})]}),name:"role",className:"mb-4",rules:[{required:!0,message:"Please select a role!"}],children:(0,c.jsx)(O.default,{children:"edit"===o&&i?[...m.roleOptions.filter(e=>e.value===i.role),...m.roleOptions.filter(e=>e.value!==i.role)].map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value)):m.roleOptions.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:e.label},e.value))})}),null===(s=m.additionalFields)||void 0===s?void 0:s.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,className:"mb-4",rules:e.rules,children:x(e)},e.name)),(0,c.jsxs)("div",{className:"text-right mt-6",children:[(0,c.jsx)(R.ZP,{onClick:r,className:"mr-2",children:"Cancel"}),(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"add"===o?"Add Member":"Save Changes"})]})]})})},sR=e=>{let{isVisible:s,onCancel:l,onSubmit:t,accessToken:a,title:r="Add Team Member",roles:n=[{label:"admin",value:"admin",description:"Admin role. Can create team keys, add members, and manage settings."},{label:"user",value:"user",description:"User role. Can view team info, but not manage it."}],defaultRole:i="user"}=e,[o]=L.Z.useForm(),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p,g]=(0,d.useState)("user_email"),j=async(e,s)=>{if(!e){u([]);return}x(!0);try{let l=new URLSearchParams;if(l.append(s,e),null==a)return;let t=(await (0,y.u5)(a,l)).map(e=>({label:"user_email"===s?"".concat(e.user_email):"".concat(e.user_id),value:"user_email"===s?e.user_email:e.user_id,user:e}));u(t)}catch(e){console.error("Error fetching users:",e)}finally{x(!1)}},f=(0,d.useCallback)(ep()((e,s)=>j(e,s),300),[]),_=(e,s)=>{g(s),f(e,s)},v=(e,s)=>{let l=s.user;o.setFieldsValue({user_email:l.user_email,user_id:l.user_id,role:o.getFieldValue("role")})};return(0,c.jsx)(M.Z,{title:r,open:s,onCancel:()=>{o.resetFields(),u([]),l()},footer:null,width:800,children:(0,c.jsxs)(L.Z,{form:o,onFinish:t,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:{role:i},children:[(0,c.jsx)(L.Z.Item,{label:"Email",name:"user_email",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by email",filterOption:!1,onSearch:e=>_(e,"user_email"),onSelect:(e,s)=>v(e,s),options:"user_email"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)("div",{className:"text-center mb-4",children:"OR"}),(0,c.jsx)(L.Z.Item,{label:"User ID",name:"user_id",className:"mb-4",children:(0,c.jsx)(O.default,{showSearch:!0,className:"w-full",placeholder:"Search by user ID",filterOption:!1,onSearch:e=>_(e,"user_id"),onSelect:(e,s)=>v(e,s),options:"user_id"===p?m:[],loading:h,allowClear:!0})}),(0,c.jsx)(L.Z.Item,{label:"Member Role",name:"role",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:i,children:n.map(e=>(0,c.jsx)(O.default.Option,{value:e.value,children:(0,c.jsxs)(W.Z,{title:e.description,children:[(0,c.jsx)("span",{className:"font-medium",children:e.label}),(0,c.jsxs)("span",{className:"ml-2 text-gray-500 text-sm",children:["- ",e.description]})]})},e.value))})}),(0,c.jsx)("div",{className:"text-right mt-4",children:(0,c.jsx)(R.ZP,{type:"default",htmlType:"submit",children:"Add Member"})})]})})},sq=e=>{var s;let{teamId:l,onClose:t,accessToken:a,is_team_admin:r,is_proxy_admin:n,userModels:i,editTeam:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p,g]=(0,d.useState)(!1),[j]=L.Z.useForm(),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(null),[Z,N]=(0,d.useState)(!1);console.log("userModels in team info",i);let S=r||n,C=async()=>{try{if(x(!0),!a)return;let e=await (0,y.Xm)(a,l);u(e)}catch(e){D.ZP.error("Failed to load team information"),console.error("Error fetching team info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{C()},[l,a]);let I=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.cu)(a,l,s),D.ZP.success("Team member added successfully"),g(!1),j.resetFields(),C()}catch(e){D.ZP.error("Failed to add team member"),console.error("Error adding team member:",e)}},T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.sN)(a,l,s),D.ZP.success("Team member updated successfully"),_(!1),C()}catch(e){D.ZP.error("Failed to update team member"),console.error("Error updating team member:",e)}},P=async e=>{try{if(null==a)return;await (0,y.Lp)(a,l,e),D.ZP.success("Team member removed successfully"),C()}catch(e){D.ZP.error("Failed to remove team member"),console.error("Error removing team member:",e)}},M=async e=>{try{if(!a)return;let s={};try{s=e.metadata?JSON.parse(e.metadata):{}}catch(e){D.ZP.error("Invalid JSON in metadata field");return}let t={team_id:l,team_alias:e.team_alias,models:e.models,tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration,metadata:{...s,guardrails:e.guardrails||[]}};await (0,y.Gh)(a,t),D.ZP.success("Team settings updated successfully"),N(!1),C()}catch(e){D.ZP.error("Failed to update team settings"),console.error("Error updating team:",e)}};if(h)return(0,c.jsx)("div",{className:"p-4",children:"Loading..."});if(!(null==m?void 0:m.team_info))return(0,c.jsx)("div",{className:"p-4",children:"Team not found"});let{team_info:F}=m;return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:F.team_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:F.team_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?3:0,children:[(0,c.jsx)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"},"overview"),...S?[(0,c.jsx)(eR.Z,{children:"Members"},"members"),(0,c.jsx)(eR.Z,{children:"Member Permissions"},"member-permissions"),(0,c.jsx)(eR.Z,{children:"Settings"},"settings")]:[]]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",F.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===F.max_budget?"Unlimited":"$".concat(F.max_budget)]}),F.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",F.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",F.rpm_limit||"Unlimited"]}),F.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",F.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sI,{teamData:m,canEditTeam:S,handleMemberDelete:P,setSelectedEditMember:b,setIsEditMemberModalVisible:_,setIsAddMemberModalVisible:g})}),S&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sM,{teamId:l,accessToken:a,canEditTeam:S})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Team Settings"}),S&&!Z&&(0,c.jsx)(k.Z,{onClick:()=>N(!0),children:"Edit Settings"})]}),Z?(0,c.jsxs)(L.Z,{form:j,onFinish:M,initialValues:{...F,team_alias:F.team_alias,models:F.models,tpm_limit:F.tpm_limit,rpm_limit:F.rpm_limit,max_budget:F.max_budget,budget_duration:F.budget_duration,guardrails:(null===(s=F.metadata)||void 0===s?void 0:s.guardrails)||[],metadata:F.metadata?JSON.stringify(F.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(q.default,{type:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map((e,s)=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},s))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",placeholder:"Select or enter guardrails"})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:10})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>N(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team Name"}),(0,c.jsx)("div",{children:F.team_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"font-mono",children:F.team_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(F.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:F.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",F.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",F.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==F.max_budget?"$".concat(F.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",F.budget_duration||"Never"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Status"}),(0,c.jsx)(eM.Z,{color:F.blocked?"red":"green",children:F.blocked?"Blocked":"Active"})]})]})]})})]})]}),(0,c.jsx)(sF,{visible:f,onCancel:()=>_(!1),onSubmit:T,initialData:v,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Admin",value:"admin"},{label:"User",value:"user"}]}}),(0,c.jsx)(sR,{isVisible:p,onCancel:()=>g(!1),onSubmit:I,accessToken:a})]})},sU=l(45589);let{Title:sz,Link:sV}=es.default;var sK=e=>{let{isVisible:s,onCancel:l,onAddCredential:t,existingCredential:a,setIsCredentialModalOpen:r}=e,[n]=L.Z.useForm();return console.log("existingCredential in add credentials tab: ".concat(JSON.stringify(a))),(0,c.jsx)(M.Z,{title:"Reuse Credentials",visible:s,onCancel:()=>{l(),n.resetFields()},footer:null,width:600,children:(0,c.jsxs)(L.Z,{form:n,onFinish:e=>{t(e),n.resetFields(),r(!1)},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Credential Name:",name:"credential_name",rules:[{required:!0,message:"Credential name is required"}],initialValue:null==a?void 0:a.credential_name,children:(0,c.jsx)(S.Z,{placeholder:"Enter a friendly name for these credentials"})}),Object.entries((null==a?void 0:a.credential_values)||{}).map(e=>{let[s,l]=e;return(0,c.jsx)(L.Z.Item,{label:s,name:s,initialValue:l,children:(0,c.jsx)(S.Z,{placeholder:"Enter ".concat(s),disabled:!0})},s)}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(sV,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:()=>{l(),n.resetFields()},style:{marginRight:10},children:"Cancel"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Reuse Credentials"})]})]})]})})},sB=l(63709),sH=l(45246),sJ=l(96473);let{Text:sW}=es.default;var sG=e=>{let{form:s,showCacheControl:l,onCacheControlChange:t}=e,a=e=>{let l=s.getFieldValue("litellm_extra_params");try{let t=l?JSON.parse(l):{};e.length>0?t.cache_control_injection_points=e:delete t.cache_control_injection_points,Object.keys(t).length>0?s.setFieldValue("litellm_extra_params",JSON.stringify(t,null,2)):s.setFieldValue("litellm_extra_params","")}catch(e){console.error("Error updating cache control points:",e)}};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Cache Control Injection Points",name:"cache_control",valuePropName:"checked",className:"mb-4",tooltip:"Tell litellm where to inject cache control checkpoints. You can specify either by role (to apply to all messages of that role) or by specific message index.",children:(0,c.jsx)(sB.Z,{onChange:t,className:"bg-gray-600"})}),l&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(sW,{className:"text-sm text-gray-500 block mb-4",children:"Providers like Anthropic, Bedrock API require users to specify where to inject cache control checkpoints, litellm can automatically add them for you as a cost saving feature."}),(0,c.jsx)(L.Z.List,{name:"cache_control_injection_points",initialValue:[{location:"message"}],children:(e,l)=>{let{add:t,remove:r}=l;return(0,c.jsxs)(c.Fragment,{children:[e.map((l,t)=>(0,c.jsxs)("div",{className:"flex items-center mb-4 gap-4",children:[(0,c.jsx)(L.Z.Item,{...l,label:"Type",name:[l.name,"location"],initialValue:"message",className:"mb-0",style:{width:"180px"},children:(0,c.jsx)(O.default,{disabled:!0,options:[{value:"message",label:"Message"}]})}),(0,c.jsx)(L.Z.Item,{...l,label:"Role",name:[l.name,"role"],className:"mb-0",style:{width:"180px"},tooltip:"LiteLLM will mark all messages of this role as cacheable",children:(0,c.jsx)(O.default,{placeholder:"Select a role",allowClear:!0,options:[{value:"user",label:"User"},{value:"system",label:"System"},{value:"assistant",label:"Assistant"}],onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),(0,c.jsx)(L.Z.Item,{...l,label:"Index",name:[l.name,"index"],className:"mb-0",style:{width:"180px"},tooltip:"(Optional) If set litellm will mark the message at this index as cacheable",children:(0,c.jsx)(z,{type:"number",placeholder:"Optional",step:1,min:0,onChange:()=>{a(s.getFieldValue("cache_control_points"))}})}),e.length>1&&(0,c.jsx)(sH.Z,{className:"text-red-500 cursor-pointer text-lg ml-12",onClick:()=>{r(l.name),setTimeout(()=>{a(s.getFieldValue("cache_control_points"))},0)}})]},l.key)),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)("button",{type:"button",className:"flex items-center justify-center w-full border border-dashed border-gray-300 py-2 px-4 text-gray-600 hover:text-blue-600 hover:border-blue-300 transition-all rounded",onClick:()=>t(),children:[(0,c.jsx)(sJ.Z,{className:"mr-2"}),"Add Injection Point"]})})]})}})]})]})};function sY(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j,f,_,v,b,Z,N;let{modelId:C,onClose:I,modelData:T,accessToken:P,userID:O,userRole:F,editModel:q,setEditModalVisible:U,setSelectedModel:V,onModelUpdate:K}=e,[B]=L.Z.useForm(),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(!1),[Y,$]=(0,d.useState)(!1),[X,Q]=(0,d.useState)(!1),[ee,es]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)(null),[en,ei]=(0,d.useState)(!1),eo="Admin"===F||T.model_info.created_by===O,ec=(null===(s=T.litellm_params)||void 0===s?void 0:s.litellm_credential_name)!=null&&(null===(l=T.litellm_params)||void 0===l?void 0:l.litellm_credential_name)!=void 0;console.log("usingExistingCredential, ",ec),console.log("modelData.litellm_params.litellm_credential_name, ",T.litellm_params.litellm_credential_name),(0,d.useEffect)(()=>{let e=async()=>{var e;if(!P)return;let s=await (0,y.ix)(P,C);console.log("modelInfoResponse, ",s);let l=s.data[0];J(l),(null==l?void 0:null===(e=l.litellm_params)||void 0===e?void 0:e.cache_control_injection_points)&&ei(!0)};(async()=>{if(console.log("accessToken, ",P),!P||ec)return;let e=await (0,y.Qg)(P,null,C);console.log("existingCredentialResponse, ",e),er({credential_name:e.credential_name,credential_values:e.credential_values,credential_info:e.credential_info})})(),e()},[P,C]);let ed=async e=>{var s;if(console.log("values, ",e),!P)return;let l={credential_name:e.credential_name,model_id:C,credential_info:{custom_llm_provider:null===(s=H.litellm_params)||void 0===s?void 0:s.custom_llm_provider}};D.ZP.info("Storing credential.."),console.log("credentialResponse, ",await (0,y.oC)(P,l)),D.ZP.success("Credential stored successfully")},em=async e=>{try{var s;if(!P)return;es(!0);let l={...H.litellm_params,model:e.litellm_model_name,api_base:e.api_base,custom_llm_provider:e.custom_llm_provider,organization:e.organization,tpm:e.tpm,rpm:e.rpm,max_retries:e.max_retries,timeout:e.timeout,stream_timeout:e.stream_timeout,input_cost_per_token:e.input_cost/1e6,output_cost_per_token:e.output_cost/1e6};e.cache_control&&(null===(s=e.cache_control_injection_points)||void 0===s?void 0:s.length)>0?l.cache_control_injection_points=e.cache_control_injection_points:delete l.cache_control_injection_points;let t={model_name:e.model_name,litellm_params:l,model_info:{id:C}};await (0,y.um)(P,t);let a={...H,model_name:e.model_name,litellm_model_name:e.litellm_model_name,litellm_params:l};J(a),K&&K(a),D.ZP.success("Model settings updated successfully"),Q(!1),et(!1)}catch(e){console.error("Error updating model:",e),D.ZP.error("Failed to update model settings")}finally{es(!1)}};if(!T)return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsx)(A.Z,{children:"Model not found"})]});let eu=async()=>{try{if(!P)return;await (0,y.Og)(P,C),D.ZP.success("Model deleted successfully"),K&&K({deleted:!0,model_info:{id:C}}),I()}catch(e){console.error("Error deleting the model:",e),D.ZP.error("Failed to delete model")}};return(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{icon:(0,c.jsx)(eK.Z,{}),onClick:I,className:"mb-4",children:"Back to Models"}),(0,c.jsxs)(E.Z,{children:["Public Model Name: ",sv(T)]}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:T.model_info.id})]}),(0,c.jsxs)("div",{className:"flex gap-2",children:["Admin"===F&&(0,c.jsx)(k.Z,{icon:sU.Z,variant:"secondary",onClick:()=>$(!0),className:"flex items-center",children:"Re-use Credentials"}),eo&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>G(!0),className:"flex items-center",children:"Delete Model"})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-6",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Raw JSON"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6 mb-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Provider"}),(0,c.jsxs)("div",{className:"mt-2 flex items-center space-x-2",children:[T.provider&&(0,c.jsx)("img",{src:sn(T.provider).logo,alt:"".concat(T.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,l=s.parentElement;if(l){var t;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(t=T.provider)||void 0===t?void 0:t.charAt(0))||"-",l.replaceChild(e,s)}}}),(0,c.jsx)(E.Z,{children:T.provider||"Not Set"})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"LiteLLM Model"}),(0,c.jsx)("pre",{children:(0,c.jsx)(E.Z,{children:T.litellm_model_name||"Not Set"})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Pricing"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Input: $",T.input_cost,"/1M tokens"]}),(0,c.jsxs)(A.Z,{children:["Output: $",T.output_cost,"/1M tokens"]})]})]})]}),(0,c.jsxs)("div",{className:"mb-6 text-sm text-gray-500 flex items-center gap-x-6",children:[(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Created At ",T.model_info.created_at?new Date(T.model_info.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"Not Set"]}),(0,c.jsxs)("div",{className:"flex items-center gap-x-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"})}),"Created By ",T.model_info.created_by||"Not Set"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Model Settings"}),eo&&!el&&(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>et(!0),className:"flex items-center",children:"Edit Model"})]}),H?(0,c.jsx)(L.Z,{form:B,onFinish:em,initialValues:{model_name:H.model_name,litellm_model_name:H.litellm_model_name,api_base:H.litellm_params.api_base,custom_llm_provider:H.litellm_params.custom_llm_provider,organization:H.litellm_params.organization,tpm:H.litellm_params.tpm,rpm:H.litellm_params.rpm,max_retries:H.litellm_params.max_retries,timeout:H.litellm_params.timeout,stream_timeout:H.litellm_params.stream_timeout,input_cost:H.litellm_params.input_cost_per_token?1e6*H.litellm_params.input_cost_per_token:(null===(t=H.model_info)||void 0===t?void 0:t.input_cost_per_token)*1e6||null,output_cost:(null===(a=H.litellm_params)||void 0===a?void 0:a.output_cost_per_token)?1e6*H.litellm_params.output_cost_per_token:(null===(r=H.model_info)||void 0===r?void 0:r.output_cost_per_token)*1e6||null,cache_control:null!==(n=H.litellm_params)&&void 0!==n&&!!n.cache_control_injection_points,cache_control_injection_points:(null===(i=H.litellm_params)||void 0===i?void 0:i.cache_control_injection_points)||[]},layout:"vertical",onValuesChange:()=>Q(!0),children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"LiteLLM Model Name"}),el?(0,c.jsx)(L.Z.Item,{name:"litellm_model_name",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter LiteLLM model name"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:H.litellm_model_name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Input Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"input_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter input cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(o=H.litellm_params)||void 0===o?void 0:o.input_cost_per_token)?((null===(m=H.litellm_params)||void 0===m?void 0:m.input_cost_per_token)*1e6).toFixed(4):(null==H?void 0:null===(u=H.model_info)||void 0===u?void 0:u.input_cost_per_token)?(1e6*H.model_info.input_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Output Cost (per 1M tokens)"}),el?(0,c.jsx)(L.Z.Item,{name:"output_cost",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter output cost"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null==H?void 0:null===(h=H.litellm_params)||void 0===h?void 0:h.output_cost_per_token)?(1e6*H.litellm_params.output_cost_per_token).toFixed(4):(null==H?void 0:null===(x=H.model_info)||void 0===x?void 0:x.output_cost_per_token)?(1e6*H.model_info.output_cost_per_token).toFixed(4):null})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Base"}),el?(0,c.jsx)(L.Z.Item,{name:"api_base",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter API base"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(p=H.litellm_params)||void 0===p?void 0:p.api_base)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Custom LLM Provider"}),el?(0,c.jsx)(L.Z.Item,{name:"custom_llm_provider",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom LLM provider"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(g=H.litellm_params)||void 0===g?void 0:g.custom_llm_provider)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization"}),el?(0,c.jsx)(L.Z.Item,{name:"organization",className:"mb-0",children:(0,c.jsx)(S.Z,{placeholder:"Enter organization"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(j=H.litellm_params)||void 0===j?void 0:j.organization)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"TPM (Tokens per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"tpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter TPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(f=H.litellm_params)||void 0===f?void 0:f.tpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"RPM (Requests per Minute)"}),el?(0,c.jsx)(L.Z.Item,{name:"rpm",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter RPM"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(_=H.litellm_params)||void 0===_?void 0:_.rpm)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Max Retries"}),el?(0,c.jsx)(L.Z.Item,{name:"max_retries",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter max retries"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(v=H.litellm_params)||void 0===v?void 0:v.max_retries)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(b=H.litellm_params)||void 0===b?void 0:b.timeout)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Stream Timeout (seconds)"}),el?(0,c.jsx)(L.Z.Item,{name:"stream_timeout",className:"mb-0",children:(0,c.jsx)(z,{placeholder:"Enter stream timeout"})}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(Z=H.litellm_params)||void 0===Z?void 0:Z.stream_timeout)||"Not Set"})]}),el?(0,c.jsx)(sG,{form:B,showCacheControl:en,onCacheControlChange:e=>ei(e)}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Cache Control"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:(null===(N=H.litellm_params)||void 0===N?void 0:N.cache_control_injection_points)?(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{children:"Enabled"}),(0,c.jsx)("div",{className:"mt-2",children:H.litellm_params.cache_control_injection_points.map((e,s)=>(0,c.jsxs)("div",{className:"text-sm text-gray-600 mb-1",children:["Location: ",e.location,",",e.role&&(0,c.jsxs)("span",{children:[" Role: ",e.role]}),void 0!==e.index&&(0,c.jsxs)("span",{children:[" Index: ",e.index]})]},s))})]}):"Disabled"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Team ID"}),(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:T.model_info.team_id||"Not Set"})]})]}),el&&(0,c.jsxs)("div",{className:"mt-6 flex justify-end gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{B.resetFields(),Q(!1),et(!1)},children:"Cancel"}),(0,c.jsx)(k.Z,{variant:"primary",onClick:()=>B.submit(),loading:ee,children:"Save Changes"})]})]})}):(0,c.jsx)(A.Z,{children:"Loading..."})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsx)("pre",{className:"bg-gray-100 p-4 rounded text-xs overflow-auto",children:JSON.stringify(T,null,2)})})})]})]}),W&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Model"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this model?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(R.ZP,{onClick:eu,className:"ml-2",danger:!0,children:"Delete"}),(0,c.jsx)(R.ZP,{onClick:()=>G(!1),children:"Cancel"})]})]})]})}),Y&&!ec?(0,c.jsx)(sK,{isVisible:Y,onCancel:()=>$(!1),onAddCredential:ed,existingCredential:ea,setIsCredentialModalOpen:$}):(0,c.jsx)(M.Z,{open:Y,onCancel:()=>$(!1),title:"Using Existing Credential",children:(0,c.jsx)(A.Z,{children:T.litellm_params.litellm_credential_name})})]})}var s$=l(67960),sX=e=>{let{selectedProvider:s,providerModels:l,getPlaceholder:t}=e,a=L.Z.useFormInstance(),r=e=>{let s=e.target.value,l=(a.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:s,litellm_model:s}:e);a.setFieldsValue({model_mappings:l})};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsxs)(L.Z.Item,{label:"LiteLLM Model Name(s)",tooltip:"Actual model name used for making litellm.completion() / litellm.embedding() call.",className:"mb-0",children:[(0,c.jsx)(L.Z.Item,{name:"model",rules:[{required:!0,message:"Please select at least one model."}],noStyle:!0,children:s===n.Azure||s===n.OpenAI_Compatible||s===n.Ollama?(0,c.jsx)(S.Z,{placeholder:t(s)}):l.length>0?(0,c.jsx)(O.default,{mode:"multiple",allowClear:!0,showSearch:!0,placeholder:"Select models",onChange:e=>{let s=Array.isArray(e)?e:[e];if(s.includes("all-wildcard"))a.setFieldsValue({model_name:void 0,model_mappings:[]});else{let e=s.map(e=>({public_name:e,litellm_model:e}));a.setFieldsValue({model_mappings:e})}},optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{label:"Custom Model Name (Enter below)",value:"custom"},{label:"All ".concat(s," Models (Wildcard)"),value:"all-wildcard"},...l.map(e=>({label:e,value:e}))],style:{width:"100%"}}):(0,c.jsx)(S.Z,{placeholder:t(s)})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.model!==s.model,children:e=>{let{getFieldValue:s}=e,l=s("model")||[];return(Array.isArray(l)?l:[l]).includes("custom")&&(0,c.jsx)(L.Z.Item,{name:"custom_model_name",rules:[{required:!0,message:"Please enter a custom model name."}],className:"mt-2",children:(0,c.jsx)(S.Z,{placeholder:"Enter custom model name",onChange:r})})}})]}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsx)(A.Z,{className:"mb-3 mt-1",children:"Actual model name used for making litellm.completion() call. We loadbalance models with the same public name"})})]})]})},sQ=()=>{let e=L.Z.useFormInstance(),[s,l]=(0,d.useState)(0),t=L.Z.useWatch("model",e)||[],a=Array.isArray(t)?t:[t],r=L.Z.useWatch("custom_model_name",e),n=!a.includes("all-wildcard");if((0,d.useEffect)(()=>{if(r&&a.includes("custom")){let s=(e.getFieldValue("model_mappings")||[]).map(e=>"custom"===e.public_name||"custom"===e.litellm_model?{public_name:r,litellm_model:r}:e);e.setFieldValue("model_mappings",s),l(e=>e+1)}},[r,a,e]),(0,d.useEffect)(()=>{if(a.length>0&&!a.includes("all-wildcard")){let s=a.map(e=>"custom"===e&&r?{public_name:r,litellm_model:r}:{public_name:e,litellm_model:e});e.setFieldValue("model_mappings",s),l(e=>e+1)}},[a,r,e]),!n)return null;let i=[{title:"Public Name",dataIndex:"public_name",key:"public_name",render:(s,l,t)=>(0,c.jsx)(S.Z,{value:s,onChange:s=>{let l=[...e.getFieldValue("model_mappings")];l[t].public_name=s.target.value,e.setFieldValue("model_mappings",l)}})},{title:"LiteLLM Model",dataIndex:"litellm_model",key:"litellm_model"}];return(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(L.Z.Item,{label:"Model Mappings",name:"model_mappings",tooltip:"Map public model names to LiteLLM model names for load balancing",labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",required:!0,children:(0,c.jsx)(ea.Z,{dataSource:e.getFieldValue("model_mappings"),columns:i,pagination:!1,size:"small"},s)})})},s0=l(90464);let{Link:s1}=es.default;var s2=e=>{let{showAdvancedSettings:s,setShowAdvancedSettings:l,teams:t}=e,[a]=L.Z.useForm(),[r,n]=d.useState(!1),[i,o]=d.useState("per_token"),[m,u]=d.useState(!1),h=(e,s)=>s&&(isNaN(Number(s))||0>Number(s))?Promise.reject("Please enter a valid positive number"):Promise.resolve(),x=(e,s)=>{if(!s)return Promise.resolve();try{return JSON.parse(s),Promise.resolve()}catch(e){return Promise.reject("Please enter valid JSON")}};return(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(C.Z,{className:"mt-2 mb-4",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Advanced Settings"})}),(0,c.jsx)(I.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg",children:[(0,c.jsx)(L.Z.Item,{label:"Custom Pricing",name:"custom_pricing",valuePropName:"checked",className:"mb-4",children:(0,c.jsx)(sB.Z,{onChange:e=>{n(e),e||a.setFieldsValue({input_cost_per_token:void 0,output_cost_per_token:void 0,input_cost_per_second:void 0})},className:"bg-gray-600"})}),r&&(0,c.jsxs)("div",{className:"ml-6 pl-4 border-l-2 border-gray-200",children:[(0,c.jsx)(L.Z.Item,{label:"Pricing Model",name:"pricing_model",className:"mb-4",children:(0,c.jsx)(O.default,{defaultValue:"per_token",onChange:e=>o(e),options:[{value:"per_token",label:"Per Million Tokens"},{value:"per_second",label:"Per Second"}]})}),"per_token"===i?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Input Cost (per 1M tokens)",name:"input_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Output Cost (per 1M tokens)",name:"output_cost_per_token",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}):(0,c.jsx)(L.Z.Item,{label:"Cost Per Second",name:"input_cost_per_second",rules:[{validator:h}],className:"mb-4",children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)(L.Z.Item,{label:"Use in pass through routes",name:"use_in_pass_through",valuePropName:"checked",className:"mb-4 mt-4",tooltip:(0,c.jsxs)("span",{children:["Allow using these credentials in pass through routes."," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/pass_through/vertex_ai",target:"_blank",children:"Learn more"})]}),children:(0,c.jsx)(sB.Z,{onChange:e=>{let s=a.getFieldValue("litellm_extra_params");try{let l=s?JSON.parse(s):{};e?l.use_in_pass_through=!0:delete l.use_in_pass_through,Object.keys(l).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(l,null,2)):a.setFieldValue("litellm_extra_params","")}catch(s){e?a.setFieldValue("litellm_extra_params",JSON.stringify({use_in_pass_through:!0},null,2)):a.setFieldValue("litellm_extra_params","")}},className:"bg-gray-600"})}),(0,c.jsx)(sG,{form:a,showCacheControl:m,onCacheControlChange:e=>{if(u(e),!e){let e=a.getFieldValue("litellm_extra_params");try{let s=e?JSON.parse(e):{};delete s.cache_control_injection_points,Object.keys(s).length>0?a.setFieldValue("litellm_extra_params",JSON.stringify(s,null,2)):a.setFieldValue("litellm_extra_params","")}catch(e){a.setFieldValue("litellm_extra_params","")}}}}),(0,c.jsx)(L.Z.Item,{label:"LiteLLM Params",name:"litellm_extra_params",tooltip:"Optional litellm params used for making a litellm.completion() call.",className:"mb-4 mt-4",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "rpm": 100, "timeout": 0, "stream_timeout": 0 }'})}),(0,c.jsxs)(su.Z,{className:"mb-4",children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"text-gray-600 text-sm",children:["Pass JSON of litellm supported params"," ",(0,c.jsx)(s1,{href:"https://docs.litellm.ai/docs/completion/input",target:"_blank",children:"litellm.completion() call"})]})})]}),(0,c.jsx)(L.Z.Item,{label:"Model Info",name:"model_info_params",tooltip:"Optional model info params. Returned when calling `/model/info` endpoint.",className:"mb-0",rules:[{validator:x}],children:(0,c.jsx)(s0.Z,{rows:4,placeholder:'{ "mode": "chat" }'})})]})})]})})},s4=l(29),s5=l.n(s4),s6=l(23496),s3=l(35291),s8=l(23639);let{Text:s7}=es.default;var s9=e=>{let{formValues:s,accessToken:l,testMode:t,modelName:a="this model",onClose:r,onTestComplete:n}=e,[i,o]=d.useState(null),[m,u]=d.useState(null),[h,x]=d.useState(null),[p,g]=d.useState(!0),[j,f]=d.useState(!1),[_,v]=d.useState(!1),b=async()=>{g(!0),v(!1),o(null),u(null),x(null),f(!1),await new Promise(e=>setTimeout(e,100));try{console.log("Testing connection with form values:",s);let a=await sc(s,l,null);if(!a){console.log("No result from prepareModelAddRequest"),o("Failed to prepare model data. Please check your form inputs."),f(!1),g(!1);return}console.log("Result from prepareModelAddRequest:",a);let{litellmParamsObj:r,modelInfoObj:n,modelName:i}=a[0],c=await (0,y.Hx)(l,r,null==n?void 0:n.mode);if("success"===c.status)D.ZP.success("Connection test successful!"),o(null),f(!0);else{var e,t;let s=(null===(e=c.result)||void 0===e?void 0:e.error)||c.message||"Unknown error";o(s),u(r),x(null===(t=c.result)||void 0===t?void 0:t.raw_request_typed_dict),f(!1)}}catch(e){console.error("Test connection error:",e),o(e instanceof Error?e.message:String(e)),f(!1)}finally{g(!1),n&&n()}};d.useEffect(()=>{let e=setTimeout(()=>{b()},200);return()=>clearTimeout(e)},[]);let Z=e=>e?e.split("stack trace:")[0].trim().replace(/^litellm\.(.*?)Error: /,""):"Unknown error",N="string"==typeof i?Z(i):(null==i?void 0:i.message)?Z(i.message):"Unknown error",w=h?((e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")})(h.raw_request_api_base,h.raw_request_body,h.raw_request_headers||{}):"";return(0,c.jsxs)("div",{style:{padding:"24px",borderRadius:"8px",backgroundColor:"#fff"},children:[p?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},className:"jsx-776cdcbc0448e4ea",children:[(0,c.jsx)("div",{style:{marginBottom:"16px"},className:"jsx-776cdcbc0448e4ea loading-spinner",children:(0,c.jsx)("div",{style:{border:"3px solid #f3f3f3",borderTop:"3px solid #1890ff",borderRadius:"50%",width:"30px",height:"30px",animation:"spin 1s linear infinite",margin:"0 auto"},className:"jsx-776cdcbc0448e4ea"})}),(0,c.jsxs)(s7,{style:{fontSize:"16px"},children:["Testing connection to ",a,"..."]}),(0,c.jsx)(s5(),{id:"776cdcbc0448e4ea",children:"@-webkit-keyframes spin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes spin{0%{-moz-transform:rotate(0deg);transform:rotate(0deg)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes spin{0%{-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes spin{0%{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}"})]}):j?(0,c.jsxs)("div",{style:{textAlign:"center",padding:"32px 20px"},children:[(0,c.jsx)("div",{style:{color:"#52c41a",fontSize:"32px",marginBottom:"16px"},children:(0,c.jsx)("svg",{viewBox:"64 64 896 896",focusable:"false","data-icon":"check-circle",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",children:(0,c.jsx)("path",{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm193.5 301.7l-210.6 292a31.8 31.8 0 01-51.7 0L318.5 484.9c-3.8-5.3 0-12.7 6.5-12.7h46.9c10.2 0 19.9 4.9 25.9 13.3l71.2 98.8 157.2-218c6-8.3 15.6-13.3 25.9-13.3H699c6.5 0 10.3 7.4 6.5 12.7z"})})}),(0,c.jsxs)(s7,{type:"success",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," successful!"]})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",marginBottom:"20px"},children:[(0,c.jsx)(s3.Z,{style:{color:"#ff4d4f",fontSize:"24px",marginRight:"12px"}}),(0,c.jsxs)(s7,{type:"danger",style:{fontSize:"18px",fontWeight:500},children:["Connection to ",a," failed"]})]}),(0,c.jsxs)("div",{style:{backgroundColor:"#fff2f0",border:"1px solid #ffccc7",borderRadius:"8px",padding:"16px",marginBottom:"20px",boxShadow:"0 1px 2px rgba(0, 0, 0, 0.03)"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px"},children:"Error: "}),(0,c.jsx)(s7,{type:"danger",style:{fontSize:"14px",lineHeight:"1.5"},children:N}),i&&(0,c.jsx)("div",{style:{marginTop:"12px"},children:(0,c.jsx)(R.ZP,{type:"link",onClick:()=>v(!_),style:{paddingLeft:0,height:"auto"},children:_?"Hide Details":"Show Details"})})]}),_&&(0,c.jsxs)("div",{style:{marginBottom:"20px"},children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"Troubleshooting Details"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"200px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:"string"==typeof i?i:JSON.stringify(i,null,2)})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(s7,{strong:!0,style:{display:"block",marginBottom:"8px",fontSize:"15px"},children:"API Request"}),(0,c.jsx)("pre",{style:{backgroundColor:"#f5f5f5",padding:"16px",borderRadius:"8px",fontSize:"13px",maxHeight:"250px",overflow:"auto",border:"1px solid #e8e8e8",lineHeight:"1.5"},children:w||"No request data available"}),(0,c.jsx)(R.ZP,{style:{marginTop:"8px"},icon:(0,c.jsx)(s8.Z,{}),onClick:()=>{navigator.clipboard.writeText(w||""),D.ZP.success("Copied to clipboard")},children:"Copy to Clipboard"})]})]})}),(0,c.jsx)(s6.Z,{style:{margin:"24px 0 16px"}}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:(0,c.jsx)(R.ZP,{type:"link",href:"https://docs.litellm.ai/docs/providers",target:"_blank",icon:(0,c.jsx)(J.Z,{}),children:"View Documentation"})})]})};let le=[{value:"chat",label:"Chat - /chat/completions"},{value:"completion",label:"Completion - /completions"},{value:"embedding",label:"Embedding - /embeddings"},{value:"audio_speech",label:"Audio Speech - /audio/speech"},{value:"audio_transcription",label:"Audio Transcription - /audio/transcriptions"},{value:"image_generation",label:"Image Generation - /images/generations"},{value:"rerank",label:"Rerank - /rerank"},{value:"realtime",label:"Realtime - /realtime"}],{Title:ls,Link:ll}=es.default;var lt=e=>{let{form:s,handleOk:l,selectedProvider:t,setSelectedProvider:a,providerModels:r,setProviderModelsFn:i,getPlaceholder:o,uploadProps:m,showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x,credentials:p,accessToken:g,userRole:j}=e,[f,_]=(0,d.useState)("chat"),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(""),k=async()=>{Z(!0),w("test-".concat(Date.now())),v(!0)},S=eg.ZL.includes(j);return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(ls,{level:2,children:"Add new model"}),(0,c.jsx)(s$.Z,{children:(0,c.jsx)(L.Z,{form:s,onFinish:l,labelCol:{span:10},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{rules:[{required:!0,message:"Required"}],label:"Provider:",name:"custom_llm_provider",tooltip:"E.g. OpenAI, Azure OpenAI, Anthropic, Bedrock, etc.",labelCol:{span:10},labelAlign:"left",children:(0,c.jsx)(O.default,{showSearch:!0,value:t,onChange:e=>{a(e),i(e),s.setFieldsValue({model:[],model_name:void 0})},children:Object.entries(n).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("img",{src:sr[l],alt:"".concat(s," logo"),className:"w-5 h-5",onError:e=>{let s=e.target,t=s.parentElement;if(t){let e=document.createElement("div");e.className="w-5 h-5 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=l.charAt(0),t.replaceChild(e,s)}}}),(0,c.jsx)("span",{children:l})]})},s)})})}),(0,c.jsx)(sX,{selectedProvider:t,providerModels:r,getPlaceholder:o}),(0,c.jsx)(sQ,{}),(0,c.jsx)(L.Z.Item,{label:"Mode",name:"mode",className:"mb-1",children:(0,c.jsx)(O.default,{style:{width:"100%"},value:f,onChange:e=>_(e),options:le})}),(0,c.jsxs)(su.Z,{children:[(0,c.jsx)(sh.Z,{span:10}),(0,c.jsx)(sh.Z,{span:10,children:(0,c.jsxs)(A.Z,{className:"mb-5 mt-1",children:[(0,c.jsx)("strong",{children:"Optional"})," - LiteLLM endpoint to use when health checking this model ",(0,c.jsx)(ll,{href:"https://docs.litellm.ai/docs/proxy/health#health",target:"_blank",children:"Learn more"})]})})]}),(0,c.jsx)("div",{className:"mb-4",children:(0,c.jsx)(es.default.Text,{className:"text-sm text-gray-500 mb-2",children:"Either select existing credentials OR enter new provider credentials below"})}),(0,c.jsx)(L.Z.Item,{label:"Existing Credentials",name:"litellm_credential_name",children:(0,c.jsx)(O.default,{showSearch:!0,placeholder:"Select or search for existing credentials",optionFilterProp:"children",filterOption:(e,s)=>{var l;return(null!==(l=null==s?void 0:s.label)&&void 0!==l?l:"").toLowerCase().includes(e.toLowerCase())},options:[{value:null,label:"None"},...p.map(e=>({value:e.credential_name,label:e.credential_name}))],allowClear:!0})}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"OR"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.litellm_credential_name!==s.litellm_credential_name||e.provider!==s.provider,children:e=>{let{getFieldValue:s}=e,l=s("litellm_credential_name");return(console.log("\uD83D\uDD11 Credential Name Changed:",l),l)?(0,c.jsx)("div",{className:"text-gray-500 text-sm text-center",children:"Using existing credentials - no additional provider fields needed"}):(0,c.jsx)(sg,{selectedProvider:t,uploadProps:m})}}),(0,c.jsxs)("div",{className:"flex items-center my-4",children:[(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"}),(0,c.jsx)("span",{className:"px-4 text-gray-500 text-sm",children:"Team Settings"}),(0,c.jsx)("div",{className:"flex-grow border-t border-gray-200"})]}),(0,c.jsx)(L.Z.Item,{label:"Team",name:"team_id",className:"mb-4",tooltip:"Only keys for this team, will be able to call this model.",rules:[{required:!S,message:"Please select a team."}],children:(0,c.jsx)(Q,{teams:x})}),(0,c.jsx)(s2,{showAdvancedSettings:u,setShowAdvancedSettings:h,teams:x}),(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(W.Z,{title:"Get help on our github",children:(0,c.jsx)(es.default.Link,{href:"https://github.com/BerriAI/litellm/issues",children:"Need Help?"})}),(0,c.jsxs)("div",{className:"space-x-2",children:[(0,c.jsx)(R.ZP,{onClick:k,loading:b,children:"Test Connect"}),(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Model"})]})]})]})})}),(0,c.jsx)(M.Z,{title:"Connection Test Results",open:y,onCancel:()=>{v(!1),Z(!1)},footer:[(0,c.jsx)(R.ZP,{onClick:()=>{v(!1),Z(!1)},children:"Close"},"close")],width:700,children:y&&(0,c.jsx)(s9,{formValues:s.getFieldsValue(),accessToken:g,testMode:f,modelName:s.getFieldValue("model_name")||s.getFieldValue("model"),onClose:()=>{v(!1),Z(!1)},onTestComplete:()=>Z(!1)},N)})]})},la=l(32986),lr=l(49084);function ln(e){let{data:s=[],columns:l,isLoading:t=!1}=e,[a,r]=d.useState([{id:"model_info.created_at",desc:!0}]),[n]=d.useState("onChange"),[i,o]=d.useState({}),[m,u]=d.useState({}),[h,x]=d.useState(!1),p=d.useRef(null);d.useEffect(()=>{let e=e=>{p.current&&!p.current.contains(e.target)&&x(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let g=(0,eS.b7)({data:s,columns:l,state:{sorting:a,columnSizing:i,columnVisibility:m},columnResizeMode:n,onSortingChange:r,onColumnSizingChange:o,onColumnVisibilityChange:u,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0,enableColumnResizing:!0,defaultColumn:{minSize:40,maxSize:500}}),j=e=>{if("string"==typeof e)return e;if("function"==typeof e){let s=e();if(s&&s.props&&s.props.children){let e=s.props.children;if("string"==typeof e)return e;if(e.props&&e.props.children)return e.props.children}}return""};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)("div",{className:"flex justify-end",children:(0,c.jsxs)("div",{className:"relative",ref:p,children:[(0,c.jsxs)("button",{onClick:()=>x(!h),className:"flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:[(0,c.jsx)(la.Z,{className:"h-4 w-4"}),"Columns"]}),h&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-56 bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50",children:(0,c.jsx)("div",{className:"py-1",children:g.getAllLeafColumns().map(e=>"actions"===e.id?null:(0,c.jsxs)("div",{className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 cursor-pointer",onClick:()=>e.toggleVisibility(),children:[(0,c.jsx)("input",{type:"checkbox",checked:e.getIsVisible(),onChange:()=>e.toggleVisibility(),className:"h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,c.jsx)("span",{className:"ml-2",children:j(e.columnDef.header)})]},e.id))})})]})}),(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsx)("div",{className:"relative min-w-full",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1 w-full",children:[(0,c.jsx)(eE.Z,{children:g.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsxs)(eP.Z,{className:"py-1 h-8 relative ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.id?120:e.getSize(),position:"actions"===e.id?"sticky":"relative",right:"actions"===e.id?0:"auto"},onClick:e.column.getToggleSortingHandler(),children:[(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]}),e.column.getCanResize()&&(0,c.jsx)("div",{onMouseDown:e.getResizeHandler(),onTouchStart:e.getResizeHandler(),className:"absolute right-0 top-0 h-full w-2 cursor-col-resize select-none touch-none ".concat(e.column.getIsResizing()?"bg-blue-500":"hover:bg-blue-200")})]},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading models..."})})})}):g.getRowModel().rows.length>0?g.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)] z-10 w-[120px] ml-8":""),style:{width:"actions"===e.column.id?120:e.column.getSize(),minWidth:"actions"===e.column.id?120:e.column.getSize(),maxWidth:"actions"===e.column.id?120:e.column.getSize(),position:"actions"===e.column.id?"sticky":"relative",right:"actions"===e.column.id?0:"auto"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No models found"})})})})})]})})})})]})}let li=(e,s,l,t,a,r,n,i,o)=>[{header:"Model ID",accessorKey:"model_info.id",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.model_info.id,children:(0,c.jsx)("div",{className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left w-full truncate whitespace-nowrap cursor-pointer",onClick:()=>t(l.model_info.id),children:l.model_info.id})})}},{header:"Public Model Name",accessorKey:"model_name",cell:e=>{let{row:s}=e,l=r(s.original)||"-";return(0,c.jsx)(W.Z,{title:l,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l})})}},{header:"Provider",accessorKey:"provider",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l.provider&&(0,c.jsx)("img",{src:sn(l.provider).logo,alt:"".concat(l.provider," logo"),className:"w-4 h-4",onError:e=>{let s=e.target,t=s.parentElement;if(t){var a;let e=document.createElement("div");e.className="w-4 h-4 rounded-full bg-gray-200 flex items-center justify-center text-xs",e.textContent=(null===(a=l.provider)||void 0===a?void 0:a.charAt(0))||"-",t.replaceChild(e,s)}}}),(0,c.jsx)("p",{className:"text-xs",children:l.provider||"-"})]})}},{header:"LiteLLM Model Name",accessorKey:"litellm_model_name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.litellm_model_name,children:(0,c.jsx)("div",{className:"text-xs truncate whitespace-nowrap",children:l.litellm_model_name||"-"})})}},{header:"Created At",accessorKey:"model_info.created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_at?new Date(l.model_info.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"model_info.updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.updated_at?new Date(l.model_info.updated_at).toLocaleDateString():"-"})}},{header:"Created By",accessorKey:"model_info.created_by",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:l.model_info.created_by||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Input Cost"})}),accessorKey:"input_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.input_cost||"-"})}},{header:()=>(0,c.jsx)(W.Z,{title:"Cost per 1M tokens",children:(0,c.jsx)("span",{children:"Output Cost"})}),accessorKey:"output_cost",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("pre",{className:"text-xs",children:l.output_cost||"-"})}},{header:"Team ID",accessorKey:"model_info.team_id",cell:e=>{let{row:s}=e,l=s.original;return l.model_info.team_id?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.model_info.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>a(l.model_info.team_id),children:[l.model_info.team_id.slice(0,7),"..."]})})}):"-"}},{header:"Credentials",accessorKey:"litellm_credential_name",cell:e=>{let{row:s}=e,l=s.original;return l.litellm_params&&l.litellm_params.litellm_credential_name?(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsxs)(W.Z,{title:l.litellm_params.litellm_credential_name,children:[l.litellm_params.litellm_credential_name.slice(0,7),"..."]})}):(0,c.jsx)("span",{className:"text-gray-400",children:"-"})}},{header:"Status",accessorKey:"model_info.db_model",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"\n inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium\n ".concat(l.model_info.db_model?"bg-blue-50 text-blue-600":"bg-gray-100 text-gray-600","\n "),children:l.model_info.db_model?"DB Model":"Config Model"})}},{id:"actions",header:"",cell:l=>{var a;let{row:r}=l,n=r.original,i="Admin"===e||(null===(a=n.model_info)||void 0===a?void 0:a.created_by)===s;return(0,c.jsxs)("div",{className:"flex items-center justify-end gap-2 pr-4",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!0))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{i&&(t(n.model_info.id),o(!1))},className:i?"cursor-pointer":"opacity-50 cursor-not-allowed"})]})}}],{Title:lo,Link:lc}=es.default,ld={"BadRequestError (400)":"BadRequestErrorRetries","AuthenticationError (401)":"AuthenticationErrorRetries","TimeoutError (408)":"TimeoutErrorRetries","RateLimitError (429)":"RateLimitErrorRetries","ContentPolicyViolationError (400)":"ContentPolicyViolationErrorRetries","InternalServerError (500)":"InternalServerErrorRetries"};var lm=e=>{let{accessToken:s,token:l,userRole:t,userID:a,modelData:r={data:[]},keys:i,setModelData:o,premiumUser:m,teams:u}=e,[h,x]=(0,d.useState)([]),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)([]);Object.values(n).filter(e=>isNaN(Number(e)));let[Z,N]=(0,d.useState)([]),[S,C]=(0,d.useState)(n.OpenAI),[I,T]=(0,d.useState)(""),[P,O]=(0,d.useState)(!1),[M,F]=(0,d.useState)(null),[R,q]=(0,d.useState)([]),[U,z]=(0,d.useState)([]),[V,K]=(0,d.useState)(null),[B,J]=(0,d.useState)([]),[W,G]=(0,d.useState)([]),[Y,$]=(0,d.useState)([]),[X,Q]=(0,d.useState)([]),[el,et]=(0,d.useState)([]),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)([]),[eo,ec]=(0,d.useState)([]),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[ex,ep]=(0,d.useState)(null),[ej,ef]=(0,d.useState)(0),[e_,ey]=(0,d.useState)({}),[ev,eb]=(0,d.useState)([]),[eZ,eN]=(0,d.useState)(!1),[ew,ek]=(0,d.useState)(null),[eS,eC]=(0,d.useState)(null),[eL,eM]=(0,d.useState)([]),[eK,eH]=(0,d.useState)([]),[eJ,eW]=(0,d.useState)(!1),[eG,eY]=(0,d.useState)(null),[e$,eQ]=(0,d.useState)(!1),[e0,e1]=(0,d.useState)(null),e2=async(e,l,r)=>{if(console.log("Updating model metrics for group:",e),!s||!a||!t||!l||!r)return;console.log("inside updateModelMetrics - startTime:",l,"endTime:",r),K(e);let n=null==ew?void 0:ew.token;void 0===n&&(n=null);let i=eS;void 0===i&&(i=null),l.setHours(0),l.setMinutes(0),l.setSeconds(0),r.setHours(23),r.setMinutes(59),r.setSeconds(59);try{let o=await (0,y.o6)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model metrics response:",o),G(o.data),$(o.all_api_bases);let c=await (0,y.Rg)(s,e,l.toISOString(),r.toISOString());Q(c.data),et(c.all_api_bases);let d=await (0,y.N8)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);console.log("Model exceptions response:",d),er(d.data),ei(d.exception_types);let m=await (0,y.fP)(s,a,t,e,l.toISOString(),r.toISOString(),n,i);if(console.log("slowResponses:",m),em(m),e){let t=await (0,y.n$)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);ey(t);let a=await (0,y.v9)(s,null==l?void 0:l.toISOString().split("T")[0],null==r?void 0:r.toISOString().split("T")[0],e);eb(a)}}catch(e){console.error("Failed to fetch model metrics",e)}},e4=async e=>{try{let s=await (0,y.N3)(e);console.log("credentials: ".concat(JSON.stringify(s))),eH(s.credentials)}catch(e){console.error("Error fetching credentials:",e)}};(0,d.useEffect)(()=>{e2(V,eu.from,eu.to)},[ew,eS]);let e5={name:"file",accept:".json",beforeUpload:e=>{if("application/json"===e.type){let s=new FileReader;s.onload=e=>{if(e.target){let s=e.target.result;p.setFieldsValue({vertex_credentials:s})}},s.readAsText(e)}return!1},onChange(e){"uploading"!==e.file.status&&console.log(e.file,e.fileList),"done"===e.file.status?D.ZP.success("".concat(e.file.name," file uploaded successfully")):"error"===e.file.status&&D.ZP.error("".concat(e.file.name," file upload failed."))}},e6=()=>{_(new Date().toLocaleString())},e3=async()=>{if(!s){console.error("Access token is missing");return}console.log("new modelGroupRetryPolicy:",ex);try{await (0,y.K_)(s,{router_settings:{model_group_retry_policy:ex}}),D.ZP.success("Retry settings saved successfully")}catch(e){console.error("Failed to save retry settings:",e),D.ZP.error("Failed to save retry settings")}};if((0,d.useEffect)(()=>{if(!s||!l||!t||!a)return;let e=async()=>{try{var e,l,r,n,i,c,d,m,u,h,x,p;let g=await (0,y.AZ)(s,a,t);console.log("Model data response:",g.data),o(g);let j=await (0,y.hy)(s);j&&N(j);let f=new Set;for(let e=0;e0&&(v=_[_.length-1],console.log("_initial_model_group:",v)),console.log("selectedModelGroup:",V);let b=await (0,y.o6)(s,a,t,v,null===(e=eu.from)||void 0===e?void 0:e.toISOString(),null===(l=eu.to)||void 0===l?void 0:l.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model metrics response:",b),G(b.data),$(b.all_api_bases);let Z=await (0,y.Rg)(s,v,null===(r=eu.from)||void 0===r?void 0:r.toISOString(),null===(n=eu.to)||void 0===n?void 0:n.toISOString());Q(Z.data),et(Z.all_api_bases);let w=await (0,y.N8)(s,a,t,v,null===(i=eu.from)||void 0===i?void 0:i.toISOString(),null===(c=eu.to)||void 0===c?void 0:c.toISOString(),null==ew?void 0:ew.token,eS);console.log("Model exceptions response:",w),er(w.data),ei(w.exception_types);let k=await (0,y.fP)(s,a,t,v,null===(d=eu.from)||void 0===d?void 0:d.toISOString(),null===(m=eu.to)||void 0===m?void 0:m.toISOString(),null==ew?void 0:ew.token,eS),S=await (0,y.n$)(s,null===(u=eu.from)||void 0===u?void 0:u.toISOString().split("T")[0],null===(h=eu.to)||void 0===h?void 0:h.toISOString().split("T")[0],v);ey(S);let C=await (0,y.v9)(s,null===(x=eu.from)||void 0===x?void 0:x.toISOString().split("T")[0],null===(p=eu.to)||void 0===p?void 0:p.toISOString().split("T")[0],v);eb(C),console.log("dailyExceptions:",S),console.log("dailyExceptionsPerDeplyment:",C),console.log("slowResponses:",k),em(k);let I=await (0,y.j2)(s);eM(null==I?void 0:I.end_users);let T=(await (0,y.BL)(s,a,t)).router_settings;console.log("routerSettingsInfo:",T);let A=T.model_group_retry_policy,E=T.num_retries;console.log("model_group_retry_policy:",A),console.log("default_retries:",E),ep(A),ef(E)}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&t&&a&&e();let r=async()=>{let e=await (0,y.qm)(s);console.log("received model cost map data: ".concat(Object.keys(e))),j(e)};null==g&&r(),e6()},[s,l,t,a,g,f]),!r||!s||!l||!t||!a)return(0,c.jsx)("div",{children:"Loading..."});let e8=[],e7=[];for(let e=0;e(console.log("GET PROVIDER CALLED! - ".concat(g)),null!=g&&"object"==typeof g&&e in g)?g[e].litellm_provider:"openai";if(l){let e=l.split("/"),s=e[0];(n=t)||(n=1===e.length?u(l):s)}else n="-";a&&(i=null==a?void 0:a.input_cost_per_token,o=null==a?void 0:a.output_cost_per_token,c=null==a?void 0:a.max_tokens,d=null==a?void 0:a.max_input_tokens),(null==s?void 0:s.litellm_params)&&(m=Object.fromEntries(Object.entries(null==s?void 0:s.litellm_params).filter(e=>{let[s]=e;return"model"!==s&&"api_base"!==s}))),r.data[e].provider=n,r.data[e].input_cost=i,r.data[e].output_cost=o,r.data[e].litellm_model_name=l,e7.push(n),r.data[e].input_cost&&(r.data[e].input_cost=(1e6*Number(r.data[e].input_cost)).toFixed(2)),r.data[e].output_cost&&(r.data[e].output_cost=(1e6*Number(r.data[e].output_cost)).toFixed(2)),r.data[e].max_tokens=c,r.data[e].max_input_tokens=d,r.data[e].api_base=null==s?void 0:null===(ss=s.litellm_params)||void 0===ss?void 0:ss.api_base,r.data[e].cleanedLitellmParams=m,e8.push(s.model_name),console.log(r.data[e])}if(t&&"Admin Viewer"==t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to view all models"})]})}let sa=async()=>{try{D.ZP.info("Running health check..."),T("");let e=await (0,y.EY)(s);T(e)}catch(e){console.error("Error running health check:",e),T("Error running health check")}},sr=(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mb-1",children:"Select API Key Name"}),m?(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{ek(e)},children:e.key_alias},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>{eC(e)},children:e},s))]})]}):(0,c.jsxs)("div",{children:[(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{ek(null)},children:"All Keys"},"all-keys"),null==i?void 0:i.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsxs)(ee.Z,{value:String(s),disabled:!0,onClick:()=>{ek(e)},children:["✨ ",e.key_alias," (Enterprise only Feature)"]},s):null)]}),(0,c.jsx)(A.Z,{className:"mt-1",children:"Select Customer Name"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-customers",children:[(0,c.jsx)(ee.Z,{value:"all-customers",onClick:()=>{eC(null)},children:"All Customers"},"all-customers"),null==eL?void 0:eL.map((e,s)=>(0,c.jsxs)(ee.Z,{value:e,disabled:!0,onClick:()=>{eC(e)},children:["✨ ",e," (Enterprise only Feature)"]},s))]})]})]}),sn=e=>{var s,l;let{payload:t,active:a}=e;if(!a||!t)return null;let r=null===(l=t[0])||void 0===l?void 0:null===(s=l.payload)||void 0===s?void 0:s.date,n=t.sort((e,s)=>s.value-e.value);if(n.length>5){let e=n.length-5;(n=n.slice(0,5)).push({dataKey:"".concat(e," other deployments"),value:t.slice(5).reduce((e,s)=>e+s.value,0),color:"gray"})}return(0,c.jsxs)("div",{className:"w-150 rounded-tremor-default border border-tremor-border bg-tremor-background p-2 text-tremor-default shadow-tremor-dropdown",children:[r&&(0,c.jsxs)("p",{className:"text-tremor-content-emphasis mb-2",children:["Date: ",r]}),n.map((e,s)=>{let l=parseFloat(e.value.toFixed(5)),t=0===l&&e.value>0?"<0.00001":l.toFixed(5);return(0,c.jsxs)("div",{className:"flex justify-between",children:[(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsx)("div",{className:"w-2 h-2 mt-1 rounded-full bg-".concat(e.color,"-500")}),(0,c.jsx)("p",{className:"text-tremor-content",children:e.dataKey})]}),(0,c.jsx)("p",{className:"font-medium text-tremor-content-emphasis text-righ ml-2",children:t})]},s)})]})};console.log("selectedProvider: ".concat(S)),console.log("providerModels.length: ".concat(v.length));let sc=Object.keys(n).find(e=>n[e]===S);return(sc&&Z&&Z.find(e=>e.name===st[sc]),e0)?(0,c.jsx)("div",{className:"w-full h-full",children:(0,c.jsx)(sq,{teamId:e0,onClose:()=>e1(null),accessToken:s,is_team_admin:"Admin"===t,is_proxy_admin:"Proxy Admin"===t,userModels:e8,editTeam:!1,onUpdate:e6})}):(0,c.jsx)("div",{style:{width:"100%",height:"100%"},children:eG?(0,c.jsx)(sY,{modelId:eG,editModel:!0,onClose:()=>{eY(null),eQ(!1)},modelData:r.data.find(e=>e.model_info.id===eG),accessToken:s,userID:a,userRole:t,setEditModalVisible:O,setSelectedModel:F,onModelUpdate:e=>{o({...r,data:r.data.map(s=>s.model_info.id===e.model_info.id?e:s)}),e6()}}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[eg.ZL.includes(t)?(0,c.jsx)(eR.Z,{children:"All Models"}):(0,c.jsx)(eR.Z,{children:"Your Models"}),(0,c.jsx)(eR.Z,{children:"Add Model"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"LLM Credentials"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"/health Models"})}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Analytics"}),eg.ZL.includes(t)&&(0,c.jsx)(eR.Z,{children:"Model Retry Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:e6})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(E.Z,{children:"Model Management"}),eg.ZL.includes(t)?(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add and manage models for the proxy"}):(0,c.jsx)(A.Z,{className:"text-tremor-content",children:"Add models for teams you are an admin for."})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name:"}),(0,c.jsxs)(eD.Z,{className:"w-64",defaultValue:null!=V?V:"all",onValueChange:e=>K("all"===e?"all":e),value:null!=V?V:"all",children:[(0,c.jsx)(ee.Z,{value:"all",children:"All Models"}),R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))]})]})]}),(0,c.jsx)(ln,{columns:li(t,a,m,eY,e1,sv,e=>{F(e),O(!0)},e6,eQ),data:r.data.filter(e=>"all"===V||e.model_name===V||!V),isLoading:!1})]})}),(0,c.jsx)(ez.Z,{className:"h-full",children:(0,c.jsx)(lt,{form:p,handleOk:()=>{p.validateFields().then(e=>{sd(e,s,p,e6)}).catch(e=>{console.error("Validation failed:",e)})},selectedProvider:S,setSelectedProvider:C,providerModels:v,setProviderModelsFn:e=>{let s=so(e,g);b(s),console.log("providerModels: ".concat(s))},getPlaceholder:si,uploadProps:e5,showAdvancedSettings:eJ,setShowAdvancedSettings:eW,teams:u,credentials:eK,accessToken:s,userRole:t})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sy,{accessToken:s,uploadProps:e5,credentialList:eK,fetchCredentials:e4})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"`/health` will run a very small request through your models configured on litellm"}),(0,c.jsx)(k.Z,{onClick:sa,children:"Run `/health`"}),I&&(0,c.jsx)("pre",{children:JSON.stringify(I,null,2)})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:4,className:"mt-2 mb-2",children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:eu,className:"mr-2",onValueChange:e=>{eh(e),e2(V,e.from,e.to)}})]}),(0,c.jsxs)(sh.Z,{className:"ml-2",children:[(0,c.jsx)(A.Z,{children:"Select Model Group"}),(0,c.jsx)(eD.Z,{defaultValue:V||R[0],value:V||R[0],children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>e2(e,eu.from,eu.to),children:e},s))})]}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(sk.Z,{trigger:"click",content:sr,overlayStyle:{width:"20vw"},children:(0,c.jsx)(k.Z,{icon:eX.Z,size:"md",variant:"secondary",className:"mt-4 ml-2",style:{border:"none"},onClick:()=>eN(!0)})})})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"mr-2 max-h-[400px] min-h-[400px]",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Avg. Latency per Token"}),(0,c.jsx)(eR.Z,{value:"2",children:"Time to first token"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)("p",{className:"text-gray-500 italic",children:" (seconds/token)"}),(0,c.jsx)(A.Z,{className:"text-gray-500 italic mt-1 mb-1",children:"average Latency for successfull requests divided by the total tokens"}),W&&Y&&(0,c.jsx)(sN.Z,{title:"Model Latency",className:"h-72",data:W,showLegend:!1,index:"date",categories:Y,connectNulls:!0,customTooltip:sn})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(sC,{modelMetrics:X,modelMetricsCategories:el,customTooltip:sn,premiumUser:m})})]})]})})}),(0,c.jsx)(sh.Z,{children:(0,c.jsx)(eF.Z,{className:"ml-2 max-h-[400px] min-h-[400px] overflow-y-auto",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Deployment"}),(0,c.jsx)(eP.Z,{children:"Success Responses"}),(0,c.jsxs)(eP.Z,{children:["Slow Responses ",(0,c.jsx)("p",{children:"Success Responses taking 600+s"})]})]})}),(0,c.jsx)(eT.Z,{children:ed.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.api_base}),(0,c.jsx)(eA.Z,{children:e.total_count}),(0,c.jsx)(eA.Z,{children:e.slow_count})]},s))})]})})})]}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Exceptions for ",V]}),(0,c.jsx)(sw.Z,{className:"h-60",data:ea,index:"model",categories:en,stack:!0,yAxisWidth:30})]})}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 w-full mt-2",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["All Up Rate Limit Errors (429) for ",V]}),(0,c.jsxs)(w.Z,{numItems:1,children:[(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e_.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e_.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]}),(0,c.jsx)(sh.Z,{})]})]}),m?(0,c.jsx)(c.Fragment,{children:ev.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base?e.api_base:"Unknown API Base"}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors (429) ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]},s))}):(0,c.jsx)(c.Fragment,{children:ev&&ev.length>0&&ev.slice(0,1).map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"✨ Rate Limit Errors by Deployment"}),(0,c.jsx)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:"Upgrade to see exceptions for all deployments"}),(0,c.jsx)(k.Z,{variant:"primary",className:"mb-2",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"Get Free Trial"})}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.api_base}),(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(sh.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Num Rate Limit Errors ",e.sum_num_rate_limit_exceptions]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["rose"],categories:["num_rate_limit_exceptions"],onValueChange:e=>console.log(e)})]})})]})]},s))})]})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(A.Z,{children:"Filter by Public Model Name"}),(0,c.jsx)(eD.Z,{className:"mb-4 mt-2 ml-2 w-50",defaultValue:V||R[0],value:V||R[0],onValueChange:e=>K(e),children:R.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>K(e),children:e},s))})]}),(0,c.jsxs)(E.Z,{children:["Retry Policy for ",V]}),(0,c.jsx)(A.Z,{className:"mb-6",children:"How many retries should be attempted based on the Exception"}),ld&&(0,c.jsx)("table",{children:(0,c.jsx)("tbody",{children:Object.entries(ld).map((e,s)=>{var l;let[t,a]=e,r=null==ex?void 0:null===(l=ex[V])||void 0===l?void 0:l[a];return null==r&&(r=ej),(0,c.jsxs)("tr",{className:"flex justify-between items-center mt-2",children:[(0,c.jsx)("td",{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)("td",{children:(0,c.jsx)(H.Z,{className:"ml-5",value:r,min:0,step:1,onChange:e=>{ep(s=>{var l;let t=null!==(l=null==s?void 0:s[V])&&void 0!==l?l:{};return{...null!=s?s:{},[V]:{...t,[a]:e}}})}})})]},s)})})}),(0,c.jsx)(k.Z,{className:"mt-6 mr-8",onClick:e3,children:"Save"})]})]})]})})},lu=e=>{let{visible:s,possibleUIRoles:l,onCancel:t,user:a,onSubmit:r}=e,[n,i]=(0,d.useState)(a),[o]=L.Z.useForm();(0,d.useEffect)(()=>{o.resetFields()},[a]);let m=async()=>{o.resetFields(),t()},u=async e=>{r(e),o.resetFields(),t()};return a?(0,c.jsx)(M.Z,{visible:s,onCancel:m,footer:null,title:"Edit User "+a.user_id,width:1e3,children:(0,c.jsx)(L.Z,{form:o,onFinish:u,initialValues:a,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"User Email",tooltip:"Email of the User",name:"user_email",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"user_id",name:"user_id",hidden:!0,children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"User Role",name:"user_role",children:(0,c.jsx)(O.default,{children:l&&Object.entries(l).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(ee.Z,{value:s,title:l,children:(0,c.jsxs)("div",{className:"flex",children:[l," ",(0,c.jsx)("p",{className:"ml-2",style:{color:"gray",fontSize:"12px"},children:t})]})},s)})})}),(0,c.jsx)(L.Z.Item,{label:"Spend (USD)",name:"spend",tooltip:"(float) - Spend of all LLM calls completed by this user",help:"Across all keys (including keys with team_id).",children:(0,c.jsx)(H.Z,{min:0,step:.01})}),(0,c.jsx)(L.Z.Item,{label:"User Budget (USD)",name:"max_budget",tooltip:"(float) - Maximum budget of this user",help:"Maximum budget of this user.",children:(0,c.jsx)(z,{min:0,step:.01})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})}):null},lh=l(15731);let lx=(e,s,l)=>[{header:"User ID",accessorKey:"user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)(W.Z,{title:s.original.user_id,children:(0,c.jsx)("span",{className:"text-xs",children:s.original.user_id?"".concat(s.original.user_id.slice(0,7),"..."):"-"})})}},{header:"User Email",accessorKey:"user_email",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.user_email||"-"})}},{header:"Global Proxy Role",accessorKey:"user_role",cell:s=>{var l;let{row:t}=s;return(0,c.jsx)("span",{className:"text-xs",children:(null==e?void 0:null===(l=e[t.original.user_role])||void 0===l?void 0:l.ui_label)||"-"})}},{header:"User Spend ($ USD)",accessorKey:"spend",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.spend?s.original.spend.toFixed(2):"-"})}},{header:"User Max Budget ($ USD)",accessorKey:"max_budget",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.max_budget?s.original.max_budget:"Unlimited"})}},{header:()=>(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{children:"SSO ID"}),(0,c.jsx)(W.Z,{title:"SSO ID is the ID of the user in the SSO provider. If the user is not using SSO, this will be null.",children:(0,c.jsx)(lh.Z,{className:"w-4 h-4"})})]}),accessorKey:"sso_user_id",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:null!==s.original.sso_user_id?s.original.sso_user_id:"-"})}},{header:"API Keys",accessorKey:"key_count",cell:e=>{let{row:s}=e;return(0,c.jsx)(w.Z,{numItems:2,children:s.original.key_count>0?(0,c.jsxs)(eM.Z,{size:"xs",color:"indigo",children:[s.original.key_count," Keys"]}):(0,c.jsx)(eM.Z,{size:"xs",color:"gray",children:"No Keys"})})}},{header:"Created At",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.created_at?new Date(s.original.created_at).toLocaleDateString():"-"})}},{header:"Updated At",accessorKey:"updated_at",sortingFn:"datetime",cell:e=>{let{row:s}=e;return(0,c.jsx)("span",{className:"text-xs",children:s.original.updated_at?new Date(s.original.updated_at).toLocaleDateString():"-"})}},{id:"actions",header:"",cell:e=>{let{row:t}=e;return(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>s(t.original)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>l(t.original.user_id)})]})}}];function lp(e){var s,l,t,a,r,n,i,o,m,u,h,x,p,g,j;let{userId:f,onClose:_,accessToken:v,userRole:b,onDelete:Z}=e,[N,S]=(0,d.useState)(null),[C,I]=(0,d.useState)(!1),[T,P]=(0,d.useState)(!0);d.useEffect(()=>{console.log("userId: ".concat(f,", userRole: ").concat(b,", accessToken: ").concat(v)),(async()=>{try{if(!v)return;let e=await (0,y.Br)(v,f,b||"",!1,null,null,!0);S(e)}catch(e){console.error("Error fetching user data:",e),D.ZP.error("Failed to fetch user data")}finally{P(!1)}})()},[v,f,b]);let O=async()=>{try{if(!v)return;await (0,y.Eb)(v,[f]),D.ZP.success("User deleted successfully"),Z&&Z(),_()}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}};return T?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"Loading user data..."})]}):N?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(E.Z,{children:(null===(s=N.user_info)||void 0===s?void 0:s.user_email)||"User"}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:N.user_id})]}),b&&eg.LQ.includes(b)&&(0,c.jsx)(k.Z,{icon:eH.Z,variant:"secondary",onClick:()=>I(!0),className:"flex items-center",children:"Delete User"})]}),C&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:O,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>I(!1),children:"Cancel"})]})]})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Details"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Spend"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",Number((null===(l=N.user_info)||void 0===l?void 0:l.spend)||0).toFixed(4)]}),(0,c.jsxs)(A.Z,{children:["of ",(null===(t=N.user_info)||void 0===t?void 0:t.max_budget)!==null?"$".concat(N.user_info.max_budget):"Unlimited"]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Teams"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(a=N.teams)||void 0===a?void 0:a.length)||0," teams"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"API Keys"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)(A.Z,{children:[(null===(r=N.keys)||void 0===r?void 0:r.length)||0," keys"]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"User ID"}),(0,c.jsx)(A.Z,{className:"font-mono",children:N.user_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Email"}),(0,c.jsx)(A.Z,{children:(null===(n=N.user_info)||void 0===n?void 0:n.user_email)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Role"}),(0,c.jsx)(A.Z,{children:(null===(i=N.user_info)||void 0===i?void 0:i.user_role)||"Not Set"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:(null===(o=N.user_info)||void 0===o?void 0:o.created_at)?new Date(N.user_info.created_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:(null===(m=N.user_info)||void 0===m?void 0:m.updated_at)?new Date(N.user_info.updated_at).toLocaleString():"Unknown"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Teams"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(u=N.teams)||void 0===u?void 0:u.length)&&(null===(h=N.teams)||void 0===h?void 0:h.length)>0?null===(x=N.teams)||void 0===x?void 0:x.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:e.team_alias||e.team_id},s)):(0,c.jsx)(A.Z,{children:"No teams"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"API Keys"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:(null===(p=N.keys)||void 0===p?void 0:p.length)&&(null===(g=N.keys)||void 0===g?void 0:g.length)>0?N.keys.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-green-100 rounded text-xs",children:e.key_alias||e.token},s)):(0,c.jsx)(A.Z,{children:"No API keys"})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Metadata"}),(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify((null===(j=N.user_info)||void 0===j?void 0:j.metadata)||{},null,2)})]})]})})})]})]})]}):(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsx)(k.Z,{icon:eK.Z,variant:"light",onClick:_,className:"mb-4",children:"Back to Users"}),(0,c.jsx)(A.Z,{children:"User not found"})]})}function lg(e){let{data:s=[],columns:l,isLoading:t=!1,onSortChange:a,currentSort:r,accessToken:n,userRole:i}=e,[o,m]=d.useState([{id:(null==r?void 0:r.sortBy)||"created_at",desc:(null==r?void 0:r.sortOrder)==="desc"}]),[u,h]=d.useState(null),x=(0,eS.b7)({data:s,columns:l,state:{sorting:o},onSortingChange:e=>{if(m(e),e.length>0){let s=e[0],l=s.id,t=s.desc?"desc":"asc";null==a||a(l,t)}},getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0}),p=e=>{h(e)};return(d.useEffect(()=>{r&&m([{id:r.sortBy,desc:"desc"===r.sortOrder}])},[r]),u)?(0,c.jsx)(lp,{userId:u,onClose:()=>{h(null)},accessToken:n,userRole:i}):(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:x.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:t?(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"\uD83D\uDE85 Loading users..."})})})}):s.length>0?x.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:()=>{"user_id"===e.column.id&&p(e.getValue())},style:{cursor:"user_id"===e.column.id?"pointer":"default",color:"user_id"===e.column.id?"#3b82f6":"inherit"},children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:l.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No users found"})})})})})]})})})}var lj=l(67982),lf=e=>{var s;let{accessToken:l,possibleUIRoles:t,userID:a,userRole:r}=e,[n,i]=(0,d.useState)(!0),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)({}),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)([]),{Paragraph:v}=es.default,{Option:b}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){i(!1);return}try{let e=await (0,y.NL)(l);if(m(e),p(e.values||{}),l)try{let e=await (0,y.So)(l,a,r);if(e&&e.data){let s=e.data.map(e=>e.id);_(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching SSO settings:",e),D.ZP.error("Failed to fetch SSO settings")}finally{i(!1)}})()},[l]);let Z=async()=>{if(l){j(!0);try{let e=await (0,y.nd)(l,x);m({...o,values:e.settings}),h(!1)}catch(e){console.error("Error updating SSO settings:",e),D.ZP.error("Failed to update settings")}finally{j(!1)}}},N=(e,s)=>{p(l=>({...l,[e]:s}))},w=(e,s,l)=>{var a;let r=s.type;return"user_role"===e&&t?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:Object.entries(t).filter(e=>{let[s]=e;return s.includes("internal_user")}).map(e=>{let[s,{ui_label:l,description:t}]=e;return(0,c.jsx)(b,{value:s,children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{children:l}),(0,c.jsx)("span",{className:"ml-2 text-xs text-gray-500",children:t})]})},s)})}):"budget_duration"===e?(0,c.jsx)(e_,{value:x[e]||null,onChange:s=>N(e,s),className:"mt-2"}):"boolean"===r?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!x[e],onChange:s=>N(e,s)})}):"array"===r&&(null===(a=s.items)||void 0===a?void 0:a.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:x[e]||[],onChange:s=>N(e,s),className:"mt-2",children:f.map(e=>(0,c.jsx)(b,{value:e,children:K(e)},e))}):"string"===r&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:x[e]||"",onChange:s=>N(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(b,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==x[e]?String(x[e]):"",onChange:s=>N(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},C=(e,s)=>{if(null==s)return(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"});if("user_role"===e&&t&&t[s]){let{ui_label:e,description:l}=t[s];return(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{className:"font-medium",children:e}),l&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:l})]})}return"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)})};return n?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):o?(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex justify-end items-center mb-4",children:!n&&o&&(u?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{h(!1),p(o.values||{})},disabled:g,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:Z,loading:g,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>h(!0),children:"Edit Settings"}))}),(null==o?void 0:null===(s=o.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(v,{className:"mb-4",children:o.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=o;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(v,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),u?(0,c.jsx)("div",{className:"mt-2",children:w(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:C(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No settings available or you do not have permission to view them."})})};console.log=function(){};var l_=e=>{let{accessToken:s,token:l,keys:t,userRole:a,userID:r,teams:n,setKeys:i}=e,[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(1),[g,j]=d.useState(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),[w,S]=(0,d.useState)(!1),[C,I]=(0,d.useState)(null),[T,A]=(0,d.useState)({}),[E,P]=(0,d.useState)(""),[O,L]=(0,d.useState)("users"),[M,F]=(0,d.useState)({email:"",user_id:"",user_role:"",sso_user_id:"",team:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"}),[R,q]=(0,d.useState)(!1),[U,z]=(0,d.useState)(!1),[V,K]=(0,d.useState)("Email");(0,d.useRef)(null);let B=(0,d.useRef)(0);window.addEventListener("beforeunload",function(){sessionStorage.clear()});let H=(e,s)=>{let l={...M,[e]:s};F(l),console.log("called from handleFilterChange - newFilters:",JSON.stringify(l)),J(l)},J=(0,d.useCallback)(ep()(async e=>{if(!s||!l||!a||!r)return;let t=Date.now();B.current=t;try{let l=await (0,y.Of)(s,e.user_id?[e.user_id]:null,1,25,e.email||null,e.user_role||null,e.team||null,e.sso_user_id||null,e.sort_by,e.sort_order);t===B.current&&l&&(m(l),console.log("called from debouncedSearch filters:",JSON.stringify(e)),console.log("called from debouncedSearch data:",JSON.stringify(l)))}catch(e){console.error("Error searching users:",e)}},300),[s,l,a,r]);(0,d.useEffect)(()=>()=>{J.cancel()},[J]);let W=async()=>{if(C&&s)try{if(await (0,y.Eb)(s,[C]),D.ZP.success("User deleted successfully"),o){var e;let s=null===(e=o.users)||void 0===e?void 0:e.filter(e=>e.user_id!==C);m({...o,users:s||[]})}}catch(e){console.error("Error deleting user:",e),D.ZP.error("Failed to delete user")}S(!1),I(null)},G=async()=>{N(null),b(!1)},Y=async e=>{if(console.log("inside handleEditSubmit:",e),s&&l&&a&&r){try{await (0,y.pf)(s,e,null),D.ZP.success("User ".concat(e.user_id," updated successfully"))}catch(e){console.error("There was an error updating the user",e)}if(o){var t;let s=null===(t=o.users)||void 0===t?void 0:t.map(s=>s.user_id===e.user_id?e:s);m({...o,users:s||[]})}N(null),b(!1)}},$=async e=>{if(s&&l&&a&&r)try{let l=await (0,y.Of)(s,M.user_id?[M.user_id]:null,e,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(e),JSON.stringify(l)),m(l),p(e)}catch(e){console.error("Error changing page:",e)}};if((0,d.useEffect)(()=>{if(!s||!l||!a||!r)return;let e=async()=>{try{let e=sessionStorage.getItem("userList_".concat(x));if(e){let s=JSON.parse(e);m(s),console.log("called from useEffect")}else{let e=await (0,y.Of)(s,M.user_id?[M.user_id]:null,x,25,M.email||null,M.user_role||null,M.team||null,M.sso_user_id||null,M.sort_by,M.sort_order);sessionStorage.setItem("userList_".concat(x),JSON.stringify(e)),m(e),console.log("called from useEffect 2")}let l=sessionStorage.getItem("possibleUserRoles");if(l)A(JSON.parse(l));else{let e=await (0,y.lg)(s);sessionStorage.setItem("possibleUserRoles",JSON.stringify(e)),A(e)}}catch(e){console.error("There was an error fetching the model data",e)}};s&&l&&a&&r&&e()},[s,l,a,r]),!o||!s||!l||!a||!r)return(0,c.jsx)("div",{children:"Loading..."});let X=lx(T,e=>{N(e),b(!0)},e=>{I(e),S(!0)});return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Users"}),(0,c.jsx)("div",{className:"flex space-x-3",children:(0,c.jsx)(eh,{userID:r,accessToken:s,teams:n,possibleUIRoles:T})})]}),(0,c.jsxs)(eq.Z,{defaultIndex:0,onIndexChange:e=>L(0===e?"users":"settings"),children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Users"}),(0,c.jsx)(eR.Z,{children:"Default User Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by email...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.email,onChange:e=>H("email",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2 ".concat(R?"bg-gray-100":""),onClick:()=>q(!R),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filters",(M.user_id||M.user_role||M.team)&&(0,c.jsx)("span",{className:"w-2 h-2 rounded-full bg-blue-500"})]}),(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>{F({email:"",user_id:"",user_role:"",team:"",sso_user_id:"",model:"",min_spend:null,max_spend:null,sort_by:"created_at",sort_order:"desc"})},children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),"Reset Filters"]})]}),R&&(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mt-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Filter by User ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.user_id,onChange:e=>H("user_id",e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"})})]}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.user_role,onValueChange:e=>H("user_role",e),placeholder:"Select Role",children:Object.entries(T).map(e=>{let[s,l]=e;return(0,c.jsx)(ee.Z,{value:s,children:l.ui_label},s)})})}),(0,c.jsx)("div",{className:"w-64",children:(0,c.jsx)(eD.Z,{value:M.team,onValueChange:e=>H("team",e),placeholder:"Select Team",children:null==n?void 0:n.map(e=>(0,c.jsx)(ee.Z,{value:e.team_id,children:e.team_alias||e.team_id},e.team_id))})}),(0,c.jsx)("div",{className:"relative w-64",children:(0,c.jsx)("input",{type:"text",placeholder:"Filter by SSO ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:M.sso_user_id,onChange:e=>H("sso_user_id",e.target.value)})})]}),(0,c.jsxs)("div",{className:"flex justify-between items-center",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",o&&o.users&&o.users.length>0?(o.page-1)*o.page_size+1:0," ","-"," ",o&&o.users?Math.min(o.page*o.page_size,o.total):0," ","of ",o?o.total:0," results"]}),(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>$(x-1),disabled:1===x,className:"px-3 py-1 text-sm border rounded-md ".concat(1===x?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Previous"}),(0,c.jsx)("button",{onClick:()=>$(x+1),disabled:!o||x>=o.total_pages,className:"px-3 py-1 text-sm border rounded-md ".concat(!o||x>=o.total_pages?"bg-gray-100 text-gray-400 cursor-not-allowed":"hover:bg-gray-50"),children:"Next"})]})]})]})}),(0,c.jsx)(lg,{data:(null==o?void 0:o.users)||[],columns:X,isLoading:!o,accessToken:s,userRole:a,onSortChange:(e,s)=>{let l={...M,sort_by:e,sort_order:s};F(l),J(l)},currentSort:{sortBy:M.sort_by,sortOrder:M.sort_order}})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lf,{accessToken:s,possibleUIRoles:T,userID:r,userRole:a})})]})]}),(0,c.jsx)(lu,{visible:v,possibleUIRoles:T,onCancel:G,user:Z,onSubmit:Y}),w&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete User"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this user?"}),(0,c.jsxs)("p",{className:"text-sm font-medium text-gray-900 mt-2",children:["User ID: ",C]})]})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:W,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{S(!1),I(null)},children:"Cancel"})]})]})]})})]})},ly=e=>{var s;let{accessToken:l,userID:t,userRole:a}=e,[r,n]=(0,d.useState)(!0),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(!1),[h,x]=(0,d.useState)({}),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)([]),{Paragraph:_}=es.default,{Option:v}=O.default;(0,d.useEffect)(()=>{(async()=>{if(!l){n(!1);return}try{let e=await (0,y.EB)(l);if(o(e),x(e.values||{}),l)try{let e=await (0,y.So)(l,t,a);if(e&&e.data){let s=e.data.map(e=>e.id);f(s)}}catch(e){console.error("Error fetching available models:",e)}}catch(e){console.error("Error fetching team SSO settings:",e),D.ZP.error("Failed to fetch team settings")}finally{n(!1)}})()},[l]);let b=async()=>{if(l){g(!0);try{let e=await (0,y.r1)(l,h);o({...i,values:e.settings}),u(!1),D.ZP.success("Default team settings updated successfully")}catch(e){console.error("Error updating team settings:",e),D.ZP.error("Failed to update team settings")}finally{g(!1)}}},Z=(e,s)=>{x(l=>({...l,[e]:s}))},N=(e,s,l)=>{var t;let a=s.type;return"budget_duration"===e?(0,c.jsx)(e_,{value:h[e]||null,onChange:s=>Z(e,s),className:"mt-2"}):"boolean"===a?(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)(sB.Z,{checked:!!h[e],onChange:s=>Z(e,s)})}):"array"===a&&(null===(t=s.items)||void 0===t?void 0:t.enum)?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:s.items.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):"models"===e?(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},value:h[e]||[],onChange:s=>Z(e,s),className:"mt-2",children:j.map(e=>(0,c.jsx)(v,{value:e,children:K(e)},e))}):"string"===a&&s.enum?(0,c.jsx)(O.default,{style:{width:"100%"},value:h[e]||"",onChange:s=>Z(e,s),className:"mt-2",children:s.enum.map(e=>(0,c.jsx)(v,{value:e,children:e},e))}):(0,c.jsx)(S.Z,{value:void 0!==h[e]?String(h[e]):"",onChange:s=>Z(e,s.target.value),placeholder:s.description||"",className:"mt-2"})},w=(e,s)=>null==s?(0,c.jsx)("span",{className:"text-gray-400",children:"Not set"}):"budget_duration"===e?(0,c.jsx)("span",{children:ef(s)}):"boolean"==typeof s?(0,c.jsx)("span",{children:s?"Enabled":"Disabled"}):"models"===e&&Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:K(e)},s))}):"object"==typeof s?Array.isArray(s)?0===s.length?(0,c.jsx)("span",{className:"text-gray-400",children:"None"}):(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:s.map((e,s)=>(0,c.jsx)("span",{className:"px-2 py-1 bg-blue-100 rounded text-xs",children:"object"==typeof e?JSON.stringify(e):String(e)},s))}):(0,c.jsx)("pre",{className:"bg-gray-100 p-2 rounded text-xs overflow-auto mt-1",children:JSON.stringify(s,null,2)}):(0,c.jsx)("span",{children:String(s)});return r?(0,c.jsx)("div",{className:"flex justify-center items-center h-64",children:(0,c.jsx)(eY.Z,{size:"large"})}):i?(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{className:"text-xl",children:"Default Team Settings"}),!r&&i&&(m?(0,c.jsxs)("div",{className:"flex gap-2",children:[(0,c.jsx)(k.Z,{variant:"secondary",onClick:()=>{u(!1),x(i.values||{})},disabled:p,children:"Cancel"}),(0,c.jsx)(k.Z,{onClick:b,loading:p,children:"Save Changes"})]}):(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Settings"}))]}),(0,c.jsx)(A.Z,{children:"These settings will be applied by default when creating new teams."}),(null==i?void 0:null===(s=i.schema)||void 0===s?void 0:s.description)&&(0,c.jsx)(_,{className:"mb-4 mt-2",children:i.schema.description}),(0,c.jsx)(lj.Z,{}),(0,c.jsx)("div",{className:"mt-4 space-y-4",children:(()=>{let{values:e,schema:s}=i;return s&&s.properties?Object.entries(s.properties).map(s=>{let[l,t]=s,a=e[l],r=l.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase());return(0,c.jsxs)("div",{className:"mb-6 pb-6 border-b border-gray-200 last:border-0",children:[(0,c.jsx)(A.Z,{className:"font-medium text-lg",children:r}),(0,c.jsx)(_,{className:"text-sm text-gray-500 mt-1",children:t.description||"No description available"}),m?(0,c.jsx)("div",{className:"mt-2",children:N(l,t,a)}):(0,c.jsx)("div",{className:"mt-1 p-2 bg-gray-50 rounded",children:w(l,a)})]},l)}):(0,c.jsx)(A.Z,{children:"No schema information available"})})()})]}):(0,c.jsx)(eF.Z,{children:(0,c.jsx)(A.Z,{children:"No team settings available or you do not have permission to view them."})})},lv=e=>{let{accessToken:s,userID:l}=e,[t,a]=(0,d.useState)([]);(0,d.useEffect)(()=>{(async()=>{if(s&&l)try{let e=await (0,y.a6)(s);a(e)}catch(e){console.error("Error fetching available teams:",e)}})()},[s,l]);let r=async e=>{if(s&&l)try{await (0,y.cu)(s,e,{user_id:l,role:"user"}),D.ZP.success("Successfully joined team"),a(s=>s.filter(s=>s.team_id!==e))}catch(e){console.error("Error joining team:",e),D.ZP.error("Failed to join team")}};return(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Description"}),(0,c.jsx)(eP.Z,{children:"Members"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsxs)(eT.Z,{children:[t.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.team_alias})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.description||"No description available"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[e.members_with_roles.length," members"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"flex flex-col",children:e.models&&0!==e.models.length?e.models.map((e,s)=>(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(e.slice(0,30),"..."):e})},s)):(0,c.jsx)(eM.Z,{size:"xs",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})})})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{size:"xs",variant:"secondary",onClick:()=>r(e.team_id),children:"Join Team"})})]},e.team_id)),0===t.length&&(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:5,className:"text-center",children:(0,c.jsx)(A.Z,{children:"No available teams to join"})})})]})]})})};console.log=function(){};let lb=(e,s)=>{let l=[];return e&&e.models.length>0?(console.log("organization.models: ".concat(e.models)),l=e.models):l=s,B(l,s)};var lZ=e=>{let{teams:s,searchParams:l,accessToken:t,setTeams:a,userID:r,userRole:n,organizations:i}=e,[o,m]=(0,d.useState)(""),[u,h]=(0,d.useState)(null),[x,p]=(0,d.useState)(null);(0,d.useEffect)(()=>{console.log("inside useeffect - ".concat(o)),t&&Z(t,r,n,u,a),ey()},[o]);let[g]=L.Z.useForm(),[j]=L.Z.useForm(),{Title:f,Paragraph:_}=es.default,[v,b]=(0,d.useState)(""),[E,P]=(0,d.useState)(!1),[F,U]=(0,d.useState)(null),[B,H]=(0,d.useState)(null),[G,Y]=(0,d.useState)(!1),[$,X]=(0,d.useState)(!1),[Q,ee]=(0,d.useState)(!1),[el,et]=(0,d.useState)(!1),[ea,er]=(0,d.useState)([]),[en,ei]=(0,d.useState)(!1),[eo,ec]=(0,d.useState)(null),[ed,em]=(0,d.useState)([]),[eu,eh]=(0,d.useState)({}),[ex,ep]=(0,d.useState)([]);(0,d.useEffect)(()=>{console.log("currentOrgForCreateTeam: ".concat(x));let e=lb(x,ea);console.log("models: ".concat(e)),em(e),g.setFieldValue("models",[])},[x,ea]),(0,d.useEffect)(()=>{(async()=>{try{if(null==t)return;let e=(await (0,y.t3)(t)).guardrails.map(e=>e.guardrail_name);ep(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})()},[t]);let ej=async e=>{ec(e),ei(!0)},ef=async()=>{if(null!=eo&&null!=s&&null!=t){try{await (0,y.rs)(t,eo),Z(t,r,n,u,a)}catch(e){console.error("Error deleting the team:",e)}ei(!1),ec(null)}};(0,d.useEffect)(()=>{(async()=>{try{if(null===r||null===n||null===t)return;let e=await V(r,n,t);e&&er(e)}catch(e){console.error("Error fetching user models:",e)}})()},[t,r,n,s]);let e_=async e=>{try{if(console.log("formValues: ".concat(JSON.stringify(e))),null!=t){var l;let r=null==e?void 0:e.team_alias,n=null!==(l=null==s?void 0:s.map(e=>e.team_alias))&&void 0!==l?l:[],i=(null==e?void 0:e.organization_id)||(null==u?void 0:u.organization_id);if(""===i||"string"!=typeof i?e.organization_id=null:e.organization_id=i.trim(),n.includes(r))throw Error("Team alias ".concat(r," already exists, please pick another alias"));D.ZP.info("Creating Team");let o=await (0,y.hT)(t,e);null!==s?a([...s,o]):a([o]),console.log("response for team create call: ".concat(o)),D.ZP.success("Team created"),g.resetFields(),X(!1)}}catch(e){console.error("Error creating the team:",e),D.ZP.error("Error creating the team: "+e,20)}},ey=()=>{m(new Date().toLocaleString())};return(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:B?(0,c.jsx)(sq,{teamId:B,onUpdate:e=>{a(s=>null==s?s:s.map(s=>e.team_id===s.team_id?e8(s,e):s))},onClose:()=>{H(null),Y(!1)},accessToken:t,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let s=0;se.team_id===B)),is_proxy_admin:"Admin"==n,userModels:ea,editTeam:G}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Your Teams"}),(0,c.jsx)(eR.Z,{children:"Available Teams"}),(0,eg.tY)(n||"")&&(0,c.jsx)(eR.Z,{children:"Default Team Settings"})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[o&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",o]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:ey})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(A.Z,{children:["Click on “Team ID” to view team details ",(0,c.jsx)("b",{children:"and"})," manage team members."]}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"w-full mx-auto flex-auto overflow-hidden overflow-y-auto max-h-[50vh]",children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Team Name"}),(0,c.jsx)(eP.Z,{children:"Team ID"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"Organization"}),(0,c.jsx)(eP.Z,{children:"Info"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.filter(e=>!u||e.organization_id===u.organization_id).sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.team_alias}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.team_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{H(e.team_id)},children:[e.team_id.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:e.spend}),(0,c.jsx)(eA.Z,{style:{maxWidth:"4px",whiteSpace:"pre-wrap",overflow:"hidden"},children:null!==e.max_budget&&void 0!==e.max_budget?e.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{style:{maxWidth:"8-x",whiteSpace:"pre-wrap",overflow:"hidden"},children:Array.isArray(e.models)?(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:(0,c.jsx)(A.Z,{children:"All Proxy Models"})},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(A.Z,{children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)})},s))}):null}),(0,c.jsx)(eA.Z,{children:e.organization_id}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].keys&&eu[e.team_id].keys.length," ","Keys"]}),(0,c.jsxs)(A.Z,{children:[eu&&e.team_id&&eu[e.team_id]&&eu[e.team_id].members_with_roles&&eu[e.team_id].members_with_roles.length," ","Members"]})]}),(0,c.jsx)(eA.Z,{children:"Admin"==n?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{H(e.team_id),Y(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>ej(e.team_id),icon:eH.Z,size:"sm"})]}):null})]},e.team_id)):null})]}),en&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Team"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this team ?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:ef,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{ei(!1),ec(null)},children:"Cancel"})]})]})]})})]})}),"Admin"==n||"Org Admin"==n?(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>X(!0),children:"+ Create New Team"}),(0,c.jsx)(M.Z,{title:"Create Team",visible:$,width:800,footer:null,onOk:()=>{X(!1),g.resetFields()},onCancel:()=>{X(!1),g.resetFields()},children:(0,c.jsxs)(L.Z,{form:g,onFinish:e_,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Team Name",name:"team_alias",rules:[{required:!0,message:"Please input a team name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Organization"," ",(0,c.jsx)(W.Z,{title:(0,c.jsxs)("span",{children:["Organizations can have multiple teams. Learn more about"," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/user_management_heirarchy",target:"_blank",rel:"noopener noreferrer",style:{color:"#1890ff",textDecoration:"underline"},onClick:e=>e.stopPropagation(),children:"user management hierarchy"})]}),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"organization_id",initialValue:u?u.organization_id:null,className:"mt-8",children:(0,c.jsx)(O.default,{showSearch:!0,allowClear:!0,placeholder:"Search or select an Organization",onChange:e=>{g.setFieldValue("organization_id",e),p((null==i?void 0:i.find(s=>s.organization_id===e))||null)},filterOption:(e,s)=>{var l;return!!s&&((null===(l=s.children)||void 0===l?void 0:l.toString())||"").toLowerCase().includes(e.toLowerCase())},optionFilterProp:"children",children:null==i?void 0:i.map(e=>(0,c.jsxs)(O.default.Option,{value:e.organization_id,children:[(0,c.jsx)("span",{className:"font-medium",children:e.organization_alias})," ",(0,c.jsxs)("span",{className:"text-gray-500",children:["(",e.organization_id,")"]})]},e.organization_id))})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Models"," ",(0,c.jsx)(W.Z,{title:"These are the models that your selected team has access to",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),ed.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Additional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Team ID",name:"team_id",help:"ID of the team you want to create. If not provided, it will be generated automatically.",children:(0,c.jsx)(S.Z,{onChange:e=>{e.target.value=e.target.value.trim()}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",help:"Additional team metadata. Enter metadata as JSON object.",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Guardrails"," ",(0,c.jsx)(W.Z,{title:"Setup your first guardrail",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",onClick:e=>e.stopPropagation(),children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})})]}),name:"guardrails",className:"mt-8",help:"Select existing guardrails or enter new ones",children:(0,c.jsx)(O.default,{mode:"tags",style:{width:"100%"},placeholder:"Select or enter guardrails",options:ex.map(e=>({value:e,label:e}))})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Team"})})]})})]}):null]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lv,{accessToken:t,userID:r})}),(0,eg.tY)(n||"")&&(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ly,{accessToken:t,userID:r||"",userRole:n||""})})]})]})})},lN=e=>{var s;let{organizationId:l,onClose:t,accessToken:a,is_org_admin:r,is_proxy_admin:n,userModels:i,editOrg:o}=e,[m,u]=(0,d.useState)(null),[h,x]=(0,d.useState)(!0),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(!1),[f,_]=(0,d.useState)(!1),[v,b]=(0,d.useState)(!1),[Z,N]=(0,d.useState)(null),C=r||n,I=async()=>{try{if(x(!0),!a)return;let e=await (0,y.t$)(a,l);u(e)}catch(e){D.ZP.error("Failed to load organization information"),console.error("Error fetching organization info:",e)}finally{x(!1)}};(0,d.useEffect)(()=>{I()},[l,a]);let T=async e=>{try{if(null==a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.vh)(a,l,s),D.ZP.success("Organization member added successfully"),_(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to add organization member"),console.error("Error adding organization member:",e)}},P=async e=>{try{if(!a)return;let s={user_email:e.user_email,user_id:e.user_id,role:e.role};await (0,y.LY)(a,l,s),D.ZP.success("Organization member updated successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to update organization member"),console.error("Error updating organization member:",e)}},M=async e=>{try{if(!a)return;await (0,y.Sb)(a,l,e.user_id),D.ZP.success("Organization member deleted successfully"),b(!1),p.resetFields(),I()}catch(e){D.ZP.error("Failed to delete organization member"),console.error("Error deleting organization member:",e)}},F=async e=>{try{if(!a)return;let s={organization_id:l,organization_alias:e.organization_alias,models:e.models,litellm_budget_table:{tpm_limit:e.tpm_limit,rpm_limit:e.rpm_limit,max_budget:e.max_budget,budget_duration:e.budget_duration},metadata:e.metadata?JSON.parse(e.metadata):null};await (0,y.VA)(a,s),D.ZP.success("Organization settings updated successfully"),j(!1),I()}catch(e){D.ZP.error("Failed to update organization settings"),console.error("Error updating organization:",e)}};return h?(0,c.jsx)("div",{className:"p-4",children:"Loading..."}):m?(0,c.jsxs)("div",{className:"w-full h-screen p-4 bg-white",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-6",children:(0,c.jsxs)("div",{children:[(0,c.jsx)(R.ZP,{onClick:t,className:"mb-4",children:"← Back"}),(0,c.jsx)(E.Z,{children:m.organization_alias}),(0,c.jsx)(A.Z,{className:"text-gray-500 font-mono",children:m.organization_id})]})}),(0,c.jsxs)(eq.Z,{defaultIndex:o?2:0,children:[(0,c.jsxs)(eU.Z,{className:"mb-4",children:[(0,c.jsx)(eR.Z,{children:"Overview"}),(0,c.jsx)(eR.Z,{children:"Members"}),(0,c.jsx)(eR.Z,{children:"Settings"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,numItemsSm:2,numItemsLg:3,className:"gap-6",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Organization Details"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["Created: ",new Date(m.created_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Updated: ",new Date(m.updated_at).toLocaleDateString()]}),(0,c.jsxs)(A.Z,{children:["Created By: ",m.created_by]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Budget Status"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(E.Z,{children:["$",m.spend.toFixed(6)]}),(0,c.jsxs)(A.Z,{children:["of ",null===m.litellm_budget_table.max_budget?"Unlimited":"$".concat(m.litellm_budget_table.max_budget)]}),m.litellm_budget_table.budget_duration&&(0,c.jsxs)(A.Z,{className:"text-gray-500",children:["Reset: ",m.litellm_budget_table.budget_duration]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Rate Limits"}),(0,c.jsxs)("div",{className:"mt-2",children:[(0,c.jsxs)(A.Z,{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)(A.Z,{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]}),m.litellm_budget_table.max_parallel_requests&&(0,c.jsxs)(A.Z,{children:["Max Parallel Requests: ",m.litellm_budget_table.max_parallel_requests]})]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Models"}),(0,c.jsx)("div",{className:"mt-2 flex flex-wrap gap-2",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[75vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"User ID"}),(0,c.jsx)(eP.Z,{children:"Role"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Created At"}),(0,c.jsx)(eP.Z,{})]})}),(0,c.jsx)(eT.Z,{children:null===(s=m.members)||void 0===s?void 0:s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_id})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{className:"font-mono",children:e.user_role})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["$",e.spend.toFixed(6)]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:new Date(e.created_at).toLocaleString()})}),(0,c.jsx)(eA.Z,{children:C&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{N({role:e.user_role,user_email:e.user_email,user_id:e.user_id}),b(!0)}}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>{M(e)}})]})})]},s))})]})}),C&&(0,c.jsx)(k.Z,{onClick:()=>{_(!0)},children:"Add Member"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-4",children:[(0,c.jsx)(E.Z,{children:"Organization Settings"}),C&&!g&&(0,c.jsx)(k.Z,{onClick:()=>j(!0),children:"Edit Settings"})]}),g?(0,c.jsxs)(L.Z,{form:p,onFinish:F,initialValues:{organization_alias:m.organization_alias,models:m.models,tpm_limit:m.litellm_budget_table.tpm_limit,rpm_limit:m.litellm_budget_table.rpm_limit,max_budget:m.litellm_budget_table.max_budget,budget_duration:m.litellm_budget_table.budget_duration,metadata:m.metadata?JSON.stringify(m.metadata,null,2):""},layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),i.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,style:{width:"100%"}})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsxs)("div",{className:"flex justify-end gap-2 mt-6",children:[(0,c.jsx)(R.ZP,{onClick:()=>j(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]}):(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization Name"}),(0,c.jsx)("div",{children:m.organization_alias})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Organization ID"}),(0,c.jsx)("div",{className:"font-mono",children:m.organization_id})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created At"}),(0,c.jsx)("div",{children:new Date(m.created_at).toLocaleString()})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Models"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-1",children:m.models.map((e,s)=>(0,c.jsx)(eM.Z,{color:"red",children:e},s))})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Rate Limits"}),(0,c.jsxs)("div",{children:["TPM: ",m.litellm_budget_table.tpm_limit||"Unlimited"]}),(0,c.jsxs)("div",{children:["RPM: ",m.litellm_budget_table.rpm_limit||"Unlimited"]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Budget"}),(0,c.jsxs)("div",{children:["Max: ",null!==m.litellm_budget_table.max_budget?"$".concat(m.litellm_budget_table.max_budget):"No Limit"]}),(0,c.jsxs)("div",{children:["Reset: ",m.litellm_budget_table.budget_duration||"Never"]})]})]})]})})]})]}),(0,c.jsx)(sR,{isVisible:f,onCancel:()=>_(!1),onSubmit:T,accessToken:a,title:"Add Organization Member",roles:[{label:"org_admin",value:"org_admin",description:"Can add and remove members, and change their roles."},{label:"internal_user",value:"internal_user",description:"Can view/create keys for themselves within organization."},{label:"internal_user_viewer",value:"internal_user_viewer",description:"Can only view their keys within organization."}],defaultRole:"internal_user"}),(0,c.jsx)(sF,{visible:v,onCancel:()=>b(!1),onSubmit:P,initialData:Z,mode:"edit",config:{title:"Edit Member",showEmail:!0,showUserId:!0,roleOptions:[{label:"Org Admin",value:"org_admin"},{label:"Internal User",value:"internal_user"},{label:"Internal User Viewer",value:"internal_user_viewer"}]}})]}):(0,c.jsx)("div",{className:"p-4",children:"Organization not found"})};let lw=async(e,s)=>{s(await (0,y.r6)(e))};var lk=e=>{let{organizations:s,userRole:l,userModels:t,accessToken:a,lastRefreshed:r,handleRefreshClick:n,currentOrg:i,guardrailsList:o=[],setOrganizations:m,premiumUser:u}=e,[h,x]=(0,d.useState)(null),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(null),[b,Z]=(0,d.useState)(!1),[C]=L.Z.useForm();(0,d.useEffect)(()=>{0===s.length&&a&&lw(a,m)},[s,a]);let I=e=>{e&&(v(e),f(!0))},T=async()=>{if(_&&a)try{await (0,y.cq)(a,_),D.ZP.success("Organization deleted successfully"),f(!1),v(null),lw(a,m)}catch(e){console.error("Error deleting organization:",e)}},E=async e=>{try{if(!a)return;console.log("values in organizations new create call: ".concat(JSON.stringify(e))),await (0,y.H1)(a,e),Z(!1),C.resetFields(),lw(a,m)}catch(e){console.error("Error creating organization:",e)}};return u?h?(0,c.jsx)(lN,{organizationId:h,onClose:()=>{x(null),g(!1)},accessToken:a,is_org_admin:!0,is_proxy_admin:"Admin"===l,userModels:t,editOrg:p}):(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsx)("div",{className:"flex",children:(0,c.jsx)(eR.Z,{children:"Your Organizations"})}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[r&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",r]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:n})]})]}),(0,c.jsx)(eV.Z,{children:(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(A.Z,{children:"Click on “Organization ID” to view organization details."}),(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(eF.Z,{className:"w-full mx-auto flex-auto overflow-y-auto max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Organization ID"}),(0,c.jsx)(eP.Z,{children:"Organization Name"}),(0,c.jsx)(eP.Z,{children:"Created"}),(0,c.jsx)(eP.Z,{children:"Spend (USD)"}),(0,c.jsx)(eP.Z,{children:"Budget (USD)"}),(0,c.jsx)(eP.Z,{children:"Models"}),(0,c.jsx)(eP.Z,{children:"TPM / RPM Limits"}),(0,c.jsx)(eP.Z,{children:"Info"}),(0,c.jsx)(eP.Z,{children:"Actions"})]})}),(0,c.jsx)(eT.Z,{children:s&&s.length>0?s.sort((e,s)=>new Date(s.created_at).getTime()-new Date(e.created_at).getTime()).map(e=>{var s,t,a,r,n,i,o,d,m;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.organization_id,children:(0,c.jsxs)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>x(e.organization_id),children:[null===(s=e.organization_id)||void 0===s?void 0:s.slice(0,7),"..."]})})})}),(0,c.jsx)(eA.Z,{children:e.organization_alias}),(0,c.jsx)(eA.Z,{children:e.created_at?new Date(e.created_at).toLocaleDateString():"N/A"}),(0,c.jsx)(eA.Z,{children:e.spend}),(0,c.jsx)(eA.Z,{children:(null===(t=e.litellm_budget_table)||void 0===t?void 0:t.max_budget)!==null&&(null===(a=e.litellm_budget_table)||void 0===a?void 0:a.max_budget)!==void 0?null===(r=e.litellm_budget_table)||void 0===r?void 0:r.max_budget:"No limit"}),(0,c.jsx)(eA.Z,{children:Array.isArray(e.models)&&(0,c.jsx)("div",{className:"flex flex-col",children:0===e.models.length?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"}):e.models.map((e,s)=>"all-proxy-models"===e?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Proxy Models"},s):(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:e.length>30?"".concat(K(e).slice(0,30),"..."):K(e)},s))})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:["TPM: ",(null===(n=e.litellm_budget_table)||void 0===n?void 0:n.tpm_limit)?null===(i=e.litellm_budget_table)||void 0===i?void 0:i.tpm_limit:"Unlimited",(0,c.jsx)("br",{}),"RPM: ",(null===(o=e.litellm_budget_table)||void 0===o?void 0:o.rpm_limit)?null===(d=e.litellm_budget_table)||void 0===d?void 0:d.rpm_limit:"Unlimited"]})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(A.Z,{children:[(null===(m=e.members)||void 0===m?void 0:m.length)||0," Members"]})}),(0,c.jsx)(eA.Z,{children:"Admin"===l&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{x(e.organization_id),g(!0)}}),(0,c.jsx)(sZ.Z,{onClick:()=>I(e.organization_id),icon:eH.Z,size:"sm"})]})})]},e.organization_id)}):null})]})})}),("Admin"===l||"Org Admin"===l)&&(0,c.jsxs)(N.Z,{numColSpan:1,children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>Z(!0),children:"+ Create New Organization"}),(0,c.jsx)(M.Z,{title:"Create Organization",visible:b,width:800,footer:null,onCancel:()=>{Z(!1),C.resetFields()},children:(0,c.jsxs)(L.Z,{form:C,onFinish:E,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Organization Name",name:"organization_alias",rules:[{required:!0,message:"Please input an organization name"}],children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Models",name:"models",children:(0,c.jsxs)(O.default,{mode:"multiple",placeholder:"Select models",style:{width:"100%"},children:[(0,c.jsx)(O.default.Option,{value:"all-proxy-models",children:"All Proxy Models"},"all-proxy-models"),t&&t.length>0&&t.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))]})}),(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})}),(0,c.jsx)(L.Z.Item,{label:"Tokens per minute Limit (TPM)",name:"tpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Requests per minute Limit (RPM)",name:"rpm_limit",children:(0,c.jsx)(z,{step:1,width:400})}),(0,c.jsx)(L.Z.Item,{label:"Metadata",name:"metadata",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Organization"})})]})})]})]})]})}),j?(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsx)("span",{className:"hidden sm:inline-block sm:align-middle sm:h-screen","aria-hidden":"true",children:"​"}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Organization"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this organization?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:T,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{f(!1),v(null)},children:"Cancel"})]})]})]})}):(0,c.jsx)(c.Fragment,{})]}):(0,c.jsx)("div",{children:(0,c.jsxs)(A.Z,{children:["This is a LiteLLM Enterprise feature, and requires a valid key to use. Get a trial key ",(0,c.jsx)("a",{href:"https://litellm.ai/pricing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})},lS=l(94789);let lC={google:"https://artificialanalysis.ai/img/logos/google_small.svg",microsoft:"https://upload.wikimedia.org/wikipedia/commons/a/a8/Microsoft_Azure_Logo.svg",okta:"https://www.okta.com/sites/default/files/Okta_Logo_BrightBlue_Medium.png",generic:""},lI={google:{envVarMap:{google_client_id:"GOOGLE_CLIENT_ID",google_client_secret:"GOOGLE_CLIENT_SECRET"},fields:[{label:"GOOGLE CLIENT ID",name:"google_client_id"},{label:"GOOGLE CLIENT SECRET",name:"google_client_secret"}]},microsoft:{envVarMap:{microsoft_client_id:"MICROSOFT_CLIENT_ID",microsoft_client_secret:"MICROSOFT_CLIENT_SECRET",microsoft_tenant:"MICROSOFT_TENANT"},fields:[{label:"MICROSOFT CLIENT ID",name:"microsoft_client_id"},{label:"MICROSOFT CLIENT SECRET",name:"microsoft_client_secret"},{label:"MICROSOFT TENANT",name:"microsoft_tenant"}]},okta:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint",placeholder:"https://your-okta-domain/authorize"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint",placeholder:"https://your-okta-domain/token"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint",placeholder:"https://your-okta-domain/userinfo"}]},generic:{envVarMap:{generic_client_id:"GENERIC_CLIENT_ID",generic_client_secret:"GENERIC_CLIENT_SECRET",generic_authorization_endpoint:"GENERIC_AUTHORIZATION_ENDPOINT",generic_token_endpoint:"GENERIC_TOKEN_ENDPOINT",generic_userinfo_endpoint:"GENERIC_USERINFO_ENDPOINT"},fields:[{label:"GENERIC CLIENT ID",name:"generic_client_id"},{label:"GENERIC CLIENT SECRET",name:"generic_client_secret"},{label:"AUTHORIZATION ENDPOINT",name:"generic_authorization_endpoint"},{label:"TOKEN ENDPOINT",name:"generic_token_endpoint"},{label:"USERINFO ENDPOINT",name:"generic_userinfo_endpoint"}]}};var lT=e=>{let{isAddSSOModalVisible:s,isInstructionsModalVisible:l,handleAddSSOOk:t,handleAddSSOCancel:a,handleShowInstructions:r,handleInstructionsOk:n,handleInstructionsCancel:i,form:o}=e,d=e=>{let s=lI[e];return s?s.fields.map(e=>(0,c.jsx)(L.Z.Item,{label:e.label,name:e.name,rules:[{required:!0,message:"Please enter the ".concat(e.label.toLowerCase())}],children:e.name.includes("client")?(0,c.jsx)(q.default.Password,{}):(0,c.jsx)(S.Z,{placeholder:e.placeholder})},e.name)):null};return(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(M.Z,{title:"Add SSO",visible:s,width:800,footer:null,onOk:t,onCancel:a,children:(0,c.jsxs)(L.Z,{form:o,onFinish:r,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"SSO Provider",name:"sso_provider",rules:[{required:!0,message:"Please select an SSO provider"}],children:(0,c.jsx)(O.default,{children:Object.entries(lC).map(e=>{let[s,l]=e;return(0,c.jsx)(O.default.Option,{value:s,children:(0,c.jsxs)("div",{style:{display:"flex",alignItems:"center",padding:"4px 0"},children:[l&&(0,c.jsx)("img",{src:l,alt:s,style:{height:24,width:24,marginRight:12,objectFit:"contain"}}),(0,c.jsxs)("span",{children:[s.charAt(0).toUpperCase()+s.slice(1)," SSO"]})]})},s)})})}),(0,c.jsx)(L.Z.Item,{noStyle:!0,shouldUpdate:(e,s)=>e.sso_provider!==s.sso_provider,children:e=>{let{getFieldValue:s}=e,l=s("sso_provider");return l?d(l):null}}),(0,c.jsx)(L.Z.Item,{label:"Proxy Admin Email",name:"user_email",rules:[{required:!0,message:"Please enter the email of the proxy admin"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"PROXY BASE URL",name:"proxy_base_url",rules:[{required:!0,message:"Please enter the proxy base url"}],children:(0,c.jsx)(S.Z,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})}),(0,c.jsxs)(M.Z,{title:"SSO Setup Instructions",visible:l,width:800,footer:null,onOk:n,onCancel:i,children:[(0,c.jsx)("p",{children:"Follow these steps to complete the SSO setup:"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"1. DO NOT Exit this TAB"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"2. Open a new tab, visit your proxy base url"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"3. Confirm your SSO is configured correctly and you can login on the new Tab"}),(0,c.jsx)(A.Z,{className:"mt-2",children:"4. If Step 3 is successful, you can close this tab"}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{onClick:n,children:"Done"})})]})]})},lA=l(62272),lE=l(92403),lP=l(29271),lO=l(34419),lL=e=>{let{accessToken:s,userID:l,proxySettings:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)("");(0,d.useEffect)(()=>{let e="";u(t&&t.PROXY_BASE_URL&&void 0!==t.PROXY_BASE_URL?t.PROXY_BASE_URL:window.location.origin)},[t]);let h="".concat(m,"/scim/v2"),x=async e=>{if(!s||!l){D.ZP.error("You need to be logged in to create a SCIM token");return}try{n(!0);let t={key_alias:e.key_alias||"SCIM Access Token",team_id:null,models:[],allowed_routes:["/scim/*"]},a=await (0,y.wX)(s,l,t);o(a),D.ZP.success("SCIM token created successfully")}catch(e){console.error("Error creating SCIM token:",e),D.ZP.error("Failed to create SCIM token")}finally{n(!1)}};return(0,c.jsx)(w.Z,{numItems:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("div",{className:"flex items-center mb-4",children:(0,c.jsx)(E.Z,{children:"SCIM Configuration"})}),(0,c.jsx)(A.Z,{className:"text-gray-600",children:"System for Cross-domain Identity Management (SCIM) allows you to automatically provision and manage users and groups in LiteLLM."}),(0,c.jsx)(lj.Z,{}),(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"1"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lA.Z,{className:"h-5 w-5 mr-2"}),"SCIM Tenant URL"]})]}),(0,c.jsx)(A.Z,{className:"text-gray-600 mb-3",children:"Use this URL in your identity provider SCIM integration settings."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:h,disabled:!0,className:"flex-grow"}),(0,c.jsx)(P.CopyToClipboard,{text:h,onCopy:()=>D.ZP.success("URL copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"ml-2 flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-2",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full bg-blue-100 text-blue-700 mr-2",children:"2"}),(0,c.jsxs)(E.Z,{className:"text-lg flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-5 w-5 mr-2"}),"Authentication Token"]})]}),(0,c.jsx)(lS.Z,{title:"Using SCIM",color:"blue",className:"mb-4",children:"You need a SCIM token to authenticate with the SCIM API. Create one below and use it in your SCIM provider configuration."}),i?(0,c.jsxs)(eF.Z,{className:"border border-yellow-300 bg-yellow-50",children:[(0,c.jsxs)("div",{className:"flex items-center mb-2 text-yellow-800",children:[(0,c.jsx)(lP.Z,{className:"h-5 w-5 mr-2"}),(0,c.jsx)(E.Z,{className:"text-lg text-yellow-800",children:"Your SCIM Token"})]}),(0,c.jsx)(A.Z,{className:"text-yellow-800 mb-4 font-medium",children:"Make sure to copy this token now. You will not be able to see it again."}),(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(S.Z,{value:i.token,className:"flex-grow mr-2 bg-white",type:"password",disabled:!0}),(0,c.jsx)(P.CopyToClipboard,{text:i.token,onCopy:()=>D.ZP.success("Token copied to clipboard"),children:(0,c.jsxs)(k.Z,{variant:"primary",className:"flex items-center",children:[(0,c.jsx)(s8.Z,{className:"h-4 w-4 mr-1"}),"Copy"]})})]}),(0,c.jsxs)(k.Z,{className:"mt-4 flex items-center",variant:"secondary",onClick:()=>o(null),children:[(0,c.jsx)(lO.Z,{className:"h-4 w-4 mr-1"}),"Create Another Token"]})]}):(0,c.jsx)("div",{className:"bg-gray-50 p-4 rounded-lg",children:(0,c.jsxs)(L.Z,{form:a,onFinish:x,layout:"vertical",children:[(0,c.jsx)(L.Z.Item,{name:"key_alias",label:"Token Name",rules:[{required:!0,message:"Please enter a name for your token"}],children:(0,c.jsx)(S.Z,{placeholder:"SCIM Access Token"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsxs)(k.Z,{variant:"primary",type:"submit",loading:r,className:"flex items-center",children:[(0,c.jsx)(lE.Z,{className:"h-4 w-4 mr-1"}),"Create SCIM Token"]})})]})})]})]})]})})};let lD=()=>{let[e,s]=(0,d.useState)("http://localhost:4000");return(0,d.useEffect)(()=>{{let{protocol:e,host:l}=window.location;s("".concat(e,"//").concat(l))}},[]),e};var lM=e=>{let{searchParams:s,accessToken:l,showSSOBanner:t,premiumUser:a,proxySettings:r}=e,[n]=L.Z.useForm(),[i]=L.Z.useForm(),{Title:o,Paragraph:u}=es.default,[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)(null),[_,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)(!1),[N,w]=(0,d.useState)(!1),[S,C]=(0,d.useState)(!1),[I,T]=(0,d.useState)(!1),[A,E]=(0,d.useState)(!1),[P,O]=(0,d.useState)(!1),[F,U]=(0,d.useState)(!1),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)([]),[H,J]=(0,d.useState)(null);(0,m.useRouter)();let[W,G]=(0,d.useState)(null);console.log=function(){};let Y=lD(),$="All IP Addresses Allowed",X=Y;X+="/fallback/login";let Q=async()=>{try{if(!0!==a){D.ZP.error("This feature is only available for premium users. Please upgrade your account.");return}if(l){let e=await (0,y.PT)(l);B(e&&e.length>0?e:[$])}else B([$])}catch(e){console.error("Error fetching allowed IPs:",e),D.ZP.error("Failed to fetch allowed IPs ".concat(e)),B([$])}finally{!0===a&&O(!0)}},ee=async e=>{try{if(l){await (0,y.eH)(l,e.ip);let s=await (0,y.PT)(l);B(s),D.ZP.success("IP address added successfully")}}catch(e){console.error("Error adding IP:",e),D.ZP.error("Failed to add IP address ".concat(e))}finally{U(!1)}},el=async e=>{J(e),V(!0)},et=async()=>{if(H&&l)try{await (0,y.$I)(l,H);let e=await (0,y.PT)(l);B(e.length>0?e:[$]),D.ZP.success("IP address deleted successfully")}catch(e){console.error("Error deleting IP:",e),D.ZP.error("Failed to delete IP address ".concat(e))}finally{V(!1),J(null)}};(0,d.useEffect)(()=>{(async()=>{if(null!=l){let e=[],s=await (0,y.Xd)(l,"proxy_admin_viewer");console.log("proxy admin viewer response: ",s);let t=s.users;console.log("proxy viewers response: ".concat(t)),t.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy viewers: ".concat(t));let a=(await (0,y.Xd)(l,"proxy_admin")).users;a.forEach(s=>{e.push({user_role:s.user_role,user_id:s.user_id,user_email:s.user_email})}),console.log("proxy admins: ".concat(a)),console.log("combinedList: ".concat(e)),g(e),G(await (0,y.lg)(l))}})()},[l]);let ea=async e=>{try{if(null!=l&&null!=p){var s;D.ZP.info("Making API Call"),e.user_email,e.user_id;let t=await (0,y.pf)(l,e,"proxy_admin"),a=(null===(s=t.data)||void 0===s?void 0:s.user_id)||t.user_id;(0,y.XO)(l,a).then(e=>{f(e),v(!0)}),console.log("response for team create call: ".concat(t));let r=p.findIndex(e=>(console.log("user.user_id=".concat(e.user_id,"; response.user_id=").concat(a)),e.user_id===t.user_id));console.log("foundIndex: ".concat(r)),-1==r&&(console.log("updates admin with new user"),p.push(t),g(p)),n.resetFields(),w(!1)}}catch(e){console.error("Error creating the key:",e)}},er=async e=>{if(null==l)return;let s=lI[e.sso_provider],t={PROXY_BASE_URL:e.proxy_base_url};s&&Object.entries(s.envVarMap).forEach(s=>{let[l,a]=s;e[l]&&(t[a]=e[l])}),(0,y.K_)(l,{environment_variables:t})};return console.log("admins: ".concat(null==p?void 0:p.length)),(0,c.jsxs)("div",{className:"w-full m-2 mt-2 p-8",children:[(0,c.jsx)(o,{level:4,children:"Admin Access "}),(0,c.jsx)(u,{children:"Go to 'Internal Users' page to add other admins."}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Security Settings"}),(0,c.jsx)(eR.Z,{children:"SCIM"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(o,{level:4,children:" ✨ Security Settings"}),(0,c.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"1rem",marginTop:"1rem"},children:[(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:()=>!0===a?T(!0):D.ZP.error("Only premium users can add SSO"),children:"Add SSO"})}),(0,c.jsx)("div",{children:(0,c.jsx)(k.Z,{onClick:Q,children:"Allowed IPs"})})]})]}),(0,c.jsxs)("div",{className:"flex justify-start mb-4",children:[(0,c.jsx)(lT,{isAddSSOModalVisible:I,isInstructionsModalVisible:A,handleAddSSOOk:()=>{T(!1),n.resetFields()},handleAddSSOCancel:()=>{T(!1),n.resetFields()},handleShowInstructions:e=>{ea(e),er(e),T(!1),E(!0)},handleInstructionsOk:()=>{E(!1)},handleInstructionsCancel:()=>{E(!1)},form:n}),(0,c.jsx)(M.Z,{title:"Manage Allowed IP Addresses",width:800,visible:P,onCancel:()=>O(!1),footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>U(!0),children:"Add IP Address"},"add"),(0,c.jsx)(k.Z,{onClick:()=>O(!1),children:"Close"},"close")],children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"IP Address"}),(0,c.jsx)(eP.Z,{className:"text-right",children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:K.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e}),(0,c.jsx)(eA.Z,{className:"text-right",children:e!==$&&(0,c.jsx)(k.Z,{onClick:()=>el(e),color:"red",size:"xs",children:"Delete"})})]},s))})]})}),(0,c.jsx)(M.Z,{title:"Add Allowed IP Address",visible:F,onCancel:()=>U(!1),footer:null,children:(0,c.jsxs)(L.Z,{onFinish:ee,children:[(0,c.jsx)(L.Z.Item,{name:"ip",rules:[{required:!0,message:"Please enter an IP address"}],children:(0,c.jsx)(q.default,{placeholder:"Enter IP address"})}),(0,c.jsx)(L.Z.Item,{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add IP Address"})})]})}),(0,c.jsx)(M.Z,{title:"Confirm Delete",visible:z,onCancel:()=>V(!1),onOk:et,footer:[(0,c.jsx)(k.Z,{className:"mx-1",onClick:()=>et(),children:"Yes"},"delete"),(0,c.jsx)(k.Z,{onClick:()=>V(!1),children:"Close"},"close")],children:(0,c.jsxs)("p",{children:["Are you sure you want to delete the IP address: ",H,"?"]})})]}),(0,c.jsxs)(lS.Z,{title:"Login without SSO",color:"teal",children:["If you need to login without sso, you can access"," ",(0,c.jsxs)("a",{href:X,target:"_blank",children:[(0,c.jsx)("b",{children:X})," "]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lL,{accessToken:l,userID:p&&p.length>0?p[0].user_id:null,proxySettings:r})})]})]})]})},lF=l(92858),lR=e=>{let{alertingSettings:s,handleInputChange:l,handleResetField:t,handleSubmit:a,premiumUser:r}=e,[n]=L.Z.useForm();return(0,c.jsxs)(L.Z,{form:n,onFinish:()=>{console.log("INSIDE ONFINISH");let e=n.getFieldsValue(),s=Object.entries(e).every(e=>{let[s,l]=e;return"boolean"!=typeof l&&(""===l||null==l)});console.log("formData: ".concat(JSON.stringify(e),", isEmpty: ").concat(s)),s?console.log("Some form fields are empty."):a(e)},labelAlign:"left",children:[s.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{align:"center",children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),e.premium_field?r?(0,c.jsx)(L.Z.Item,{name:e.field_name,children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s)}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>l(e.field_name,s)}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}):(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})})}):(0,c.jsx)(L.Z.Item,{name:e.field_name,className:"mb-0",valuePropName:"Boolean"===e.field_type?"checked":"value",children:(0,c.jsx)(eA.Z,{children:"Integer"===e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>l(e.field_name,s),className:"p-0"}):"Boolean"===e.field_type?(0,c.jsx)(lF.Z,{checked:e.field_value,onChange:s=>{l(e.field_name,s),n.setFieldsValue({[e.field_name]:s})}}):(0,c.jsx)(q.default,{value:e.field_value,onChange:s=>l(e.field_name,s)})})}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>t(e.field_name,s),children:"Reset"})})]},s)),(0,c.jsx)("div",{children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Update Settings"})})]})},lq=e=>{let{accessToken:s,premiumUser:l}=e,[t,a]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(0,y.RQ)(s).then(e=>{a(e)})},[s]),(0,c.jsx)(lR,{alertingSettings:t,handleInputChange:(e,s)=>{let l=t.map(l=>l.field_name===e?{...l,field_value:s}:l);console.log("updatedSettings: ".concat(JSON.stringify(l))),a(l)},handleResetField:(e,l)=>{if(s)try{let s=t.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:s.field_default_value}:s);a(s)}catch(e){console.log("ERROR OCCURRED!")}},handleSubmit:e=>{if(!s||(console.log("formValues: ".concat(e)),null==e||void 0==e))return;let l={};t.forEach(e=>{l[e.field_name]=e.field_value});let a={...e,...l};console.log("mergedFormValues: ".concat(JSON.stringify(a)));let{slack_alerting:r,...n}=a;console.log("slack_alerting: ".concat(r,", alertingArgs: ").concat(JSON.stringify(n)));try{(0,y.jA)(s,"alerting_args",n),"boolean"==typeof r&&(!0==r?(0,y.jA)(s,"alerting",["slack"]):(0,y.jA)(s,"alerting",[])),D.ZP.success("Wait 10s for proxy to update.")}catch(e){}},premiumUser:l})},lU=l(86582);let{Title:lz,Paragraph:lV}=es.default;console.log=function(){};var lK=e=>{let{accessToken:s,userRole:l,userID:t,premiumUser:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)([]),[m,u]=(0,d.useState)(!1),[h]=L.Z.useForm(),[x,p]=(0,d.useState)(null),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)(""),[v,b]=(0,d.useState)({}),[Z,N]=(0,d.useState)([]),[C,I]=(0,d.useState)(!1),[T,E]=(0,d.useState)([]),[P,F]=(0,d.useState)(null),[q,U]=(0,d.useState)([]),[z,V]=(0,d.useState)(!1),[K,B]=(0,d.useState)(null),H=e=>{Z.includes(e)?N(Z.filter(s=>s!==e)):N([...Z,e])},J={llm_exceptions:"LLM Exceptions",llm_too_slow:"LLM Responses Too Slow",llm_requests_hanging:"LLM Requests Hanging",budget_alerts:"Budget Alerts (API Keys, Users)",db_exceptions:"Database Exceptions (Read/Write)",daily_reports:"Weekly/Monthly Spend Reports",outage_alerts:"Outage Alerts",region_outage_alerts:"Region Outage Alerts"};(0,d.useEffect)(()=>{s&&l&&t&&(0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e),n(e.callbacks),E(e.available_callbacks);let s=e.alerts;if(console.log("alerts_data",s),s&&s.length>0){let e=s[0];console.log("_alert_info",e);let l=e.variables.SLACK_WEBHOOK_URL;console.log("catch_all_webhook",l),N(e.active_alerts),_(l),b(e.alerts_to_webhook)}o(s)})},[s,l,t]);let W=e=>Z&&Z.includes(e),G=()=>{if(!s)return;let e={};i.filter(e=>"email"===e.name).forEach(s=>{var l;Object.entries(null!==(l=s.variables)&&void 0!==l?l:{}).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));a&&a.value&&(e[l]=null==a?void 0:a.value)})}),console.log("updatedVariables",e);try{(0,y.K_)(s,{general_settings:{alerting:["email"]},environment_variables:e})}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Email settings updated successfully")},Y=async e=>{if(!s)return;let l={};Object.entries(e).forEach(e=>{let[s,t]=e;"callback"!==s&&(l[s]=t)});try{await (0,y.K_)(s,{environment_variables:l}),D.ZP.success("Callback added successfully"),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},$=async e=>{if(!s)return;let l=null==e?void 0:e.callback,t={};Object.entries(e).forEach(e=>{let[s,l]=e;"callback"!==s&&(t[s]=l)});try{await (0,y.K_)(s,{environment_variables:t,litellm_settings:{success_callback:[l]}}),D.ZP.success("Callback ".concat(l," added successfully")),u(!1),h.resetFields(),p(null)}catch(e){D.ZP.error("Failed to add callback: "+e,20)}},X=e=>{console.log("inside handleSelectedCallbackChange",e),p(e.litellm_callback_name),console.log("all callbacks",T),e&&e.litellm_callback_params?(U(e.litellm_callback_params),console.log("selectedCallbackParams",q)):U([])};return s?(console.log("callbacks: ".concat(r)),(0,c.jsxs)("div",{className:"w-full mx-4",children:[(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Logging Callbacks"}),(0,c.jsx)(eR.Z,{value:"2",children:"Alerting Types"}),(0,c.jsx)(eR.Z,{value:"3",children:"Alerting Settings"}),(0,c.jsx)(eR.Z,{value:"4",children:"Email Alerts"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Active Logging Callbacks"}),(0,c.jsx)(w.Z,{numItems:2,children:(0,c.jsx)(eF.Z,{className:"max-h-[50vh]",children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eP.Z,{children:"Callback Name"})})}),(0,c.jsx)(eT.Z,{children:r.map((e,l)=>(0,c.jsxs)(eO.Z,{className:"flex justify-between",children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.name})}),(0,c.jsx)(eA.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"flex justify-between",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>{B(e),V(!0)}}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,e.name),className:"ml-2",variant:"secondary",children:"Test Callback"})]})})]},l))})]})})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>I(!0),children:"Add Callback"})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(A.Z,{className:"my-2",children:["Alerts are only supported for Slack Webhook URLs. Get your webhook urls from"," ",(0,c.jsx)("a",{href:"https://api.slack.com/messaging/webhooks",target:"_blank",style:{color:"blue"},children:"here"})]}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{}),(0,c.jsx)(eP.Z,{children:"Slack Webhook URL"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(J).map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:"region_outage_alerts"==l?a?(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)}):(0,c.jsx)(k.Z,{className:"flex items-center justify-center",children:(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:"✨ Enterprise Feature"})}):(0,c.jsx)(lF.Z,{id:"switch",name:"switch",checked:W(l),onChange:()=>H(l)})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:t})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:l,type:"password",defaultValue:v&&v[l]?v[l]:f})})]},s)})})]}),(0,c.jsx)(k.Z,{size:"xs",className:"mt-2",onClick:()=>{if(!s)return;let e={};Object.entries(J).forEach(s=>{let[l,t]=s,a=document.querySelector('input[name="'.concat(l,'"]'));console.log("key",l),console.log("webhookInput",a);let r=(null==a?void 0:a.value)||"";console.log("newWebhookValue",r),e[l]=r}),console.log("updatedAlertToWebhooks",e);let l={general_settings:{alert_to_webhook_url:e,alert_types:Z}};console.log("payload",l);try{(0,y.K_)(s,l)}catch(e){D.ZP.error("Failed to update alerts: "+e,20)}D.ZP.success("Alerts updated successfully")},children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"slack"),className:"mx-2",children:"Test Alerts"})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(lq,{accessToken:s,premiumUser:a})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(lz,{level:4,children:"Email Settings"}),(0,c.jsxs)(A.Z,{children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/email",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: email alerts"})," ",(0,c.jsx)("br",{})]}),(0,c.jsx)("div",{className:"flex w-full",children:i.filter(e=>"email"===e.name).map((e,s)=>{var l;return(0,c.jsx)(eA.Z,{children:(0,c.jsx)("ul",{children:(0,c.jsx)(w.Z,{numItems:2,children:Object.entries(null!==(l=e.variables)&&void 0!==l?l:{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("li",{className:"mx-2 my-2",children:[!0!=a&&("EMAIL_LOGO_URL"===s||"EMAIL_SUPPORT_CONTACT"===s)?(0,c.jsxs)("div",{children:[(0,c.jsx)("a",{href:"https://forms.gle/W3U4PZpJGFHWtHyA9",target:"_blank",children:(0,c.jsxs)(A.Z,{className:"mt-2",children:[" ","✨ ",s]})}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",disabled:!0,style:{width:"400px"}})]}):(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"mt-2",children:s}),(0,c.jsx)(S.Z,{name:s,defaultValue:l,type:"password",style:{width:"400px"}})]}),(0,c.jsxs)("p",{style:{fontSize:"small",fontStyle:"italic"},children:["SMTP_HOST"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP host address, e.g. `smtp.resend.com`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PORT"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP port number, e.g. `587`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_USERNAME"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the SMTP username, e.g. `username`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"SMTP_PASSWORD"===s&&(0,c.jsx)("span",{style:{color:"red"},children:" Required * "}),"SMTP_SENDER_EMAIL"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Enter the sender email address, e.g. `sender@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"TEST_EMAIL_ADDRESS"===s&&(0,c.jsxs)("div",{style:{color:"gray"},children:["Email Address to send `Test Email Alert` to. example: `info@berri.ai`",(0,c.jsx)("span",{style:{color:"red"},children:" Required * "})]}),"EMAIL_LOGO_URL"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the Logo that appears in the email, pass a url to your logo"}),"EMAIL_SUPPORT_CONTACT"===s&&(0,c.jsx)("div",{style:{color:"gray"},children:"(Optional) Customize the support email address that appears in the email. Default is support@berri.ai"})]})]},s)})})})},s)})}),(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>G(),children:"Save Changes"}),(0,c.jsx)(k.Z,{onClick:()=>(0,y.jE)(s,"email"),className:"mx-2",children:"Test Email Alerts"})]})})]})]})}),(0,c.jsxs)(M.Z,{title:"Add Logging Callback",visible:C,width:800,onCancel:()=>I(!1),footer:null,children:[(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/logging",className:"mb-8 mt-4",target:"_blank",style:{color:"blue"},children:" LiteLLM Docs: Logging"}),(0,c.jsx)(L.Z,{form:h,onFinish:$,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(lU.Z,{label:"Callback",name:"callback",rules:[{required:!0,message:"Please select a callback"}],children:(0,c.jsx)(O.default,{onChange:e=>{let s=T[e];s&&(console.log(s.ui_callback_name),X(s))},children:T&&Object.values(T).map(e=>(0,c.jsx)(ee.Z,{value:e.litellm_callback_name,children:e.ui_callback_name},e.litellm_callback_name))})}),q&&q.map(e=>(0,c.jsx)(lU.Z,{label:e,name:e,rules:[{required:!0,message:"Please enter the value for "+e}],children:(0,c.jsx)(S.Z,{type:"password"})},e)),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]}),(0,c.jsx)(M.Z,{visible:z,width:800,title:"Edit ".concat(null==K?void 0:K.name," Settings"),onCancel:()=>V(!1),footer:null,children:(0,c.jsxs)(L.Z,{form:h,onFinish:Y,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(c.Fragment,{children:K&&K.variables&&Object.entries(K.variables).map(e=>{let[s,l]=e;return(0,c.jsx)(lU.Z,{label:s,name:s,children:(0,c.jsx)(S.Z,{type:"password",defaultValue:l})},s)})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})]})):null},lB=l(92414),lH=l(46030);let{Option:lJ}=O.default;var lW=e=>{let{models:s,accessToken:l,routerSettings:t,setRouterSettings:a}=e,[r]=L.Z.useForm(),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>i(!0),children:"+ Add Fallbacks"}),(0,c.jsx)(M.Z,{title:"Add Fallbacks",visible:n,width:800,footer:null,onOk:()=>{i(!1),r.resetFields()},onCancel:()=>{i(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:e=>{console.log(e);let{model_name:s,models:n}=e,o=[...t.fallbacks||[],{[s]:n}],c={...t,fallbacks:o};console.log(c);try{(0,y.K_)(l,{router_settings:c}),a(c)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully"),i(!1),r.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Public Model Name",name:"model_name",rules:[{required:!0,message:"Set the model to fallback for"}],help:"required",children:(0,c.jsx)(eD.Z,{defaultValue:o,children:s&&s.map((e,s)=>(0,c.jsx)(ee.Z,{value:e,onClick:()=>m(e),children:e},s))})}),(0,c.jsx)(L.Z.Item,{label:"Fallback Models",name:"models",rules:[{required:!0,message:"Please select a model"}],help:"required",children:(0,c.jsx)(lB.Z,{value:s,children:s&&s.filter(e=>e!=o).map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Fallbacks"})})]})})]})},lG=l(26433);async function lY(e,s){console.log=function(){},console.log("isLocal:",!1);let l=window.location.origin,t=new lG.ZP.OpenAI({apiKey:s,baseURL:l,dangerouslyAllowBrowser:!0});try{let s=await t.chat.completions.create({model:e,messages:[{role:"user",content:"Hi, this is a test message"}],mock_testing_fallbacks:!0});D.ZP.success((0,c.jsxs)("span",{children:["Test model=",(0,c.jsx)("strong",{children:e}),", received model=",(0,c.jsx)("strong",{children:s.model}),". See"," ",(0,c.jsx)("a",{href:"#",onClick:()=>window.open("https://docs.litellm.ai/docs/proxy/reliability","_blank"),style:{textDecoration:"underline",color:"blue"},children:"curl"})]}))}catch(e){D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20)}}let l$={ttl:3600,lowest_latency_buffer:0},lX=e=>{let{selectedStrategy:s,strategyArgs:l,paramExplanation:t}=e;return(0,c.jsxs)(C.Z,{children:[(0,c.jsx)(T.Z,{className:"text-sm font-medium text-tremor-content-strong dark:text-dark-tremor-content-strong",children:"Routing Strategy Specific Args"}),(0,c.jsx)(I.Z,{children:"latency-based-routing"==s?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(l).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:t[s]})]}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]})}):(0,c.jsx)(A.Z,{children:"No specific settings"})})]})};var lQ=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)({}),[i,o]=(0,d.useState)({}),[m,u]=(0,d.useState)([]),[h,x]=(0,d.useState)(!1),[p]=L.Z.useForm(),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(null),[v,b]=(0,d.useState)(null),Z={routing_strategy_args:"(dict) Arguments to pass to the routing strategy",routing_strategy:"(string) Routing strategy to use",allowed_fails:"(int) Number of times a deployment can fail before being added to cooldown",cooldown_time:"(int) time in seconds to cooldown a deployment after failure",num_retries:"(int) Number of retries for failed requests. Defaults to 0.",timeout:"(float) Timeout for requests. Defaults to None.",retry_after:"(int) Minimum time to wait before retrying a failed request",ttl:"(int) Sliding window to look back over when calculating the average latency of a deployment. Default - 1 hour (in seconds).",lowest_latency_buffer:"(float) Shuffle between deployments within this % of the lowest latency. Default - 0 (i.e. always pick lowest latency)."};(0,d.useEffect)(()=>{s&&l&&t&&((0,y.BL)(s,t,l).then(e=>{console.log("callbacks",e);let s=e.router_settings;"model_group_retry_policy"in s&&delete s.model_group_retry_policy,n(s)}),(0,y.YU)(s).then(e=>{u(e)}))},[s,l,t]);let C=async e=>{if(!s)return;console.log("received key: ".concat(e)),console.log("routerSettings['fallbacks']: ".concat(r.fallbacks));let l=r.fallbacks.map(s=>(e in s&&delete s[e],s)).filter(e=>Object.keys(e).length>0),t={...r,fallbacks:l};try{await (0,y.K_)(s,{router_settings:t}),n(t),D.ZP.success("Router settings updated successfully")}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}},I=(e,s)=>{u(m.map(l=>l.field_name===e?{...l,field_value:s}:l))},T=(e,l)=>{if(!s)return;let t=m[l].field_value;if(null!=t&&void 0!=t)try{(0,y.jA)(s,e,t);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:!0}:s);u(l)}catch(e){}},P=(e,l)=>{if(s)try{(0,y.ao)(s,e);let l=m.map(s=>s.field_name===e?{...s,stored_in_db:null,field_value:null}:s);u(l)}catch(e){}},O=e=>{if(!s)return;console.log("router_settings",e);let l=Object.fromEntries(Object.entries(e).map(e=>{let[s,l]=e;if("routing_strategy_args"!==s&&"routing_strategy"!==s){var t;return[s,(null===(t=document.querySelector('input[name="'.concat(s,'"]')))||void 0===t?void 0:t.value)||l]}if("routing_strategy"==s)return[s,f];if("routing_strategy_args"==s&&"latency-based-routing"==f){let e={},s=document.querySelector('input[name="lowest_latency_buffer"]'),l=document.querySelector('input[name="ttl"]');return(null==s?void 0:s.value)&&(e.lowest_latency_buffer=Number(s.value)),(null==l?void 0:l.value)&&(e.ttl=Number(l.value)),console.log("setRoutingStrategyArgs: ".concat(e)),["routing_strategy_args",e]}return null}).filter(e=>null!=e));console.log("updatedVariables",l);try{(0,y.K_)(s,{router_settings:l})}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("router settings updated successfully")};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)(eU.Z,{variant:"line",defaultValue:"1",children:[(0,c.jsx)(eR.Z,{value:"1",children:"Loadbalancing"}),(0,c.jsx)(eR.Z,{value:"2",children:"Fallbacks"}),(0,c.jsx)(eR.Z,{value:"3",children:"General"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:[(0,c.jsx)(E.Z,{children:"Router Settings"}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"})]})}),(0,c.jsx)(eT.Z,{children:Object.entries(r).filter(e=>{let[s,l]=e;return"fallbacks"!=s&&"context_window_fallbacks"!=s&&"routing_strategy_args"!=s}).map(e=>{let[s,l]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:s}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:Z[s]})]}),(0,c.jsx)(eA.Z,{children:"routing_strategy"==s?(0,c.jsxs)(eD.Z,{defaultValue:l,className:"w-full max-w-md",onValueChange:_,children:[(0,c.jsx)(ee.Z,{value:"usage-based-routing",children:"usage-based-routing"}),(0,c.jsx)(ee.Z,{value:"latency-based-routing",children:"latency-based-routing"}),(0,c.jsx)(ee.Z,{value:"simple-shuffle",children:"simple-shuffle"})]}):(0,c.jsx)(S.Z,{name:s,defaultValue:"object"==typeof l?JSON.stringify(l,null,2):l.toString()})})]},s)})})]}),(0,c.jsx)(lX,{selectedStrategy:f,strategyArgs:r&&r.routing_strategy_args&&Object.keys(r.routing_strategy_args).length>0?r.routing_strategy_args:l$,paramExplanation:Z})]}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(k.Z,{className:"mt-2",onClick:()=>O(r),children:"Save Changes"})})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Model Name"}),(0,c.jsx)(eP.Z,{children:"Fallbacks"})]})}),(0,c.jsx)(eT.Z,{children:r.fallbacks&&r.fallbacks.map((e,l)=>Object.entries(e).map(e=>{let[t,a]=e;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:t}),(0,c.jsx)(eA.Z,{children:Array.isArray(a)?a.join(", "):a}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(k.Z,{onClick:()=>lY(t,s),children:"Test Fallback"})}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>C(t)})})]},l.toString()+t)}))})]}),(0,c.jsx)(lW,{models:(null==a?void 0:a.data)?a.data.map(e=>e.model_name):[],accessToken:s,routerSettings:r,setRouterSettings:n})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Setting"}),(0,c.jsx)(eP.Z,{children:"Value"}),(0,c.jsx)(eP.Z,{children:"Status"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:m.filter(e=>"TypedDictionary"!==e.field_type).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(A.Z,{children:e.field_name}),(0,c.jsx)("p",{style:{fontSize:"0.65rem",color:"#808080",fontStyle:"italic"},className:"mt-1",children:e.field_description})]}),(0,c.jsx)(eA.Z,{children:"Integer"==e.field_type?(0,c.jsx)(H.Z,{step:1,value:e.field_value,onChange:s=>I(e.field_name,s)}):null}),(0,c.jsx)(eA.Z,{children:!0==e.stored_in_db?(0,c.jsx)(eM.Z,{icon:ed.Z,className:"text-white",children:"In DB"}):!1==e.stored_in_db?(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"In Config"}):(0,c.jsx)(eM.Z,{className:"text-gray bg-white outline",children:"Not Set"})}),(0,c.jsxs)(eA.Z,{children:[(0,c.jsx)(k.Z,{onClick:()=>T(e.field_name,s),children:"Update"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>P(e.field_name,s),children:"Reset"})]})]},s))})]})})})]})]})}):null},l0=l(93142),l1=e=>{let{value:s={},onChange:l}=e,[t,a]=(0,d.useState)(Object.entries(s)),r=e=>{let s=t.filter((s,l)=>l!==e);a(s),null==l||l(Object.fromEntries(s))},n=(e,s,r)=>{let n=[...t];n[e]=[s,r],a(n),null==l||l(Object.fromEntries(n))};return(0,c.jsxs)("div",{children:[t.map((e,s)=>{let[l,t]=e;return(0,c.jsxs)(l0.Z,{style:{display:"flex",marginBottom:8},align:"start",children:[(0,c.jsx)(S.Z,{placeholder:"Header Name",value:l,onChange:e=>n(s,e.target.value,t)}),(0,c.jsx)(S.Z,{placeholder:"Header Value",value:t,onChange:e=>n(s,l,e.target.value)}),(0,c.jsx)(sH.Z,{onClick:()=>r(s)})]},s)}),(0,c.jsx)(R.ZP,{type:"dashed",onClick:()=>{a([...t,["",""]])},icon:(0,c.jsx)(sJ.Z,{}),children:"Add Header"})]})};let{Option:l2}=O.default;var l4=e=>{let{accessToken:s,setPassThroughItems:l,passThroughItems:t}=e,[a]=L.Z.useForm(),[r,n]=(0,d.useState)(!1),[i,o]=(0,d.useState)("");return(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{className:"mx-auto",onClick:()=>n(!0),children:"+ Add Pass-Through Endpoint"}),(0,c.jsx)(M.Z,{title:"Add Pass-Through Endpoint",visible:r,width:800,footer:null,onOk:()=>{n(!1),a.resetFields()},onCancel:()=>{n(!1),a.resetFields()},children:(0,c.jsxs)(L.Z,{form:a,onFinish:e=>{console.log(e);let r=[...t,{headers:e.headers,path:e.path,target:e.target}];try{(0,y.Vt)(s,e),l(r)}catch(e){D.ZP.error("Failed to update router settings: "+e,20)}D.ZP.success("Pass through endpoint successfully added"),n(!1),a.resetFields()},labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Path",name:"path",rules:[{required:!0,message:"The route to be added to the LiteLLM Proxy Server."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Target",name:"target",rules:[{required:!0,message:"The URL to which requests for this path should be forwarded."}],help:"required",children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Headers",name:"headers",rules:[{required:!0,message:"Key-value pairs of headers to be forwarded with the request. You can set any key value pair here and it will be forwarded to your target endpoint"}],help:"required",children:(0,c.jsx)(l1,{})})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Add Pass-Through Endpoint"})})]})})]})},l5=e=>{let{accessToken:s,userRole:l,userID:t,modelData:a}=e,[r,n]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&l&&t&&(0,y.mp)(s).then(e=>{n(e.endpoints)})},[s,l,t]);let i=(e,l)=>{if(s)try{(0,y.EG)(s,e);let l=r.filter(s=>s.path!==e);n(l),D.ZP.success("Endpoint deleted successfully.")}catch(e){}};return s?(0,c.jsx)("div",{className:"w-full mx-4",children:(0,c.jsx)(eq.Z,{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Path"}),(0,c.jsx)(eP.Z,{children:"Target"}),(0,c.jsx)(eP.Z,{children:"Headers"}),(0,c.jsx)(eP.Z,{children:"Action"})]})}),(0,c.jsx)(eT.Z,{children:r.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:(0,c.jsx)(A.Z,{children:e.path})}),(0,c.jsx)(eA.Z,{children:e.target}),(0,c.jsx)(eA.Z,{children:JSON.stringify(e.headers)}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)(sZ.Z,{icon:eH.Z,color:"red",onClick:()=>i(e.path,s),children:"Reset"})})]},s))})]}),(0,c.jsx)(l4,{accessToken:s,setPassThroughItems:n,passThroughItems:r})]})})}):null},l6=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a}=e,[r]=L.Z.useForm(),n=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call");let s=await (0,y.Zr)(l,e);console.log("key create Response:",s),a(e=>e?[...e,s]:[s]),D.ZP.success("API Key Created"),r.resetFields()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Create Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),r.resetFields()},onCancel:()=>{t(!1),r.resetFields()},children:(0,c.jsxs)(L.Z,{form:r,onFinish:n,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Create Budget"})})]})})},l3=e=>{let{isModalVisible:s,accessToken:l,setIsModalVisible:t,setBudgetList:a,existingBudget:r,handleUpdateCall:n}=e;console.log("existingBudget",r);let[i]=L.Z.useForm();(0,d.useEffect)(()=>{i.setFieldsValue(r)},[r,i]);let o=async e=>{if(null!=l&&void 0!=l)try{D.ZP.info("Making API Call"),t(!0);let s=await (0,y.qI)(l,e);a(e=>e?[...e,s]:[s]),D.ZP.success("Budget Updated"),i.resetFields(),n()}catch(e){console.error("Error creating the key:",e),D.ZP.error("Error creating the key: ".concat(e),20)}};return(0,c.jsx)(M.Z,{title:"Edit Budget",visible:s,width:800,footer:null,onOk:()=>{t(!1),i.resetFields()},onCancel:()=>{t(!1),i.resetFields()},children:(0,c.jsxs)(L.Z,{form:i,onFinish:o,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",initialValues:r,children:[(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(L.Z.Item,{label:"Budget ID",name:"budget_id",rules:[{required:!0,message:"Please input a human-friendly name for the budget"}],help:"A human-friendly name for the budget",children:(0,c.jsx)(S.Z,{placeholder:""})}),(0,c.jsx)(L.Z.Item,{label:"Max Tokens per minute",name:"tpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{label:"Max Requests per minute",name:"rpm_limit",help:"Default is model limit.",children:(0,c.jsx)(H.Z,{step:1,precision:2,width:200})}),(0,c.jsxs)(C.Z,{className:"mt-20 mb-8",children:[(0,c.jsx)(T.Z,{children:(0,c.jsx)("b",{children:"Optional Settings"})}),(0,c.jsxs)(I.Z,{children:[(0,c.jsx)(L.Z.Item,{label:"Max Budget (USD)",name:"max_budget",children:(0,c.jsx)(H.Z,{step:.01,precision:2,width:200})}),(0,c.jsx)(L.Z.Item,{className:"mt-8",label:"Reset Budget",name:"budget_duration",children:(0,c.jsxs)(O.default,{defaultValue:null,placeholder:"n/a",children:[(0,c.jsx)(O.default.Option,{value:"24h",children:"daily"}),(0,c.jsx)(O.default.Option,{value:"7d",children:"weekly"}),(0,c.jsx)(O.default.Option,{value:"30d",children:"monthly"})]})})]})]})]}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(R.ZP,{htmlType:"submit",children:"Save"})})]})})},l8=l(17906),l7=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)([]);(0,d.useEffect)(()=>{s&&(0,y.O3)(s).then(e=>{m(e)})},[s]);let u=async(e,l)=>{console.log("budget_id",e),null!=s&&(i(o.find(s=>s.budget_id===e)||null),r(!0))},h=async(e,l)=>{if(null==s)return;D.ZP.info("Request made"),await (0,y.NV)(s,e);let t=[...o];t.splice(l,1),m(t),D.ZP.success("Budget Deleted.")},x=async()=>{null!=s&&(0,y.O3)(s).then(e=>{m(e)})};return(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsx)(k.Z,{size:"sm",variant:"primary",className:"mb-2",onClick:()=>t(!0),children:"+ Create Budget"}),(0,c.jsx)(l6,{accessToken:s,isModalVisible:l,setIsModalVisible:t,setBudgetList:m}),n&&(0,c.jsx)(l3,{accessToken:s,isModalVisible:a,setIsModalVisible:r,setBudgetList:m,existingBudget:n,handleUpdateCall:x}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Create a budget to assign to customers."}),(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Budget ID"}),(0,c.jsx)(eP.Z,{children:"Max Budget"}),(0,c.jsx)(eP.Z,{children:"TPM"}),(0,c.jsx)(eP.Z,{children:"RPM"})]})}),(0,c.jsx)(eT.Z,{children:o.slice().sort((e,s)=>new Date(s.updated_at).getTime()-new Date(e.updated_at).getTime()).map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.budget_id}),(0,c.jsx)(eA.Z,{children:e.max_budget?e.max_budget:"n/a"}),(0,c.jsx)(eA.Z,{children:e.tpm_limit?e.tpm_limit:"n/a"}),(0,c.jsx)(eA.Z,{children:e.rpm_limit?e.rpm_limit:"n/a"}),(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>u(e.budget_id,s)}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>h(e.budget_id,s)})]},s))})]})]}),(0,c.jsxs)("div",{className:"mt-5",children:[(0,c.jsx)(A.Z,{className:"text-base",children:"How to use budget id"}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"Assign Budget to Customer"}),(0,c.jsx)(eR.Z,{children:"Test it (Curl)"}),(0,c.jsx)(eR.Z,{children:"Test it (OpenAI SDK)"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:"\ncurl -X POST --location '/end_user/new' \n-H 'Authorization: Bearer ' \n-H 'Content-Type: application/json' \n-d '{\"user_id\": \"my-customer-id', \"budget_id\": \"\"}' # \uD83D\uDC48 KEY CHANGE\n\n "})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"bash",children:'\ncurl -X POST --location \'/chat/completions\' \n-H \'Authorization: Bearer \' \n-H \'Content-Type: application/json\' \n-d \'{\n "model": "gpt-3.5-turbo\', \n "messages":[{"role": "user", "content": "Hey, how\'s it going?"}],\n "user": "my-customer-id"\n}\' # \uD83D\uDC48 KEY CHANGE\n\n '})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'from openai import OpenAI\nclient = OpenAI(\n base_url="",\n api_key=""\n)\n\ncompletion = client.chat.completions.create(\n model="gpt-3.5-turbo",\n messages=[\n {"role": "system", "content": "You are a helpful assistant."},\n {"role": "user", "content": "Hello!"}\n ],\n user="my-customer-id"\n)\n\nprint(completion.choices[0].message)'})})]})]})]})]})},l9=l(77398),te=l.n(l9);async function ts(e){try{let s=await fetch("http://ip-api.com/json/".concat(e)),l=await s.json();console.log("ip lookup data",l);let t=l.countryCode?l.countryCode.toUpperCase().split("").map(e=>String.fromCodePoint(e.charCodeAt(0)+127397)).join(""):"";return l.country?"".concat(t," ").concat(l.country):"Unknown"}catch(e){return console.error("Error looking up IP:",e),"Unknown"}}let tl=e=>{let{ipAddress:s}=e,[l,t]=d.useState("-");return d.useEffect(()=>{if(!s)return;let e=!0;return ts(s).then(s=>{e&&t(s)}).catch(()=>{e&&t("-")}),()=>{e=!1}},[s]),(0,c.jsx)("span",{children:l})},tt=e=>{try{return new Date(e).toLocaleString("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!0}).replace(",","")}catch(e){return"Error converting time"}},ta=e=>{let{utcTime:s}=e;return(0,c.jsx)("span",{style:{fontFamily:"monospace",width:"180px",display:"inline-block"},children:tt(s)})},tr=(e,s)=>{var l,t;return(null===(t=e.metadata)||void 0===t?void 0:null===(l=t.mcp_tool_call_metadata)||void 0===l?void 0:l.mcp_server_logo_url)?e.metadata.mcp_tool_call_metadata.mcp_server_logo_url:s?sn(s).logo:""},tn=[{id:"expander",header:()=>null,cell:e=>{let{row:s}=e;return(0,c.jsx)(()=>{let[e,l]=d.useState(s.getIsExpanded()),t=d.useCallback(()=>{l(e=>!e),s.getToggleExpandedHandler()()},[s]);return s.getCanExpand()?(0,c.jsx)("button",{onClick:t,style:{cursor:"pointer"},"aria-label":e?"Collapse row":"Expand row",className:"w-6 h-6 flex items-center justify-center focus:outline-none",children:(0,c.jsx)("svg",{className:"w-4 h-4 transform transition-transform duration-75 ".concat(e?"rotate-90":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})})}):(0,c.jsx)("span",{className:"w-6 h-6 flex items-center justify-center",children:"●"})},{})}},{header:"Time",accessorKey:"startTime",cell:e=>(0,c.jsx)(ta,{utcTime:e.getValue()})},{header:"Status",accessorKey:"metadata.status",cell:e=>{let s="failure"!==(e.getValue()||"Success").toLowerCase();return(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat(s?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:s?"Success":"Failure"})}},{header:"Request ID",accessorKey:"request_id",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||""),children:(0,c.jsx)("span",{className:"font-mono text-xs max-w-[15ch] truncate block",children:String(e.getValue()||"")})})},{header:"Cost",accessorKey:"spend",cell:e=>(0,c.jsxs)("span",{children:["$",Number(e.getValue()||0).toFixed(6)]})},{header:"Country",accessorKey:"requester_ip_address",cell:e=>(0,c.jsx)(tl,{ipAddress:e.getValue()})},{header:"Team Name",accessorKey:"metadata.user_api_key_team_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Key Hash",accessorKey:"metadata.user_api_key",cell:e=>{let s=String(e.getValue()||"-"),l=e.row.original.onKeyHashClick;return(0,c.jsx)(W.Z,{title:s,children:(0,c.jsx)("span",{className:"font-mono max-w-[15ch] truncate block cursor-pointer hover:text-blue-600",onClick:()=>null==l?void 0:l(s),children:s})})}},{header:"Key Name",accessorKey:"metadata.user_api_key_alias",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Model",accessorKey:"model",cell:e=>{let s=e.row.original,l=s.custom_llm_provider,t=String(e.getValue()||"");return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[l&&(0,c.jsx)("img",{src:tr(s,l),alt:"",className:"w-4 h-4",onError:e=>{e.target.style.display="none"}}),(0,c.jsx)(W.Z,{title:t,children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:t})})]})}},{header:"Tokens",accessorKey:"total_tokens",cell:e=>{let s=e.row.original;return(0,c.jsxs)("span",{className:"text-sm",children:[String(s.total_tokens||"0"),(0,c.jsxs)("span",{className:"text-gray-400 text-xs ml-1",children:["(",String(s.prompt_tokens||"0"),"+",String(s.completion_tokens||"0"),")"]})]})}},{header:"Internal User",accessorKey:"user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"End User",accessorKey:"end_user",cell:e=>(0,c.jsx)(W.Z,{title:String(e.getValue()||"-"),children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:String(e.getValue()||"-")})})},{header:"Tags",accessorKey:"request_tags",cell:e=>{let s=e.getValue();if(!s||0===Object.keys(s).length)return"-";let l=Object.entries(s),t=l[0],a=l.slice(1);return(0,c.jsx)("div",{className:"flex flex-wrap gap-1",children:(0,c.jsx)(W.Z,{title:(0,c.jsx)("div",{className:"flex flex-col gap-1",children:l.map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{children:[s,": ",String(l)]},s)})}),children:(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[t[0],": ",String(t[1]),a.length>0&&" +".concat(a.length)]})})})}}],ti=async(e,s,l,t)=>{console.log("prefetchLogDetails called with",e.length,"logs");let a=e.map(e=>{if(e.request_id)return console.log("Prefetching details for request_id:",e.request_id),t.prefetchQuery({queryKey:["logDetails",e.request_id,s],queryFn:async()=>{console.log("Fetching details for",e.request_id);let t=await (0,y.qk)(l,e.request_id,s);return console.log("Received details for",e.request_id,":",t?"success":"failed"),t},staleTime:6e5,gcTime:6e5})});try{let e=await Promise.all(a);return console.log("All prefetch promises completed:",e.length),e}catch(e){throw console.error("Error in prefetchLogDetails:",e),e}},to=e=>{var s;let{errorInfo:l}=e,[t,a]=d.useState({}),[r,n]=d.useState(!1),i=e=>{a(s=>({...s,[e]:!s[e]}))},o=l.traceback&&(s=l.traceback)?Array.from(s.matchAll(/File "([^"]+)", line (\d+)/g)).map(e=>{let l=e[1],t=e[2],a=l.split("/").pop()||l,r=e.index||0,n=s.indexOf('File "',r+1),i=n>-1?s.substring(r,n).trim():s.substring(r).trim(),o=i.split("\n"),c="";return o.length>1&&(c=o[o.length-1].trim()),{filePath:l,fileName:a,lineNumber:t,code:c,inFunction:i.includes(" in ")?i.split(" in ")[1].split("\n")[0]:""}}):[];return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsxs)("h3",{className:"text-lg font-medium flex items-center text-red-600",children:[(0,c.jsx)("svg",{className:"w-5 h-5 mr-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"})}),"Error Details"]})}),(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"bg-red-50 rounded-md p-4 mb-4",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Type:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_class||"Unknown Error"})]}),(0,c.jsxs)("div",{className:"flex mt-2",children:[(0,c.jsx)("span",{className:"text-red-800 font-medium w-20",children:"Message:"}),(0,c.jsx)("span",{className:"text-red-700",children:l.error_message||"Unknown error occurred"})]})]}),l.traceback&&(0,c.jsxs)("div",{className:"mt-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-2",children:[(0,c.jsx)("h4",{className:"font-medium",children:"Traceback"}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsx)("button",{onClick:()=>{let e=!r;if(n(e),o.length>0){let s={};o.forEach((l,t)=>{s[t]=e}),a(s)}},className:"text-gray-500 hover:text-gray-700 flex items-center text-sm",children:r?"Collapse All":"Expand All"}),(0,c.jsxs)("button",{onClick:()=>navigator.clipboard.writeText(l.traceback||""),className:"text-gray-500 hover:text-gray-700 flex items-center",title:"Copy traceback",children:[(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),(0,c.jsx)("span",{className:"ml-1",children:"Copy"})]})]})]}),(0,c.jsx)("div",{className:"bg-white rounded-md border border-gray-200 overflow-hidden shadow-sm",children:o.map((e,s)=>(0,c.jsxs)("div",{className:"border-b border-gray-200 last:border-b-0",children:[(0,c.jsxs)("div",{className:"px-4 py-2 flex items-center justify-between cursor-pointer hover:bg-gray-50",onClick:()=>i(s),children:[(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("span",{className:"text-gray-400 mr-2 w-12 text-right",children:e.lineNumber}),(0,c.jsx)("span",{className:"text-gray-600 font-medium",children:e.fileName}),(0,c.jsx)("span",{className:"text-gray-500 mx-1",children:"in"}),(0,c.jsx)("span",{className:"text-indigo-600 font-medium",children:e.inFunction||e.fileName})]}),(0,c.jsx)("svg",{className:"w-5 h-5 text-gray-500 transition-transform ".concat(t[s]?"transform rotate-180":""),fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),(t[s]||!1)&&e.code&&(0,c.jsx)("div",{className:"px-12 py-2 font-mono text-sm text-gray-800 bg-gray-50 overflow-x-auto border-t border-gray-100",children:e.code})]},s))})]})]})]})},tc=e=>{let{show:s}=e;return s?(0,c.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start",children:[(0,c.jsx)("div",{className:"text-blue-500 mr-3 flex-shrink-0 mt-0.5",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("circle",{cx:"12",cy:"12",r:"10"}),(0,c.jsx)("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),(0,c.jsx)("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}),(0,c.jsxs)("div",{children:[(0,c.jsx)("h4",{className:"text-sm font-medium text-blue-800",children:"Request/Response Data Not Available"}),(0,c.jsxs)("p",{className:"text-sm text-blue-700 mt-1",children:["To view request and response details, enable prompt storage in your LiteLLM configuration by adding the following to your ",(0,c.jsx)("code",{className:"bg-blue-100 px-1 py-0.5 rounded",children:"proxy_config.yaml"})," file:"]}),(0,c.jsx)("pre",{className:"mt-2 bg-white p-3 rounded border border-blue-200 text-xs font-mono overflow-auto",children:"general_settings:\n store_model_in_db: true\n store_prompts_in_spend_logs: true"}),(0,c.jsx)("p",{className:"text-xs text-blue-700 mt-2",children:"Note: This will only affect new requests after the configuration change."})]})]}):null};function td(e){var s,l,t,a;let{accessToken:r,token:n,userRole:i,userID:o,allTeams:m}=e,[u,h]=(0,d.useState)(""),[p,g]=(0,d.useState)(!1),[j,f]=(0,d.useState)(!1),[_,v]=(0,d.useState)(1),[b]=(0,d.useState)(50),Z=(0,d.useRef)(null),N=(0,d.useRef)(null),w=(0,d.useRef)(null),[k,S]=(0,d.useState)(te()().subtract(24,"hours").format("YYYY-MM-DDTHH:mm")),[C,I]=(0,d.useState)(te()().format("YYYY-MM-DDTHH:mm")),[T,A]=(0,d.useState)(!1),[E,P]=(0,d.useState)(!1),[O,L]=(0,d.useState)(""),[D,M]=(0,d.useState)(""),[F,R]=(0,d.useState)(""),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(null),[K,B]=(0,d.useState)(null),[H,J]=(0,d.useState)("Team ID"),[W,G]=(0,d.useState)(i&&eg.lo.includes(i)),[Y,$]=(0,d.useState)(null),X=(0,x.NL)();(0,d.useEffect)(()=>{(async()=>{if(K&&r){let e=await (0,y.t0)(r,K);console.log("keyData",e),V({...e.info,token:K,api_key:K})}})()},[K,r]),(0,d.useEffect)(()=>{function e(e){Z.current&&!Z.current.contains(e.target)&&f(!1),N.current&&!N.current.contains(e.target)&&g(!1),w.current&&!w.current.contains(e.target)&&P(!1)}return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]),(0,d.useEffect)(()=>{i&&eg.lo.includes(i)&&G(!0)},[i]);let Q=(0,e4.a)({queryKey:["logs","table",_,b,k,C,F,q,W?o:null],queryFn:async()=>{if(!r||!n||!i||!o)return console.log("Missing required auth parameters"),{data:[],total:0,page:1,page_size:b,total_pages:0};let e=te()(k).utc().format("YYYY-MM-DD HH:mm:ss"),s=T?te()(C).utc().format("YYYY-MM-DD HH:mm:ss"):te()().utc().format("YYYY-MM-DD HH:mm:ss"),l=await (0,y.h3)(r,q||void 0,F||void 0,void 0,e,s,_,b,W?o:void 0);return await ti(l.data,e,r,X),l.data=l.data.map(s=>{let l=X.getQueryData(["logDetails",s.request_id,e]);return(null==l?void 0:l.messages)&&(null==l?void 0:l.response)&&(s.messages=l.messages,s.response=l.response),s}),l},enabled:!!r&&!!n&&!!i&&!!o,refetchInterval:5e3,refetchIntervalInBackground:!0});if((0,d.useEffect)(()=>{var e;(null===(e=Q.data)||void 0===e?void 0:e.data)&&Y&&!Q.data.data.some(e=>e.request_id===Y)&&$(null)},[null===(s=Q.data)||void 0===s?void 0:s.data,Y]),!r||!n||!i||!o)return console.log("got None values for one of accessToken, token, userRole, userID"),null;let ee=(null===(t=Q.data)||void 0===t?void 0:null===(l=t.data)||void 0===l?void 0:l.filter(e=>!u||e.request_id.includes(u)||e.model.includes(u)||e.user&&e.user.includes(u)).map(e=>({...e,onKeyHashClick:e=>B(e)})))||[],es=()=>{if(T)return"".concat(te()(k).format("MMM D, h:mm A")," - ").concat(te()(C).format("MMM D, h:mm A"));let e=te()(),s=te()(k),l=e.diff(s,"minutes");if(l<=15)return"Last 15 Minutes";if(l<=60)return"Last Hour";let t=e.diff(s,"hours");return t<=4?"Last 4 Hours":t<=24?"Last 24 Hours":t<=168?"Last 7 Days":"".concat(s.format("MMM D")," - ").concat(e.format("MMM D"))};return(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"Request Logs"})}),z&&K&&z.api_key===K?(0,c.jsx)(eG,{keyId:K,keyData:z,accessToken:r,userID:o,userRole:i,teams:m,onClose:()=>B(null)}):(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between space-y-4 md:space-y-0",children:[(0,c.jsxs)("div",{className:"flex flex-wrap items-center gap-3",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search by Request ID",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:u,onChange:e=>h(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"relative",ref:N,children:[(0,c.jsxs)("button",{className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",onClick:()=>g(!p),children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z"})}),"Filter"]}),p&&(0,c.jsx)("div",{className:"absolute left-0 mt-2 w-[500px] bg-white rounded-lg shadow-lg border p-4 z-50",children:(0,c.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("span",{className:"text-sm font-medium",children:"Where"}),(0,c.jsxs)("div",{className:"relative",children:[(0,c.jsxs)("button",{onClick:()=>f(!j),className:"px-3 py-1.5 border rounded-md bg-white text-sm min-w-[160px] focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 text-left flex justify-between items-center",children:[H,(0,c.jsx)("svg",{className:"h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),j&&(0,c.jsx)("div",{className:"absolute left-0 mt-1 w-[160px] bg-white border rounded-md shadow-lg z-50",children:["Team ID","Key Hash"].map(e=>(0,c.jsxs)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2 ".concat(H===e?"bg-blue-50 text-blue-600":""),onClick:()=>{J(e),f(!1),"Team ID"===e?M(""):L("")},children:[H===e&&(0,c.jsx)("svg",{className:"h-4 w-4 text-blue-600",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),e]},e))})]}),(0,c.jsx)("input",{type:"text",placeholder:"Enter value...",className:"px-3 py-1.5 border rounded-md text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:"Team ID"===H?O:D,onChange:e=>{"Team ID"===H?L(e.target.value):M(e.target.value)}}),(0,c.jsx)("button",{className:"p-1 hover:bg-gray-100 rounded-md",onClick:()=>{L(""),M("")},children:(0,c.jsx)("span",{className:"text-gray-500",children:"\xd7"})})]}),(0,c.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm border rounded-md hover:bg-gray-50",onClick:()=>{L(""),M(""),g(!1)},children:"Cancel"}),(0,c.jsx)("button",{className:"px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{R(O),U(D),v(1),g(!1)},children:"Apply Filters"})]})]})})]}),(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsxs)("div",{className:"relative",ref:w,children:[(0,c.jsxs)("button",{onClick:()=>P(!E),className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",children:[(0,c.jsx)("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"})}),es()]}),E&&(0,c.jsx)("div",{className:"absolute right-0 mt-2 w-64 bg-white rounded-lg shadow-lg border p-2 z-50",children:(0,c.jsxs)("div",{className:"space-y-1",children:[[{label:"Last 15 Minutes",value:15,unit:"minutes"},{label:"Last Hour",value:1,unit:"hours"},{label:"Last 4 Hours",value:4,unit:"hours"},{label:"Last 24 Hours",value:24,unit:"hours"},{label:"Last 7 Days",value:7,unit:"days"}].map(e=>(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(es()===e.label?"bg-blue-50 text-blue-600":""),onClick:()=>{I(te()().format("YYYY-MM-DDTHH:mm")),S(te()().subtract(e.value,e.unit).format("YYYY-MM-DDTHH:mm")),P(!1),A(!1)},children:e.label},e.label)),(0,c.jsx)("div",{className:"border-t my-2"}),(0,c.jsx)("button",{className:"w-full px-3 py-2 text-left text-sm hover:bg-gray-50 rounded-md ".concat(T?"bg-blue-50 text-blue-600":""),onClick:()=>A(!T),children:"Custom Range"})]})})]}),(0,c.jsxs)("button",{onClick:()=>{Q.refetch()},className:"px-3 py-2 text-sm border rounded-md hover:bg-gray-50 flex items-center gap-2",title:"Refresh data",children:[(0,c.jsx)("svg",{className:"w-4 h-4 ".concat(Q.isFetching?"animate-spin":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),(0,c.jsx)("span",{children:"Refresh"})]})]}),T&&(0,c.jsxs)("div",{className:"flex items-center gap-2",children:[(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:k,onChange:e=>{S(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})}),(0,c.jsx)("span",{className:"text-gray-500",children:"to"}),(0,c.jsx)("div",{children:(0,c.jsx)("input",{type:"datetime-local",value:C,onChange:e=>{I(e.target.value),v(1)},className:"px-3 py-2 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"})})]})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-4",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Showing"," ",Q.isLoading?"...":Q.data?(_-1)*b+1:0," ","-"," ",Q.isLoading?"...":Q.data?Math.min(_*b,Q.data.total):0," ","of"," ",Q.isLoading?"...":Q.data?Q.data.total:0," ","results"]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,c.jsxs)("span",{className:"text-sm text-gray-700",children:["Page ",Q.isLoading?"...":_," of"," ",Q.isLoading?"...":Q.data?Q.data.total_pages:1]}),(0,c.jsx)("button",{onClick:()=>v(e=>Math.max(1,e-1)),disabled:Q.isLoading||1===_,className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Previous"}),(0,c.jsx)("button",{onClick:()=>v(e=>{var s;return Math.min((null===(s=Q.data)||void 0===s?void 0:s.total_pages)||1,e+1)}),disabled:Q.isLoading||_===((null===(a=Q.data)||void 0===a?void 0:a.total_pages)||1),className:"px-3 py-1 text-sm border rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed",children:"Next"})]})]})]})}),(0,c.jsx)(eL,{columns:tn,data:ee,renderSubComponent:tm,getRowCanExpand:()=>!0,onRowExpand:e=>{$(e)},expandedRequestId:Y})]})})]})}function tm(e){var s,l,t,a,r,n;let{row:i}=e,o=e=>{let s={...e};return"proxy_server_request"in s&&delete s.proxy_server_request,s},d=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){}return e},m=()=>{var e;return(null===(e=i.original.metadata)||void 0===e?void 0:e.proxy_server_request)?d(i.original.metadata.proxy_server_request):d(i.original.messages)},u=(null===(s=i.original.metadata)||void 0===s?void 0:s.status)==="failure",h=u?null===(l=i.original.metadata)||void 0===l?void 0:l.error_information:null,x=i.original.messages&&(Array.isArray(i.original.messages)?i.original.messages.length>0:Object.keys(i.original.messages).length>0),p=i.original.response&&Object.keys(d(i.original.response)).length>0,g=()=>u&&h?{error:{message:h.error_message||"An error occurred",type:h.error_class||"error",code:h.error_code||"unknown",param:null}}:d(i.original.response);return(0,c.jsxs)("div",{className:"p-6 bg-gray-50 space-y-6",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Details"})}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4 p-4",children:[(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Request ID:"}),(0,c.jsx)("span",{className:"font-mono text-sm",children:i.original.request_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model:"}),(0,c.jsx)("span",{children:i.original.model})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Model ID:"}),(0,c.jsx)("span",{children:i.original.model_id})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Provider:"}),(0,c.jsx)("span",{children:i.original.custom_llm_provider||"-"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"API Base:"}),(0,c.jsx)(W.Z,{title:i.original.api_base||"-",children:(0,c.jsx)("span",{className:"max-w-[15ch] truncate block",children:i.original.api_base||"-"})})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Start Time:"}),(0,c.jsx)("span",{children:i.original.startTime})]})]}),(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Tokens:"}),(0,c.jsxs)("span",{children:[i.original.total_tokens," (",i.original.prompt_tokens,"+",i.original.completion_tokens,")"]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cost:"}),(0,c.jsxs)("span",{children:["$",Number(i.original.spend||0).toFixed(6)]})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Cache Hit:"}),(0,c.jsx)("span",{children:i.original.cache_hit})]}),(null==i?void 0:null===(t=i.original)||void 0===t?void 0:t.requester_ip_address)&&(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"IP Address:"}),(0,c.jsx)("span",{children:null==i?void 0:null===(a=i.original)||void 0===a?void 0:a.requester_ip_address})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"Status:"}),(0,c.jsx)("span",{className:"px-2 py-1 rounded-md text-xs font-medium inline-block text-center w-16 ".concat("failure"!==((null===(r=i.original.metadata)||void 0===r?void 0:r.status)||"Success").toLowerCase()?"bg-green-100 text-green-800":"bg-red-100 text-red-800"),children:"failure"!==((null===(n=i.original.metadata)||void 0===n?void 0:n.status)||"Success").toLowerCase()?"Success":"Failure"})]}),(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)("span",{className:"font-medium w-1/3",children:"End Time:"}),(0,c.jsx)("span",{children:i.original.endTime})]})]})]})]}),(0,c.jsx)(tc,{show:!x&&!p}),(0,c.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request"}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(m(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy request",disabled:!x,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(m(),null,2)})})]}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsxs)("h3",{className:"text-lg font-medium",children:["Response",u&&(0,c.jsxs)("span",{className:"ml-2 text-sm text-red-600",children:["• HTTP code ",(null==h?void 0:h.error_code)||400]})]}),(0,c.jsx)("button",{onClick:()=>navigator.clipboard.writeText(JSON.stringify(g(),null,2)),className:"p-1 hover:bg-gray-200 rounded",title:"Copy response",disabled:!p,children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-96 bg-gray-50",children:p?(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(g(),null,2)}):(0,c.jsx)("div",{className:"text-gray-500 text-sm italic text-center py-4",children:"Response data not available"})})]})]}),u&&h&&(0,c.jsx)(to,{errorInfo:h}),i.original.request_tags&&Object.keys(i.original.request_tags).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"flex justify-between items-center p-4 border-b",children:(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Request Tags"})}),(0,c.jsx)("div",{className:"p-4",children:(0,c.jsx)("div",{className:"flex flex-wrap gap-2",children:Object.entries(i.original.request_tags).map(e=>{let[s,l]=e;return(0,c.jsxs)("span",{className:"px-2 py-1 bg-gray-100 rounded-full text-xs",children:[s,": ",String(l)]},s)})})})]}),i.original.metadata&&Object.keys(i.original.metadata).length>0&&(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,c.jsx)("h3",{className:"text-lg font-medium",children:"Metadata"}),(0,c.jsx)("button",{onClick:()=>{let e=o(i.original.metadata);navigator.clipboard.writeText(JSON.stringify(e,null,2))},className:"p-1 hover:bg-gray-200 rounded",title:"Copy metadata",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),(0,c.jsx)("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]}),(0,c.jsx)("div",{className:"p-4 overflow-auto max-h-64",children:(0,c.jsx)("pre",{className:"text-xs font-mono whitespace-pre-wrap break-all",children:JSON.stringify(o(i.original.metadata),null,2)})})]})]})}var tu=l(92699),th=l(14042);console.log=function(){};var tx=e=>{let{userID:s,userRole:l,accessToken:t,userSpend:a,userMaxBudget:r,selectedTeam:n}=e;console.log("userSpend: ".concat(a));let[i,o]=(0,d.useState)(null!==a?a:0),[m,u]=(0,d.useState)(n?n.max_budget:null);(0,d.useEffect)(()=>{if(n){if("Default Team"===n.team_alias)u(r);else{let e=!1;if(n.team_memberships)for(let l of n.team_memberships)l.user_id===s&&"max_budget"in l.litellm_budget_table&&null!==l.litellm_budget_table.max_budget&&(u(l.litellm_budget_table.max_budget),e=!0);e||u(n.max_budget)}}},[n,r]);let[h,x]=(0,d.useState)([]);(0,d.useEffect)(()=>{let e=async()=>{if(!t||!s||!l)return};(async()=>{try{if(null===s||null===l)return;if(null!==t){let e=(await (0,y.So)(t,s,l)).data.map(e=>e.id);console.log("available_model_names:",e),x(e)}}catch(e){console.error("Error fetching user models:",e)}})(),e()},[l,t,s]),(0,d.useEffect)(()=>{null!==a&&o(a)},[a]);let p=[];n&&n.models&&(p=n.models),p&&p.includes("all-proxy-models")?(console.log("user models:",h),p=h):p&&p.includes("all-team-models")?p=n.models:p&&0===p.length&&(p=h);let g=void 0!==i?i.toFixed(4):null;return console.log("spend in view user spend: ".concat(i)),(0,c.jsx)("div",{className:"flex items-center",children:(0,c.jsxs)("div",{className:"flex justify-between gap-x-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Total Spend"}),(0,c.jsxs)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:["$",g]})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)("p",{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content",children:"Max Budget"}),(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:null!==m?"$".concat(m," limit"):"No limit"})]})]})})};let tp=e=>{let{key:s,info:l}=e;return{token:s,...l}};var tg=e=>{let{topKeys:s,accessToken:l,userID:t,userRole:a,teams:r}=e,[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(void 0),[x,p]=(0,d.useState)("table"),g=async e=>{if(l)try{let s=await (0,y.t0)(l,e.api_key),t=tp(s);h(t),m(e.api_key),i(!0)}catch(e){console.error("Error fetching key info:",e)}},j=()=>{i(!1),m(null),h(void 0)};return d.useEffect(()=>{let e=e=>{"Escape"===e.key&&n&&j()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[n]),(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("div",{className:"mb-4 flex justify-end items-center",children:(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)("button",{onClick:()=>p("table"),className:"px-3 py-1 text-sm rounded-md ".concat("table"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Table View"}),(0,c.jsx)("button",{onClick:()=>p("chart"),className:"px-3 py-1 text-sm rounded-md ".concat("chart"===x?"bg-blue-100 text-blue-700":"bg-gray-100 text-gray-700"),children:"Chart View"})]})}),"chart"===x?(0,c.jsx)("div",{className:"relative",children:(0,c.jsx)(sw.Z,{className:"mt-4 h-40 cursor-pointer hover:opacity-90",data:s,index:"key_alias",categories:["spend"],colors:["cyan"],yAxisWidth:80,tickGap:5,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>e?"$".concat(e.toFixed(2)):"No Key Alias",onValueChange:e=>g(e),showTooltip:!0,customTooltip:e=>{var s,l,t;let a=null===(l=e.payload)||void 0===l?void 0:null===(s=l[0])||void 0===s?void 0:s.payload;return(0,c.jsx)("div",{className:"p-3 bg-black/90 shadow-lg rounded-lg text-white",children:(0,c.jsxs)("div",{className:"space-y-1.5",children:[(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Key: "}),(0,c.jsxs)("span",{className:"font-mono text-gray-100",children:[null==a?void 0:null===(t=a.api_key)||void 0===t?void 0:t.slice(0,10),"..."]})]}),(0,c.jsxs)("div",{className:"text-sm",children:[(0,c.jsx)("span",{className:"text-gray-300",children:"Spend: "}),(0,c.jsxs)("span",{className:"text-white font-medium",children:["$",null==a?void 0:a.spend.toFixed(2)]})]})]})})}})}):(0,c.jsx)("div",{className:"border rounded-lg overflow-hidden",children:(0,c.jsx)(eL,{columns:[{header:"Key ID",accessorKey:"api_key",cell:e=>(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:e.getValue(),children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>g(e.row.original),children:e.getValue()?"".concat(e.getValue().slice(0,7),"..."):"-"})})})},{header:"Key Alias",accessorKey:"key_alias",cell:e=>e.getValue()||"-"},{header:"Spend (USD)",accessorKey:"spend",cell:e=>"$".concat(Number(e.getValue()).toFixed(2))}],data:s,renderSubComponent:()=>(0,c.jsx)(c.Fragment,{}),getRowCanExpand:()=>!1,isLoading:!1})}),n&&o&&u&&(console.log("Rendering modal with:",{isModalOpen:n,selectedKey:o,keyData:u}),(0,c.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",onClick:e=>{e.target===e.currentTarget&&j()},children:(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-xl relative w-11/12 max-w-6xl max-h-[90vh] overflow-y-auto min-h-[750px]",children:[(0,c.jsx)("button",{onClick:j,className:"absolute top-4 right-4 text-gray-500 hover:text-gray-700 focus:outline-none","aria-label":"Close",children:(0,c.jsx)("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"2",d:"M6 18L18 6M6 6l12 12"})})}),(0,c.jsx)("div",{className:"p-6 h-full",children:(0,c.jsx)(eG,{keyId:o,onClose:j,keyData:u,accessToken:l,userID:t,userRole:a,teams:r})})]})}))]})},tj=l(44851);let tf=e=>{var s,l;let{modelName:t,metrics:a}=e;return(0,c.jsxs)("div",{className:"space-y-2",children:[(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:a.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:a.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:a.total_tokens.toLocaleString()}),(0,c.jsxs)(A.Z,{children:[Math.round(a.total_tokens/a.total_successful_requests)," avg per successful request"]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",a.total_spend.toFixed(2)]}),(0,c.jsxs)(A.Z,{children:["$",(a.total_spend/a.total_successful_requests).toFixed(3)," per successful request"]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Requests per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.api_requests"],colors:["blue"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend per day"}),(0,c.jsx)(sw.Z,{data:a.daily_data,index:"date",categories:["metrics.spend"],colors:["green"],valueFormatter:e=>"$".concat(e.toFixed(2))})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Success vs Failed Requests"}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Prompt Caching Metrics"}),(0,c.jsxs)("div",{className:"mb-2",children:[(0,c.jsxs)(A.Z,{children:["Cache Read: ",(null===(s=a.total_cache_read_input_tokens)||void 0===s?void 0:s.toLocaleString())||0," tokens"]}),(0,c.jsxs)(A.Z,{children:["Cache Creation: ",(null===(l=a.total_cache_creation_input_tokens)||void 0===l?void 0:l.toLocaleString())||0," tokens"]})]}),(0,c.jsx)(sN.Z,{data:a.daily_data,index:"date",categories:["metrics.cache_read_input_tokens","metrics.cache_creation_input_tokens"],colors:["cyan","purple"],valueFormatter:e=>e.toLocaleString()})]})]})]})},t_=e=>{let{modelMetrics:s}=e,l=Object.keys(s).sort((e,l)=>""===e?1:""===l?-1:s[l].total_spend-s[e].total_spend),t={total_requests:0,total_successful_requests:0,total_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:{}};Object.values(s).forEach(e=>{t.total_requests+=e.total_requests,t.total_successful_requests+=e.total_successful_requests,t.total_tokens+=e.total_tokens,t.total_spend+=e.total_spend,t.total_cache_read_input_tokens+=e.total_cache_read_input_tokens||0,t.total_cache_creation_input_tokens+=e.total_cache_creation_input_tokens||0,e.daily_data.forEach(e=>{t.daily_data[e.date]||(t.daily_data[e.date]={prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,spend:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0}),t.daily_data[e.date].prompt_tokens+=e.metrics.prompt_tokens,t.daily_data[e.date].completion_tokens+=e.metrics.completion_tokens,t.daily_data[e.date].total_tokens+=e.metrics.total_tokens,t.daily_data[e.date].api_requests+=e.metrics.api_requests,t.daily_data[e.date].spend+=e.metrics.spend,t.daily_data[e.date].successful_requests+=e.metrics.successful_requests,t.daily_data[e.date].failed_requests+=e.metrics.failed_requests,t.daily_data[e.date].cache_read_input_tokens+=e.metrics.cache_read_input_tokens||0,t.daily_data[e.date].cache_creation_input_tokens+=e.metrics.cache_creation_input_tokens||0})});let a=Object.entries(t.daily_data).map(e=>{let[s,l]=e;return{date:s,metrics:l}}).sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime());return(0,c.jsxs)("div",{className:"space-y-8",children:[(0,c.jsxs)("div",{className:"border rounded-lg p-4",children:[(0,c.jsx)(E.Z,{children:"Overall Usage"}),(0,c.jsxs)(w.Z,{numItems:4,className:"gap-4 mb-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Requests"}),(0,c.jsx)(E.Z,{children:t.total_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Successful Requests"}),(0,c.jsx)(E.Z,{children:t.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Tokens"}),(0,c.jsx)(E.Z,{children:t.total_tokens.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(A.Z,{children:"Total Spend"}),(0,c.jsxs)(E.Z,{children:["$",t.total_spend.toFixed(2)]})]})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.prompt_tokens","metrics.completion_tokens","metrics.total_tokens"],colors:["blue","cyan","indigo"],valueFormatter:e=>e.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests Over Time"}),(0,c.jsx)(sN.Z,{data:a,index:"date",categories:["metrics.successful_requests","metrics.failed_requests"],colors:["emerald","red"],valueFormatter:e=>e.toLocaleString(),stack:!0})]})]})]}),(0,c.jsx)(tj.Z,{defaultActiveKey:l[0],children:l.map(e=>(0,c.jsx)(tj.Z.Panel,{header:(0,c.jsxs)("div",{className:"flex justify-between items-center w-full",children:[(0,c.jsx)(E.Z,{children:s[e].label||"Unknown Item"}),(0,c.jsxs)("div",{className:"flex space-x-4 text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["$",s[e].total_spend.toFixed(2)]}),(0,c.jsxs)("span",{children:[s[e].total_requests.toLocaleString()," requests"]})]})]}),children:(0,c.jsx)(tf,{modelName:e||"Unknown Model",metrics:s[e]})},e))})]})},ty=(e,s)=>{let l=e.metadata.key_alias||"key-hash-".concat(s),t=e.metadata.team_id;return t?"".concat(l," (team_id: ").concat(t,")"):l},tv=(e,s)=>{let l={};return e.results.forEach(e=>{Object.entries(e.breakdown[s]||{}).forEach(t=>{let[a,r]=t;l[a]||(l[a]={label:"api_keys"===s?ty(r,a):a,total_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0,prompt_tokens:0,completion_tokens:0,total_spend:0,total_cache_read_input_tokens:0,total_cache_creation_input_tokens:0,daily_data:[]}),l[a].total_requests+=r.metrics.api_requests,l[a].prompt_tokens+=r.metrics.prompt_tokens,l[a].completion_tokens+=r.metrics.completion_tokens,l[a].total_tokens+=r.metrics.total_tokens,l[a].total_spend+=r.metrics.spend,l[a].total_successful_requests+=r.metrics.successful_requests,l[a].total_failed_requests+=r.metrics.failed_requests,l[a].total_cache_read_input_tokens+=r.metrics.cache_read_input_tokens||0,l[a].total_cache_creation_input_tokens+=r.metrics.cache_creation_input_tokens||0,l[a].daily_data.push({date:e.date,metrics:{prompt_tokens:r.metrics.prompt_tokens,completion_tokens:r.metrics.completion_tokens,total_tokens:r.metrics.total_tokens,api_requests:r.metrics.api_requests,spend:r.metrics.spend,successful_requests:r.metrics.successful_requests,failed_requests:r.metrics.failed_requests,cache_read_input_tokens:r.metrics.cache_read_input_tokens||0,cache_creation_input_tokens:r.metrics.cache_creation_input_tokens||0}})})}),Object.values(l).forEach(e=>{e.daily_data.sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime())}),l};var tb=e=>{let{accessToken:s,entityType:l,entityId:t,userID:a,userRole:r,entityList:n}=e,[i,o]=(0,d.useState)({results:[],metadata:{total_spend:0,total_api_requests:0,total_successful_requests:0,total_failed_requests:0,total_tokens:0}}),m=tv(i,"models"),u=tv(i,"api_keys"),[h,x]=(0,d.useState)([]),[p,g]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),j=async()=>{if(!s||!p.from||!p.to)return;let e=p.from,t=p.to;if("tag"===l)o(await (0,y.Z9)(s,e,t,1,h.length>0?h:null));else if("team"===l)o(await (0,y.ol)(s,e,t,1,h.length>0?h:null));else throw Error("Invalid entity type")};(0,d.useEffect)(()=>{j()},[s,p,t,h]);let f=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={provider:l,spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend,e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens}catch(e){console.log("Error processing provider ".concat(l,": ").concat(e))}})}),Object.values(e).filter(e=>e.spend>0).sort((e,s)=>s.spend-e.spend)},_=e=>0===h.length?e:e.filter(e=>h.includes(e.metadata.id)),v=()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.entities||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{alias:t.metadata.team_alias||l,id:l}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.total_tokens+=t.metrics.total_tokens})}),_(Object.values(e).sort((e,s)=>s.metrics.spend-e.metrics.spend))};return(0,c.jsxs)("div",{style:{width:"100%"},children:[(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:p,onValueChange:g})]}),n&&n.length>0&&(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(A.Z,{children:["Filter by ","tag"===l?"Tags":"Teams"]}),(0,c.jsx)(O.default,{mode:"multiple",style:{width:"100%"},placeholder:"Select ".concat("tag"===l?"tags":"teams"," to filter..."),value:h,onChange:x,options:(()=>{if(n)return n})(),className:"mt-2",allowClear:!0})]})]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(E.Z,{children:["tag"===l?"Tag":"Team"," Spend Overview"]}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Spend"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",i.metadata.total_spend.toFixed(2)]})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_api_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:i.metadata.total_successful_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:i.metadata.total_failed_requests.toLocaleString()})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:i.metadata.total_tokens.toLocaleString()})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...i.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:t}=e;if(!t||!(null==s?void 0:s[0]))return null;let a=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:a.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Total Spend: $",a.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",a.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",a.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",a.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Tokens: ",a.metrics.total_tokens]}),(0,c.jsxs)("div",{className:"mt-2 border-t pt-2",children:[(0,c.jsxs)("p",{className:"font-semibold",children:["Spend by ","tag"===l?"Tag":"Team",":"]}),Object.entries(a.breakdown.entities||{}).map(e=>{let[s,l]=e;return(0,c.jsxs)("p",{className:"text-sm text-gray-600",children:[l.metadata.team_alias||s,": $",l.metrics.spend.toFixed(2)]},s)})]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsxs)("div",{className:"flex flex-col space-y-2",children:[(0,c.jsxs)(E.Z,{children:["Spend Per ","tag"===l?"Tag":"Team"]}),(0,c.jsxs)("div",{className:"flex items-center text-sm text-gray-500",children:[(0,c.jsxs)("span",{children:["Get Started Tracking cost per ",l," "]}),(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tags",className:"text-blue-500 hover:text-blue-700 ml-1",children:"here"})]})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sw.Z,{className:"mt-4 h-52",data:v(),index:"metadata.alias",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(4)),layout:"vertical",showLegend:!1,yAxisWidth:100})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"tag"===l?"Tag":"Team"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:v().filter(e=>e.metrics.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.metadata.alias}),(0,c.jsxs)(eA.Z,{children:["$",e.metrics.spend.toFixed(4)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.metrics.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.metrics.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.metrics.total_tokens.toLocaleString()})]},e.metadata.id))})]})})]})]})})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:s,userID:a,userRole:r,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return i.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={spend:0,requests:0,successful_requests:0,failed_requests:0,tokens:0});try{e[l].spend+=t.metrics.spend}catch(e){console.log("Error adding spend for ".concat(l,": ").concat(e,", got metrics: ").concat(JSON.stringify(t)))}e[l].requests+=t.metrics.api_requests,e[l].successful_requests+=t.metrics.successful_requests,e[l].failed_requests+=t.metrics.failed_requests,e[l].tokens+=t.metrics.total_tokens})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,...l}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsx)(eF.Z,{children:(0,c.jsxs)("div",{className:"flex flex-col space-y-4",children:[(0,c.jsx)(E.Z,{children:"Provider Usage"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:f(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan","blue","indigo","violet","purple"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:f().map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:m})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:u})})]})]})]})},tZ=e=>{var s,l,t,a,r,n,i,o,m,u;let{accessToken:h,userRole:x,userID:p,teams:g}=e,[j,f]=(0,d.useState)({results:[],metadata:{}}),[_,v]=(0,d.useState)({from:new Date(Date.now()-24192e5),to:new Date}),[b,Z]=(0,d.useState)([]),k=async()=>{h&&Z(Object.values(await (0,y.UM)(h)).map(e=>({label:e.name,value:e.name})))};(0,d.useEffect)(()=>{k()},[h]);let S=(null===(s=j.metadata)||void 0===s?void 0:s.total_spend)||0,C=()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.providers||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{provider:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}})},I=async()=>{if(!h||!_.from||!_.to)return;let e=_.from,s=_.to;try{let l=await (0,y.xX)(h,e,s);if(l.metadata.total_pages>10)throw Error("Too many pages of data (>10). Please select a smaller date range.");if(1===l.metadata.total_pages){f(l);return}let t=[...l.results];for(let a=2;a<=l.metadata.total_pages;a++){let l=await (0,y.xX)(h,e,s,a);t.push(...l.results)}f({results:t,metadata:l.metadata})}catch(e){throw console.error("Error fetching user spend data:",e),e}};(0,d.useEffect)(()=>{I()},[h,_]);let T=tv(j,"models"),P=tv(j,"api_keys");return(0,c.jsxs)("div",{style:{width:"100%"},className:"p-8",children:[(0,c.jsxs)(A.Z,{className:"text-sm text-gray-500 mb-4",children:["This is the new usage dashboard. ",(0,c.jsx)("br",{})," You may see empty data, as these use ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/blob/6de348125208dd4be81ff0e5813753df2fbe9735/schema.prisma#L320",className:"text-blue-500 hover:text-blue-700 ml-1",children:"new aggregate tables"})," to allow UI to work at 1M+ spend logs. To access the old dashboard, go to Experimental ",">"," Old Usage."]}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Global Usage"}):(0,c.jsx)(eR.Z,{children:"Your Usage"}),(0,c.jsx)(eR.Z,{children:"Team Usage"}),eg.ZL.includes(x||"")?(0,c.jsx)(eR.Z,{children:"Tag Usage"}):(0,c.jsx)(c.Fragment,{})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsxs)(ez.Z,{children:[(0,c.jsx)(w.Z,{numItems:2,className:"gap-2 w-full mb-4",children:(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:_,onValueChange:e=>{v(e)}})]})}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Model Activity"}),(0,c.jsx)(eR.Z,{children:"Key Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:p,userRole:x,accessToken:h,userSpend:S,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Usage Metrics"}),(0,c.jsxs)(w.Z,{numItems:5,className:"gap-4 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(t=j.metadata)||void 0===t?void 0:null===(l=t.total_api_requests)||void 0===l?void 0:l.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Successful Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-green-600",children:(null===(r=j.metadata)||void 0===r?void 0:null===(a=r.total_successful_requests)||void 0===a?void 0:a.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Failed Requests"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2 text-red-600",children:(null===(i=j.metadata)||void 0===i?void 0:null===(n=i.total_failed_requests)||void 0===n?void 0:n.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Total Tokens"}),(0,c.jsx)(A.Z,{className:"text-2xl font-bold mt-2",children:(null===(m=j.metadata)||void 0===m?void 0:null===(o=m.total_tokens)||void 0===o?void 0:o.toLocaleString())||0})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Average Cost per Request"}),(0,c.jsxs)(A.Z,{className:"text-2xl font-bold mt-2",children:["$",((S||0)/((null===(u=j.metadata)||void 0===u?void 0:u.total_api_requests)||1)).toFixed(4)]})]})]})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend"}),(0,c.jsx)(sw.Z,{data:[...j.results].sort((e,s)=>new Date(e.date).getTime()-new Date(s.date).getTime()),index:"date",categories:["metrics.spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),yAxisWidth:100,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.date}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.metrics.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Requests: ",t.metrics.api_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Successful: ",t.metrics.successful_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Failed: ",t.metrics.failed_requests]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.metrics.total_tokens]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.api_keys||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{key_alias:t.metadata.key_alias}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests,e[l].metrics.failed_requests+=t.metrics.failed_requests,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{api_key:s,key_alias:l.metadata.key_alias||"-",spend:l.metrics.spend}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),accessToken:h,userID:p,userRole:x,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Top Models"})}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:(()=>{let e={};return j.results.forEach(s=>{Object.entries(s.breakdown.models||{}).forEach(s=>{let[l,t]=s;e[l]||(e[l]={metrics:{spend:0,prompt_tokens:0,completion_tokens:0,total_tokens:0,api_requests:0,successful_requests:0,failed_requests:0,cache_read_input_tokens:0,cache_creation_input_tokens:0},metadata:{}}),e[l].metrics.spend+=t.metrics.spend,e[l].metrics.prompt_tokens+=t.metrics.prompt_tokens,e[l].metrics.completion_tokens+=t.metrics.completion_tokens,e[l].metrics.total_tokens+=t.metrics.total_tokens,e[l].metrics.api_requests+=t.metrics.api_requests,e[l].metrics.successful_requests+=t.metrics.successful_requests||0,e[l].metrics.failed_requests+=t.metrics.failed_requests||0,e[l].metrics.cache_read_input_tokens+=t.metrics.cache_read_input_tokens||0,e[l].metrics.cache_creation_input_tokens+=t.metrics.cache_creation_input_tokens||0})}),Object.entries(e).map(e=>{let[s,l]=e;return{key:s,spend:l.metrics.spend,requests:l.metrics.api_requests,successful_requests:l.metrics.successful_requests,failed_requests:l.metrics.failed_requests,tokens:l.metrics.total_tokens}}).sort((e,s)=>s.spend-e.spend).slice(0,5)})(),index:"key",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2)),layout:"vertical",yAxisWidth:200,showLegend:!1,customTooltip:e=>{let{payload:s,active:l}=e;if(!l||!(null==s?void 0:s[0]))return null;let t=s[0].payload;return(0,c.jsxs)("div",{className:"bg-white p-4 shadow-lg rounded-lg border",children:[(0,c.jsx)("p",{className:"font-bold",children:t.key}),(0,c.jsxs)("p",{className:"text-cyan-500",children:["Spend: $",t.spend.toFixed(2)]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Total Requests: ",t.requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-green-600",children:["Successful: ",t.successful_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-red-600",children:["Failed: ",t.failed_requests.toLocaleString()]}),(0,c.jsxs)("p",{className:"text-gray-600",children:["Tokens: ",t.tokens.toLocaleString()]})]})}})]})}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)("div",{className:"flex justify-between items-center mb-4",children:(0,c.jsx)(E.Z,{children:"Spend by Provider"})}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",data:C(),index:"provider",category:"spend",valueFormatter:e=>"$".concat(e.toFixed(2)),colors:["cyan"]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{className:"text-green-600",children:"Successful"}),(0,c.jsx)(eP.Z,{className:"text-red-600",children:"Failed"}),(0,c.jsx)(eP.Z,{children:"Tokens"})]})}),(0,c.jsx)(eT.Z,{children:C().filter(e=>e.spend>0).map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsxs)(eA.Z,{children:["$",e.spend<1e-5?"less than 0.00001":e.spend.toFixed(2)]}),(0,c.jsx)(eA.Z,{className:"text-green-600",children:e.successful_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{className:"text-red-600",children:e.failed_requests.toLocaleString()}),(0,c.jsx)(eA.Z,{children:e.tokens.toLocaleString()})]},e.provider))})]})})]})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:T})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(t_,{modelMetrics:P})})]})]})]}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"team",userID:p,userRole:x,entityList:(null==g?void 0:g.map(e=>({label:e.team_alias,value:e.team_id})))||null})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(tb,{accessToken:h,entityType:"tag",userID:p,userRole:x,entityList:b})})]})]})]})},tN=e=>{let{proxySettings:s}=e,l="";return s&&s.PROXY_BASE_URL&&void 0!==s.PROXY_BASE_URL&&(l=s.PROXY_BASE_URL),(0,c.jsx)(c.Fragment,{children:(0,c.jsx)(w.Z,{className:"gap-2 p-8 h-[80vh] w-full mt-2",children:(0,c.jsxs)("div",{className:"mb-5",children:[(0,c.jsx)("p",{className:"text-2xl text-tremor-content-strong dark:text-dark-tremor-content-strong font-semibold",children:"OpenAI Compatible Proxy: API Reference"}),(0,c.jsx)(A.Z,{className:"mt-2 mb-2",children:"LiteLLM is OpenAI Compatible. This means your API Key works with the OpenAI SDK. Just replace the base_url to point to your litellm proxy. Example Below "}),(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{children:[(0,c.jsx)(eR.Z,{children:"OpenAI Python SDK"}),(0,c.jsx)(eR.Z,{children:"LlamaIndex"}),(0,c.jsx)(eR.Z,{children:"Langchain Py"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport openai\nclient = openai.OpenAI(\n api_key="your_api_key",\n base_url="'.concat(l,'" # LiteLLM Proxy is OpenAI compatible, Read More: https://docs.litellm.ai/docs/proxy/user_keys\n)\n\nresponse = client.chat.completions.create(\n model="gpt-3.5-turbo", # model to send to the proxy\n messages = [\n {\n "role": "user",\n "content": "this is a test request, write a short poem"\n }\n ]\n)\n\nprint(response)\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nimport os, dotenv\n\nfrom llama_index.llms import AzureOpenAI\nfrom llama_index.embeddings import AzureOpenAIEmbedding\nfrom llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext\n\nllm = AzureOpenAI(\n engine="azure-gpt-3.5", # model_name on litellm proxy\n temperature=0.0,\n azure_endpoint="'.concat(l,'", # litellm proxy endpoint\n api_key="sk-1234", # litellm proxy API Key\n api_version="2023-07-01-preview",\n)\n\nembed_model = AzureOpenAIEmbedding(\n deployment_name="azure-embedding-model",\n azure_endpoint="').concat(l,'",\n api_key="sk-1234",\n api_version="2023-07-01-preview",\n)\n\n\ndocuments = SimpleDirectoryReader("llama_index_data").load_data()\nservice_context = ServiceContext.from_defaults(llm=llm, embed_model=embed_model)\nindex = VectorStoreIndex.from_documents(documents, service_context=service_context)\n\nquery_engine = index.as_query_engine()\nresponse = query_engine.query("What did the author do growing up?")\nprint(response)\n\n ')})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(l8.Z,{language:"python",children:'\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.prompts.chat import (\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n SystemMessagePromptTemplate,\n)\nfrom langchain.schema import HumanMessage, SystemMessage\n\nchat = ChatOpenAI(\n openai_api_base="'.concat(l,'",\n model = "gpt-3.5-turbo",\n temperature=0.1\n)\n\nmessages = [\n SystemMessage(\n content="You are a helpful assistant that im using to make a test request to."\n ),\n HumanMessage(\n content="test from litellm. tell me why it\'s amazing in 1 sentence"\n ),\n]\nresponse = chat(messages)\n\nprint(response)\n\n ')})})]})]})]})})})},tw=l(243);async function tk(e,s,l,t,a,r,n,i,o){console.log=function(){},console.log("isLocal:",!1);let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t;let a=Date.now(),c=!1;for await(let _ of(await d.chat.completions.create({model:l,stream:!0,stream_options:{include_usage:!0},messages:e},{signal:r}))){var m,u,h,x,p,g,j,f;console.log("Stream chunk:",_);let e=null===(m=_.choices[0])||void 0===m?void 0:m.delta;if(console.log("Delta content:",null===(h=_.choices[0])||void 0===h?void 0:null===(u=h.delta)||void 0===u?void 0:u.content),console.log("Delta reasoning content:",null==e?void 0:e.reasoning_content),!c&&((null===(p=_.choices[0])||void 0===p?void 0:null===(x=p.delta)||void 0===x?void 0:x.content)||e&&e.reasoning_content)&&(c=!0,t=Date.now()-a,console.log("First token received! Time:",t,"ms"),i?(console.log("Calling onTimingData with:",t),i(t)):console.log("onTimingData callback is not defined!")),null===(j=_.choices[0])||void 0===j?void 0:null===(g=j.delta)||void 0===g?void 0:g.content){let e=_.choices[0].delta.content;s(e,_.model)}if(e&&e.reasoning_content){let s=e.reasoning_content;n&&n(s)}if(_.usage&&o){console.log("Usage data found:",_.usage);let e={completionTokens:_.usage.completion_tokens,promptTokens:_.usage.prompt_tokens,totalTokens:_.usage.total_tokens};(null===(f=_.usage.completion_tokens_details)||void 0===f?void 0:f.reasoning_tokens)&&(e.reasoningTokens=_.usage.completion_tokens_details.reasoning_tokens),o(e)}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Chat completion request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}async function tS(e,s,l,t,a,r){console.log=function(){},console.log("isLocal:",!1);let n=window.location.origin,i=new lG.ZP.OpenAI({apiKey:t,baseURL:n,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=await i.images.generate({model:l,prompt:e},{signal:r});if(console.log(t.data),t.data&&t.data[0]){if(t.data[0].url)s(t.data[0].url,l);else if(t.data[0].b64_json){let e=t.data[0].b64_json;s("data:image/png;base64,".concat(e),l)}else throw Error("No image data found in response")}else throw Error("Invalid response format")}catch(e){throw(null==r?void 0:r.aborted)?console.log("Image generation request was cancelled"):D.ZP.error("Error occurred while generating image. Please try again. Error: ".concat(e),20),e}}async function tC(e,s,l,t){let a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:[],r=arguments.length>5?arguments[5]:void 0,n=arguments.length>6?arguments[6]:void 0,i=arguments.length>7?arguments[7]:void 0,o=arguments.length>8?arguments[8]:void 0;if(!t)throw Error("API key is required");console.log=function(){};let c=window.location.origin,d=new lG.ZP.OpenAI({apiKey:t,baseURL:c,dangerouslyAllowBrowser:!0,defaultHeaders:a&&a.length>0?{"x-litellm-tags":a.join(",")}:void 0});try{let t=Date.now(),a=!1,c=e.map(e=>({role:e.role,content:e.content,type:"message"}));for await(let e of(await d.responses.create({model:l,input:c,stream:!0},{signal:r})))if(console.log("Response event:",e),"object"==typeof e&&null!==e){if("response.role.delta"===e.type)continue;if("response.output_text.delta"===e.type&&"string"==typeof e.delta){let r=e.delta;if(console.log("Text delta",r),r.trim().length>0&&(s("assistant",r,l),!a)){a=!0;let e=Date.now()-t;console.log("First token received! Time:",e,"ms"),i&&i(e)}}if("response.reasoning.delta"===e.type&&"delta"in e){let s=e.delta;"string"==typeof s&&n&&n(s)}if("response.completed"===e.type&&"response"in e){let s=e.response.usage;if(console.log("Usage data:",s),s&&o){var m;console.log("Usage data:",s);let e={completionTokens:s.output_tokens,promptTokens:s.input_tokens,totalTokens:s.total_tokens};(null===(m=s.completion_tokens_details)||void 0===m?void 0:m.reasoning_tokens)&&(e.reasoningTokens=s.completion_tokens_details.reasoning_tokens),o(e)}}}}catch(e){throw(null==r?void 0:r.aborted)?console.log("Responses API request was cancelled"):D.ZP.error("Error occurred while generating model response. Please try again. Error: ".concat(e),20),e}}let tI=async e=>{try{let s=await (0,y.kn)(e);if(console.log("model_info:",s),(null==s?void 0:s.data.length)>0){let e=s.data.map(e=>({model_group:e.model_group,mode:null==e?void 0:e.mode}));return e.sort((e,s)=>e.model_group.localeCompare(s.model_group)),e}return[]}catch(e){throw console.error("Error fetching model info:",e),e}};(a=i||(i={})).IMAGE_GENERATION="image_generation",a.CHAT="chat",a.RESPONSES="responses",(r=o||(o={})).IMAGE="image",r.CHAT="chat",r.RESPONSES="responses";let tT={image_generation:"image",chat:"chat",responses:"responses"},tA=e=>{if(console.log("getEndpointType:",e),Object.values(i).includes(e)){let s=tT[e];return console.log("endpointType:",s),s}return"chat"};var tE=l(94263),tP=e=>{let{endpointType:s,onEndpointChange:l,className:t}=e,a=[{value:o.CHAT,label:"/v1/chat/completions"},{value:o.RESPONSES,label:"/v1/responses"},{value:o.IMAGE,label:"/v1/images/generations"}];return(0,c.jsxs)("div",{className:t,children:[(0,c.jsx)(A.Z,{children:"Endpoint Type:"}),(0,c.jsx)(O.default,{value:s,style:{width:"100%"},onChange:l,options:a,className:"rounded-md"})]})},tO=e=>{let{onChange:s,value:l,className:t,accessToken:a}=e,[r,n]=(0,d.useState)([]),[i,o]=(0,d.useState)(!1);return(0,d.useEffect)(()=>{(async()=>{if(a)try{let e=await (0,y.UM)(a);console.log("List tags response:",e),n(Object.values(e))}catch(e){console.error("Error fetching tags:",e)}})()},[]),(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select tags",onChange:s,value:l,loading:i,className:t,options:r.map(e=>({label:e.name,value:e.name,title:e.description||e.name})),optionFilterProp:"label",showSearch:!0,style:{width:"100%"}})};let tL=(e,s)=>{let l=s.find(s=>s.model_group===e);return(null==l?void 0:l.mode)?tA(l.mode):o.CHAT};var tD=l(83322),tM=l(70464),tF=l(77565),tR=e=>{let{reasoningContent:s}=e,[l,t]=(0,d.useState)(!0);return s?(0,c.jsxs)("div",{className:"reasoning-content mt-1 mb-2",children:[(0,c.jsxs)(R.ZP,{type:"text",className:"flex items-center text-xs text-gray-500 hover:text-gray-700",onClick:()=>t(!l),icon:(0,c.jsx)(tD.Z,{}),children:[l?"Hide reasoning":"Show reasoning",l?(0,c.jsx)(tM.Z,{className:"ml-1"}):(0,c.jsx)(tF.Z,{className:"ml-1"})]}),l&&(0,c.jsx)("div",{className:"mt-2 p-3 bg-gray-50 border border-gray-200 rounded-md text-sm text-gray-700",children:(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),...r,children:a})}},children:s})})]}):null},tq=l(5540),tU=l(71282),tz=l(11741),tV=l(16601),tK=e=>{let{timeToFirstToken:s,usage:l}=e;return s||l?(0,c.jsxs)("div",{className:"response-metrics mt-2 pt-2 border-t border-gray-100 text-xs text-gray-500 flex flex-wrap gap-3",children:[void 0!==s&&(0,c.jsx)(W.Z,{title:"Time to first token",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tq.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:[(s/1e3).toFixed(2),"s"]})]})}),(null==l?void 0:l.promptTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Prompt tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tU.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["In: ",l.promptTokens]})]})}),(null==l?void 0:l.completionTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Completion tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tz.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Out: ",l.completionTokens]})]})}),(null==l?void 0:l.reasoningTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Reasoning tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tD.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Reasoning: ",l.reasoningTokens]})]})}),(null==l?void 0:l.totalTokens)!==void 0&&(0,c.jsx)(W.Z,{title:"Total tokens",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tV.Z,{className:"mr-1"}),(0,c.jsxs)("span",{children:["Total: ",l.totalTokens]})]})})]}):null},tB=l(61935),tH=l(69993),tJ=l(12660),tW=l(71891),tG=l(26430),tY=l(26349),t$=l(23907);let{TextArea:tX}=q.default;var tQ=e=>{let{accessToken:s,token:l,userRole:t,userID:a,disabledPersonalKeyCreation:r}=e,[n,i]=(0,d.useState)(r?"custom":"session"),[m,u]=(0,d.useState)(""),[h,x]=(0,d.useState)(""),[p,g]=(0,d.useState)([]),[f,_]=(0,d.useState)(void 0),[y,v]=(0,d.useState)(!1),[b,Z]=(0,d.useState)([]),N=(0,d.useRef)(null),[w,C]=(0,d.useState)(o.CHAT),[I,T]=(0,d.useState)(!1),E=(0,d.useRef)(null),[P,L]=(0,d.useState)([]),M=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e="session"===n?s:m;if(!e||!l||!t||!a){console.log("userApiKey or token or userRole or userID is missing = ",e,l,t,a);return}(async()=>{try{if(!e){console.log("userApiKey is missing");return}let s=await tI(e);if(console.log("Fetched models:",s),s.length>0&&(Z(s),_(s[0].model_group),s[0].mode)){let e=tL(s[0].model_group,s);C(e)}}catch(e){console.error("Error fetching model info:",e)}})()},[s,a,t,n,m]),(0,d.useEffect)(()=>{M.current&&setTimeout(()=>{var e;null===(e=M.current)||void 0===e||e.scrollIntoView({behavior:"smooth",block:"end"})},100)},[p]);let F=(e,s,l)=>{console.log("updateTextUI called with:",e,s,l),g(t=>{let a=t[t.length-1];if(!a||a.role!==e||a.isImage)return[...t,{role:e,content:s,model:l}];{var r;let e={...a,content:a.content+s,model:null!==(r=a.model)&&void 0!==r?r:l};return[...t.slice(0,-1),e]}})},R=e=>{g(s=>{let l=s[s.length-1];return l&&"assistant"===l.role&&!l.isImage?[...s.slice(0,s.length-1),{...l,reasoningContent:(l.reasoningContent||"")+e}]:s.length>0&&"user"===s[s.length-1].role?[...s,{role:"assistant",content:"",reasoningContent:e}]:s})},q=e=>{console.log("updateTimingData called with:",e),g(s=>{let l=s[s.length-1];if(console.log("Current last message:",l),l&&"assistant"===l.role){console.log("Updating assistant message with timeToFirstToken:",e);let t=[...s.slice(0,s.length-1),{...l,timeToFirstToken:e}];return console.log("Updated chat history:",t),t}return l&&"user"===l.role?(console.log("Creating new assistant message with timeToFirstToken:",e),[...s,{role:"assistant",content:"",timeToFirstToken:e}]):(console.log("No appropriate message found to update timing"),s)})},U=e=>{console.log("Received usage data:",e),g(s=>{let l=s[s.length-1];if(l&&"assistant"===l.role){console.log("Updating message with usage data:",e);let t={...l,usage:e};return console.log("Updated message:",t),[...s.slice(0,s.length-1),t]}return s})},z=(e,s)=>{g(l=>[...l,{role:"assistant",content:e,model:s,isImage:!0}])},V=async()=>{if(""===h.trim()||!l||!t||!a)return;let e="session"===n?s:m;if(!e){D.ZP.error("Please provide an API key or select Current UI Session");return}E.current=new AbortController;let r=E.current.signal,i={role:"user",content:h};g([...p,i]),T(!0);try{if(f){if(w===o.CHAT){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tk(s,(e,s)=>F("assistant",e,s),f,e,P,r,R,q,U)}else if(w===o.IMAGE)await tS(h,(e,s)=>z(e,s),f,e,P,r);else if(w===o.RESPONSES){let s=[...p.filter(e=>!e.isImage).map(e=>{let{role:s,content:l}=e;return{role:s,content:l}}),i];await tC(s,(e,s,l)=>F(e,s,l),f,e,P,r,R,q,U)}}}catch(e){r.aborted?console.log("Request was cancelled"):(console.error("Error fetching response",e),F("assistant","Error fetching response"))}finally{T(!1),E.current=null}x("")};if(t&&"Admin Viewer"===t){let{Title:e,Paragraph:s}=es.default;return(0,c.jsxs)("div",{children:[(0,c.jsx)(e,{level:1,children:"Access Denied"}),(0,c.jsx)(s,{children:"Ask your proxy admin for access to test models"})]})}let K=(0,c.jsx)(tB.Z,{style:{fontSize:24},spin:!0});return(0,c.jsx)("div",{className:"w-full h-screen p-4 bg-white",children:(0,c.jsx)(eF.Z,{className:"w-full rounded-xl shadow-md overflow-hidden",children:(0,c.jsxs)("div",{className:"flex h-[80vh] w-full",children:[(0,c.jsx)("div",{className:"w-1/4 p-4 border-r border-gray-200 bg-gray-50",children:(0,c.jsx)("div",{className:"mb-6",children:(0,c.jsxs)("div",{className:"space-y-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(lE.Z,{className:"mr-2"})," API Key Source"]}),(0,c.jsx)(O.default,{disabled:r,defaultValue:"session",style:{width:"100%"},onChange:e=>i(e),options:[{value:"session",label:"Current UI Session"},{value:"custom",label:"Virtual Key"}],className:"rounded-md"}),"custom"===n&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom API key",type:"password",onValueChange:u,value:m,icon:lE.Z})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tH.Z,{className:"mr-2"})," Select Model"]}),(0,c.jsx)(O.default,{placeholder:"Select a Model",onChange:e=>{console.log("selected ".concat(e)),_(e),"custom"!==e&&C(tL(e,b)),v("custom"===e)},options:[...b.map(e=>({value:e.model_group,label:e.model_group})),{value:"custom",label:"Enter custom model"}],style:{width:"100%"},showSearch:!0,className:"rounded-md"}),y&&(0,c.jsx)(S.Z,{className:"mt-2",placeholder:"Enter custom model name",onValueChange:e=>{N.current&&clearTimeout(N.current),N.current=setTimeout(()=>{_(e)},500)}})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tJ.Z,{className:"mr-2"})," Endpoint Type"]}),(0,c.jsx)(tP,{endpointType:w,onEndpointChange:e=>{C(e)},className:"mb-4"})]}),(0,c.jsxs)("div",{children:[(0,c.jsxs)(A.Z,{className:"font-medium block mb-2 text-gray-700 flex items-center",children:[(0,c.jsx)(tW.Z,{className:"mr-2"})," Tags"]}),(0,c.jsx)(tO,{value:P,onChange:L,className:"mb-4",accessToken:s||""})]}),(0,c.jsx)(k.Z,{onClick:()=>{g([]),D.ZP.success("Chat history cleared.")},className:"w-full bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300 mt-4",icon:tG.Z,children:"Clear Chat"})]})})}),(0,c.jsxs)("div",{className:"w-3/4 flex flex-col bg-white",children:[(0,c.jsxs)("div",{className:"flex-1 overflow-auto p-4 pb-0",children:[0===p.length&&(0,c.jsxs)("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[(0,c.jsx)(tH.Z,{style:{fontSize:"48px",marginBottom:"16px"}}),(0,c.jsx)(A.Z,{children:"Start a conversation or generate an image"})]}),p.map((e,s)=>(0,c.jsx)("div",{className:"mb-4 ".concat("user"===e.role?"text-right":"text-left"),children:(0,c.jsxs)("div",{className:"inline-block max-w-[80%] rounded-lg shadow-sm p-3.5 px-4",style:{backgroundColor:"user"===e.role?"#f0f8ff":"#ffffff",border:"user"===e.role?"1px solid #e6f0fa":"1px solid #f0f0f0",textAlign:"left"},children:[(0,c.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,c.jsx)("div",{className:"flex items-center justify-center w-6 h-6 rounded-full mr-1",style:{backgroundColor:"user"===e.role?"#e6f0fa":"#f5f5f5"},children:"user"===e.role?(0,c.jsx)(j.Z,{style:{fontSize:"12px",color:"#2563eb"}}):(0,c.jsx)(tH.Z,{style:{fontSize:"12px",color:"#4b5563"}})}),(0,c.jsx)("strong",{className:"text-sm capitalize",children:e.role}),"assistant"===e.role&&e.model&&(0,c.jsx)("span",{className:"text-xs px-2 py-0.5 rounded bg-gray-100 text-gray-600 font-normal",children:e.model})]}),e.reasoningContent&&(0,c.jsx)(tR,{reasoningContent:e.reasoningContent}),(0,c.jsxs)("div",{className:"whitespace-pre-wrap break-words max-w-full message-content",style:{wordWrap:"break-word",overflowWrap:"break-word",wordBreak:"break-word",hyphens:"auto"},children:[e.isImage?(0,c.jsx)("img",{src:e.content,alt:"Generated image",className:"max-w-full rounded-md border border-gray-200 shadow-sm",style:{maxHeight:"500px"}}):(0,c.jsx)(tw.U,{components:{code(e){let{node:s,inline:l,className:t,children:a,...r}=e,n=/language-(\w+)/.exec(t||"");return!l&&n?(0,c.jsx)(l8.Z,{style:tE.Z,language:n[1],PreTag:"div",className:"rounded-md my-2",wrapLines:!0,wrapLongLines:!0,...r,children:String(a).replace(/\n$/,"")}):(0,c.jsx)("code",{className:"".concat(t," px-1.5 py-0.5 rounded bg-gray-100 text-sm font-mono"),style:{wordBreak:"break-word"},...r,children:a})},pre:e=>{let{node:s,...l}=e;return(0,c.jsx)("pre",{style:{overflowX:"auto",maxWidth:"100%"},...l})}},children:e.content}),"assistant"===e.role&&(e.timeToFirstToken||e.usage)&&(0,c.jsx)(tK,{timeToFirstToken:e.timeToFirstToken,usage:e.usage})]})]})},s)),I&&(0,c.jsx)("div",{className:"flex justify-center items-center my-4",children:(0,c.jsx)(eY.Z,{indicator:K})}),(0,c.jsx)("div",{ref:M,style:{height:"1px"}})]}),(0,c.jsx)("div",{className:"p-4 border-t border-gray-200 bg-white",children:(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)(tX,{value:h,onChange:e=>x(e.target.value),onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),V())},placeholder:w===o.CHAT||w===o.RESPONSES?"Type your message... (Shift+Enter for new line)":"Describe the image you want to generate...",disabled:I,className:"flex-1",autoSize:{minRows:1,maxRows:6},style:{resize:"none",paddingRight:"10px",paddingLeft:"10px"}}),I?(0,c.jsx)(k.Z,{onClick:()=>{E.current&&(E.current.abort(),E.current=null,T(!1),D.ZP.info("Request cancelled"))},className:"ml-2 bg-red-50 hover:bg-red-100 text-red-600 border-red-200",icon:tY.Z,children:"Cancel"}):(0,c.jsx)(k.Z,{onClick:V,className:"ml-2 text-white",icon:w===o.CHAT?t$.Z:tH.Z,children:w===o.CHAT?"Send":"Generate"})]})})]})]})})})},t0=l(19226),t1=l(45937),t2=l(28595),t4=l(68208),t5=l(9775),t6=l(41361),t3=l(37527),t8=l(88009),t7=l(48231),t9=l(41169),ae=l(44625),as=l(57400),al=l(58630),at=l(55322);let{Sider:aa}=t0.default;var ar=e=>{let{setPage:s,userRole:l,defaultSelectedKey:t}=e,a=[{key:"1",page:"api-keys",label:"Virtual Keys",icon:(0,c.jsx)(lE.Z,{})},{key:"3",page:"llm-playground",label:"Test Key",icon:(0,c.jsx)(t2.Z,{}),roles:eg.LQ},{key:"2",page:"models",label:"Models",icon:(0,c.jsx)(t4.Z,{}),roles:eg.LQ},{key:"12",page:"new_usage",label:"Usage",icon:(0,c.jsx)(t5.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"6",page:"teams",label:"Teams",icon:(0,c.jsx)(t6.Z,{})},{key:"17",page:"organizations",label:"Organizations",icon:(0,c.jsx)(t3.Z,{}),roles:eg.ZL},{key:"5",page:"users",label:"Internal Users",icon:(0,c.jsx)(j.Z,{}),roles:eg.ZL},{key:"14",page:"api_ref",label:"API Reference",icon:(0,c.jsx)(tJ.Z,{})},{key:"16",page:"model-hub",label:"Model Hub",icon:(0,c.jsx)(t8.Z,{})},{key:"15",page:"logs",label:"Logs",icon:(0,c.jsx)(t7.Z,{})},{key:"experimental",page:"experimental",label:"Experimental",icon:(0,c.jsx)(t9.Z,{}),children:[{key:"9",page:"caching",label:"Caching",icon:(0,c.jsx)(ae.Z,{}),roles:eg.ZL},{key:"10",page:"budgets",label:"Budgets",icon:(0,c.jsx)(t3.Z,{}),roles:eg.ZL},{key:"11",page:"guardrails",label:"Guardrails",icon:(0,c.jsx)(as.Z,{}),roles:eg.ZL},{key:"4",page:"usage",label:"Old Usage",icon:(0,c.jsx)(t5.Z,{})},{key:"20",page:"transform-request",label:"API Playground",icon:(0,c.jsx)(tJ.Z,{}),roles:[...eg.ZL,...eg.lo]},{key:"18",page:"mcp-tools",label:"MCP Tools",icon:(0,c.jsx)(al.Z,{}),roles:eg.ZL},{key:"19",page:"tag-management",label:"Tag Management",icon:(0,c.jsx)(tW.Z,{}),roles:eg.ZL}]},{key:"settings",page:"settings",label:"Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL,children:[{key:"11",page:"general-settings",label:"Router Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"12",page:"pass-through-settings",label:"Pass-Through",icon:(0,c.jsx)(tJ.Z,{}),roles:eg.ZL},{key:"8",page:"settings",label:"Logging & Alerts",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL},{key:"13",page:"admin-panel",label:"Admin Settings",icon:(0,c.jsx)(at.Z,{}),roles:eg.ZL}]}],r=(e=>{let s=a.find(s=>s.page===e);if(s)return s.key;for(let s of a)if(s.children){let l=s.children.find(s=>s.page===e);if(l)return l.key}return"1"})(t),n=a.filter(e=>!!(!e.roles||e.roles.includes(l))&&(e.children&&(e.children=e.children.filter(e=>!e.roles||e.roles.includes(l))),!0));return(0,c.jsx)(t0.default,{style:{minHeight:"100vh"},children:(0,c.jsx)(aa,{theme:"light",width:220,children:(0,c.jsx)(t1.Z,{mode:"inline",selectedKeys:[r],style:{borderRight:0,backgroundColor:"transparent",fontSize:"14px"},items:n.map(e=>{var l;return{key:e.key,icon:e.icon,label:e.label,children:null===(l=e.children)||void 0===l?void 0:l.map(e=>({key:e.key,icon:e.icon,label:e.label,onClick:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}})),onClick:e.children?void 0:()=>{let l=new URLSearchParams(window.location.search);l.set("page",e.page),window.history.pushState(null,"","?".concat(l.toString())),s(e.page)}}})})})})},an=l(96889);console.log("process.env.NODE_ENV","production"),console.log=function(){};let ai=e=>null!==e&&("Admin"===e||"Admin Viewer"===e);var ao=e=>{let{accessToken:s,token:l,userRole:t,userID:a,keys:r,premiumUser:n}=e,i=new Date,[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)([]),[f,_]=(0,d.useState)([]),[v,b]=(0,d.useState)([]),[Z,S]=(0,d.useState)([]),[C,I]=(0,d.useState)([]),[T,P]=(0,d.useState)([]),[O,L]=(0,d.useState)([]),[D,M]=(0,d.useState)({}),[F,R]=(0,d.useState)([]),[q,U]=(0,d.useState)(""),[z,V]=(0,d.useState)(["all-tags"]),[K,B]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[H,J]=(0,d.useState)(null),[W,G]=(0,d.useState)(0),Y=new Date(i.getFullYear(),i.getMonth(),1),$=new Date(i.getFullYear(),i.getMonth()+1,0),X=er(Y),Q=er($);function es(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}console.log("keys in usage",r),console.log("premium user in usage",n);let el=async()=>{if(s)try{let e=await (0,y.g)(s);return console.log("usage tab: proxy_settings",e),e}catch(e){console.error("Error fetching proxy settings:",e)}};(0,d.useEffect)(()=>{ea(K.from,K.to)},[K,z]);let et=async(e,l,t)=>{if(!e||!l||!s)return;l.setHours(23,59,59,999),e.setHours(0,0,0,0),console.log("uiSelectedKey",t);let a=await (0,y.b1)(s,t,e.toISOString(),l.toISOString());console.log("End user data updated successfully",a),j(a)},ea=async(e,l)=>{if(!e||!l||!s)return;let t=await el();null!=t&&t.DISABLE_EXPENSIVE_DB_QUERIES||(l.setHours(23,59,59,999),e.setHours(0,0,0,0),b((await (0,y.J$)(s,e.toISOString(),l.toISOString(),0===z.length?void 0:z)).spend_per_tag),console.log("Tag spend data updated successfully"))};function er(e){let s=e.getFullYear(),l=e.getMonth()+1,t=e.getDate();return"".concat(s,"-").concat(l<10?"0"+l:l,"-").concat(t<10?"0"+t:t)}console.log("Start date is ".concat(X)),console.log("End date is ".concat(Q));let en=async(e,s,l)=>{try{let l=await e();s(l)}catch(e){console.error(l,e)}},ei=(e,s,l,t)=>{let a=[],r=new Date(s),n=e=>{if(e.includes("-"))return e;{let[s,l]=e.split(" ");return new Date(new Date().getFullYear(),new Date("".concat(s," 01 2024")).getMonth(),parseInt(l)).toISOString().split("T")[0]}},i=new Map(e.map(e=>{let s=n(e.date);return[s,{...e,date:s}]}));for(;r<=l;){let e=r.toISOString().split("T")[0];if(i.has(e))a.push(i.get(e));else{let s={date:e,api_requests:0,total_tokens:0};t.forEach(e=>{s[e]||(s[e]=0)}),a.push(s)}r.setDate(r.getDate()+1)}return a},eo=async()=>{if(s)try{let e=await (0,y.FC)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e,t,a,[]),n=Number(r.reduce((e,s)=>e+(s.spend||0),0).toFixed(2));G(n),m(r)}catch(e){console.error("Error fetching overall spend:",e)}},ec=()=>en(()=>s&&l?(0,y.OU)(s,l,X,Q):Promise.reject("No access token or token"),L,"Error fetching provider spend"),ed=async()=>{s&&await en(async()=>(await (0,y.tN)(s)).map(e=>({key:e.api_key.substring(0,10),api_key:e.api_key,key_alias:e.key_alias,spend:Number(e.total_spend.toFixed(2))})),h,"Error fetching top keys")},em=async()=>{s&&await en(async()=>(await (0,y.Au)(s)).map(e=>({key:e.model,spend:Number(e.total_spend.toFixed(2))})),p,"Error fetching top models")},eu=async()=>{s&&await en(async()=>{let e=await (0,y.mR)(s),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0);return _(ei(e.daily_spend,t,a,e.teams)),I(e.teams),e.total_spend_per_team.map(e=>({name:e.team_id||"",value:Number(e.total_spend||0).toFixed(2)}))},P,"Error fetching team spend")},eh=()=>{s&&en(async()=>(await (0,y.X)(s)).tag_names,S,"Error fetching tag names")},ex=()=>{s&&en(()=>{var e,l;return(0,y.J$)(s,null===(e=K.from)||void 0===e?void 0:e.toISOString(),null===(l=K.to)||void 0===l?void 0:l.toISOString(),void 0)},e=>b(e.spend_per_tag),"Error fetching top tags")},ep=()=>{s&&en(()=>(0,y.b1)(s,null,void 0,void 0),j,"Error fetching top end users")},eg=async()=>{if(s)try{let e=await (0,y.wd)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=ei(e.daily_data||[],t,a,["api_requests","total_tokens"]);M({...e,daily_data:r})}catch(e){console.error("Error fetching global activity:",e)}},ej=async()=>{if(s)try{let e=await (0,y.xA)(s,X,Q),l=new Date,t=new Date(l.getFullYear(),l.getMonth(),1),a=new Date(l.getFullYear(),l.getMonth()+1,0),r=e.map(e=>({...e,daily_data:ei(e.daily_data||[],t,a,["api_requests","total_tokens"])}));R(r)}catch(e){console.error("Error fetching global activity per model:",e)}};return((0,d.useEffect)(()=>{(async()=>{if(s&&l&&t&&a){let e=await el();e&&(J(e),null!=e&&e.DISABLE_EXPENSIVE_DB_QUERIES)||(console.log("fetching data - valiue of proxySettings",H),eo(),ec(),ed(),em(),eg(),ej(),ai(t)&&(eu(),eh(),ex(),ep()))}})()},[s,l,t,a,X,Q]),null==H?void 0:H.DISABLE_EXPENSIVE_DB_QUERIES)?(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Database Query Limit Reached"}),(0,c.jsxs)(A.Z,{className:"mt-4",children:["SpendLogs in DB has ",H.NUM_SPEND_LOGS_ROWS," rows.",(0,c.jsx)("br",{}),"Please follow our guide to view usage when SpendLogs has more than 1M rows."]}),(0,c.jsx)(k.Z,{className:"mt-4",children:(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/spending_monitoring",target:"_blank",children:"View Usage Guide"})})]})}):(0,c.jsx)("div",{style:{width:"100%"},className:"p-8",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"mt-2",children:[(0,c.jsx)(eR.Z,{children:"All Up"}),ai(t)?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(eR.Z,{children:"Team Based Usage"}),(0,c.jsx)(eR.Z,{children:"Customer Usage"}),(0,c.jsx)(eR.Z,{children:"Tag Based Usage"})]}):(0,c.jsx)(c.Fragment,{children:(0,c.jsx)("div",{})})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{variant:"solid",className:"mt-1",children:[(0,c.jsx)(eR.Z,{children:"Cost"}),(0,c.jsx)(eR.Z,{children:"Activity"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[100vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(A.Z,{className:"text-tremor-default text-tremor-content dark:text-dark-tremor-content mb-2 mt-2 text-lg",children:["Project Spend ",new Date().toLocaleString("default",{month:"long"})," 1 - ",new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate()]}),(0,c.jsx)(tx,{userID:a,userRole:t,accessToken:s,userSpend:W,selectedTeam:null,userMaxBudget:null})]}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Monthly Spend"}),(0,c.jsx)(sw.Z,{data:o,index:"date",categories:["spend"],colors:["cyan"],valueFormatter:e=>"$ ".concat(e.toFixed(2)),yAxisWidth:100,tickGap:5})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top API Keys"}),(0,c.jsx)(tg,{topKeys:u,accessToken:s,userID:a,userRole:t,teams:null})]})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eF.Z,{className:"h-full",children:[(0,c.jsx)(E.Z,{children:"Top Models"}),(0,c.jsx)(sw.Z,{className:"mt-4 h-40",data:x,index:"key",categories:["spend"],colors:["cyan"],yAxisWidth:200,layout:"vertical",showXAxis:!1,showLegend:!1,valueFormatter:e=>"$".concat(e.toFixed(2))})]})}),(0,c.jsx)(N.Z,{numColSpan:1}),(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Spend by Provider"}),(0,c.jsx)(c.Fragment,{children:(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(th.Z,{className:"mt-4 h-40",variant:"pie",data:O,index:"provider",category:"spend",colors:["cyan"],valueFormatter:e=>"$".concat(e.toFixed(2))})}),(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Provider"}),(0,c.jsx)(eP.Z,{children:"Spend"})]})}),(0,c.jsx)(eT.Z,{children:O.map(e=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.provider}),(0,c.jsx)(eA.Z,{children:1e-5>parseFloat(e.spend.toFixed(2))?"less than 0.00":e.spend.toFixed(2)})]},e.provider))})]})})]})})]})})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:1,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"All Up"}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(D.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["api_requests"],onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(D.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:D.daily_data,valueFormatter:es,index:"date",colors:["cyan"],categories:["total_tokens"],onValueChange:e=>console.log(e)})]})]})]}),(0,c.jsx)(c.Fragment,{children:F.map((e,s)=>(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:e.model}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["API Requests ",es(e.sum_api_requests)]}),(0,c.jsx)(sN.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["api_requests"],valueFormatter:es,onValueChange:e=>console.log(e)})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsxs)(sl.Z,{style:{fontSize:"15px",fontWeight:"normal",color:"#535452"},children:["Tokens ",es(e.sum_total_tokens)]}),(0,c.jsx)(sw.Z,{className:"h-40",data:e.daily_data,index:"date",colors:["cyan"],categories:["total_tokens"],valueFormatter:es,onValueChange:e=>console.log(e)})]})]})]},s))})]})})]})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full",children:[(0,c.jsxs)(N.Z,{numColSpan:2,children:[(0,c.jsxs)(eF.Z,{className:"mb-2",children:[(0,c.jsx)(E.Z,{children:"Total Spend Per Team"}),(0,c.jsx)(an.Z,{data:T})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Daily Spend Per Team"}),(0,c.jsx)(sw.Z,{className:"h-72",data:f,showLegend:!0,index:"date",categories:C,yAxisWidth:80,stack:!0})]})]}),(0,c.jsx)(N.Z,{numColSpan:2})]})}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)("p",{className:"mb-2 text-gray-500 italic text-[12px]",children:["Customers of your LLM API calls. Tracked when a `user` param is passed in your LLM calls ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/users",target:"_blank",children:"docs here"})]}),(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Time Range"}),(0,c.jsx)(sb.Z,{enableSelect:!0,value:K,onValueChange:e=>{B(e),et(e.from,e.to,null)}})]}),(0,c.jsxs)(N.Z,{children:[(0,c.jsx)(A.Z,{children:"Select Key"}),(0,c.jsxs)(eD.Z,{defaultValue:"all-keys",children:[(0,c.jsx)(ee.Z,{value:"all-keys",onClick:()=>{et(K.from,K.to,null)},children:"All Keys"},"all-keys"),null==r?void 0:r.map((e,s)=>e&&null!==e.key_alias&&e.key_alias.length>0?(0,c.jsx)(ee.Z,{value:String(s),onClick:()=>{et(K.from,K.to,e.token)},children:e.key_alias},s):null)]})]})]}),(0,c.jsx)(eF.Z,{className:"mt-4",children:(0,c.jsxs)(eI.Z,{className:"max-h-[70vh] min-h-[500px]",children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Customer"}),(0,c.jsx)(eP.Z,{children:"Spend"}),(0,c.jsx)(eP.Z,{children:"Total Events"})]})}),(0,c.jsx)(eT.Z,{children:null==g?void 0:g.map((e,s)=>{var l;return(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.end_user}),(0,c.jsx)(eA.Z,{children:null===(l=e.total_spend)||void 0===l?void 0:l.toFixed(4)}),(0,c.jsx)(eA.Z,{children:e.total_count})]},s)})})]})})]}),(0,c.jsxs)(ez.Z,{children:[(0,c.jsxs)(w.Z,{numItems:2,children:[(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(sb.Z,{className:"mb-4",enableSelect:!0,value:K,onValueChange:e=>{B(e),ea(e.from,e.to)}})}),(0,c.jsx)(N.Z,{children:n?(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsx)(lH.Z,{value:String(e),children:e},e))]})}):(0,c.jsx)("div",{children:(0,c.jsxs)(lB.Z,{value:z,onValueChange:e=>V(e),children:[(0,c.jsx)(lH.Z,{value:"all-tags",onClick:()=>V(["all-tags"]),children:"All Tags"},"all-tags"),Z&&Z.filter(e=>"all-tags"!==e).map((e,s)=>(0,c.jsxs)(ee.Z,{value:String(e),disabled:!0,children:["✨ ",e," (Enterprise only Feature)"]},e))]})})})]}),(0,c.jsxs)(w.Z,{numItems:2,className:"gap-2 h-[75vh] w-full mb-4",children:[(0,c.jsx)(N.Z,{numColSpan:2,children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Spend Per Tag"}),(0,c.jsxs)(A.Z,{children:["Get Started Tracking cost per tag ",(0,c.jsx)("a",{className:"text-blue-500",href:"https://docs.litellm.ai/docs/proxy/cost_tracking",target:"_blank",children:"here"})]}),(0,c.jsx)(sw.Z,{className:"h-72",data:v,index:"name",categories:["spend"],colors:["cyan"]})]})}),(0,c.jsx)(N.Z,{numColSpan:2})]})]})]})]})})},ac=l(51853);let ad=e=>{let{responseTimeMs:s}=e;return null==s?null:(0,c.jsxs)("div",{className:"flex items-center space-x-1 text-xs text-gray-500 font-mono",children:[(0,c.jsx)("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:(0,c.jsx)("path",{d:"M12 6V12L16 14M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2Z",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})}),(0,c.jsxs)("span",{children:[s.toFixed(0),"ms"]})]})},am=e=>{let s=e;if("string"==typeof s)try{s=JSON.parse(s)}catch(e){}return s},au=e=>{let{label:s,value:l}=e,[t,a]=d.useState(!1),[r,n]=d.useState(!1),i=(null==l?void 0:l.toString())||"N/A",o=i.length>50?i.substring(0,50)+"...":i;return(0,c.jsx)("tr",{className:"hover:bg-gray-50",children:(0,c.jsx)("td",{className:"px-4 py-2 align-top",colSpan:2,children:(0,c.jsxs)("div",{className:"flex items-center justify-between group",children:[(0,c.jsxs)("div",{className:"flex items-center flex-1",children:[(0,c.jsx)("button",{onClick:()=>a(!t),className:"text-gray-400 hover:text-gray-600 mr-2",children:t?"▼":"▶"}),(0,c.jsxs)("div",{children:[(0,c.jsx)("div",{className:"text-sm text-gray-600",children:s}),(0,c.jsx)("pre",{className:"mt-1 text-sm font-mono text-gray-800 whitespace-pre-wrap",children:t?i:o})]})]}),(0,c.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(i),n(!0),setTimeout(()=>n(!1),2e3)},className:"opacity-0 group-hover:opacity-100 text-gray-400 hover:text-gray-600",children:(0,c.jsx)(ac.Z,{className:"h-4 w-4"})})]})})})},ah=e=>{var s,l,t,a,r,n,i,o,d,m,u,h,x,p;let{response:g}=e,j=null,f={},_={};try{if(null==g?void 0:g.error)try{let e="string"==typeof g.error.message?JSON.parse(g.error.message):g.error.message;j={message:(null==e?void 0:e.message)||"Unknown error",traceback:(null==e?void 0:e.traceback)||"No traceback available",litellm_params:(null==e?void 0:e.litellm_cache_params)||{},health_check_cache_params:(null==e?void 0:e.health_check_cache_params)||{}},f=am(j.litellm_params)||{},_=am(j.health_check_cache_params)||{}}catch(e){console.warn("Error parsing error details:",e),j={message:String(g.error.message||"Unknown error"),traceback:"Error parsing details",litellm_params:{},health_check_cache_params:{}}}else f=am(null==g?void 0:g.litellm_cache_params)||{},_=am(null==g?void 0:g.health_check_cache_params)||{}}catch(e){console.warn("Error in response parsing:",e),f={},_={}}let y={redis_host:(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host)||(null==_?void 0:null===(i=_.connection_kwargs)||void 0===i?void 0:i.host)||(null==_?void 0:_.host)||"N/A",redis_port:(null==_?void 0:null===(m=_.redis_client)||void 0===m?void 0:null===(d=m.connection_pool)||void 0===d?void 0:null===(o=d.connection_kwargs)||void 0===o?void 0:o.port)||(null==_?void 0:null===(x=_.redis_async_client)||void 0===x?void 0:null===(h=x.connection_pool)||void 0===h?void 0:null===(u=h.connection_kwargs)||void 0===u?void 0:u.port)||(null==_?void 0:null===(p=_.connection_kwargs)||void 0===p?void 0:p.port)||(null==_?void 0:_.port)||"N/A",redis_version:(null==_?void 0:_.redis_version)||"N/A",startup_nodes:(()=>{try{var e,s,l,t,a,r,n,i,o,c,d,m,u;if(null==_?void 0:null===(e=_.redis_kwargs)||void 0===e?void 0:e.startup_nodes)return JSON.stringify(_.redis_kwargs.startup_nodes);let h=(null==_?void 0:null===(t=_.redis_client)||void 0===t?void 0:null===(l=t.connection_pool)||void 0===l?void 0:null===(s=l.connection_kwargs)||void 0===s?void 0:s.host)||(null==_?void 0:null===(n=_.redis_async_client)||void 0===n?void 0:null===(r=n.connection_pool)||void 0===r?void 0:null===(a=r.connection_kwargs)||void 0===a?void 0:a.host),x=(null==_?void 0:null===(c=_.redis_client)||void 0===c?void 0:null===(o=c.connection_pool)||void 0===o?void 0:null===(i=o.connection_kwargs)||void 0===i?void 0:i.port)||(null==_?void 0:null===(u=_.redis_async_client)||void 0===u?void 0:null===(m=u.connection_pool)||void 0===m?void 0:null===(d=m.connection_kwargs)||void 0===d?void 0:d.port);return h&&x?JSON.stringify([{host:h,port:x}]):"N/A"}catch(e){return"N/A"}})(),namespace:(null==_?void 0:_.namespace)||"N/A"};return(0,c.jsx)("div",{className:"bg-white rounded-lg shadow",children:(0,c.jsxs)(eq.Z,{children:[(0,c.jsxs)(eU.Z,{className:"border-b border-gray-200 px-4",children:[(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Summary"}),(0,c.jsx)(eR.Z,{className:"px-4 py-2 text-sm font-medium text-gray-600 hover:text-gray-800",children:"Raw Response"})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsxs)("div",{children:[(0,c.jsxs)("div",{className:"flex items-center mb-6",children:[(null==g?void 0:g.status)==="healthy"?(0,c.jsx)(ed.Z,{className:"h-5 w-5 text-green-500 mr-2"}):(0,c.jsx)(ec.Z,{className:"h-5 w-5 text-red-500 mr-2"}),(0,c.jsxs)(A.Z,{className:"text-sm font-medium ".concat((null==g?void 0:g.status)==="healthy"?"text-green-500":"text-red-500"),children:["Cache Status: ",(null==g?void 0:g.status)||"unhealthy"]})]}),(0,c.jsx)("table",{className:"w-full border-collapse",children:(0,c.jsxs)("tbody",{children:[j&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold text-red-600",children:"Error Details"})}),(0,c.jsx)(au,{label:"Error Message",value:j.message}),(0,c.jsx)(au,{label:"Traceback",value:j.traceback})]}),(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Cache Details"})}),(0,c.jsx)(au,{label:"Cache Configuration",value:String(null==f?void 0:f.type)}),(0,c.jsx)(au,{label:"Ping Response",value:String(g.ping_response)}),(0,c.jsx)(au,{label:"Set Cache Response",value:g.set_cache_response||"N/A"}),(0,c.jsx)(au,{label:"litellm_settings.cache_params",value:JSON.stringify(f,null,2)}),(null==f?void 0:f.type)==="redis"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("tr",{children:(0,c.jsx)("td",{colSpan:2,className:"pt-4 pb-2 font-semibold",children:"Redis Details"})}),(0,c.jsx)(au,{label:"Redis Host",value:y.redis_host||"N/A"}),(0,c.jsx)(au,{label:"Redis Port",value:y.redis_port||"N/A"}),(0,c.jsx)(au,{label:"Redis Version",value:y.redis_version||"N/A"}),(0,c.jsx)(au,{label:"Startup Nodes",value:y.startup_nodes||"N/A"}),(0,c.jsx)(au,{label:"Namespace",value:y.namespace||"N/A"})]})]})})]})}),(0,c.jsx)(ez.Z,{className:"p-4",children:(0,c.jsx)("div",{className:"bg-gray-50 rounded-md p-4 font-mono text-sm",children:(0,c.jsx)("pre",{className:"whitespace-pre-wrap break-words overflow-auto max-h-[500px]",children:(()=>{try{let e={...g,litellm_cache_params:f,health_check_cache_params:_},s=JSON.parse(JSON.stringify(e,(e,s)=>{if("string"==typeof s)try{return JSON.parse(s)}catch(e){}return s}));return JSON.stringify(s,null,2)}catch(e){return"Error formatting JSON: "+e.message}})()})})})]})]})})},ax=e=>{let{accessToken:s,healthCheckResponse:l,runCachingHealthCheck:t,responseTimeMs:a}=e,[r,n]=d.useState(null),[i,o]=d.useState(!1),m=async()=>{o(!0);let e=performance.now();await t(),n(performance.now()-e),o(!1)};return(0,c.jsxs)("div",{className:"space-y-4",children:[(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsx)(k.Z,{onClick:m,disabled:i,className:"bg-indigo-600 hover:bg-indigo-700 disabled:bg-indigo-400 text-white text-sm px-4 py-2 rounded-md",children:i?"Running Health Check...":"Run Health Check"}),(0,c.jsx)(ad,{responseTimeMs:r})]}),l&&(0,c.jsx)(ah,{response:l})]})},ap=e=>{if(e)return e.toISOString().split("T")[0]};function ag(e){return new Intl.NumberFormat("en-US",{maximumFractionDigits:0,notation:"compact",compactDisplay:"short"}).format(e)}var aj=e=>{let{accessToken:s,token:l,userRole:t,userID:a,premiumUser:r}=e,[n,i]=(0,d.useState)([]),[o,m]=(0,d.useState)([]),[u,h]=(0,d.useState)([]),[x,p]=(0,d.useState)([]),[g,j]=(0,d.useState)("0"),[f,_]=(0,d.useState)("0"),[v,b]=(0,d.useState)("0"),[Z,k]=(0,d.useState)({from:new Date(Date.now()-6048e5),to:new Date}),[S,C]=(0,d.useState)(""),[I,T]=(0,d.useState)("");(0,d.useEffect)(()=>{s&&Z&&((async()=>{p(await (0,y.zg)(s,ap(Z.from),ap(Z.to)))})(),C(new Date().toLocaleString()))},[s]);let E=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.api_key)&&void 0!==s?s:""}))),P=Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.model)&&void 0!==s?s:""})));Array.from(new Set(x.map(e=>{var s;return null!==(s=null==e?void 0:e.call_type)&&void 0!==s?s:""})));let O=async(e,l)=>{e&&l&&s&&(l.setHours(23,59,59,999),e.setHours(0,0,0,0),p(await (0,y.zg)(s,ap(e),ap(l))))};(0,d.useEffect)(()=>{console.log("DATA IN CACHE DASHBOARD",x);let e=x;o.length>0&&(e=e.filter(e=>o.includes(e.api_key))),u.length>0&&(e=e.filter(e=>u.includes(e.model))),console.log("before processed data in cache dashboard",e);let s=0,l=0,t=0,a=e.reduce((e,a)=>{console.log("Processing item:",a),a.call_type||(console.log("Item has no call_type:",a),a.call_type="Unknown"),s+=(a.total_rows||0)-(a.cache_hit_true_rows||0),l+=a.cache_hit_true_rows||0,t+=a.cached_completion_tokens||0;let r=e.find(e=>e.name===a.call_type);return r?(r["LLM API requests"]+=(a.total_rows||0)-(a.cache_hit_true_rows||0),r["Cache hit"]+=a.cache_hit_true_rows||0,r["Cached Completion Tokens"]+=a.cached_completion_tokens||0,r["Generated Completion Tokens"]+=a.generated_completion_tokens||0):e.push({name:a.call_type,"LLM API requests":(a.total_rows||0)-(a.cache_hit_true_rows||0),"Cache hit":a.cache_hit_true_rows||0,"Cached Completion Tokens":a.cached_completion_tokens||0,"Generated Completion Tokens":a.generated_completion_tokens||0}),e},[]);j(ag(l)),_(ag(t));let r=l+s;r>0?b((l/r*100).toFixed(2)):b("0"),i(a),console.log("PROCESSED DATA IN CACHE DASHBOARD",a)},[o,u,Z,x]);let L=async()=>{try{D.ZP.info("Running cache health check..."),T("");let e=await (0,y.Tj)(null!==s?s:"");console.log("CACHING HEALTH CHECK RESPONSE",e),T(e)}catch(s){let e;if(console.error("Error running health check:",s),s&&s.message)try{let l=JSON.parse(s.message);l.error&&(l=l.error),e=l}catch(l){e={message:s.message}}else e={message:"Unknown error occurred"};T({error:e})}};return(0,c.jsxs)(eq.Z,{className:"gap-2 p-8 h-full w-full mt-2 mb-8",children:[(0,c.jsxs)(eU.Z,{className:"flex justify-between mt-2 w-full items-center",children:[(0,c.jsxs)("div",{className:"flex",children:[(0,c.jsx)(eR.Z,{children:"Cache Analytics"}),(0,c.jsx)(eR.Z,{children:(0,c.jsx)("pre",{children:"Cache Health"})})]}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[S&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",S]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center",onClick:()=>{C(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(eV.Z,{children:[(0,c.jsx)(ez.Z,{children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsxs)(w.Z,{numItems:3,className:"gap-4 mt-4",children:[(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select API Keys",value:o,onValueChange:m,children:E.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(lB.Z,{placeholder:"Select Models",value:u,onValueChange:h,children:P.map(e=>(0,c.jsx)(lH.Z,{value:e,children:e},e))})}),(0,c.jsx)(N.Z,{children:(0,c.jsx)(sb.Z,{enableSelect:!0,value:Z,onValueChange:e=>{k(e),O(e.from,e.to)},selectPlaceholder:"Select date range"})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 mt-4",children:[(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hit Ratio"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsxs)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:[v,"%"]})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cache Hits"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:g})})]}),(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)("p",{className:"text-tremor-default font-medium text-tremor-content dark:text-dark-tremor-content",children:"Cached Tokens"}),(0,c.jsx)("div",{className:"mt-2 flex items-baseline space-x-2.5",children:(0,c.jsx)("p",{className:"text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong",children:f})})]})]}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cache Hits vs API Requests"}),(0,c.jsx)(sw.Z,{title:"Cache Hits vs API Requests",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["LLM API requests","Cache hit"],colors:["sky","teal"],yAxisWidth:48}),(0,c.jsx)(sl.Z,{className:"mt-4",children:"Cached Completion Tokens vs Generated Completion Tokens"}),(0,c.jsx)(sw.Z,{className:"mt-6",data:n,stack:!0,index:"name",valueFormatter:ag,categories:["Generated Completion Tokens","Cached Completion Tokens"],colors:["sky","teal"],yAxisWidth:48})]})}),(0,c.jsx)(ez.Z,{children:(0,c.jsx)(ax,{accessToken:s,healthCheckResponse:I,runCachingHealthCheck:L})})]})]})},af=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)([]);return(0,d.useEffect)(()=>{s&&(async()=>{try{let e=await (0,y.t3)(s);console.log("guardrails: ".concat(JSON.stringify(e))),t(e.guardrails)}catch(e){console.error("Error fetching guardrails:",e)}})()},[s]),(0,c.jsxs)("div",{className:"w-full mx-auto flex-auto overflow-y-auto m-8 p-2",children:[(0,c.jsxs)(A.Z,{className:"mb-4",children:["Configured guardrails and their current status. Setup guardrails in config.yaml."," ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/guardrails/quick_start",target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:text-blue-700 underline",children:"Docs"})]}),(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(eI.Z,{children:[(0,c.jsx)(eE.Z,{children:(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eP.Z,{children:"Guardrail Name"}),(0,c.jsx)(eP.Z,{children:"Mode"}),(0,c.jsx)(eP.Z,{children:"Status"})]})}),(0,c.jsx)(eT.Z,{children:l&&0!==l.length?null==l?void 0:l.map((e,s)=>(0,c.jsxs)(eO.Z,{children:[(0,c.jsx)(eA.Z,{children:e.guardrail_name}),(0,c.jsx)(eA.Z,{children:e.litellm_params.mode}),(0,c.jsx)(eA.Z,{children:(0,c.jsx)("div",{className:"inline-flex rounded-full px-2 py-1 text-xs font-medium\n ".concat(e.litellm_params.default_on?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"),children:e.litellm_params.default_on?"Always On":"Per Request"})})]},s)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:3,className:"mt-4 text-gray-500 text-center py-4",children:"No guardrails configured"})})})]})})]})},a_=e=>{let{accessToken:s}=e,[l,t]=(0,d.useState)('{\n "model": "openai/gpt-4o",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n },\n {\n "role": "user",\n "content": "Explain quantum computing in simple terms"\n }\n ],\n "temperature": 0.7,\n "max_tokens": 500,\n "stream": true\n}'),[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(!1),o=(e,s,l)=>{let t=JSON.stringify(s,null,2).split("\n").map(e=>" ".concat(e)).join("\n"),a=Object.entries(l).map(e=>{let[s,l]=e;return"-H '".concat(s,": ").concat(l,"'")}).join(" \\\n ");return"curl -X POST \\\n ".concat(e," \\\n ").concat(a?"".concat(a," \\\n "):"","-H 'Content-Type: application/json' \\\n -d '{\n").concat(t,"\n }'")},m=async()=>{i(!0);try{let e;try{e=JSON.parse(l)}catch(e){D.ZP.error("Invalid JSON in request body"),i(!1);return}let t={call_type:"completion",request_body:e};if(!s){D.ZP.error("No access token found"),i(!1);return}let a=await (0,y.Yo)(s,t);if(a.raw_request_api_base&&a.raw_request_body){let e=o(a.raw_request_api_base,a.raw_request_body,a.raw_request_headers||{});r(e),D.ZP.success("Request transformed successfully")}else{let e="string"==typeof a?a:JSON.stringify(a);r(e),D.ZP.info("Transformed request received in unexpected format")}}catch(e){console.error("Error transforming request:",e),D.ZP.error("Failed to transform request")}finally{i(!1)}};return(0,c.jsxs)("div",{className:"w-full m-2",style:{overflow:"hidden"},children:[(0,c.jsx)(E.Z,{children:"Playground"}),(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"See how LiteLLM transforms your request for the specified provider."}),(0,c.jsxs)("div",{style:{display:"flex",gap:"16px",width:"100%",minWidth:0,overflow:"hidden"},className:"mt-4",children:[(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"600px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Original Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"The request you would send to LiteLLM /chat/completions endpoint."})]}),(0,c.jsx)("textarea",{style:{flex:"1 1 auto",width:"100%",minHeight:"240px",padding:"16px",border:"1px solid #e8e8e8",borderRadius:"6px",fontFamily:"monospace",fontSize:"14px",resize:"none",marginBottom:"24px",overflow:"auto"},value:l,onChange:e=>t(e.target.value),onKeyDown:e=>{(e.metaKey||e.ctrlKey)&&"Enter"===e.key&&(e.preventDefault(),m())},placeholder:"Press Cmd/Ctrl + Enter to transform"}),(0,c.jsx)("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"auto"},children:(0,c.jsxs)(R.ZP,{type:"primary",style:{backgroundColor:"#000",display:"flex",alignItems:"center",gap:"8px"},onClick:m,loading:n,children:[(0,c.jsx)("span",{children:"Transform"}),(0,c.jsx)("span",{children:"→"})]})})]}),(0,c.jsxs)("div",{style:{flex:"1 1 50%",display:"flex",flexDirection:"column",border:"1px solid #e8e8e8",borderRadius:"8px",padding:"24px",overflow:"hidden",maxHeight:"800px",minWidth:0},children:[(0,c.jsxs)("div",{style:{marginBottom:"24px"},children:[(0,c.jsx)("h2",{style:{fontSize:"24px",fontWeight:"bold",margin:"0 0 4px 0"},children:"Transformed Request"}),(0,c.jsx)("p",{style:{color:"#666",margin:0},children:"How LiteLLM transforms your request for the specified provider."}),(0,c.jsx)("br",{}),(0,c.jsx)("p",{style:{color:"#666",margin:0},className:"text-xs",children:"Note: Sensitive headers are not shown."})]}),(0,c.jsxs)("div",{style:{position:"relative",backgroundColor:"#f5f5f5",borderRadius:"6px",flex:"1 1 auto",display:"flex",flexDirection:"column",overflow:"hidden"},children:[(0,c.jsx)("pre",{style:{padding:"16px",fontFamily:"monospace",fontSize:"14px",margin:0,overflow:"auto",flex:"1 1 auto"},children:a||'curl -X POST \\\n https://api.openai.com/v1/chat/completions \\\n -H \'Authorization: Bearer sk-xxx\' \\\n -H \'Content-Type: application/json\' \\\n -d \'{\n "model": "gpt-4",\n "messages": [\n {\n "role": "system",\n "content": "You are a helpful assistant."\n }\n ],\n "temperature": 0.7\n }\''}),(0,c.jsx)(R.ZP,{type:"text",icon:(0,c.jsx)(s8.Z,{}),style:{position:"absolute",right:"8px",top:"8px"},size:"small",onClick:()=>{navigator.clipboard.writeText(a||""),D.ZP.success("Copied to clipboard")}})]})]})]}),(0,c.jsx)("div",{className:"mt-4 text-right w-full",children:(0,c.jsxs)("p",{className:"text-sm text-gray-500",children:["Found an error? File an issue ",(0,c.jsx)("a",{href:"https://github.com/BerriAI/litellm/issues",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})})]})},ay=l(21770);let av=[{accessorKey:"mcp_info.server_name",header:"Provider",cell:e=>{let{row:s}=e,l=s.original.mcp_info.server_name,t=s.original.mcp_info.logo_url;return(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[t&&(0,c.jsx)("img",{src:t,alt:"".concat(l," logo"),className:"h-5 w-5 object-contain"}),(0,c.jsx)("span",{className:"font-medium",children:l})]})}},{accessorKey:"name",header:"Tool Name",cell:e=>{let{row:s}=e,l=s.getValue("name");return(0,c.jsx)("div",{children:(0,c.jsx)("span",{className:"font-mono text-sm",children:l})})}},{accessorKey:"description",header:"Description",cell:e=>{let{row:s}=e,l=s.getValue("description");return(0,c.jsx)("div",{className:"max-w-md",children:(0,c.jsx)("span",{className:"text-sm text-gray-700",children:l})})}},{id:"actions",header:"Actions",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"flex items-center space-x-2",children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5 text-left overflow-hidden truncate max-w-[200px]",onClick:()=>{"function"==typeof s.original.onToolSelect&&s.original.onToolSelect(l)},children:"Test Tool"})})}}];function ab(e){let{tool:s,onSubmit:l,isLoading:t,result:a,error:r,onClose:n}=e,[i,o]=d.useState({}),m=d.useMemo(()=>"string"==typeof s.inputSchema?{type:"object",properties:{input:{type:"string",description:"Input for this tool"}},required:["input"]}:s.inputSchema,[s.inputSchema]),u=(e,s)=>{o(l=>({...l,[e]:s}))};return(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow-lg border p-6 max-w-4xl w-full",children:[(0,c.jsxs)("div",{className:"flex justify-between items-start mb-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsxs)("h2",{className:"text-xl font-bold",children:["Test Tool: ",(0,c.jsx)("span",{className:"font-mono",children:s.name})]}),(0,c.jsx)("p",{className:"text-gray-600",children:s.description}),(0,c.jsxs)("p",{className:"text-sm text-gray-500 mt-1",children:["Provider: ",s.mcp_info.server_name]})]}),(0,c.jsx)("button",{onClick:n,className:"p-1 rounded-full hover:bg-gray-200",children:(0,c.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,c.jsx)("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),(0,c.jsx)("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),(0,c.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Input Parameters"}),(0,c.jsxs)("form",{onSubmit:e=>{e.preventDefault(),l(i)},children:["string"==typeof s.inputSchema?(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:"This tool uses a dynamic input schema."}),(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Input ",(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),(0,c.jsx)("input",{type:"text",value:i.input||"",onChange:e=>u("input",e.target.value),required:!0,className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"})]})]}):Object.entries(m.properties).map(e=>{var s,l,t;let[a,r]=e;return(0,c.jsxs)("div",{className:"mb-4",children:[(0,c.jsxs)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[a," ",(null===(s=m.required)||void 0===s?void 0:s.includes(a))&&(0,c.jsx)("span",{className:"text-red-500",children:"*"})]}),r.description&&(0,c.jsx)("p",{className:"text-xs text-gray-500 mb-1",children:r.description}),"string"===r.type&&(0,c.jsx)("input",{type:"text",value:i[a]||"",onChange:e=>u(a,e.target.value),required:null===(l=m.required)||void 0===l?void 0:l.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"number"===r.type&&(0,c.jsx)("input",{type:"number",value:i[a]||"",onChange:e=>u(a,parseFloat(e.target.value)),required:null===(t=m.required)||void 0===t?void 0:t.includes(a),className:"w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm"}),"boolean"===r.type&&(0,c.jsxs)("div",{className:"flex items-center",children:[(0,c.jsx)("input",{type:"checkbox",checked:i[a]||!1,onChange:e=>u(a,e.target.checked),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),(0,c.jsx)("span",{className:"ml-2 text-sm text-gray-600",children:"Enable"})]})]},a)}),(0,c.jsx)("div",{className:"mt-6",children:(0,c.jsx)(k.Z,{type:"submit",disabled:t,className:"w-full px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white",children:t?"Calling...":"Call Tool"})})]})]}),(0,c.jsxs)("div",{className:"bg-gray-50 p-4 rounded-lg overflow-auto max-h-[500px]",children:[(0,c.jsx)("h3",{className:"font-medium mb-4",children:"Result"}),t&&(0,c.jsx)("div",{className:"flex justify-center items-center py-8",children:(0,c.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-blue-700"})}),r&&(0,c.jsxs)("div",{className:"bg-red-50 border border-red-200 text-red-800 px-4 py-3 rounded-md",children:[(0,c.jsx)("p",{className:"font-medium",children:"Error"}),(0,c.jsx)("pre",{className:"mt-2 text-xs overflow-auto whitespace-pre-wrap",children:r.message})]}),a&&!t&&!r&&(0,c.jsxs)("div",{children:[a.map((e,s)=>(0,c.jsxs)("div",{className:"mb-4",children:["text"===e.type&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("p",{className:"whitespace-pre-wrap text-sm",children:e.text})}),"image"===e.type&&e.url&&(0,c.jsx)("div",{className:"bg-white border p-3 rounded-md",children:(0,c.jsx)("img",{src:e.url,alt:"Tool result",className:"max-w-full h-auto rounded"})}),"embedded_resource"===e.type&&(0,c.jsxs)("div",{className:"bg-white border p-3 rounded-md",children:[(0,c.jsx)("p",{className:"text-sm font-medium",children:"Embedded Resource"}),(0,c.jsxs)("p",{className:"text-xs text-gray-500",children:["Type: ",e.resource_type]}),e.url&&(0,c.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-blue-600 hover:underline",children:"View Resource"})]})]},s)),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsxs)("details",{className:"text-xs",children:[(0,c.jsx)("summary",{className:"cursor-pointer text-gray-500 hover:text-gray-700",children:"Raw JSON Response"}),(0,c.jsx)("pre",{className:"mt-2 bg-gray-100 p-2 rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(a,null,2)})]})})]}),!a&&!t&&!r&&(0,c.jsx)("div",{className:"text-center py-8 text-gray-500",children:(0,c.jsx)("p",{children:"The result will appear here after you call the tool."})})]})]})]})}function aZ(e){let{columns:s,data:l,isLoading:t}=e;return(0,c.jsx)(eL,{columns:s,data:l,isLoading:t,renderSubComponent:()=>(0,c.jsx)("div",{}),getRowCanExpand:()=>!1})}function aN(e){let{accessToken:s,userRole:l,userID:t}=e,[a,r]=(0,d.useState)(""),[n,i]=(0,d.useState)(null),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(null),{data:x,isLoading:p}=(0,e4.a)({queryKey:["mcpTools"],queryFn:()=>{if(!s)throw Error("Access Token required");return(0,y.lU)(s)},enabled:!!s}),{mutate:g,isPending:j}=(0,ay.D)({mutationFn:e=>{if(!s)throw Error("Access Token required");return(0,y.tB)(s,e.tool.name,e.arguments)},onSuccess:e=>{m(e),h(null)},onError:e=>{h(e),m(null)}}),f=d.useMemo(()=>x?x.map(e=>({...e,onToolSelect:e=>{i(e),m(null),h(null)}})):[],[x]),_=d.useMemo(()=>f.filter(e=>{let s=a.toLowerCase();return e.name.toLowerCase().includes(s)||e.description.toLowerCase().includes(s)||e.mcp_info.server_name.toLowerCase().includes(s)}),[f,a]);return s&&l&&t?(0,c.jsxs)("div",{className:"w-full p-6",children:[(0,c.jsx)("div",{className:"flex items-center justify-between mb-4",children:(0,c.jsx)("h1",{className:"text-xl font-semibold",children:"MCP Tools"})}),(0,c.jsxs)("div",{className:"bg-white rounded-lg shadow",children:[(0,c.jsx)("div",{className:"border-b px-6 py-4",children:(0,c.jsxs)("div",{className:"flex items-center justify-between",children:[(0,c.jsxs)("div",{className:"relative w-64",children:[(0,c.jsx)("input",{type:"text",placeholder:"Search tools...",className:"w-full px-3 py-2 pl-8 border rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500",value:a,onChange:e=>r(e.target.value)}),(0,c.jsx)("svg",{className:"absolute left-2.5 top-2.5 h-4 w-4 text-gray-500",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,c.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})})]}),(0,c.jsxs)("div",{className:"text-sm text-gray-500",children:[_.length," tool",1!==_.length?"s":""," available"]})]})}),(0,c.jsx)(aZ,{columns:av,data:_,isLoading:p})]}),n&&(0,c.jsx)("div",{className:"fixed inset-0 bg-gray-800 bg-opacity-75 flex items-center justify-center z-50 p-4",children:(0,c.jsx)(ab,{tool:n,onSubmit:e=>{n&&g({tool:n,arguments:e})},isLoading:j,result:o,error:u,onClose:()=>i(null)})})]}):(0,c.jsx)("div",{className:"p-6 text-center text-gray-500",children:"Missing required authentication parameters."})}var aw=e=>{let{tagId:s,onClose:l,accessToken:t,is_admin:a,editTag:r}=e,[n]=L.Z.useForm(),[i,o]=(0,d.useState)(null),[m,u]=(0,d.useState)(r),[h,x]=(0,d.useState)([]),p=async()=>{if(t)try{let e=(await (0,y.mC)(t,[s]))[s];e&&(o(e),r&&n.setFieldsValue({name:e.name,description:e.description,models:e.models}))}catch(e){console.error("Error fetching tag details:",e),D.ZP.error("Error fetching tag details: "+e)}};(0,d.useEffect)(()=>{p()},[s,t]),(0,d.useEffect)(()=>{t&&eZ("dummy-user","Admin",t,x)},[t]);let g=async e=>{if(t)try{await (0,y.n9)(t,{name:e.name,description:e.description,models:e.models}),D.ZP.success("Tag updated successfully"),u(!1),p()}catch(e){console.error("Error updating tag:",e),D.ZP.error("Error updating tag: "+e)}};return i?(0,c.jsxs)("div",{className:"p-4",children:[(0,c.jsxs)("div",{className:"flex justify-between items-center mb-6",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(k.Z,{onClick:l,className:"mb-4",children:"← Back to Tags"}),(0,c.jsxs)(E.Z,{children:["Tag Name: ",i.name]}),(0,c.jsx)(A.Z,{className:"text-gray-500",children:i.description||"No description"})]}),a&&!m&&(0,c.jsx)(k.Z,{onClick:()=>u(!0),children:"Edit Tag"})]}),m?(0,c.jsx)(eF.Z,{children:(0,c.jsxs)(L.Z,{form:n,onFinish:g,layout:"vertical",initialValues:i,children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(q.default,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed LLMs"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process this type of data",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"models",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:h.map(e=>(0,c.jsx)(O.default.Option,{value:e,children:K(e)},e))})}),(0,c.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,c.jsx)(k.Z,{onClick:()=>u(!1),children:"Cancel"}),(0,c.jsx)(k.Z,{type:"submit",children:"Save Changes"})]})]})}):(0,c.jsx)("div",{className:"space-y-6",children:(0,c.jsxs)(eF.Z,{children:[(0,c.jsx)(E.Z,{children:"Tag Details"}),(0,c.jsxs)("div",{className:"space-y-4 mt-4",children:[(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Name"}),(0,c.jsx)(A.Z,{children:i.name})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Description"}),(0,c.jsx)(A.Z,{children:i.description||"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Allowed LLMs"}),(0,c.jsx)("div",{className:"flex flex-wrap gap-2 mt-2",children:0===i.models.length?(0,c.jsx)(eM.Z,{color:"red",children:"All Models"}):i.models.map(e=>{var s;return(0,c.jsx)(eM.Z,{color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(null===(s=i.model_info)||void 0===s?void 0:s[e])||e})},e)})})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Created"}),(0,c.jsx)(A.Z,{children:i.created_at?new Date(i.created_at).toLocaleString():"-"})]}),(0,c.jsxs)("div",{children:[(0,c.jsx)(A.Z,{className:"font-medium",children:"Last Updated"}),(0,c.jsx)(A.Z,{children:i.updated_at?new Date(i.updated_at).toLocaleString():"-"})]})]})]})})]}):(0,c.jsx)("div",{children:"Loading..."})},ak=e=>{let{data:s,onEdit:l,onDelete:t,onSelectTag:a}=e,[r,n]=d.useState([{id:"created_at",desc:!0}]),i=[{header:"Tag Name",accessorKey:"name",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("div",{className:"overflow-hidden",children:(0,c.jsx)(W.Z,{title:l.name,children:(0,c.jsx)(k.Z,{size:"xs",variant:"light",className:"font-mono text-blue-500 bg-blue-50 hover:bg-blue-100 text-xs font-normal px-2 py-0.5",onClick:()=>a(l.name),children:l.name})})})}},{header:"Description",accessorKey:"description",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)(W.Z,{title:l.description,children:(0,c.jsx)("span",{className:"text-xs",children:l.description||"-"})})}},{header:"Allowed LLMs",accessorKey:"models",cell:e=>{var s,l;let{row:t}=e,a=t.original;return(0,c.jsx)("div",{style:{display:"flex",flexDirection:"column"},children:(null==a?void 0:null===(s=a.models)||void 0===s?void 0:s.length)===0?(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"red",children:"All Models"}):null==a?void 0:null===(l=a.models)||void 0===l?void 0:l.map(e=>{var s;return(0,c.jsx)(eM.Z,{size:"xs",className:"mb-1",color:"blue",children:(0,c.jsx)(W.Z,{title:"ID: ".concat(e),children:(0,c.jsx)(A.Z,{children:(null===(s=a.model_info)||void 0===s?void 0:s[e])||e})})},e)})})}},{header:"Created",accessorKey:"created_at",sortingFn:"datetime",cell:e=>{let{row:s}=e,l=s.original;return(0,c.jsx)("span",{className:"text-xs",children:new Date(l.created_at).toLocaleDateString()})}},{id:"actions",header:"",cell:e=>{let{row:s}=e,a=s.original;return(0,c.jsxs)("div",{className:"flex space-x-2",children:[(0,c.jsx)(sZ.Z,{icon:sm.Z,size:"sm",onClick:()=>l(a),className:"cursor-pointer"}),(0,c.jsx)(sZ.Z,{icon:eH.Z,size:"sm",onClick:()=>t(a.name),className:"cursor-pointer"})]})}}],o=(0,eS.b7)({data:s,columns:i,state:{sorting:r},onSortingChange:n,getCoreRowModel:(0,eC.sC)(),getSortedRowModel:(0,eC.tj)(),enableSorting:!0});return(0,c.jsx)("div",{className:"rounded-lg custom-border relative",children:(0,c.jsx)("div",{className:"overflow-x-auto",children:(0,c.jsxs)(eI.Z,{className:"[&_td]:py-0.5 [&_th]:py-1",children:[(0,c.jsx)(eE.Z,{children:o.getHeaderGroups().map(e=>(0,c.jsx)(eO.Z,{children:e.headers.map(e=>(0,c.jsx)(eP.Z,{className:"py-1 h-8 ".concat("actions"===e.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),onClick:e.column.getToggleSortingHandler(),children:(0,c.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,c.jsx)("div",{className:"flex items-center",children:e.isPlaceholder?null:(0,eS.ie)(e.column.columnDef.header,e.getContext())}),"actions"!==e.id&&(0,c.jsx)("div",{className:"w-4",children:e.column.getIsSorted()?({asc:(0,c.jsx)(eQ.Z,{className:"h-4 w-4 text-blue-500"}),desc:(0,c.jsx)(e0.Z,{className:"h-4 w-4 text-blue-500"})})[e.column.getIsSorted()]:(0,c.jsx)(lr.Z,{className:"h-4 w-4 text-gray-400"})})]})},e.id))},e.id))}),(0,c.jsx)(eT.Z,{children:o.getRowModel().rows.length>0?o.getRowModel().rows.map(e=>(0,c.jsx)(eO.Z,{className:"h-8",children:e.getVisibleCells().map(e=>(0,c.jsx)(eA.Z,{className:"py-0.5 max-h-8 overflow-hidden text-ellipsis whitespace-nowrap ".concat("actions"===e.column.id?"sticky right-0 bg-white shadow-[-4px_0_8px_-6px_rgba(0,0,0,0.1)]":""),children:(0,eS.ie)(e.column.columnDef.cell,e.getContext())},e.id))},e.id)):(0,c.jsx)(eO.Z,{children:(0,c.jsx)(eA.Z,{colSpan:i.length,className:"h-8 text-center",children:(0,c.jsx)("div",{className:"text-center text-gray-500",children:(0,c.jsx)("p",{children:"No tags found"})})})})})]})})})},aS=e=>{let{accessToken:s,userID:l,userRole:t}=e,[a,r]=(0,d.useState)([]),[n,i]=(0,d.useState)(!1),[o,m]=(0,d.useState)(null),[u,h]=(0,d.useState)(!1),[x,p]=(0,d.useState)(!1),[g,j]=(0,d.useState)(null),[f,_]=(0,d.useState)(""),[v]=L.Z.useForm(),[b,Z]=(0,d.useState)([]),C=async()=>{if(s)try{let e=await (0,y.UM)(s);console.log("List tags response:",e),r(Object.values(e))}catch(e){console.error("Error fetching tags:",e),D.ZP.error("Error fetching tags: "+e)}},I=async e=>{if(s)try{await (0,y.mY)(s,{name:e.tag_name,description:e.description,models:e.allowed_llms}),D.ZP.success("Tag created successfully"),i(!1),v.resetFields(),C()}catch(e){console.error("Error creating tag:",e),D.ZP.error("Error creating tag: "+e)}},T=async e=>{j(e),p(!0)},E=async()=>{if(s&&g){try{await (0,y.fE)(s,g),D.ZP.success("Tag deleted successfully"),C()}catch(e){console.error("Error deleting tag:",e),D.ZP.error("Error deleting tag: "+e)}p(!1),j(null)}};return(0,d.useEffect)(()=>{l&&t&&s&&(async()=>{try{let e=await (0,y.AZ)(s,l,t);e&&e.data&&Z(e.data)}catch(e){console.error("Error fetching models:",e),D.ZP.error("Error fetching models: "+e)}})()},[s,l,t]),(0,d.useEffect)(()=>{C()},[s]),(0,c.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:o?(0,c.jsx)(aw,{tagId:o,onClose:()=>{m(null),h(!1)},accessToken:s,is_admin:"Admin"===t,editTag:u}):(0,c.jsxs)("div",{className:"gap-2 p-8 h-[75vh] w-full mt-2",children:[(0,c.jsxs)("div",{className:"flex justify-between mt-2 w-full items-center mb-4",children:[(0,c.jsx)("h1",{children:"Tag Management"}),(0,c.jsxs)("div",{className:"flex items-center space-x-2",children:[f&&(0,c.jsxs)(A.Z,{children:["Last Refreshed: ",f]}),(0,c.jsx)(sZ.Z,{icon:eB.Z,variant:"shadow",size:"xs",className:"self-center cursor-pointer",onClick:()=>{C(),_(new Date().toLocaleString())}})]})]}),(0,c.jsxs)(A.Z,{className:"mb-4",children:["Click on a tag name to view and edit its details.",(0,c.jsxs)("p",{children:["You can use tags to restrict the usage of certain LLMs based on tags passed in the request. Read more about tag routing ",(0,c.jsx)("a",{href:"https://docs.litellm.ai/docs/proxy/tag_routing",target:"_blank",rel:"noopener noreferrer",children:"here"}),"."]})]}),(0,c.jsx)(k.Z,{className:"mb-4",onClick:()=>i(!0),children:"+ Create New Tag"}),(0,c.jsx)(w.Z,{numItems:1,className:"gap-2 pt-2 pb-2 h-[75vh] w-full mt-2",children:(0,c.jsx)(N.Z,{numColSpan:1,children:(0,c.jsx)(ak,{data:a,onEdit:e=>{m(e.name),h(!0)},onDelete:T,onSelectTag:m})})}),(0,c.jsx)(M.Z,{title:"Create New Tag",visible:n,width:800,footer:null,onCancel:()=>{i(!1),v.resetFields()},children:(0,c.jsxs)(L.Z,{form:v,onFinish:I,labelCol:{span:8},wrapperCol:{span:16},labelAlign:"left",children:[(0,c.jsx)(L.Z.Item,{label:"Tag Name",name:"tag_name",rules:[{required:!0,message:"Please input a tag name"}],children:(0,c.jsx)(S.Z,{})}),(0,c.jsx)(L.Z.Item,{label:"Description",name:"description",children:(0,c.jsx)(q.default.TextArea,{rows:4})}),(0,c.jsx)(L.Z.Item,{label:(0,c.jsxs)("span",{children:["Allowed Models"," ",(0,c.jsx)(W.Z,{title:"Select which LLMs are allowed to process requests from this tag",children:(0,c.jsx)(J.Z,{style:{marginLeft:"4px"}})})]}),name:"allowed_llms",children:(0,c.jsx)(O.default,{mode:"multiple",placeholder:"Select LLMs",children:b.map(e=>(0,c.jsx)(O.default.Option,{value:e.model_info.id,children:(0,c.jsxs)("div",{children:[(0,c.jsx)("span",{children:e.model_name}),(0,c.jsxs)("span",{className:"text-gray-400 ml-2",children:["(",e.model_info.id,")"]})]})},e.model_info.id))})}),(0,c.jsx)("div",{style:{textAlign:"right",marginTop:"10px"},children:(0,c.jsx)(k.Z,{type:"submit",children:"Create Tag"})})]})}),x&&(0,c.jsx)("div",{className:"fixed z-10 inset-0 overflow-y-auto",children:(0,c.jsxs)("div",{className:"flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0",children:[(0,c.jsx)("div",{className:"fixed inset-0 transition-opacity","aria-hidden":"true",children:(0,c.jsx)("div",{className:"absolute inset-0 bg-gray-500 opacity-75"})}),(0,c.jsxs)("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full",children:[(0,c.jsx)("div",{className:"bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4",children:(0,c.jsx)("div",{className:"sm:flex sm:items-start",children:(0,c.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left",children:[(0,c.jsx)("h3",{className:"text-lg leading-6 font-medium text-gray-900",children:"Delete Tag"}),(0,c.jsx)("div",{className:"mt-2",children:(0,c.jsx)("p",{className:"text-sm text-gray-500",children:"Are you sure you want to delete this tag?"})})]})})}),(0,c.jsxs)("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse",children:[(0,c.jsx)(k.Z,{onClick:E,color:"red",className:"ml-2",children:"Delete"}),(0,c.jsx)(k.Z,{onClick:()=>{p(!1),j(null)},children:"Cancel"})]})]})]})})]})})},aC=l(49096),aI=l(53335);let{cva:aT,cx:aA,compose:aE}=(0,aC.ZD)({hooks:{onComplete:e=>(0,aI.m6)(e)}});function aP(e){var s,l;let{className:t="",...a}=e,r=(0,d.useId)();return s=()=>{let e=document.getAnimations().filter(e=>e instanceof CSSAnimation&&"spin"===e.animationName),s=e.find(e=>{var s;return(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))===r}),l=e.find(e=>{var s;return e.effect instanceof KeyframeEffect&&(null===(s=e.effect.target)||void 0===s?void 0:s.getAttribute("data-spinner-id"))!==r});s&&l&&(s.currentTime=l.currentTime)},l=[r],(0,d.useLayoutEffect)(s,l),(0,c.jsxs)("svg",{"data-spinner-id":r,className:aA("pointer-events-none size-12 animate-spin text-current",t),fill:"none",viewBox:"0 0 24 24",...a,children:[(0,c.jsx)("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),(0,c.jsx)("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]})}let aO=new h.S;function aL(){return(0,c.jsxs)("div",{className:aA("h-screen","flex items-center justify-center gap-4"),children:[(0,c.jsx)("div",{className:"text-lg font-medium py-2 pr-4 border-r border-r-gray-200",children:"\uD83D\uDE85 LiteLLM"}),(0,c.jsxs)("div",{className:"flex items-center justify-center gap-2",children:[(0,c.jsx)(aP,{className:"size-4"}),(0,c.jsx)("span",{className:"text-gray-600 text-sm",children:"Loading..."})]})]})}function aD(){let[e,s]=(0,d.useState)(""),[l,t]=(0,d.useState)(!1),[a,r]=(0,d.useState)(!1),[n,i]=(0,d.useState)(null),[o,h]=(0,d.useState)(null),[p,g]=(0,d.useState)(null),[j,f]=(0,d.useState)([]),[_,v]=(0,d.useState)([]),[N,w]=(0,d.useState)({PROXY_BASE_URL:"",PROXY_LOGOUT_URL:""}),[k,S]=(0,d.useState)(!0),C=(0,m.useSearchParams)(),[I,T]=(0,d.useState)({data:[]}),[A,E]=(0,d.useState)(null),[P,O]=(0,d.useState)(!0),[L,D]=(0,d.useState)(null),M=C.get("invitation_id"),[F,R]=(0,d.useState)(()=>C.get("page")||"api-keys"),[q,U]=(0,d.useState)(null);return((0,d.useEffect)(()=>{E(function(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}("token")),O(!1)},[]),(0,d.useEffect)(()=>{!1===P&&null===A&&(window.location.href=(y.H2||"")+"/sso/key/generate")},[A,P]),(0,d.useEffect)(()=>{if(!A)return;let e=(0,u.o)(A);if(e){if(console.log("Decoded token:",e),console.log("Decoded key:",e.key),U(e.key),r(e.disabled_non_admin_personal_key_creation),e.user_role){let l=function(e){if(!e)return"Undefined Role";switch(console.log("Received user role: ".concat(e.toLowerCase())),console.log("Received user role length: ".concat(e.toLowerCase().length)),e.toLowerCase()){case"app_owner":case"demo_app_owner":return"App Owner";case"app_admin":case"proxy_admin":return"Admin";case"proxy_admin_viewer":return"Admin Viewer";case"org_admin":return"Org Admin";case"internal_user":return"Internal User";case"internal_viewer":return"Internal Viewer";case"app_user":return"App User";default:return"Unknown Role"}}(e.user_role);console.log("Decoded user_role:",l),s(l),"Admin Viewer"==l&&R("usage")}else console.log("User role not defined");e.user_email?i(e.user_email):console.log("User Email is not set ".concat(e)),e.login_method?S("username_password"==e.login_method):console.log("User Email is not set ".concat(e)),e.premium_user&&t(e.premium_user),e.auth_header_name&&(0,y.K8)(e.auth_header_name),e.user_id&&D(e.user_id)}},[A]),(0,d.useEffect)(()=>{q&&L&&e&&eZ(L,e,q,v),q&&L&&e&&Z(q,L,e,null,h),q&&lw(q,f)},[q,L,e]),P||!1==P&&null===A)?(0,c.jsx)(aL,{}):(0,c.jsx)(d.Suspense,{fallback:(0,c.jsx)(aL,{}),children:(0,c.jsx)(x.aH,{client:aO,children:M?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):(0,c.jsxs)("div",{className:"flex flex-col min-h-screen",children:[(0,c.jsx)(b,{userID:L,userRole:e,premiumUser:l,userEmail:n,setProxySettings:w,proxySettings:N,accessToken:q}),(0,c.jsxs)("div",{className:"flex flex-1 overflow-auto",children:[(0,c.jsx)("div",{className:"mt-8",children:(0,c.jsx)(ar,{setPage:e=>{let s=new URLSearchParams(C);s.set("page",e),window.history.pushState(null,"","?".concat(s.toString())),R(e)},userRole:e,defaultSelectedKey:F})}),"api-keys"==F?(0,c.jsx)(ss,{userID:L,userRole:e,premiumUser:l,teams:o,keys:p,setUserRole:s,userEmail:n,setUserEmail:i,setTeams:h,setKeys:g,organizations:j}):"models"==F?(0,c.jsx)(lm,{userID:L,userRole:e,token:A,keys:p,accessToken:q,modelData:I,setModelData:T,premiumUser:l,teams:o}):"llm-playground"==F?(0,c.jsx)(tQ,{userID:L,userRole:e,token:A,accessToken:q,disabledPersonalKeyCreation:a}):"users"==F?(0,c.jsx)(l_,{userID:L,userRole:e,token:A,keys:p,teams:o,accessToken:q,setKeys:g}):"teams"==F?(0,c.jsx)(lZ,{teams:o,setTeams:h,searchParams:C,accessToken:q,userID:L,userRole:e,organizations:j}):"organizations"==F?(0,c.jsx)(lk,{organizations:j,setOrganizations:f,userModels:_,accessToken:q,userRole:e,premiumUser:l}):"admin-panel"==F?(0,c.jsx)(lM,{setTeams:h,searchParams:C,accessToken:q,showSSOBanner:k,premiumUser:l,proxySettings:N}):"api_ref"==F?(0,c.jsx)(tN,{proxySettings:N}):"settings"==F?(0,c.jsx)(lK,{userID:L,userRole:e,accessToken:q,premiumUser:l}):"budgets"==F?(0,c.jsx)(l7,{accessToken:q}):"guardrails"==F?(0,c.jsx)(af,{accessToken:q}):"transform-request"==F?(0,c.jsx)(a_,{accessToken:q}):"general-settings"==F?(0,c.jsx)(lQ,{userID:L,userRole:e,accessToken:q,modelData:I}):"model-hub"==F?(0,c.jsx)(tu.Z,{accessToken:q,publicPage:!1,premiumUser:l}):"caching"==F?(0,c.jsx)(aj,{userID:L,userRole:e,token:A,accessToken:q,premiumUser:l}):"pass-through-settings"==F?(0,c.jsx)(l5,{userID:L,userRole:e,accessToken:q,modelData:I}):"logs"==F?(0,c.jsx)(td,{userID:L,userRole:e,token:A,accessToken:q,allTeams:null!=o?o:[]}):"mcp-tools"==F?(0,c.jsx)(aN,{accessToken:q,userRole:e,userID:L}):"tag-management"==F?(0,c.jsx)(aS,{accessToken:q,userRole:e,userID:L}):"new_usage"==F?(0,c.jsx)(tZ,{userID:L,userRole:e,accessToken:q,teams:null!=o?o:[]}):(0,c.jsx)(ao,{userID:L,userRole:e,token:A,accessToken:q,keys:p,premiumUser:l})]})]})})})}},3914:function(e,s,l){"use strict";function t(){let e=window.location.hostname,s=["Lax","Strict","None"];["/","/ui"].forEach(l=>{document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,";"),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,";"),s.forEach(s=>{let t="None"===s?" Secure;":"";document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; SameSite=").concat(s,";").concat(t),document.cookie="token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=".concat(l,"; domain=").concat(e,"; SameSite=").concat(s,";").concat(t)})}),console.log("After clearing cookies:",document.cookie)}function a(e){let s=document.cookie.split("; ").find(s=>s.startsWith(e+"="));return s?s.split("=")[1]:null}l.d(s,{b:function(){return t},e:function(){return a}})}},function(e){e.O(0,[665,990,42,261,899,466,250,699,971,117,744],function(){return e(e.s=60497)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/_next/static/chunks/main-app-2b16cdb7ff4e1af7.js b/ui/litellm-dashboard/out/_next/static/chunks/main-app-4f7318ae681a6d94.js similarity index 54% rename from ui/litellm-dashboard/out/_next/static/chunks/main-app-2b16cdb7ff4e1af7.js rename to ui/litellm-dashboard/out/_next/static/chunks/main-app-4f7318ae681a6d94.js index 33781e7a63..04cf9b1105 100644 --- a/ui/litellm-dashboard/out/_next/static/chunks/main-app-2b16cdb7ff4e1af7.js +++ b/ui/litellm-dashboard/out/_next/static/chunks/main-app-4f7318ae681a6d94.js @@ -1 +1 @@ -(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{35618:function(e,n,t){Promise.resolve().then(t.t.bind(t,12846,23)),Promise.resolve().then(t.t.bind(t,19107,23)),Promise.resolve().then(t.t.bind(t,61060,23)),Promise.resolve().then(t.t.bind(t,4707,23)),Promise.resolve().then(t.t.bind(t,80,23)),Promise.resolve().then(t.t.bind(t,36423,23))}},function(e){var n=function(n){return e(e.s=n)};e.O(0,[971,117],function(){return n(54278),n(35618)}),_N_E=e.O()}]); \ No newline at end of file +(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[744],{10264:function(e,n,t){Promise.resolve().then(t.t.bind(t,12846,23)),Promise.resolve().then(t.t.bind(t,19107,23)),Promise.resolve().then(t.t.bind(t,61060,23)),Promise.resolve().then(t.t.bind(t,4707,23)),Promise.resolve().then(t.t.bind(t,80,23)),Promise.resolve().then(t.t.bind(t,36423,23))}},function(e){var n=function(n){return e(e.s=n)};e.O(0,[971,117],function(){return n(54278),n(10264)}),_N_E=e.O()}]); \ No newline at end of file diff --git a/ui/litellm-dashboard/out/index.html b/ui/litellm-dashboard/out/index.html index fe18b9be80..d46d2b1454 100644 --- a/ui/litellm-dashboard/out/index.html +++ b/ui/litellm-dashboard/out/index.html @@ -1 +1 @@ -LiteLLM Dashboard \ No newline at end of file +LiteLLM Dashboard \ No newline at end of file diff --git a/ui/litellm-dashboard/out/index.txt b/ui/litellm-dashboard/out/index.txt index 0f27cbf775..a83c327f95 100644 --- a/ui/litellm-dashboard/out/index.txt +++ b/ui/litellm-dashboard/out/index.txt @@ -1,7 +1,7 @@ 2:I[19107,[],"ClientPageRoot"] -3:I[76737,["665","static/chunks/3014691f-b7b79b78e27792f3.js","990","static/chunks/13b76428-ebdf3012af0e4489.js","42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","899","static/chunks/899-57685cedd1dcbc78.js","466","static/chunks/466-65538e7f331af98e.js","250","static/chunks/250-7d480872c0e251dc.js","699","static/chunks/699-2176ba2273e4676d.js","931","static/chunks/app/page-36914b80c40b5032.js"],"default",1] +3:I[76737,["665","static/chunks/3014691f-b7b79b78e27792f3.js","990","static/chunks/13b76428-ebdf3012af0e4489.js","42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","899","static/chunks/899-57685cedd1dcbc78.js","466","static/chunks/466-65538e7f331af98e.js","250","static/chunks/250-85fb4e9c2fdebf3e.js","699","static/chunks/699-907a1bb245b7369a.js","931","static/chunks/app/page-225a364dd94a768d.js"],"default",1] 4:I[4707,[],""] 5:I[36423,[],""] -0:["fzhvjOFL6KeNsWYrLD4ya",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] +0:["TGdu5EOOYr2m-EAOFIND0",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"LiteLLM Dashboard"}],["$","meta","3",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","4",{"rel":"icon","href":"/ui/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]] 1:null diff --git a/ui/litellm-dashboard/out/model_hub.html b/ui/litellm-dashboard/out/model_hub.html index 208f7ab9b7..0b146e82c3 100644 --- a/ui/litellm-dashboard/out/model_hub.html +++ b/ui/litellm-dashboard/out/model_hub.html @@ -1 +1 @@ -LiteLLM Dashboard \ No newline at end of file +LiteLLM Dashboard \ No newline at end of file diff --git a/ui/litellm-dashboard/out/model_hub.txt b/ui/litellm-dashboard/out/model_hub.txt index 3bdb89cd19..14962120fd 100644 --- a/ui/litellm-dashboard/out/model_hub.txt +++ b/ui/litellm-dashboard/out/model_hub.txt @@ -1,7 +1,7 @@ 2:I[19107,[],"ClientPageRoot"] -3:I[52829,["42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","250","static/chunks/250-7d480872c0e251dc.js","699","static/chunks/699-2176ba2273e4676d.js","418","static/chunks/app/model_hub/page-a965e43ba9638156.js"],"default",1] +3:I[52829,["42","static/chunks/42-69f5b4e6a9942a9f.js","261","static/chunks/261-ee7f0f1f1c8c22a0.js","250","static/chunks/250-85fb4e9c2fdebf3e.js","699","static/chunks/699-907a1bb245b7369a.js","418","static/chunks/app/model_hub/page-3d2c374ee41b38e5.js"],"default",1] 4:I[4707,[],""] 5:I[36423,[],""] -0:["fzhvjOFL6KeNsWYrLD4ya",[[["",{"children":["model_hub",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["model_hub",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","model_hub","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] +0:["TGdu5EOOYr2m-EAOFIND0",[[["",{"children":["model_hub",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["model_hub",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","model_hub","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"LiteLLM Dashboard"}],["$","meta","3",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","4",{"rel":"icon","href":"/ui/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]] 1:null diff --git a/ui/litellm-dashboard/out/onboarding.html b/ui/litellm-dashboard/out/onboarding.html index 9b3880cffd..085f63f727 100644 --- a/ui/litellm-dashboard/out/onboarding.html +++ b/ui/litellm-dashboard/out/onboarding.html @@ -1 +1 @@ -LiteLLM Dashboard \ No newline at end of file +LiteLLM Dashboard \ No newline at end of file diff --git a/ui/litellm-dashboard/out/onboarding.txt b/ui/litellm-dashboard/out/onboarding.txt index 4e77654a7b..9ef840aba3 100644 --- a/ui/litellm-dashboard/out/onboarding.txt +++ b/ui/litellm-dashboard/out/onboarding.txt @@ -1,7 +1,7 @@ 2:I[19107,[],"ClientPageRoot"] -3:I[12011,["665","static/chunks/3014691f-b7b79b78e27792f3.js","42","static/chunks/42-69f5b4e6a9942a9f.js","899","static/chunks/899-57685cedd1dcbc78.js","250","static/chunks/250-7d480872c0e251dc.js","461","static/chunks/app/onboarding/page-9598003bc1e91371.js"],"default",1] +3:I[12011,["665","static/chunks/3014691f-b7b79b78e27792f3.js","42","static/chunks/42-69f5b4e6a9942a9f.js","899","static/chunks/899-57685cedd1dcbc78.js","250","static/chunks/250-85fb4e9c2fdebf3e.js","461","static/chunks/app/onboarding/page-339a46b35fba4423.js"],"default",1] 4:I[4707,[],""] 5:I[36423,[],""] -0:["fzhvjOFL6KeNsWYrLD4ya",[[["",{"children":["onboarding",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["onboarding",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","onboarding","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] +0:["TGdu5EOOYr2m-EAOFIND0",[[["",{"children":["onboarding",{"children":["__PAGE__",{}]}]},"$undefined","$undefined",true],["",{"children":["onboarding",{"children":["__PAGE__",{},[["$L1",["$","$L2",null,{"props":{"params":{},"searchParams":{}},"Component":"$3"}],null],null],null]},[null,["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children","onboarding","children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":"$undefined","notFoundStyles":"$undefined"}]],null]},[[[["$","link","0",{"rel":"stylesheet","href":"/ui/_next/static/css/86f6cc749f6b8493.css","precedence":"next","crossOrigin":"$undefined"}],["$","link","1",{"rel":"stylesheet","href":"/ui/_next/static/css/005c96178151b9fd.css","precedence":"next","crossOrigin":"$undefined"}]],["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_cf7686","children":["$","$L4",null,{"parallelRouterKey":"children","segmentPath":["children"],"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L5",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,\"Segoe UI\",Roboto,Helvetica,Arial,sans-serif,\"Apple Color Emoji\",\"Segoe UI Emoji\"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[]}]}]}]],null],null],["$L6",null]]]] 6:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"LiteLLM Dashboard"}],["$","meta","3",{"name":"description","content":"LiteLLM Proxy Admin UI"}],["$","link","4",{"rel":"icon","href":"/ui/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]] 1:null From f3291bde4d969a4efba2a2a4fdc3f29f7dce97ad Mon Sep 17 00:00:00 2001 From: Ishaan Jaff Date: Wed, 23 Apr 2025 20:56:31 -0700 Subject: [PATCH 28/40] fix for serviceAccountName on migration job (#10258) --- deploy/charts/litellm-helm/templates/migrations-job.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/deploy/charts/litellm-helm/templates/migrations-job.yaml b/deploy/charts/litellm-helm/templates/migrations-job.yaml index 1c4b6817fa..ba69f0fef8 100644 --- a/deploy/charts/litellm-helm/templates/migrations-job.yaml +++ b/deploy/charts/litellm-helm/templates/migrations-job.yaml @@ -16,6 +16,7 @@ spec: {{- toYaml . | nindent 8 }} {{- end }} spec: + serviceAccountName: {{ include "litellm.serviceAccountName" . }} containers: - name: prisma-migrations image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default (printf "main-%s" .Chart.AppVersion) }}" From 5e2fd49dd326ff2267cd6e4055f7f6dbc99fd183 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos Orfanos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 24 Apr 2025 05:59:25 +0200 Subject: [PATCH 29/40] Fix typos (#10232) --- docs/my-website/docs/completion/audio.md | 2 +- .../docs/completion/document_understanding.md | 2 +- docs/my-website/docs/completion/vision.md | 2 +- .../observability/greenscale_integration.md | 2 +- .../observability/langfuse_integration.md | 2 +- .../my-website/docs/pass_through/vertex_ai.md | 2 +- docs/my-website/docs/providers/anthropic.md | 2 +- docs/my-website/docs/providers/azure.md | 2 +- docs/my-website/docs/providers/vertex.md | 6 ++-- docs/my-website/docs/proxy/admin_ui_sso.md | 4 +-- docs/my-website/docs/proxy/alerting.md | 8 ++--- docs/my-website/docs/proxy/custom_pricing.md | 4 +-- docs/my-website/docs/proxy/db_deadlocks.md | 2 +- docs/my-website/docs/proxy/deploy.md | 6 ++-- docs/my-website/docs/proxy/enterprise.md | 4 +-- .../docs/proxy/guardrails/quick_start.md | 2 +- docs/my-website/docs/proxy/logging.md | 32 +++++++++---------- docs/my-website/docs/proxy/prod.md | 4 +-- .../docs/proxy/temporary_budget_increase.md | 2 +- docs/my-website/docs/proxy/ui_credentials.md | 2 +- docs/my-website/docs/proxy/virtual_keys.md | 4 +-- docs/my-website/docs/simple_proxy_old_doc.md | 14 ++++---- .../my-website/docs/tutorials/compare_llms.md | 2 +- .../docs/tutorials/gradio_integration.md | 2 +- 24 files changed, 57 insertions(+), 57 deletions(-) diff --git a/docs/my-website/docs/completion/audio.md b/docs/my-website/docs/completion/audio.md index 97153a5867..96b5e4f41c 100644 --- a/docs/my-website/docs/completion/audio.md +++ b/docs/my-website/docs/completion/audio.md @@ -3,7 +3,7 @@ import TabItem from '@theme/TabItem'; # Using Audio Models -How to send / receieve audio to a `/chat/completions` endpoint +How to send / receive audio to a `/chat/completions` endpoint ## Audio Output from a model diff --git a/docs/my-website/docs/completion/document_understanding.md b/docs/my-website/docs/completion/document_understanding.md index f58b836c63..acebb2e160 100644 --- a/docs/my-website/docs/completion/document_understanding.md +++ b/docs/my-website/docs/completion/document_understanding.md @@ -3,7 +3,7 @@ import TabItem from '@theme/TabItem'; # Using PDF Input -How to send / receieve pdf's (other document types) to a `/chat/completions` endpoint +How to send / receive pdf's (other document types) to a `/chat/completions` endpoint Works for: - Vertex AI models (Gemini + Anthropic) diff --git a/docs/my-website/docs/completion/vision.md b/docs/my-website/docs/completion/vision.md index 1e18109b3b..7670008486 100644 --- a/docs/my-website/docs/completion/vision.md +++ b/docs/my-website/docs/completion/vision.md @@ -194,7 +194,7 @@ Expected Response ## Explicitly specify image type -If you have images without a mime-type, or if litellm is incorrectly inferring the mime type of your image (e.g. calling `gs://` url's with vertex ai), you can set this explicity via the `format` param. +If you have images without a mime-type, or if litellm is incorrectly inferring the mime type of your image (e.g. calling `gs://` url's with vertex ai), you can set this explicitly via the `format` param. ```python "image_url": { diff --git a/docs/my-website/docs/observability/greenscale_integration.md b/docs/my-website/docs/observability/greenscale_integration.md index 49eadc6453..c9b00cd0e8 100644 --- a/docs/my-website/docs/observability/greenscale_integration.md +++ b/docs/my-website/docs/observability/greenscale_integration.md @@ -53,7 +53,7 @@ response = completion( ## Additional information in metadata -You can send any additional information to Greenscale by using the `metadata` field in completion and `greenscale_` prefix. This can be useful for sending metadata about the request, such as the project and application name, customer_id, enviornment, or any other information you want to track usage. `greenscale_project` and `greenscale_application` are required fields. +You can send any additional information to Greenscale by using the `metadata` field in completion and `greenscale_` prefix. This can be useful for sending metadata about the request, such as the project and application name, customer_id, environment, or any other information you want to track usage. `greenscale_project` and `greenscale_application` are required fields. ```python #openai call with additional metadata diff --git a/docs/my-website/docs/observability/langfuse_integration.md b/docs/my-website/docs/observability/langfuse_integration.md index 9727730363..576135ba67 100644 --- a/docs/my-website/docs/observability/langfuse_integration.md +++ b/docs/my-website/docs/observability/langfuse_integration.md @@ -185,7 +185,7 @@ curl --location --request POST 'http://0.0.0.0:4000/chat/completions' \ * `trace_release` - Release for the trace, defaults to `None` * `trace_metadata` - Metadata for the trace, defaults to `None` * `trace_user_id` - User identifier for the trace, defaults to completion argument `user` -* `tags` - Tags for the trace, defeaults to `None` +* `tags` - Tags for the trace, defaults to `None` ##### Updatable Parameters on Continuation diff --git a/docs/my-website/docs/pass_through/vertex_ai.md b/docs/my-website/docs/pass_through/vertex_ai.md index f40dfa70eb..b99f0fcf98 100644 --- a/docs/my-website/docs/pass_through/vertex_ai.md +++ b/docs/my-website/docs/pass_through/vertex_ai.md @@ -222,7 +222,7 @@ curl http://localhost:4000/vertex-ai/v1/projects/${PROJECT_ID}/locations/us-cent LiteLLM Proxy Server supports two methods of authentication to Vertex AI: -1. Pass Vertex Credetials client side to proxy server +1. Pass Vertex Credentials client side to proxy server 2. Set Vertex AI credentials on proxy server diff --git a/docs/my-website/docs/providers/anthropic.md b/docs/my-website/docs/providers/anthropic.md index 9e4f6908a4..95323719f0 100644 --- a/docs/my-website/docs/providers/anthropic.md +++ b/docs/my-website/docs/providers/anthropic.md @@ -1095,7 +1095,7 @@ response = completion( print(response.choices[0]) ``` - + 1. Add model to config diff --git a/docs/my-website/docs/providers/azure.md b/docs/my-website/docs/providers/azure.md index e58d8a7b5d..2ea444b029 100644 --- a/docs/my-website/docs/providers/azure.md +++ b/docs/my-website/docs/providers/azure.md @@ -483,7 +483,7 @@ response.stream_to_file(speech_file_path) This is a walkthrough on how to use Azure Active Directory Tokens - Microsoft Entra ID to make `litellm.completion()` calls Step 1 - Download Azure CLI -Installation instructons: https://learn.microsoft.com/en-us/cli/azure/install-azure-cli +Installation instructions: https://learn.microsoft.com/en-us/cli/azure/install-azure-cli ```shell brew update && brew install azure-cli ``` diff --git a/docs/my-website/docs/providers/vertex.md b/docs/my-website/docs/providers/vertex.md index 762bd5f332..7f60de27ee 100644 --- a/docs/my-website/docs/providers/vertex.md +++ b/docs/my-website/docs/providers/vertex.md @@ -692,7 +692,7 @@ curl http://0.0.0.0:4000/v1/chat/completions \ ### **Context Caching** -Use Vertex AI context caching is supported by calling provider api directly. (Unified Endpoint support comin soon.). +Use Vertex AI context caching is supported by calling provider api directly. (Unified Endpoint support coming soon.). [**Go straight to provider**](../pass_through/vertex_ai.md#context-caching) @@ -910,7 +910,7 @@ export VERTEXAI_PROJECT="my-test-project" # ONLY use if model project is differe ## Specifying Safety Settings -In certain use-cases you may need to make calls to the models and pass [safety settigns](https://ai.google.dev/docs/safety_setting_gemini) different from the defaults. To do so, simple pass the `safety_settings` argument to `completion` or `acompletion`. For example: +In certain use-cases you may need to make calls to the models and pass [safety settings](https://ai.google.dev/docs/safety_setting_gemini) different from the defaults. To do so, simple pass the `safety_settings` argument to `completion` or `acompletion`. For example: ### Set per model/request @@ -2050,7 +2050,7 @@ response = completion( print(response.choices[0]) ``` - + 1. Add model to config diff --git a/docs/my-website/docs/proxy/admin_ui_sso.md b/docs/my-website/docs/proxy/admin_ui_sso.md index 0bbba57fd9..a0dde80e9c 100644 --- a/docs/my-website/docs/proxy/admin_ui_sso.md +++ b/docs/my-website/docs/proxy/admin_ui_sso.md @@ -243,12 +243,12 @@ We allow you to pass a local image or a an http/https url of your image Set `UI_LOGO_PATH` on your env. We recommend using a hosted image, it's a lot easier to set up and configure / debug -Exaple setting Hosted image +Example setting Hosted image ```shell UI_LOGO_PATH="https://litellm-logo-aws-marketplace.s3.us-west-2.amazonaws.com/berriai-logo-github.png" ``` -Exaple setting a local image (on your container) +Example setting a local image (on your container) ```shell UI_LOGO_PATH="ui_images/logo.jpg" ``` diff --git a/docs/my-website/docs/proxy/alerting.md b/docs/my-website/docs/proxy/alerting.md index c2fc510d96..e2f6223c8f 100644 --- a/docs/my-website/docs/proxy/alerting.md +++ b/docs/my-website/docs/proxy/alerting.md @@ -213,7 +213,7 @@ model_list: general_settings: master_key: sk-1234 alerting: ["slack"] - alerting_threshold: 0.0001 # (Seconds) set an artifically low threshold for testing alerting + alerting_threshold: 0.0001 # (Seconds) set an artificially low threshold for testing alerting alert_to_webhook_url: { "llm_exceptions": "https://hooks.slack.com/services/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", "llm_too_slow": "https://hooks.slack.com/services/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", @@ -247,7 +247,7 @@ model_list: general_settings: master_key: sk-1234 alerting: ["slack"] - alerting_threshold: 0.0001 # (Seconds) set an artifically low threshold for testing alerting + alerting_threshold: 0.0001 # (Seconds) set an artificially low threshold for testing alerting alert_to_webhook_url: { "llm_exceptions": ["os.environ/SLACK_WEBHOOK_URL", "os.environ/SLACK_WEBHOOK_URL_2"], "llm_too_slow": ["https://webhook.site/7843a980-a494-4967-80fb-d502dbc16886", "https://webhook.site/28cfb179-f4fb-4408-8129-729ff55cf213"], @@ -425,7 +425,7 @@ curl -X GET --location 'http://0.0.0.0:4000/health/services?service=webhook' \ - `projected_exceeded_date` *str or null*: The date when the budget is projected to be exceeded, returned when 'soft_budget' is set for key (optional). - `projected_spend` *float or null*: The projected spend amount, returned when 'soft_budget' is set for key (optional). - `event` *Literal["budget_crossed", "threshold_crossed", "projected_limit_exceeded"]*: The type of event that triggered the webhook. Possible values are: - * "spend_tracked": Emitted whenver spend is tracked for a customer id. + * "spend_tracked": Emitted whenever spend is tracked for a customer id. * "budget_crossed": Indicates that the spend has exceeded the max budget. * "threshold_crossed": Indicates that spend has crossed a threshold (currently sent when 85% and 95% of budget is reached). * "projected_limit_exceeded": For "key" only - Indicates that the projected spend is expected to exceed the soft budget threshold. @@ -480,7 +480,7 @@ LLM-related Alerts | `cooldown_deployment` | Alerts when a deployment is put into cooldown | ✅ | | `new_model_added` | Notifications when a new model is added to litellm proxy through /model/new| ✅ | | `outage_alerts` | Alerts when a specific LLM deployment is facing an outage | ✅ | -| `region_outage_alerts` | Alerts when a specfic LLM region is facing an outage. Example us-east-1 | ✅ | +| `region_outage_alerts` | Alerts when a specific LLM region is facing an outage. Example us-east-1 | ✅ | Budget and Spend Alerts diff --git a/docs/my-website/docs/proxy/custom_pricing.md b/docs/my-website/docs/proxy/custom_pricing.md index 792d5c26dd..e2df7721bf 100644 --- a/docs/my-website/docs/proxy/custom_pricing.md +++ b/docs/my-website/docs/proxy/custom_pricing.md @@ -56,7 +56,7 @@ model_list: model: azure/ api_key: os.environ/AZURE_API_KEY api_base: os.environ/AZURE_API_BASE - api_version: os.envrion/AZURE_API_VERSION + api_version: os.environ/AZURE_API_VERSION model_info: input_cost_per_token: 0.000421 # 👈 ONLY to track cost per token output_cost_per_token: 0.000520 # 👈 ONLY to track cost per token @@ -133,4 +133,4 @@ acompletion( If these keys are not present, LiteLLM will not use your custom pricing. -If the problem persists, please file an issue on [GitHub](https://github.com/BerriAI/litellm/issues). \ No newline at end of file +If the problem persists, please file an issue on [GitHub](https://github.com/BerriAI/litellm/issues). diff --git a/docs/my-website/docs/proxy/db_deadlocks.md b/docs/my-website/docs/proxy/db_deadlocks.md index 332374995d..0eee928fa6 100644 --- a/docs/my-website/docs/proxy/db_deadlocks.md +++ b/docs/my-website/docs/proxy/db_deadlocks.md @@ -19,7 +19,7 @@ LiteLLM writes `UPDATE` and `UPSERT` queries to the DB. When using 10+ instances ### Stage 1. Each instance writes updates to redis -Each instance will accumlate the spend updates for a key, user, team, etc and write the updates to a redis queue. +Each instance will accumulate the spend updates for a key, user, team, etc and write the updates to a redis queue.

diff --git a/docs/my-website/docs/proxy/deploy.md b/docs/my-website/docs/proxy/deploy.md index 011778f584..d57686dc78 100644 --- a/docs/my-website/docs/proxy/deploy.md +++ b/docs/my-website/docs/proxy/deploy.md @@ -22,7 +22,7 @@ echo 'LITELLM_MASTER_KEY="sk-1234"' > .env # Add the litellm salt key - you cannot change this after adding a model # It is used to encrypt / decrypt your LLM API Key credentials -# We recommned - https://1password.com/password-generator/ +# We recommend - https://1password.com/password-generator/ # password generator to get a random hash for litellm salt key echo 'LITELLM_SALT_KEY="sk-1234"' >> .env @@ -125,7 +125,7 @@ CMD ["--port", "4000", "--config", "config.yaml", "--detailed_debug"] ### Build from litellm `pip` package -Follow these instructons to build a docker container from the litellm pip package. If your company has a strict requirement around security / building images you can follow these steps. +Follow these instructions to build a docker container from the litellm pip package. If your company has a strict requirement around security / building images you can follow these steps. Dockerfile @@ -999,7 +999,7 @@ services: - "4000:4000" # Map the container port to the host, change the host port if necessary volumes: - ./litellm-config.yaml:/app/config.yaml # Mount the local configuration file - # You can change the port or number of workers as per your requirements or pass any new supported CLI augument. Make sure the port passed here matches with the container port defined above in `ports` value + # You can change the port or number of workers as per your requirements or pass any new supported CLI argument. Make sure the port passed here matches with the container port defined above in `ports` value command: [ "--config", "/app/config.yaml", "--port", "4000", "--num_workers", "8" ] # ...rest of your docker-compose config if any diff --git a/docs/my-website/docs/proxy/enterprise.md b/docs/my-website/docs/proxy/enterprise.md index fb0945d488..26dc9d4950 100644 --- a/docs/my-website/docs/proxy/enterprise.md +++ b/docs/my-website/docs/proxy/enterprise.md @@ -691,7 +691,7 @@ curl --request POST \ -**Successfull Request** +**Successful Request** ```shell curl --location 'http://0.0.0.0:4000/key/generate' \ @@ -729,7 +729,7 @@ curl --location 'http://0.0.0.0:4000/key/generate' \ -**Successfull Request** +**Successful Request** ```shell curl http://localhost:4000/chat/completions \ diff --git a/docs/my-website/docs/proxy/guardrails/quick_start.md b/docs/my-website/docs/proxy/guardrails/quick_start.md index aeac507e0a..55cfa98d48 100644 --- a/docs/my-website/docs/proxy/guardrails/quick_start.md +++ b/docs/my-website/docs/proxy/guardrails/quick_start.md @@ -164,7 +164,7 @@ curl -i http://localhost:4000/v1/chat/completions \ **Expected response** -Your response headers will incude `x-litellm-applied-guardrails` with the guardrail applied +Your response headers will include `x-litellm-applied-guardrails` with the guardrail applied ``` x-litellm-applied-guardrails: aporia-pre-guard diff --git a/docs/my-website/docs/proxy/logging.md b/docs/my-website/docs/proxy/logging.md index c8731dd270..ad4cababc0 100644 --- a/docs/my-website/docs/proxy/logging.md +++ b/docs/my-website/docs/proxy/logging.md @@ -277,7 +277,7 @@ Found under `kwargs["standard_logging_object"]`. This is a standard payload, log ## Langfuse -We will use the `--config` to set `litellm.success_callback = ["langfuse"]` this will log all successfull LLM calls to langfuse. Make sure to set `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` in your environment +We will use the `--config` to set `litellm.success_callback = ["langfuse"]` this will log all successful LLM calls to langfuse. Make sure to set `LANGFUSE_PUBLIC_KEY` and `LANGFUSE_SECRET_KEY` in your environment **Step 1** Install langfuse @@ -534,15 +534,15 @@ print(response) Use this if you want to control which LiteLLM-specific fields are logged as tags by the LiteLLM proxy. By default LiteLLM Proxy logs no LiteLLM-specific fields -| LiteLLM specific field | Description | Example Value | -|------------------------|-------------------------------------------------------|------------------------------------------------| -| `cache_hit` | Indicates whether a cache hit occured (True) or not (False) | `true`, `false` | -| `cache_key` | The Cache key used for this request | `d2b758c****`| -| `proxy_base_url` | The base URL for the proxy server, the value of env var `PROXY_BASE_URL` on your server | `https://proxy.example.com`| -| `user_api_key_alias` | An alias for the LiteLLM Virtual Key.| `prod-app1` | -| `user_api_key_user_id` | The unique ID associated with a user's API key. | `user_123`, `user_456` | -| `user_api_key_user_email` | The email associated with a user's API key. | `user@example.com`, `admin@example.com` | -| `user_api_key_team_alias` | An alias for a team associated with an API key. | `team_alpha`, `dev_team` | +| LiteLLM specific field | Description | Example Value | +|---------------------------|-----------------------------------------------------------------------------------------|------------------------------------------------| +| `cache_hit` | Indicates whether a cache hit occurred (True) or not (False) | `true`, `false` | +| `cache_key` | The Cache key used for this request | `d2b758c****` | +| `proxy_base_url` | The base URL for the proxy server, the value of env var `PROXY_BASE_URL` on your server | `https://proxy.example.com` | +| `user_api_key_alias` | An alias for the LiteLLM Virtual Key. | `prod-app1` | +| `user_api_key_user_id` | The unique ID associated with a user's API key. | `user_123`, `user_456` | +| `user_api_key_user_email` | The email associated with a user's API key. | `user@example.com`, `admin@example.com` | +| `user_api_key_team_alias` | An alias for a team associated with an API key. | `team_alpha`, `dev_team` | **Usage** @@ -1190,7 +1190,7 @@ We will use the `--config` to set - `litellm.success_callback = ["s3"]` -This will log all successfull LLM calls to s3 Bucket +This will log all successful LLM calls to s3 Bucket **Step 1** Set AWS Credentials in .env @@ -1279,7 +1279,7 @@ Log LLM Logs to [Azure Data Lake Storage](https://learn.microsoft.com/en-us/azur | Property | Details | |----------|---------| -| Description | Log LLM Input/Output to Azure Blob Storag (Bucket) | +| Description | Log LLM Input/Output to Azure Blob Storage (Bucket) | | Azure Docs on Data Lake Storage | [Azure Data Lake Storage](https://learn.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-introduction) | @@ -1360,7 +1360,7 @@ LiteLLM Supports logging to the following Datdog Integrations: -We will use the `--config` to set `litellm.callbacks = ["datadog"]` this will log all successfull LLM calls to DataDog +We will use the `--config` to set `litellm.callbacks = ["datadog"]` this will log all successful LLM calls to DataDog **Step 1**: Create a `config.yaml` file and set `litellm_settings`: `success_callback` @@ -1636,7 +1636,7 @@ class MyCustomHandler(CustomLogger): litellm_params = kwargs.get("litellm_params", {}) metadata = litellm_params.get("metadata", {}) # headers passed to LiteLLM proxy, can be found here - # Acess Exceptions & Traceback + # Access Exceptions & Traceback exception_event = kwargs.get("exception", None) traceback_event = kwargs.get("traceback_exception", None) @@ -2205,7 +2205,7 @@ We will use the `--config` to set - `litellm.success_callback = ["dynamodb"]` - `litellm.dynamodb_table_name = "your-table-name"` -This will log all successfull LLM calls to DynamoDB +This will log all successful LLM calls to DynamoDB **Step 1** Set AWS Credentials in .env @@ -2370,7 +2370,7 @@ litellm --test [Athina](https://athina.ai/) allows you to log LLM Input/Output for monitoring, analytics, and observability. -We will use the `--config` to set `litellm.success_callback = ["athina"]` this will log all successfull LLM calls to athina +We will use the `--config` to set `litellm.success_callback = ["athina"]` this will log all successful LLM calls to athina **Step 1** Set Athina API key diff --git a/docs/my-website/docs/proxy/prod.md b/docs/my-website/docs/proxy/prod.md index 2d09502d52..e1b8336401 100644 --- a/docs/my-website/docs/proxy/prod.md +++ b/docs/my-website/docs/proxy/prod.md @@ -61,7 +61,7 @@ CMD ["--port", "4000", "--config", "./proxy_server_config.yaml"] ## 3. Use Redis 'port','host', 'password'. NOT 'redis_url' -If you decide to use Redis, DO NOT use 'redis_url'. We recommend usig redis port, host, and password params. +If you decide to use Redis, DO NOT use 'redis_url'. We recommend using redis port, host, and password params. `redis_url`is 80 RPS slower @@ -169,7 +169,7 @@ If you plan on using the DB, set a salt key for encrypting/decrypting variables Do not change this after adding a model. It is used to encrypt / decrypt your LLM API Key credentials -We recommned - https://1password.com/password-generator/ password generator to get a random hash for litellm salt key. +We recommend - https://1password.com/password-generator/ password generator to get a random hash for litellm salt key. ```bash export LITELLM_SALT_KEY="sk-1234" diff --git a/docs/my-website/docs/proxy/temporary_budget_increase.md b/docs/my-website/docs/proxy/temporary_budget_increase.md index 917ff0d6b5..de985eb9bd 100644 --- a/docs/my-website/docs/proxy/temporary_budget_increase.md +++ b/docs/my-website/docs/proxy/temporary_budget_increase.md @@ -3,7 +3,7 @@ Set temporary budget increase for a LiteLLM Virtual Key. Use this if you get asked to increase the budget for a key temporarily. -| Heirarchy | Supported | +| Hierarchy | Supported | |-----------|-----------| | LiteLLM Virtual Key | ✅ | | User | ❌ | diff --git a/docs/my-website/docs/proxy/ui_credentials.md b/docs/my-website/docs/proxy/ui_credentials.md index ba9d1c4c66..40db536859 100644 --- a/docs/my-website/docs/proxy/ui_credentials.md +++ b/docs/my-website/docs/proxy/ui_credentials.md @@ -4,7 +4,7 @@ import TabItem from '@theme/TabItem'; # Adding LLM Credentials -You can add LLM provider credentials on the UI. Once you add credentials you can re-use them when adding new models +You can add LLM provider credentials on the UI. Once you add credentials you can reuse them when adding new models ## Add a credential + model diff --git a/docs/my-website/docs/proxy/virtual_keys.md b/docs/my-website/docs/proxy/virtual_keys.md index 04be4ade48..26ec69b30d 100644 --- a/docs/my-website/docs/proxy/virtual_keys.md +++ b/docs/my-website/docs/proxy/virtual_keys.md @@ -23,7 +23,7 @@ Requirements: - ** Set on config.yaml** set your master key under `general_settings:master_key`, example below - ** Set env variable** set `LITELLM_MASTER_KEY` -(the proxy Dockerfile checks if the `DATABASE_URL` is set and then intializes the DB connection) +(the proxy Dockerfile checks if the `DATABASE_URL` is set and then initializes the DB connection) ```shell export DATABASE_URL=postgresql://:@:/ @@ -333,7 +333,7 @@ curl http://localhost:4000/v1/chat/completions \ **Expected Response** -Expect to see a successfull response from the litellm proxy since the key passed in `X-Litellm-Key` is valid +Expect to see a successful response from the litellm proxy since the key passed in `X-Litellm-Key` is valid ```shell {"id":"chatcmpl-f9b2b79a7c30477ab93cd0e717d1773e","choices":[{"finish_reason":"stop","index":0,"message":{"content":"\n\nHello there, how may I assist you today?","role":"assistant","tool_calls":null,"function_call":null}}],"created":1677652288,"model":"gpt-3.5-turbo-0125","object":"chat.completion","system_fingerprint":"fp_44709d6fcb","usage":{"completion_tokens":12,"prompt_tokens":9,"total_tokens":21} ``` diff --git a/docs/my-website/docs/simple_proxy_old_doc.md b/docs/my-website/docs/simple_proxy_old_doc.md index 64491b1ea8..730fd0aab4 100644 --- a/docs/my-website/docs/simple_proxy_old_doc.md +++ b/docs/my-website/docs/simple_proxy_old_doc.md @@ -994,16 +994,16 @@ litellm --health ## Logging Proxy Input/Output - OpenTelemetry -### Step 1 Start OpenTelemetry Collecter Docker Container +### Step 1 Start OpenTelemetry Collector Docker Container This container sends logs to your selected destination -#### Install OpenTelemetry Collecter Docker Image +#### Install OpenTelemetry Collector Docker Image ```shell docker pull otel/opentelemetry-collector:0.90.0 docker run -p 127.0.0.1:4317:4317 -p 127.0.0.1:55679:55679 otel/opentelemetry-collector:0.90.0 ``` -#### Set Destination paths on OpenTelemetry Collecter +#### Set Destination paths on OpenTelemetry Collector Here's the OpenTelemetry yaml config to use with Elastic Search ```yaml @@ -1077,7 +1077,7 @@ general_settings: LiteLLM will read the `OTEL_ENDPOINT` environment variable to send data to your OTEL collector ```python -os.environ['OTEL_ENDPOINT'] # defauls to 127.0.0.1:4317 if not provided +os.environ['OTEL_ENDPOINT'] # defaults to 127.0.0.1:4317 if not provided ``` #### Start LiteLLM Proxy @@ -1101,8 +1101,8 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \ ``` -#### Test & View Logs on OpenTelemetry Collecter -On successfull logging you should be able to see this log on your `OpenTelemetry Collecter` Docker Container +#### Test & View Logs on OpenTelemetry Collector +On successful logging you should be able to see this log on your `OpenTelemetry Collector` Docker Container ```shell Events: SpanEvent #0 @@ -1149,7 +1149,7 @@ Here's the log view on Elastic Search. You can see the request `input`, `output` ## Logging Proxy Input/Output - Langfuse -We will use the `--config` to set `litellm.success_callback = ["langfuse"]` this will log all successfull LLM calls to langfuse +We will use the `--config` to set `litellm.success_callback = ["langfuse"]` this will log all successful LLM calls to langfuse **Step 1** Install langfuse diff --git a/docs/my-website/docs/tutorials/compare_llms.md b/docs/my-website/docs/tutorials/compare_llms.md index a7eda2c85f..d7fdf8d7d9 100644 --- a/docs/my-website/docs/tutorials/compare_llms.md +++ b/docs/my-website/docs/tutorials/compare_llms.md @@ -117,7 +117,7 @@ response = completion("command-nightly", messages) """ -# qustions/logs you want to run the LLM on +# questions/logs you want to run the LLM on questions = [ "what is litellm?", "why should I use LiteLLM", diff --git a/docs/my-website/docs/tutorials/gradio_integration.md b/docs/my-website/docs/tutorials/gradio_integration.md index 4854fc2ac9..021815d937 100644 --- a/docs/my-website/docs/tutorials/gradio_integration.md +++ b/docs/my-website/docs/tutorials/gradio_integration.md @@ -30,7 +30,7 @@ def inference(message, history): yield partial_message except Exception as e: print("Exception encountered:", str(e)) - yield f"An Error occured please 'Clear' the error and try your question again" + yield f"An Error occurred please 'Clear' the error and try your question again" ``` ### Define Chat Interface From a260afb74dcc63925cb4f6cd6925202aac8e0d13 Mon Sep 17 00:00:00 2001 From: Christian Owusu <36159205+crisshaker@users.noreply.github.com> Date: Thu, 24 Apr 2025 04:04:40 +0000 Subject: [PATCH 30/40] Reset key alias value when resetting filters (#10099) --- .../src/components/key_team_helpers/filter_logic.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx b/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx index f82178c341..cc3d0eea38 100644 --- a/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx +++ b/ui/litellm-dashboard/src/components/key_team_helpers/filter_logic.tsx @@ -154,9 +154,10 @@ export function useFilterLogic({ 'Key Alias': '' }); - // Reset team and org selections + // Reset selections setSelectedTeam(null); setCurrentOrg(null); + setSelectedKeyAlias(null); }; return { From 2486a106f45d0a0bd4b067a2e5ae979b78e2fea3 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 21:50:16 -0700 Subject: [PATCH 31/40] test: mark flaky tests --- litellm/litellm_core_utils/exception_mapping_utils.py | 3 +++ tests/llm_translation/base_llm_unit_tests.py | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/litellm/litellm_core_utils/exception_mapping_utils.py b/litellm/litellm_core_utils/exception_mapping_utils.py index 54d87cc42e..7578019dff 100644 --- a/litellm/litellm_core_utils/exception_mapping_utils.py +++ b/litellm/litellm_core_utils/exception_mapping_utils.py @@ -311,6 +311,9 @@ def exception_type( # type: ignore # noqa: PLR0915 elif ( "invalid_request_error" in error_str and "content_policy_violation" in error_str + ) or ( + "Invalid prompt" in error_str + and "violating our usage policy" in error_str ): exception_mapping_worked = True raise ContentPolicyViolationError( diff --git a/tests/llm_translation/base_llm_unit_tests.py b/tests/llm_translation/base_llm_unit_tests.py index bbdb8e776f..230781c636 100644 --- a/tests/llm_translation/base_llm_unit_tests.py +++ b/tests/llm_translation/base_llm_unit_tests.py @@ -811,6 +811,7 @@ class BaseLLMChatTest(ABC): return url + @pytest.mark.flaky(retries=3, delay=1) def test_empty_tools(self): """ Related Issue: https://github.com/BerriAI/litellm/issues/9080 @@ -833,6 +834,8 @@ class BaseLLMChatTest(ABC): response = completion(**base_completion_call_args, messages=[{"role": "user", "content": "Hello, how are you?"}], tools=[]) # just make sure call doesn't fail print("response: ", response) assert response is not None + except litellm.ContentPolicyViolationError: + pass except litellm.InternalServerError: pytest.skip("Model is overloaded") except litellm.RateLimitError: @@ -840,6 +843,7 @@ class BaseLLMChatTest(ABC): except Exception as e: pytest.fail(f"Error occurred: {e}") + @pytest.mark.flaky(retries=3, delay=1) def test_basic_tool_calling(self): try: from litellm import completion, ModelResponse From 6023427daecae22eeefb82644d1dddc00ba9e4c1 Mon Sep 17 00:00:00 2001 From: Krrish Dholakia Date: Wed, 23 Apr 2025 21:54:12 -0700 Subject: [PATCH 32/40] docs(gemini.md): cleanup --- docs/my-website/docs/providers/gemini.md | 4 ++-- docs/my-website/docs/providers/vertex.md | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/my-website/docs/providers/gemini.md b/docs/my-website/docs/providers/gemini.md index 434df6a7c9..957c5c13c2 100644 --- a/docs/my-website/docs/providers/gemini.md +++ b/docs/my-website/docs/providers/gemini.md @@ -655,7 +655,7 @@ import os os.environ["GEMINI_API_KEY"] = ".." -tools = [{"googleSearchRetrieval": {}}] # 👈 ADD GOOGLE SEARCH +tools = [{"googleSearch": {}}] # 👈 ADD GOOGLE SEARCH response = completion( model="gemini/gemini-2.0-flash", @@ -691,7 +691,7 @@ curl -X POST 'http://0.0.0.0:4000/chat/completions' \ -d '{ "model": "gemini-2.0-flash", "messages": [{"role": "user", "content": "What is the weather in San Francisco?"}], - "tools": [{"googleSearchRetrieval": {}}] + "tools": [{"googleSearch": {}}] } ' ``` diff --git a/docs/my-website/docs/providers/vertex.md b/docs/my-website/docs/providers/vertex.md index 7f60de27ee..b328c80577 100644 --- a/docs/my-website/docs/providers/vertex.md +++ b/docs/my-website/docs/providers/vertex.md @@ -364,7 +364,7 @@ from litellm import completion ## SETUP ENVIRONMENT # !gcloud auth application-default login - run this to add vertex credentials to your env -tools = [{"googleSearchRetrieval": {}}] # 👈 ADD GOOGLE SEARCH +tools = [{"googleSearch": {}}] # 👈 ADD GOOGLE SEARCH resp = litellm.completion( model="vertex_ai/gemini-1.0-pro-001", @@ -391,7 +391,7 @@ client = OpenAI( response = client.chat.completions.create( model="gemini-pro", messages=[{"role": "user", "content": "Who won the world cup?"}], - tools=[{"googleSearchRetrieval": {}}], + tools=[{"googleSearch": {}}], ) print(response) @@ -410,7 +410,7 @@ curl http://localhost:4000/v1/chat/completions \ ], "tools": [ { - "googleSearchRetrieval": {} + "googleSearch": {} } ] }' @@ -529,7 +529,7 @@ from litellm import completion # !gcloud auth application-default login - run this to add vertex credentials to your env -tools = [{"googleSearchRetrieval": {"disable_attributon": False}}] # 👈 ADD GOOGLE SEARCH +tools = [{"googleSearch": {"disable_attributon": False}}] # 👈 ADD GOOGLE SEARCH resp = litellm.completion( model="vertex_ai/gemini-1.0-pro-001", From acd2c1783c7b6618764460a2a3bb6b8d7eee0d66 Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Wed, 23 Apr 2025 21:56:05 -0700 Subject: [PATCH 33/40] fix(converse_transformation.py): support all bedrock - openai params for arn models (#10256) Fixes https://github.com/BerriAI/litellm/issues/10207 --- .../bedrock/chat/converse_transformation.py | 9 +++++++ .../test_bedrock_completion.py | 26 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/litellm/llms/bedrock/chat/converse_transformation.py b/litellm/llms/bedrock/chat/converse_transformation.py index 31d7542cb4..8332463c5c 100644 --- a/litellm/llms/bedrock/chat/converse_transformation.py +++ b/litellm/llms/bedrock/chat/converse_transformation.py @@ -107,6 +107,15 @@ class AmazonConverseConfig(BaseConfig): "response_format", ] + if ( + "arn" in model + ): # we can't infer the model from the arn, so just add all params + supported_params.append("tools") + supported_params.append("tool_choice") + supported_params.append("thinking") + supported_params.append("reasoning_effort") + return supported_params + ## Filter out 'cross-region' from model name base_model = BedrockModelInfo.get_base_model(model) diff --git a/tests/llm_translation/test_bedrock_completion.py b/tests/llm_translation/test_bedrock_completion.py index d6e8ed4ff8..101e72e3db 100644 --- a/tests/llm_translation/test_bedrock_completion.py +++ b/tests/llm_translation/test_bedrock_completion.py @@ -2972,6 +2972,30 @@ def test_bedrock_application_inference_profile(): client = HTTPHandler() client2 = HTTPHandler() + tools = [{ + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"], + }, + }, + "required": ["location"], + } + } + } + ] + + with patch.object(client, "post") as mock_post, patch.object( client2, "post" ) as mock_post2: @@ -2981,6 +3005,7 @@ def test_bedrock_application_inference_profile(): messages=[{"role": "user", "content": "Hello, how are you?"}], model_id="arn:aws:bedrock:eu-central-1:000000000000:application-inference-profile/a0a0a0a0a0a0", client=client, + tools=tools ) except Exception as e: print(e) @@ -2990,6 +3015,7 @@ def test_bedrock_application_inference_profile(): model="bedrock/converse/arn:aws:bedrock:eu-central-1:000000000000:application-inference-profile/a0a0a0a0a0a0", messages=[{"role": "user", "content": "Hello, how are you?"}], client=client2, + tools=tools ) except Exception as e: print(e) From be4152c8d56c395a841b9f1559d3263035ad74ee Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Wed, 23 Apr 2025 21:56:56 -0700 Subject: [PATCH 34/40] UI - fix edit azure public model name + fix editing model name post create * test(test_router.py): add unit test confirming fallbacks with tag based routing works as expected * test: update testing * test: update test to not use gemini-pro google removed it * fix(conditional_public_model_name.tsx): edit azure public model name Fixes https://github.com/BerriAI/litellm/issues/10093 * fix(model_info_view.tsx): migrate to patch model updates Enables changing model name easily --- tests/litellm/test_router.py | 40 +++++++++++++++++ .../conditional_public_model_name.tsx | 38 ++++++++++------ .../add_model/litellm_model_name.tsx | 30 ++++++++++--- .../src/components/model_info_view.tsx | 6 ++- .../src/components/networking.tsx | 43 +++++++++++++++++++ 5 files changed, 136 insertions(+), 21 deletions(-) diff --git a/tests/litellm/test_router.py b/tests/litellm/test_router.py index 3a572d861d..95bdfccebb 100644 --- a/tests/litellm/test_router.py +++ b/tests/litellm/test_router.py @@ -78,3 +78,43 @@ def test_router_with_model_info_and_model_group(): model_group="gpt-3.5-turbo", user_facing_model_group_name="gpt-3.5-turbo", ) + + +@pytest.mark.asyncio +async def test_router_with_tags_and_fallbacks(): + """ + If fallback model missing tag, raise error + """ + from litellm import Router + + router = Router( + model_list=[ + { + "model_name": "gpt-3.5-turbo", + "litellm_params": { + "model": "gpt-3.5-turbo", + "mock_response": "Hello, world!", + "tags": ["test"], + }, + }, + { + "model_name": "anthropic-claude-3-5-sonnet", + "litellm_params": { + "model": "claude-3-5-sonnet-latest", + "mock_response": "Hello, world 2!", + }, + }, + ], + fallbacks=[ + {"gpt-3.5-turbo": ["anthropic-claude-3-5-sonnet"]}, + ], + enable_tag_filtering=True, + ) + + with pytest.raises(Exception): + response = await router.acompletion( + model="gpt-3.5-turbo", + messages=[{"role": "user", "content": "Hello, world!"}], + mock_testing_fallbacks=True, + metadata={"tags": ["test"]}, + ) diff --git a/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx b/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx index 75ca5ae328..0f79401753 100644 --- a/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx +++ b/ui/litellm-dashboard/src/components/add_model/conditional_public_model_name.tsx @@ -14,6 +14,7 @@ const ConditionalPublicModelName: React.FC = () => { const customModelName = Form.useWatch('custom_model_name', form); const showPublicModelName = !selectedModels.includes('all-wildcard'); + // Force table to re-render when custom model name changes useEffect(() => { if (customModelName && selectedModels.includes('custom')) { @@ -35,20 +36,33 @@ const ConditionalPublicModelName: React.FC = () => { // Initial setup of model mappings when models are selected useEffect(() => { if (selectedModels.length > 0 && !selectedModels.includes('all-wildcard')) { - const mappings = selectedModels.map((model: string) => { - if (model === 'custom' && customModelName) { + // Check if we already have mappings that match the selected models + const currentMappings = form.getFieldValue('model_mappings') || []; + + // Only update if the mappings don't exist or don't match the selected models + const shouldUpdateMappings = currentMappings.length !== selectedModels.length || + !selectedModels.every(model => + currentMappings.some((mapping: { public_name: string; litellm_model: string }) => + mapping.public_name === model || + (model === 'custom' && mapping.public_name === customModelName))); + + if (shouldUpdateMappings) { + const mappings = selectedModels.map((model: string) => { + if (model === 'custom' && customModelName) { + return { + public_name: customModelName, + litellm_model: customModelName + }; + } return { - public_name: customModelName, - litellm_model: customModelName + public_name: model, + litellm_model: model }; - } - return { - public_name: model, - litellm_model: model - }; - }); - form.setFieldValue('model_mappings', mappings); - setTableKey(prev => prev + 1); // Force table re-render + }); + + form.setFieldValue('model_mappings', mappings); + setTableKey(prev => prev + 1); // Force table re-render + } } }, [selectedModels, customModelName, form]); diff --git a/ui/litellm-dashboard/src/components/add_model/litellm_model_name.tsx b/ui/litellm-dashboard/src/components/add_model/litellm_model_name.tsx index 06fad01187..f5c92f8df5 100644 --- a/ui/litellm-dashboard/src/components/add_model/litellm_model_name.tsx +++ b/ui/litellm-dashboard/src/components/add_model/litellm_model_name.tsx @@ -23,22 +23,34 @@ const LiteLLMModelNameField: React.FC = ({ // If "all-wildcard" is selected, clear the model_name field if (values.includes("all-wildcard")) { - form.setFieldsValue({ model_name: undefined, model_mappings: [] }); + form.setFieldsValue({ model: undefined, model_mappings: [] }); } else { - // Update model mappings immediately for each selected model - const mappings = values - .map(model => ({ + // Get current model value to check if we need to update + const currentModel = form.getFieldValue('model'); + + // Only update if the value has actually changed + if (JSON.stringify(currentModel) !== JSON.stringify(values)) { + + // Create mappings first + const mappings = values.map(model => ({ public_name: model, litellm_model: model })); - form.setFieldsValue({ model_mappings: mappings }); + + // Update both fields in one call to reduce re-renders + form.setFieldsValue({ + model: values, + model_mappings: mappings + }); + + } } }; // Handle custom model name changes const handleCustomModelNameChange = (e: React.ChangeEvent) => { const customName = e.target.value; - + // Immediately update the model mappings const currentMappings = form.getFieldValue('model_mappings') || []; const updatedMappings = currentMappings.map((mapping: any) => { @@ -69,7 +81,11 @@ const LiteLLMModelNameField: React.FC = ({ {(selectedProvider === Providers.Azure) || (selectedProvider === Providers.OpenAI_Compatible) || (selectedProvider === Providers.Ollama) ? ( - + <> + + ) : providerModels.length > 0 ? ( , // Assuming formValues is an object + modelId: string +) => { + try { + console.log("Form Values in modelUpateCall:", formValues); // Log the form values before making the API call + + const url = proxyBaseUrl ? `${proxyBaseUrl}/model/${modelId}/update` : `/model/${modelId}/update`; + const response = await fetch(url, { + method: "PATCH", + headers: { + [globalLitellmHeaderName]: `Bearer ${accessToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + ...formValues, // Include formValues in the request body + }), + }); + + if (!response.ok) { + const errorData = await response.text(); + handleError(errorData); + console.error("Error update from the server:", errorData); + throw new Error("Network response was not ok"); + } + const data = await response.json(); + console.log("Update model Response:", data); + return data; + // Handle success - you might want to update some state or UI based on the created key + } catch (error) { + console.error("Failed to update model:", error); + throw error; + } +}; + export const modelUpdateCall = async ( accessToken: string, formValues: Record // Assuming formValues is an object From 430cc60e62e621f8451979b694b693a2562742a2 Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Wed, 23 Apr 2025 22:01:38 -0700 Subject: [PATCH 35/40] Litellm fix UI login (#10260) * fix(user_dashboard.tsx): add token expiry logic to user dashboard if token expired redirect to `/sso/key/generate` for login * fix(user_dashboard.tsx): check key health on login - if invalid -> redirect to login handles invalid / expired key scenario * fix(user_dashboard.tsx): fix linting error * fix(page.tsx): fix invitation link flow From ab68af4ff55721337ea8dac40860568230f2f2af Mon Sep 17 00:00:00 2001 From: Krish Dholakia Date: Wed, 23 Apr 2025 22:02:02 -0700 Subject: [PATCH 36/40] Litellm multi admin fixes (#10259) * fix(create_user_button.tsx): do not set 'no-default-models' when user is a proxy admin * fix(user_info_view.tsx): show all user personal models * feat(user_info_view.tsx): allow giving users more personal models * feat(user_edit_view.tsx): allow proxy admin to edit user role, available models, etc. --- .../src/components/create_user_button.tsx | 5 +- .../src/components/user_edit_view.tsx | 168 +++++++++++++ .../src/components/view_users.tsx | 1 + .../src/components/view_users/table.tsx | 3 + .../components/view_users/user_info_view.tsx | 233 ++++++++++++------ 5 files changed, 336 insertions(+), 74 deletions(-) create mode 100644 ui/litellm-dashboard/src/components/user_edit_view.tsx diff --git a/ui/litellm-dashboard/src/components/create_user_button.tsx b/ui/litellm-dashboard/src/components/create_user_button.tsx index 65a20823f1..eeed238d85 100644 --- a/ui/litellm-dashboard/src/components/create_user_button.tsx +++ b/ui/litellm-dashboard/src/components/create_user_button.tsx @@ -117,13 +117,14 @@ const Createuser: React.FC = ({ form.resetFields(); }; - const handleCreate = async (formValues: { user_id: string, models?: string[] }) => { + const handleCreate = async (formValues: { user_id: string, models?: string[], user_role: string }) => { try { message.info("Making API Call"); if (!isEmbedded) { setIsModalVisible(true); } - if (!formValues.models || formValues.models.length === 0) { + if ((!formValues.models || formValues.models.length === 0) && formValues.user_role !== "proxy_admin") { + console.log("formValues.user_role", formValues.user_role) // If models is empty or undefined, set it to "no-default-models" formValues.models = ["no-default-models"]; } diff --git a/ui/litellm-dashboard/src/components/user_edit_view.tsx b/ui/litellm-dashboard/src/components/user_edit_view.tsx new file mode 100644 index 0000000000..9c0fcbced9 --- /dev/null +++ b/ui/litellm-dashboard/src/components/user_edit_view.tsx @@ -0,0 +1,168 @@ +import React from "react"; +import { Form, InputNumber, Select, Tooltip } from "antd"; +import { TextInput, Textarea, SelectItem } from "@tremor/react"; +import { Button } from "@tremor/react"; +import { getModelDisplayName } from "./key_team_helpers/fetch_available_models_team_key"; +import { all_admin_roles } from "../utils/roles"; +import { InfoCircleOutlined } from "@ant-design/icons"; +interface UserEditViewProps { + userData: any; + onCancel: () => void; + onSubmit: (values: any) => void; + teams: any[] | null; + accessToken: string | null; + userID: string | null; + userRole: string | null; + userModels: string[]; + possibleUIRoles: Record> | null; +} + +export function UserEditView({ + userData, + onCancel, + onSubmit, + teams, + accessToken, + userID, + userRole, + userModels, + possibleUIRoles, +}: UserEditViewProps) { + const [form] = Form.useForm(); + + // Set initial form values + React.useEffect(() => { + form.setFieldsValue({ + user_id: userData.user_id, + user_email: userData.user_info?.user_email, + user_role: userData.user_info?.user_role, + models: userData.user_info?.models || [], + max_budget: userData.user_info?.max_budget, + metadata: userData.user_info?.metadata ? JSON.stringify(userData.user_info.metadata, null, 2) : undefined, + }); + }, [userData, form]); + + const handleSubmit = (values: any) => { + // Convert metadata back to an object if it exists and is a string + if (values.metadata && typeof values.metadata === "string") { + try { + values.metadata = JSON.parse(values.metadata); + } catch (error) { + console.error("Error parsing metadata JSON:", error); + return; + } + } + + onSubmit(values); + }; + + return ( +

+ + + + + + + + + + Global Proxy Role{' '} + + + + + } + name="user_role"> + + + + + Personal Models{' '} + + + + + } + name="models" + > + + + + + + + + +